language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
JavaScript | class CompetencyMatrixView extends ComponentJSON{
constructor(props){
super(props);
this.objectType="workflow";
this.state={dropped_list:[]}
}
render(){
let data = this.props.workflow;
if(data.outcomeworkflow_set.length==0){
let text=gettext("This view renders a table showing the relationships between nodes and outcomes. Add outcomes and nodes to the workflow to get started.");
return(
<div class="emptytext">
{text}
</div>
);
}else{
let outcomes = this.props.outcomes_tree.map((outcome)=>
<MatrixOutcomeView renderer={this.props.renderer} tree_data={outcome} objectID={outcome.id} dropped_list={this.state.dropped_list}/>
);
let weekworkflows = data.weekworkflow_set.map((weekworkflow,i)=>
<MatrixWeekWorkflowView renderer={this.props.renderer} objectID={weekworkflow} rank={i} outcomes_tree={this.props.outcomes_tree} dropped_list={this.state.dropped_list}/>
);
return(
<div class="workflow-details">
<div ref={this.maindiv} class="outcome-table competency-matrix">
<div class="outcome-row node-row">
<div class="outcome-head"></div>
<div class="table-cell nodewrapper blank"><div class="outcome"></div></div>
<div class="outcome-cells">{outcomes}</div>
<div class="table-cell nodewrapper blank"><div class="outcome"></div></div>
<div class="table-cell nodewrapper"><div class="outcome">{gettext("General Education")}</div></div>
<div class="table-cell nodewrapper"><div class="outcome">{gettext("Specific Education")}</div></div>
<div class="table-cell nodewrapper"><div class="outcome">{gettext("Total Hours")}</div></div>
<div class="table-cell nodewrapper blank"><div class="outcome"></div></div>
<div class="table-cell nodewrapper"><div class="outcome">{gettext("Theory")}</div></div>
<div class="table-cell nodewrapper"><div class="outcome">{gettext("Practical")}</div></div>
<div class="table-cell nodewrapper"><div class="outcome">{gettext("Individual Work")}</div></div>
<div class="table-cell nodewrapper"><div class="outcome">{gettext("Total")}</div></div>
<div class="table-cell nodewrapper"><div class="outcome">{gettext("Time")}</div></div>
</div>
{weekworkflows}
</div>
<button class="menu-create" onClick={this.outputCSV.bind(this)}>{gettext("Output CSV")}</button>
</div>
);
}
}
getOutcomes(outcomes_tree,state,display=true){
let outcomes=[];
outcomes_tree.forEach(outcome=>{
let descendants;
descendants = this.getOutcomes(outcome.children,state,this.state.dropped_list.indexOf(outcome.id)>=0);
outcomes.push({...getOutcomeByID(state,outcome.id),descendants:descendants.map(des=>des.data.id),display:display});
outcomes.concat(descendants);
});
return outcomes;
}
getWeeks(state){
let weeks = Constants.filterThenSortByID(state.week,Constants.filterThenSortByID(state.weekworkflow,state.workflow.weekworkflow_set).map(weekworkflow=>weekworkflow.week)).map(week=>{
let nodes = Constants.filterThenSortByID(state.node,Constants.filterThenSortByID(state.nodeweek,week.nodeweek_set).map(nodeweek=>nodeweek.node));
return {week_data:week,nodes:nodes}
});
return weeks;
}
createWeekRow(week_data,rank,outcome_ids,totals_data){
let text = week_data.week_type_display+" "+(rank+1);
if(week_data.title)text = week_data.title;
let row = text+",";
row+=outcome_ids.map(id=>"").join(",")+",";
row+=","+totals_data.general_education;
row+=","+totals_data.specific_education;
row+=","+(totals_data.general_education+totals_data.specific_education);
row+=",";
row+=","+totals_data.theory;
row+=","+totals_data.practical;
row+=","+totals_data.individual;
row+=","+totals_data.total;
row+=","+totals_data.required;
return row;
}
createNodeRow(state,node_data,outcomes_displayed,totals_data){
let title="";
let linked_workflow_data=node_data.linked_workflow_data;
if(linked_workflow_data){
if(linked_workflow_data.code)title=linked_workflow_data.code+" - ";
title+=linked_workflow_data.title;
}else title+=node_data.title;
let row = title+",";
let outcomenodes_all = state.outcomenode.filter(outcomenode=>outcomenode.node==node_data.id);
row+=outcomes_displayed.map(outcome=>{
let outcomenode = getTableOutcomeNodeByID(state,node_data.id,outcome.data.id).data;
let degree;
if(!outcomenode){
for(let i=0;i<outcome.descendants.length;i++){
for(let j=0;j<outcomenodes_all.length;j++){
if(outcome.descendants[i]==outcomenodes_all[j].outcome){
degree=0;
break;
}
}
if(degree===0)break;
}
}else{
degree=outcomenode.degree;
}
if(degree===0)return "P";
else if(degree==1)return "X";
else{
let returnval="";
if(degree & 2)returnval+="I";
if(degree & 4)returnval+="D";
if(degree & 8)returnval+="A";
}
}).join(",");
if(linked_workflow_data){
row+=",";
let general_education = linked_workflow_data.time_general_hours;
row+=","+general_education;
if(!general_education)general_education=0;
totals_data.general_education+=general_education;
let specific_education = linked_workflow_data.time_specific_hours;
row+=","+specific_education;
if(!specific_education)specific_education=0;
totals_data.specific_education+=specific_education;
row+=","+(general_education+specific_education);
row+=",";
let theory = linked_workflow_data.ponderation_theory
row+=","+theory;
if(!theory)theory=0;
totals_data.theory+=theory;
let practical = linked_workflow_data.ponderation_practical
row+=","+practical;
if(!practical)practical=0;
totals_data.practical+=practical;
let individual = linked_workflow_data.ponderation_individual
row+=","+individual;
if(!individual)individual=0;
totals_data.individual+=individual;
let total = theory+practical+individual;
row+=","+total;
totals_data.total+=total;
let time_required = parseInt(linked_workflow_data.time_required);
if(!time_required)time_required=0;
row+=","+time_required;
totals_data.required+=time_required;
}
else row+=",,,,,,,,,,";
return row;
}
outputCSV(){
let state = this.props.renderer.store.getState();
//Get the top row of competencies
let outcomes = this.getOutcomes(this.props.outcomes_tree,state,outcomes);
let outcomes_displayed = outcomes.filter(outcome=>outcome.display)
let outcomes_row = ","+outcomes_displayed.map(outcome=>{
return '"'+Constants.csv_safe(outcome.rank.join(".")+" - "+outcome.data.title)+'"';
}).join(",");
outcomes_row+=",,Gen Ed, Specific Ed,Total Hours,,Theory,Practical,Individual,Total,Credits";
//Get individual weeks and nodes
let weeks = this.getWeeks(state)
//Convert each week/node into a row
let rows=[outcomes_row];
weeks.forEach((week,i)=>{
let totals_data = {theory:0,practical:0,individual:0,total:0,required:0,general_education:0,specific_education:0};
week.nodes.forEach(node=>{
let node_row = this.createNodeRow(state,node,outcomes_displayed,totals_data);
rows.push(node_row);
});
let week_row = this.createWeekRow(week.week_data,i,outcomes_displayed,totals_data);
rows.push(week_row);
rows.push("\n");
});
Constants.download("outcomes_matrix.csv",rows.join("\n"));
alert(gettext("Data has been output to csv in your downloads folder."));
}
postMountFunction(){
$(this.maindiv.current).on("toggle-outcome-drop",(evt,extra_data)=>{
this.setState((prev_state)=>{
let dropped = prev_state.dropped_list.slice();
if(dropped.indexOf(extra_data.id)>=0)dropped.splice(dropped.indexOf(extra_data.id),1);
else dropped.push(extra_data.id);
return {dropped_list:dropped};
})
});
}
} |
JavaScript | class XMLscene extends CGFscene {
/**
* @constructor
* @param {MyInterface} myinterface
*/
constructor(myinterface) {
super();
this.interface = myinterface;
}
/**
* Initializes the scene, setting some WebGL defaults, initializing the camera and the axis.
* @param {CGFApplication} application
*/
init(application) {
super.init(application);
this.sceneInited = false;
this.currentView;
this.securityView;
this.initCameras();
this.enableTextures(true);
this.gl.clearDepth(100.0);
this.gl.enable(this.gl.DEPTH_TEST);
this.gl.enable(this.gl.CULL_FACE);
this.gl.depthFunc(this.gl.LEQUAL);
this.axis = new CGFaxis(this);
this.setUpdatePeriod(1000/30); // 30 fps
this.viewsList = [];
this.viewsIDs = {};
this.views = {};
this.time = Date.now();
this.securityCameraTexture = new CGFtextureRTT(this, this.gl.canvas.width, this.gl.canvas.height);
this.securityCamera = new MySecurityCamera(this);
}
addViews(defaultCamera) {
this.currentView = defaultCamera ? defaultCamera : Object.keys(this.views)[0];
this.securityView = this.currentView;
this.interface.gui
.add(this, 'currentView', Object.keys(this.views))
.name('Scene View')
.onChange(this.onSelectedView.bind(this));
this.interface.gui
.add(this, 'securityView', Object.keys(this.views))
.name('Security Camera')
.onChange(this.onSelectedView.bind(this));
}
onSelectedView() {
this.sceneCamera = this.views[this.currentView];
this.secondaryCamera = this.views[this.securityView];
this.interface.setActiveCamera(this.sceneCamera);
}
/**
* Initializes the scene cameras.
*/
initCameras() {
this.camera = new CGFcamera(0.4, 0.1, 500, vec3.fromValues(15, 15, 15), vec3.fromValues(0, 0, 0));
this.sceneCamera = this.camera;
this.secondaryCamera = this.camera;
}
/**
* Initializes the scene lights with the values read from the XML file.
*/
initLights() {
// Reads the lights from the scene graph.
this.lightsState={};
Object.keys(this.graph.lights).forEach((key, index) => {
if (index < 8) { // Only eight lights allowed by WebGL.
const light = this.graph.lights[key];
const attenuation = light[6];
this.lights[index].setPosition(light[2][0], light[2][1], light[2][2], light[2][3]);
this.lights[index].setAmbient(light[3][0], light[3][1], light[3][2], light[3][3]);
this.lights[index].setDiffuse(light[4][0], light[4][1], light[4][2], light[4][3]);
this.lights[index].setSpecular(light[5][0], light[5][1], light[5][2], light[5][3]);
if (attenuation.constant) this.lights[index].setConstantAttenuation(attenuation.constant);
if (attenuation.linear) this.lights[index].setLinearAttenuation(attenuation.linear);
if (attenuation.quadratic) this.lights[index].setQuadraticAttenuation(attenuation.quadratic);
if (light[1] == 'spot') {
this.lights[index].setSpotCutOff(light[8]);
this.lights[index].setSpotExponent(light[9]);
this.lights[index].setSpotDirection(light[10][0], light[10][1], light[10][2]);
}
this.lights[index].setVisible(true);
if (light[0]) this.lights[index].enable();
else this.lights[index].disable();
this.lights[index].update();
this.lightsState[key] = {
isEnabled: light[0],
lightIndex: index
};
}
});
this.addLightsToInterface();
}
addLightsToInterface(){
Object.keys(this.lightsState).forEach(key => {
this.interface.gui.add(this.lightsState[key], 'isEnabled').name(key);
});
}
updateLights(){
Object.keys(this.lightsState).forEach(key => {
const currentLightState = this.lightsState[key];
const currentLight = this.lights[currentLightState.lightIndex];
if(currentLightState.isEnabled)
currentLight.enable();
else
currentLight.disable();
currentLight.update();
})
}
setDefaultAppearance() {
this.setAmbient(0.2, 0.4, 0.8, 1.0);
this.setDiffuse(0.2, 0.4, 0.8, 1.0);
this.setSpecular(0.2, 0.4, 0.8, 1.0);
this.setShininess(10.0);
}
/** Handler called when the graph is finally loaded.
* As loading is asynchronous, this may be called already after the application has started the run loop
*/
onGraphLoaded() {
this.axis = new CGFaxis(this, this.graph.referenceLength);
this.gl.clearColor(
this.graph.background[0],
this.graph.background[1],
this.graph.background[2],
this.graph.background[3]
);
this.setGlobalAmbientLight(
this.graph.ambient[0],
this.graph.ambient[1],
this.graph.ambient[2],
this.graph.ambient[3]
);
this.initLights();
this.sceneInited = true;
}
update(currTime) {
if(this.sceneInited){
const currentInstant = currTime - this.time;
this.graph.updateComponentAnimations(currentInstant);
}
this.securityCamera.update(currTime);
}
checkKeys(eventCode) {
if (eventCode == "KeyM") {
this.graph.updateMaterial();
}
}
/**
* Displays the scene.
*/
render(renderCamera) {
// ---- BEGIN Background, camera and axis setup
// Clear image and depth buffer everytime we update the scene
this.gl.viewport(0, 0, this.gl.canvas.width, this.gl.canvas.height);
this.gl.clear(this.gl.COLOR_BUFFER_BIT | this.gl.DEPTH_BUFFER_BIT);
// Change current camera used for render
this.camera = renderCamera;
// Initialize Model-View matrix as identity (no transformation
this.updateProjectionMatrix();
this.loadIdentity();
// Apply transformations corresponding to the camera position relative to the origin
this.applyViewMatrix();
this.pushMatrix();
this.axis.display();
if (this.sceneInited) {
// Draw axis
this.updateLights();
this.setDefaultAppearance();
// Displays the scene (MySceneGraph function).
this.graph.displayScene();
}
this.popMatrix();
// ---- END Background, camera and axis setup
}
display() {
this.securityCameraTexture.attachToFrameBuffer();
this.render(this.secondaryCamera);
this.securityCameraTexture.detachFromFrameBuffer();
this.render(this.sceneCamera);
this.gl.disable(this.gl.DEPTH_TEST);
this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_S, this.gl.REPEAT);
this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_T, this.gl.REPEAT);
this.securityCamera.display(this.securityCameraTexture);
this.gl.enable(this.gl.DEPTH_TEST);
}
} |
JavaScript | class Token {
/**
* @param {TokenTypes} type This argument is the one of enumeration values that is defined by `TokenTypes`.
* @param {string} token This argument is a string that constructs of token.
*/
constructor(type, token) {
this.type = type;
this.token = token;
this.value = parseInt(token, 10);
}
/**
* This method is getter for token type.
*/
getType() {
return this.type || null;
}
/**
* This method is getter for token.
*/
getToken() {
return this.token;
}
/**
* This method is getter for token value if token is number.
*/
getValue() {
return isNaN(this.value) ? null : this.value;
}
} |
JavaScript | class Notes {
/**
* Get Likes for this note
* @param {string} note_id
*/
static async getLikes(note_id) {
return db.all(`SELECT * from noteLikes
WHERE ${db.columnNames.note_id} = '${note_id}'`);
}
} |
JavaScript | class ContainerModel {
constructor(id, command, name, image, status, ports, isRunning) {
this.id = id;
this.command = command;
this.name = name;
this.image = image;
this.status = status;
this.ports = ports;
this.isRunning = isRunning;
}
} |
JavaScript | class DoorFactory {
constructor() {
this.makeDoor = () => {};
this.makeFittingExpert = () => {};
}
} |
JavaScript | class WoodenDoorFactory extends DoorFactory {
constructor() {
super();
this.makeDoor = () => new WoodenDoor();
this.makeFittingExpert = () => new Carpenter();
}
} |
JavaScript | class IronDoorFactory extends DoorFactory {
constructor() {
super();
this.makeDoor = () => new IronDoor();
this.makeFittingExpert = () => new Welder();
}
} |
JavaScript | class LexerTransformation {
/**
* Construct a new LexerTransformation.
*
* You cannot construct a LexerTransformation directly. You should
* extend this class instead.
*
* @param {string} type The Token type this transformation operates on.
*/
constructor(type) {
if (this.constructor === LexerTransformation) {
throw new Error("Can't instantiate an abstract class.");
}
this.type = type;
}
/**
* Transform a Lexeme array.
*
* You cannot call this method directly. You need to override it instead.
*
* @param {Lexeme[]} lexemes An array of lexemes to operate on.
*
* @return {Lexeme[]} A modified Lexeme array.
*/
transform(lexemes) {
throw new Error("You should override this method.");
}
/**
* Get the Token type a LexerTransformation operates on.
*
* @return {string} A Token type.
*/
get_type() {
return this.type;
}
} |
JavaScript | class Graph {
constructor() {
this.list = {};
}
//number of edges
get size() {
let size = 0;
for (let i in this.list) {
size += Object.keys(this.list[i]).length;
}
return size;
}
//number of vertices
get order() {
return Object.keys(this.list).length;
}
insertVertex(v) {
this.list[v] = {};
}
insertEdge(v1, v2, weight = 1) {
this.list[v1][v2] = weight;
}
getWeight(v1, v2) {
const w = this.list[v1][v2];
return w ? w : Infinity;
}
//dijkstra's algorithm
findPath(v1, v2) {
let current = v1;
const vertices = Object.keys(this.list);
let unvisited = [...vertices];
//initialize all weights to infinity
const weights = vertices.reduce((obj, item) => {
obj[item] = Infinity;
return obj;
}, {});
weights[v1] = 0;
const previous = {};
while (unvisited.length > 0) {
for (let v of vertices) {
const n = this.getWeight(current, v) + weights[current];
if (n < weights[v]) {
weights[v] = n;
previous[v] = current;
}
}
//remove current
unvisited = unvisited.filter(item => item != current);
if (unvisited.length == 0) break;
//find the unvisited vertex with the minimum weight
let min = unvisited.reduce((prev, cur) => {
return weights[cur] > weights[prev] ? prev : cur;
}, unvisited[0]);
current = min;
}
if (!previous[v2]) {
//there is no path from v1 to v2
return undefined;
}
//the algorithm is done here all that remains is to format the data
//in an array so it looks like an actual path
let v = v2;
const ret = [v2];
do {
v = previous[v];
ret.push(v);
} while (v != v1);
return ret.reverse();
}
} |
JavaScript | class SumoClient {
constructor(options, context, flush_failure_callback, success_callback) {
let myOptions = options || {};
if (myOptions.urlString) {
let urlObj = parse(options.urlString);
myOptions.hostname = urlObj.hostname;
myOptions.path = urlObj.pathname;
myOptions.protocol = urlObj.protocol;
}
myOptions.method = 'POST';
this.options = myOptions;
if (this.options.compress_data == undefined) {
this.options.compress_data = true;
}
// use messagesSent, messagesAttempted and messagedFailed below to keep track of the final delivery status for the overall message batch
this.messagesReceived = 0;
this.messagesSent = 0;
this.messagesAttempted = 0;
this.messagesFailed = 0;
this.dataMap = new Map();
this.context = context || console;
this.generateBucketKey = options.generateBucketKey || this.generateLogBucketKey;
this.MaxAttempts = this.options.MaxAttempts || 3;
this.RetryInterval = this.options.RetryInterval || 3000; // 3 secs
this.failure_callback = flush_failure_callback;
this.success_callback = success_callback;
this._timerID = null;
this._timerInterval = null;
if (this.options.timerinterval) {
this.enableTimer(this.options.timerinterval);
}
}
enableTimer(interval) {
if (Number(interval) > 0) {
this.disableTimer();
this._timerInterval = Number(interval);
let self = this;
this._timerID = setInterval(() => {
self.flushAll();
}, self._timerInterval);
}
}
disableTimer() {
if (this._timerID) {
clearInterval(this._timerID);
this._timerID = null;
this._timerInterval = 0;
}
}
/**
* Default method to generate a headersObj object for the bucket
* @param message input message
*/
generateHeaders(message, delete_metadata) {
let sourceCategory = (this.options.metadata) ? (this.options.metadata.category || '') : '';
let sourceName = (this.options.metadata) ? (this.options.metadata.name || '') : '';
let sourceHost = (this.options.metadata) ? (this.options.metadata.host || '') : '';
let headerObj = {
"X-Sumo-Name": sourceName,
"X-Sumo-Category": sourceCategory,
"X-Sumo-Host": sourceHost,
"X-Sumo-Client": this.options.clientHeader || "eventhublogs-azure-function",
};
if (message.hasOwnProperty('_sumo_metadata')) {
let metadataOverride = message._sumo_metadata;
Object.getOwnPropertyNames(metadataOverride).forEach(property => {
if (metadataMap[property]) {
this.targetProperty = metadataMap[property];
} else {
this.targetProperty = property;
}
headerObj[this.targetProperty] = metadataOverride[property];
});
if (typeof delete_metadata === 'undefined' || delete_metadata) {
delete message._sumo_metadata;
}
}
return headerObj;
}
/**
* Default method to generate the bucket key for the input message. For log messages, we'll use 3 metadata fields as the key
* @param message input message
* @return: a string used as the key for the bucket map
*/
generateLogBucketKey(message) {
return JSON.stringify(this.generateHeaders(message, false));
}
emptyBufferToSumo(metaKey) {
let targetBuffer = this.dataMap.get(metaKey);
if (targetBuffer) {
let message;
while ((message = targetBuffer.pop())) {
this.context.log(metaKey + '=' + JSON.stringify(message));
}
}
}
/**
* Flush a whole message bucket to sumo, compress data if needed and with up to MaxAttempts
* @param {string} metaKey - key to identify the buffer from the internal map
*/
flushBucketToSumo(metaKey) {
let targetBuffer = this.dataMap.get(metaKey);
var self = this;
let curOptions = Object.assign({}, this.options);
this.context.log("Flush buffer for metaKey:" + metaKey);
function httpSend(messageArray, data) {
return new Promise((resolve, reject) => {
var req = request(curOptions, function (res) {
var body = '';
res.setEncoding('utf8');
res.on('data', function (chunk) {
body += chunk; // don't really do anything with body
});
res.on('end', function () {
if (res.statusCode == 200) {
self.messagesSent += messageArray.length;
self.messagesAttempted += messageArray.length;
resolve(body);
// TODO: anything here?
} else {
reject({ error: null, res: res });
}
// TODO: finalizeContext();
});
});
req.on('error', function (e) {
reject({ error: e, res: null });
// TODO: finalizeContext();
});
req.write(data);
req.end();
});
}
if (targetBuffer) {
curOptions.headers = targetBuffer.getHeadersObject();
let msgArray = [];
let message;
while (targetBuffer.getSize() > 0) {
message = targetBuffer.remove();
if (message instanceof Object) {
msgArray.push(JSON.stringify(message));
} else {
msgArray.push(message);
}
}
if (curOptions.compress_data) {
curOptions.headers['Content-Encoding'] = 'gzip';
gzip(msgArray.join('\n'), function (e, compressed_data) {
if (!e) {
p_retryMax(httpSend, self.MaxAttempts, self.RetryInterval, [msgArray, compressed_data])
.then(() => {
//self.context.log("Succesfully sent to Sumo after "+self.MaxAttempts);
self.success_callback(self.context);
})
.catch(() => {
//self.context.log("Uh oh, failed to send to Sumo after "+self.MaxAttempts);
self.messagesFailed += msgArray.length;
self.messagesAttempted += msgArray.length;
self.failure_callback(msgArray, self.context);
});
} else {
self.messagesFailed += msgArray.length;
self.messagesAttempted += msgArray.length;
self.failure_callback(msgArray, self.context);
}
});
} else {
//self.context.log('Send raw data to Sumo');
p_retryMax(httpSend, self.MaxAttempts, self.RetryInterval, [msgArray, msgArray.join('\n')])
.then(() => { self.success_callback(self.context); })
.catch(() => {
self.messagesFailed += msgArray.length;
self.messagesAttempted += msgArray.length;
self.failure_callback(msgArray, self.context);
});
}
}
}
/**
* Flush all internal buckets to Sumo
*/
flushAll() {
var self = this;
this.dataMap.forEach((buffer, key, dataMap) => {
self.flushBucketToSumo(key);
});
}
addData(data) {
var self = this;
if (data instanceof Array) {
data.forEach((item, index, array) => {
self.messagesReceived += 1;
self.submitMessage(item);
});
} else {
self.messagesReceived += 1;
self.submitMessage(data);
}
}
submitMessage(message) {
let metaKey = this.generateLogBucketKey(message);
if (!this.dataMap.has(metaKey)) {
this.dataMap.set(metaKey, new MessageBucket(this.generateHeaders(message)));
}
this.dataMap.get(metaKey).add(message);
}
} |
JavaScript | class LandingPageHero extends React.Component {
constructor(props) {
super(props)
}
render() {
/**
* @desc Default landing page styles.
* By supplying options in props, we can override
* these styles.
*
* At some point, documentation for this component will
* become more necessary.
*/
let settings = {
options: {
alignment: 'left',
centerHeroContainer: true,
image: null,
hasPolygon: false,
buttons: {
alreadyOnComponentActive: false,
},
hero: {
showHeroMask: false,
showDarkMask: false,
showColorMask: false,
color: '#555555',
},
overrideClass: null,
},
}
settings = Object.assign({}, settings, this.props)
return (
<div
style={get(settings, 'options.styles.container')}
className={`landing-page-container ${styles.container}`}
>
<div
style={{
backgroundImage: `url(${settings.options.image})`,
backgroundColor: settings.options.hero
? settings.options.hero.color
: '',
}}
className={styles.imageOrColour}
>
<div
style={applyLandingStyles(settings.options)}
className={shouldShowMask(settings.options)}
/>
<LandingPageContent
title={settings.heroTitle}
subTitle={settings.heroSubTitle}
buttons={settings.options.buttons}
alignment={settings.options.alignment}
/>
</div>
</div>
)
}
} |
JavaScript | class MatTabContent {
constructor(
/** Content for the tab. */ template) {
this.template = template;
}
} |
JavaScript | class OracleQueryInterface extends QueryInterface {
/**
* A wrapper that fixes Oracle's inability to cleanly drop constraints on multiple tables if the calls are made at the same time
*
* @param {object} options
*/
async dropAllTables(options) {
options = options || {};
const skip = options.skip || [];
//As oracle uppercase all tables names, we create a mapping array with everything in upperCase
const upperSkip = skip.map(table => {
return table.toUpperCase();
});
const dropAllTablesFct = tableNames =>
Promise.each(tableNames, tableName => {
// if tableName is not in the Array of tables names then dont drop it
if (Object.keys(tableName).length > 0) {
if (upperSkip.indexOf(tableName.tableName) === -1) {
return this.dropTable(tableName, _.assign({}, options, { cascade: true }));
}
} else {
if (upperSkip.indexOf(tableName) === -1) {
return this.dropTable(tableName, _.assign({}, options, { cascade: true }));
}
}
});
return this.showAllTables(options).then(tableNames => {
return dropAllTablesFct(tableNames).then(res => {
return res;
});
});
}
/**
* A wrapper that fixes Oracle's inability to cleanly remove columns from existing tables if they have a default constraint.
*
* @function removeColumn
* @for QueryInterface
* @param {string} tableName The name of the table.
* @param {string} attributeName The name of the attribute that we want to remove.
* @param {object} options
* @param {boolean|Function} [options.logging] A function that logs the sql queries, or false for explicitly not logging these queries
* @private
*/
removeColumn(tableName, attributeName, options) {
options = Object.assign({ raw: true }, options || {});
const constraintsSql = [];
//We start by searching if the primary key is an identity
const descriptionTableQuery = this.QueryGenerator.isIdentityPrimaryKey(tableName);
return this.sequelize.query(descriptionTableQuery, options).spread(PKResult => {
for (let i = 0; i < PKResult.length; i++) {
//We iterate through the primary keys to determine if we are working on it
if (PKResult[i].column_name === attributeName.toUpperCase()) {
//The column we are working on is in the PK AND is an identity column, we have to drop the identity
const dropIdentitySql = this.QueryGenerator.dropIdentityColumn(tableName, attributeName);
constraintsSql.push({
sql: dropIdentitySql,
options
});
break;
}
}
//This method return all constraints on a table with a given attribute
const findConstraintSql = this.QueryGenerator.getConstraintsOnColumn(tableName, attributeName);
return this.sequelize
.query(findConstraintSql, options)
.spread(results => {
if (!results.length && constraintsSql.length === 0) {
// No default constraint found -- we can cleanly remove the column
return;
}
//Function to execute the different remove one by one
const deleteRecursively = (constraints, idx, sequelizeInstance) => {
if (constraints.length > 0) {
if (idx < constraints.length) {
const elem = constraints[idx];
idx++;
//While elements, we execute the query
return sequelizeInstance.query(elem.sql, elem.options).then(() => {
return deleteRecursively(constraints, idx, sequelizeInstance);
});
} else {
//Done, we get out
return Promise.resolve({});
}
} else {
return Promise.resolve({});
}
};
results.forEach(result => {
//For each constraint, we get the sql
constraintsSql.push({
sql: this.QueryGenerator.dropConstraintQuery(tableName, result.constraint_name),
options
});
});
// const dropConstraintSql = this.QueryGenerator.dropConstraintQuery(tableName, results[0].name);
return deleteRecursively(constraintsSql, 0, this.sequelize);
})
.then(() => {
const removeSql = this.QueryGenerator.removeColumnQuery(tableName, attributeName);
return this.sequelize.query(removeSql, options);
});
});
}
/**
* A wrapper that adds the currentModel of the describe in options
* This is used for mapping the real column names to those returned by Oracle
*
* @param tableName
* @param options
*/
addOptionsForDescribe(tableName, options) {
if (this.sequelize && this.sequelize.models && Object.keys(this.sequelize.models).length > 0) {
const keys = Object.keys(this.sequelize.models);
let i = 0,
found = false;
while (i < keys.length && !found) {
const model = this.sequelize.models[keys[i]];
if (model.tableName === tableName) {
if (options) {
options['describeModelAttributes'] = model.rawAttributes;
} else {
options = {
describeModelAttributes: model.rawAttributes
};
}
found = true;
}
i++;
}
}
return options;
}
} |
JavaScript | class LrnsysButton extends PolymerElement{constructor(){super();import("./node_modules/@polymer/iron-icons/iron-icons.js");import("./node_modules/@polymer/paper-tooltip/paper-tooltip.js")}static get template(){return html`
<style include="materializecss-styles-colors">
:host {
display: block;
@apply --paper-font-common-base;
@apply --paper-button;
--lrnsys-button-height: 48px;
}
a {
text-decoration: none;
display: block;
color: var(--lrnsys-button-link-color, #000000);
display: flex;
}
paper-button {
padding: 0;
margin: 0;
min-width: 0.16px;
height: inherit;
-webkit-justify-content: flex-start;
justify-content: flex-start;
align-items: center;
width: 100%;
text-transform: unset;
border-radius: unset;
display: flex;
}
.no-padding {
padding: 0;
}
paper-button iron-icon {
height: var(--lrnsys-button-height);
margin: 0 4px;
}
paper-button iron-icon:first-child {
margin: 0 4px 0 0;
}
paper-button iron-icon:last-child {
margin: 0 0 0 4px;
}
paper-button div.inner {
height: var(--lrnsys-button-height);
line-height: var(--lrnsys-button-height);
display: flex;
padding: 0 16px;
}
paper-button span.label {
height: var(--lrnsys-button-height);
line-height: var(--lrnsys-button-height);
}
.no-margin {
margin: 0 !important;
}
.no-right-padding {
padding-right: 0 !important;
}
.no-left-padding {
padding-left: 0 !important;
}
</style>
<a
tabindex="-1"
id="lrnsys-button-link"
href\$="[[showHref]]"
target\$="[[target]]"
>
<paper-button
id="button"
title="[[alt]]"
raised="[[raised]]"
class\$="[[buttonClass]] [[color]] [[textColor]]"
disabled\$="[[disabled]]"
>
<div class\$="inner [[innerClass]]">
<slot name="prefix"></slot>
<iron-icon
icon="[[icon]]"
id="icon"
class\$="[[iconClass]]"
hidden\$="[[!icon]]"
></iron-icon>
<span class="label" hidden\$="[[!label]]"> [[label]] </span>
<slot></slot>
</div>
</paper-button>
</a>
<paper-tooltip
for="lrnsys-button-link"
animation-delay="0"
hidden\$="[[!alt]]"
>[[alt]]</paper-tooltip
>
`}static get tag(){return"lrnsys-button"}static get properties(){return{/**
* Standard href pass down
*/href:{type:String,value:"#",reflectToAttribute:!0},showHref:{type:String,value:!1,reflectToAttribute:!0,computed:"_getShowHref(href,disabled)"},/**
* If the button should be visually lifted off the UI.
*/raised:{type:Boolean,reflectToAttribute:!0},/**
* Label to place in the text area
*/label:{type:String,value:""},/**
* Support for target to open in new windows.
*/target:{type:String,value:""},/**
* iron-icon to use (with iconset if needed)
*/icon:{type:String,value:!1},/**
* Classes to add / subtract based on the item being hovered.
*/hoverClass:{type:String},/**
* Button class.
*/buttonClass:{type:String},/**
* Icon class in the event you want it to look different from the text.
*/iconClass:{type:String},/**
* Inner container classes.
*/innerClass:{type:String},/**
* Color class work to apply
*/color:{type:String,reflectToAttribute:!0},/**
* materializeCSS color class for text
*/textColor:{type:String},/**
* Allow for prefetch data automatically
*/prefetch:{type:Boolean,observer:"_applyPrefetch"},/**
* Alt via tooltip.
*/alt:{type:String},/**
* Disabled state.
*/disabled:{type:Boolean,value:!1},/**
* Tracks if focus state is applied
*/focusState:{type:Boolean,value:!1}}}_applyPrefetch(newValue){if(newValue&&this.__ready&&!this.__prefetchLink){let link=document.createElement("link");link.setAttribute("rel","prefetch");link.setAttribute("href",this.href);// store for disconnect so we can clean up if needed
this.__prefetchLink=link;document.head.appendChild(link)}}/**
* attached life cycle
*/ready(){super.ready();afterNextRender(this,function(){this.addEventListener("mousedown",this.tapEventOn.bind(this));this.addEventListener("mouseover",this.tapEventOn.bind(this));this.addEventListener("mouseout",this.tapEventOff.bind(this));this.$.button.addEventListener("focused-changed",this.focusToggle.bind(this))})}connectedCallback(){super.connectedCallback();this.__ready=!0;afterNextRender(this,function(){// if we have been told to prefetch, give it a second after everything's ready
if(this.prefetch){setTimeout(()=>{this._applyPrefetch(this.prefetch)},1e3)}})}/**
* detached event listener
*/disconnectedCallback(){if(this.__prefetchLink){document.head.removeChild(this.__prefetchLink)}this.removeEventListener("mousedown",this.tapEventOn.bind(this));this.removeEventListener("mouseover",this.tapEventOn.bind(this));this.removeEventListener("mouseout",this.tapEventOff.bind(this));this.$.button.removeEventListener("focused-changed",this.focusToggle.bind(this));super.disconnectedCallback()}/**
* Generate the pass down href if it exists. This helps
* ensure that if a button is disabled it won't do anything
* even if it has a resource reference.
*/_getShowHref(href,disabled){if(href&&!disabled){return href}}/**
* Class processing on un-tap / hover
*/tapEventOn(e){if(typeof this.hoverClass!==typeof void 0&&!this.disabled){// break class into array
var classes=this.hoverClass.split(" ");// run through each and add or remove classes
classes.forEach((item,index)=>{if(""!=item){this.$.button.classList.add(item);if(-1!=item.indexOf("-")){this.$.icon.classList.add(item)}}})}}/**
* Undo class processing on un-tap / hover
*/tapEventOff(e){if(typeof this.hoverClass!==typeof void 0&&!this.disabled){// break class into array
var classes=this.hoverClass.split(" ");// run through each and add or remove classes
classes.forEach((item,index)=>{if(""!=item){this.$.button.classList.remove(item);if(-1!=item.indexOf("-")){this.$.icon.classList.remove(item)}}})}}/**
* Handle toggle for mouse class and manage classList array for paper-button.
*/focusToggle(e){// weird but reality... focus event is the button inside of here
if(typeof this.hoverClass!==typeof void 0&&!this.disabled){// break class into array
var classes=this.hoverClass.split(" ");// run through each and add or remove classes
classes.forEach((item,index)=>{if(""!=item){if(!this.focusState){this.$.button.classList.add(item);if(-1!=item.indexOf("-")){this.$.icon.classList.add(item)}}else{this.$.button.classList.remove(item);if(-1!=item.indexOf("-")){this.$.icon.classList.remove(item)}}}})}this.focusState=!this.focusState}} |
JavaScript | class DeltaTimer {
// Timer object does not start until 'start' is called.
constructor() {
// Base timer functionality.
this.isRunning = false;
this.deltaTime = 0.0;
this.time = 0.0;
}
// Start or resume the timer.
start() {
this.isRunning = true;
}
// Update the timer.
update() {
if(this.isRunning) {
let now = Date.now();
this.deltaTime = now - this.time;
this.time = this.time + this.deltaTime;
}
}
// Pause the timer.
pause() {
this.isRunning = false;
}
// Stop and reset the timer.
stop() {
this.isRunning = false;
this.deltaTime = 0.0;
this.time = 0.0;
}
} |
JavaScript | class ImportExport {
constructor(editor) {
this.editor = editor;
}
/**
* @typedef {Object} resultingNode
* @property {Object} temporary A temporary field was created by {@link ImportExport#_addNode()}.
* @property {Object.<string, string>} [temporary.inputs] The inputs of the entry, only existing for conditions and actions
*/
/**
* Adds a rule component to the editor.
*
* @param {Object} entry An trigger, condition, action entry of a rule
* @param {String} entry.type The module-type
* @param {String} entry.label The label of the entry
* @param {String} entry.description The description of the entry
* @param {Object.<string, String|Number>} [entry.configuration] The configuration of the entry
* @param {Object.<string, string>} [entry.inputs] The inputs of the entry, only existing for conditions and actions
* @private
* @return {resultingNode} The node that has been created and was added to the editor is returned.
*/
async _addNode(entry) {
const component = this.editor.getComponent(entry.type);
if (!component) {
throw new Error("Did not find component " + entry.type);
}
const node = await component.createNode({ label: entry.label, description: entry.description, type: entry.type })
node.id = entry.id;
if (entry.configuration) {
Object.keys(entry.configuration).forEach(controlKey => {
let control = node.controls.get(controlKey);
if (control) {
const value = entry.configuration[controlKey];
control.value = value;
}
});
}
node.temporary = { inputs: entry.inputs };
this.editor.addNode(node);
return node;
}
/**
* Connect the input and output sockets of the given node.
*
* A rule condition and action can have a field "inputs". That might look like the following:
* ```
* "inputs":{
* "conditionInput":"SampleTriggerID.triggerOutput"
* }
* ```
*
* It means that the, in the moduletypes defined, input "conditionInput" is connected to
* an output of a component in the same rule. That component has the id "SampleTriggerID"
* and the output can be found with "triggerOutput".
*
* @param {Object} node A trigger, condition, action node
* @param {Map} node.inputs The nodes inputs
* @param {Map} node.outputs The nodes outputs
* @param {OHRuleComponent} node.moduletype The module type of this node, see {@link OHRuleComponent}.
* @param {Object} node.temporary This temporary field was created by {@link ImportExport#_addNode()}.
* @param {Object.<string, string>} [node.temporary.inputs] The inputs of the entry, only existing for conditions and actions
* @private
*/
_connectSockets(node, nodes) {
// Don't do anything if the nodes moduletype does not have inputs or the rule has no inputs for this node
if (!node.moduletype.inputs || !node.temporary.inputs) return;
// Extract the temporarly injected rule components' input mapping
const ruleComponentInputMapping = node.temporary.inputs;
delete node.temporary;
// For every input of this nodes moduletype try to find the output
for (let inputid of node.moduletype.inputs) {
const inputMapping = ruleComponentInputMapping.get(inputid);
if (!inputMapping) continue; // no connection for an input
// Determine output
const [targetnodeid, outputid] = inputMapping.split("\.");
const targetNode = nodes[targetnodeid];
if (!targetNode) {
throw new Error("Connection failed: Target node not found!", targetNode);
}
const output = targetNode.outputs.get(outputid);
if (!output) {
throw new Error("Connection failed: Target node output not found!", outputid);
}
this.editor.connect(output, node.inputs.get(inputid));
}
}
/**
* Adds all triggers, conditions and actions from a rule object to the editor.
* Does not prune the editor before!
*
* @param {Object} rule An OH rule object
* @param {Boolean} clearEditor Clears the editor before importing
* @returns A promise that resolves on success
*/
async fromJSON(rule, clearEditor = false) {
this.editor.beforeImport(rule, clearEditor);
const nodes = {};
try {
if (rule.triggers && rule.triggers.length > 0) {
for (const entry of rule.triggers) {
nodes[entry.id] = await this._addNode(entry);
}
}
if (rule.conditions && rule.conditions.length > 0) {
for (const entry of rule.conditions) {
nodes[entry.id] = await this._addNode(entry);
}
}
if (rule.actions && rule.actions.length > 0) {
for (const entry of rule.actions) {
nodes[entry.id] = await this._addNode(entry);
}
}
Object.keys(nodes).forEach(id => {
this._connectSockets(nodes[id], nodes);
});
}
catch (e) {
this.editor.trigger('warn', e);
this.editor.afterImport();
return false;
}
this.editor.afterImport();
return true;
}
/**
* Exports the editor nodes to an OH rule json partial containing the
* trigger, condition and action part.
*
* @returns An object with trigger, condition and action part
*/
toJSON() {
const data = { triggers: [], conditions: [], actions: [] };
for (let node of this.editor.nodes) {
if (!node.data.type) continue; // Skip any auxilary nodes like captions
let ruleComponent = { label: node.data.label, description: node.data.description, type: node.moduletype.name, id: node.id, configuration: {} };
for (let [key, control] of node.controls) {
ruleComponent.configuration[control.key] = control.value;
}
const inputs = Array.from(node.inputs);
if (inputs.length) {
ruleComponent.inputs = {};
for (let [key, input] of inputs) {
for (let connection of input.connections) {
ruleComponent.inputs[key] = connection.output.node.id + "." + connection.output.key;
}
}
}
if (!data[node.data.type + "s"]) {
console.warn("Unexpected node type!", node);
continue;
}
data[node.data.type + "s"].push(ruleComponent);
}
this.editor.trigger('export', data);
return data;
}
} |
JavaScript | class SatCalendarCell {
constructor(value, displayValue, ariaLabel, enabled, cssClasses) {
this.value = value;
this.displayValue = displayValue;
this.ariaLabel = ariaLabel;
this.enabled = enabled;
this.cssClasses = cssClasses;
}
} |
JavaScript | class SatCalendarBody {
constructor(_elementRef, _ngZone) {
this._elementRef = _elementRef;
this._ngZone = _ngZone;
/** Enables datepicker MouseOver effect on range mode */
this.rangeHoverEffect = true;
/** Whether to use date range selection behaviour.*/
this.rangeMode = false;
/** The number of columns in the table. */
this.numCols = 7;
/** The cell number of the active cell in the table. */
this.activeCell = 0;
/**
* The aspect ratio (width / height) to use for the cells in the table. This aspect ratio will be
* maintained even as the table resizes.
*/
this.cellAspectRatio = 1;
/** Emits when a new value is selected. */
this.selectedValueChange = new EventEmitter();
}
_cellClicked(cell) {
if (cell.enabled) {
this.selectedValueChange.emit(cell.value);
}
}
_mouseOverCell(cell) {
if (this.rangeHoverEffect) {
this._cellOver = cell.value;
}
}
ngOnChanges(changes) {
const columnChanges = changes['numCols'];
const { rows, numCols } = this;
if (changes['rows'] || columnChanges) {
this._firstRowOffset = rows && rows.length && rows[0].length ? numCols - rows[0].length : 0;
}
if (changes['cellAspectRatio'] || columnChanges || !this._cellPadding) {
this._cellPadding = `${50 * this.cellAspectRatio / numCols}%`;
}
if (columnChanges || !this._cellWidth) {
this._cellWidth = `${100 / numCols}%`;
}
if (changes.activeCell) {
// Only modify hovered cell variable when rangeHoverEffect is enabled
if (this.rangeHoverEffect) {
this._cellOver = this.activeCell + 1;
}
}
}
_isActiveCell(rowIndex, colIndex) {
let cellNumber = rowIndex * this.numCols + colIndex;
// Account for the fact that the first row may not have as many cells.
if (rowIndex) {
cellNumber -= this._firstRowOffset;
}
return cellNumber == this.activeCell;
}
/** Whenever to mark cell as semi-selected (inside dates interval). */
_isSemiSelected(date) {
if (!this.rangeMode) {
return false;
}
if (this.rangeFull) {
return true;
}
/** Do not mark start and end of interval. */
if (date === this.begin || date === this.end) {
return false;
}
if (this.begin && !this.end) {
return date > this.begin;
}
if (this.end && !this.begin) {
return date < this.end;
}
return date > this.begin && date < this.end;
}
/** Whenever to mark cell as semi-selected before the second date is selected (between the begin cell and the hovered cell). */
_isBetweenOverAndBegin(date) {
if (!this._cellOver || !this.rangeMode || !this.beginSelected) {
return false;
}
if (this.isBeforeSelected && !this.begin) {
return date > this._cellOver;
}
if (this._cellOver > this.begin) {
return date > this.begin && date < this._cellOver;
}
if (this._cellOver < this.begin) {
return date < this.begin && date > this._cellOver;
}
return false;
}
/** Whenever to mark cell as begin of the range. */
_isBegin(date) {
if (this.rangeMode && this.beginSelected && this._cellOver) {
if (this.isBeforeSelected && !this.begin) {
return this._cellOver === date;
}
else {
return (this.begin === date && !(this._cellOver < this.begin)) ||
(this._cellOver === date && this._cellOver < this.begin);
}
}
return this.begin === date;
}
/** Whenever to mark cell as end of the range. */
_isEnd(date) {
if (this.rangeMode && this.beginSelected && this._cellOver) {
if (this.isBeforeSelected && !this.begin) {
return false;
}
else {
return (this.end === date && !(this._cellOver > this.begin)) ||
(this._cellOver === date && this._cellOver > this.begin);
}
}
return this.end === date;
}
/** Focuses the active cell after the microtask queue is empty. */
_focusActiveCell() {
this._ngZone.runOutsideAngular(() => {
this._ngZone.onStable.asObservable().pipe(take(1)).subscribe(() => {
const activeCell = this._elementRef.nativeElement.querySelector('.mat-calendar-body-active');
if (activeCell) {
activeCell.focus();
}
});
});
}
/** Whenever to highlight the target cell when selecting the second date in range mode */
_previewCellOver(date) {
return this._cellOver === date && this.rangeMode && this.beginSelected;
}
} |
JavaScript | class KeyboardHandler {
constructor () {
this.listeners = {};
}
/**
* registers new listener for given keycode
* @param keyCode {String} https://developer.mozilla.org/de/docs/Web/API/KeyboardEvent/keyCode
* @param fn {Function}
*/
register (options) {
const {
keyCode,
fn
} = options;
this.listeners[keyCode] = fn;
}
/**
* executes registered function with given arguments
* @param keyCode {String}
* @param args {Object}
*/
execute (options) {
const {
keyCode,
args
} = options;
const callback = this.listeners[keyCode];
if (typeof callback === 'function') {
return callback(args);
}
}
} |
JavaScript | class Message {
constructor(parameters) {
this.parameters = parameters;
this.name = undefined;
}
/**
* Check if any updates are needed to the data on the native side. The reason
* for updates is that on the native side, 64-bit integers are representable,
* but large 64-bit integers lose precision in JavaScript. In order to get
* around this, the large integers may be passed as strings, and this function
* will notify the native side that it needs to convert them back.
*/
checkForUpdates(parameters)
{
const updates = [];
// Iterate over each of the class's update requirements, and see if any
// match the parameters.
for(const update of this.updateList()) {
if(check(update, parameters)) {
updates.push(update);
}
}
// Don't return anything to the native side if there are no updates.
if( updates.length) {
return updates;
} else {
return undefined;
}
}
/**
* Serializes Message to a a BBMDS message format and send it to the SDK.
*/
send() {
if (this.name === undefined) {
throw new Error('The Message name property has to be overridden');
}
// Encode the message.
const message = [ {[ this.name ]: this.parameters } ];
// See if the data needs any manipulation on the native side.
const updates = this.checkForUpdates(this.parameters);
if (updates) {
message.push(updates)
}
Cordova.exec(
() => {},
() => {},
'SparkProxy',
'invoke',
message);
}
} |
JavaScript | class EleventyManager {
/**
*
* @param {import('@11ty/eleventy/src/UserConfig')} eleventyConfig
* @returns {any}
*/
initialize (eleventyConfig) {
this._configureMarkdown(eleventyConfig)
// Disable automatic use of your .gitignore
eleventyConfig.setUseGitIgnore(false)
// Merge data instead of overriding
eleventyConfig.setDataDeepMerge(true)
// human readable date
eleventyConfig.addFilter('readableDate', (dateObj) => {
return DateTime.fromJSDate(dateObj, { zone: 'utc' }).toFormat(
'dd LLL yyyy'
)
})
// Syntax Highlighting for Code blocks
eleventyConfig.addPlugin(syntaxHighlight)
// To Support .yaml Extension in _data
// You may remove this if you can use JSON
eleventyConfig.addDataExtension('yaml', (contents) =>
yaml.safeLoad(contents)
)
// Copy Static Files to /_Site
eleventyConfig.addPassthroughCopy({
'./node_modules/alpinejs/dist/alpine.js': './static/js/alpine.js',
'./node_modules/prismjs/themes/prism-tomorrow.css': './static/css/prism-tomorrow.css',
'./src/admin/config.yml': './admin/config.yml'
})
// Copy Image Folder to /_site
eleventyConfig.addPassthroughCopy('./site/static/img')
// Copy favicon to route of /_site
eleventyConfig.addPassthroughCopy('./site/favicon.ico')
// Minify HTML
eleventyConfig.addTransform('htmlmin', function (content, outputPath) {
// Eleventy 1.0+: use this.inputPath and this.outputPath instead
if (outputPath.endsWith('.html')) {
const minified = htmlmin.minify(content, {
collapseWhitespace: true,
removeComments: true,
useShortDoctype: true
})
return minified
}
return content
})
// We do some pre-processing on our terms collection
eleventyConfig.addCollection('term', function (collectionApi) {
return collectionApi.getFilteredByGlob('**/terms/*.md').filter(t => {
// console.info('filtering: ' + t.inputPath + ' title: ' + JSON.stringify(t.data.title))
return t.data.title !== undefined
}).sort(function (a, b) {
return b.data.title.localeCompare(a.data.title)
})
})
// Allow sorting of collections alphabetically
eleventyConfig.addFilter('alphabetical', (items) => {
const sortedItems = items.sort((a, b) => {
return a.data.title.toLowerCase().localeCompare(b.data.title.toLowerCase())
})
return sortedItems
})
// Let Eleventy transform HTML files as nunjucks
// So that we can use .html instead of .njk
return {
dir: {
includes: '_includes',
input: 'site'
},
htmlTemplateEngine: 'njk'
}
};
/**
* @param {import('@11ty/eleventy/src/UserConfig')} eleventyConfig
* @returns {void}
*/
_configureMarkdown (eleventyConfig) {
console.info('Configure markdown')
const glossaryManager = new GlossaryManager('./site/terms')
glossaryManager.initialize()
const options = {
html: true
}
const markdown = require('markdown-it')(options)
// We override the default renderer for the text rules - so we save it off for default handling
const defaultRender = markdown.renderer.rules.text
// We examine all text blocks in markdown for terms to hyperlink
// We are overriding this default rule from markdown-it:
// https://github.com/markdown-it/markdown-it/blob/master/lib/renderer.js#L116
markdown.renderer.rules.text = (tokens, idx, options, env, renderer) => {
// console.info('Tokens: ' + JSON.stringify(tokens))
for (const token of tokens) {
if (tokens.length === 1) {
const newContent = this._linkContent(glossaryManager, token.content)
if (newContent !== token.content) {
// console.info('Content changed: ' + newContent)
return newContent
}
}
}
return defaultRender(tokens, idx, options, env, renderer)
}
eleventyConfig.setLibrary('md', markdown)
}
/**
*
* @param {GlossaryManager} manager
* @param {string} content
* @returns {string}
*/
_linkContent (manager, content) {
const terms = manager.allTerms()
let hyperlinkedContent = ''
let unlinkedBuffer = ''
const words = content.split(' ')
for (let i = 0; i < words.length; i++) {
unlinkedBuffer += words[i]
if (i < words.length - 1) {
unlinkedBuffer += ' '
}
const linkedBuffer = this._replaceTerms(terms, unlinkedBuffer)
if (linkedBuffer !== unlinkedBuffer) {
hyperlinkedContent += linkedBuffer
unlinkedBuffer = ''
}
}
hyperlinkedContent += unlinkedBuffer
return hyperlinkedContent
}
/**
*@param {GlossaryTerm[]} terms
* @param {string} contentSection
* @returns {string}
*/
_replaceTerms (terms, contentSection) {
const originalContentSection = contentSection
for (const term of terms) {
const regexString = `(\\W|^)(${term.synonyms().join('|')})(\\W|$)`
// console.info('Checking term: ' + term.name + ' regex: ' + regexString)
const regex = new RegExp(regexString, 'gi')
const escapedContent = this._escapeHTML(term.html).replace(/\n/g, ' ')
// console.info('contentsection: ' + contentSection)
contentSection = contentSection.replace(regex, `$1<a href="javascript:tooltip('${term.name}')"
class="tooltip"
data-glossary="${escapedContent}">$2</a>$3`)
if (originalContentSection !== contentSection) {
return contentSection
}
}
return contentSection
}
/**
* Escape special characters in the given string of text.
*
* @param {string} s The string to escape for inserting into HTML
* @return {string}
*/
/**
* @param {string} s
* @returns {string}
*/
_escapeHTML (s) {
const matchHtmlRegExp = /["'&<>]/
const str = '' + s
const match = matchHtmlRegExp.exec(str)
if (!match) {
return str
}
let escape
let html = ''
let index = 0
let lastIndex = 0
for (index = match.index; index < str.length; index++) {
switch (str.charCodeAt(index)) {
case 34: // "
escape = '"'
break
case 38: // &
escape = '&'
break
case 39: // '
escape = '''
break
case 60: // <
escape = '<'
break
case 62: // >
escape = '>'
break
default:
continue
}
if (lastIndex !== index) {
html += str.substring(lastIndex, index)
}
lastIndex = index + 1
html += escape
}
return lastIndex !== index
? html + str.substring(lastIndex, index)
: html
}
} |
JavaScript | class Controller extends AreaImportCtrl {
/**
* Constructor.
* @param {!angular.Scope} $scope
* @param {!angular.JQLite} $element
* @param {!angular.$timeout} $timeout The Angular $timeout service.
* @ngInject
*/
constructor($scope, $element, $timeout) {
super($scope, $element, $timeout);
this.scope.$on(WizardStepEvent.VALIDATE, this.onFileChange_.bind(this));
// If this is the zip file, run the preview
if (this.config['zipFile']) {
this.config.updateZipPreview(ui.apply.bind(this, this.scope));
}
}
/**
* Update Title/Description
*
* @param {angular.Scope.Event} event The Angular event
* @param {boolean} valid
* @private
*/
onFileChange_(event, valid) {
this.config.updatePreview();
ui.apply(this.scope);
}
/**
* Validate the done button
*
* @return {boolean} if the form is valid
* @export
*/
invalid() {
var config = this.config;
if (config['zipFile']) {
return !config['columns'] || config['columns'].length == 0 || (!config['title'] && !config['titleColumn']);
} else {
return !config['file'] || !config['file2'] || (!config['title'] && !config['titleColumn']);
}
}
/**
* @inheritDoc
* @export
*/
finish() {
super.finish();
var parser = new SHPParser(this.config);
var importer = new Importer(parser);
importer.listenOnce(EventType.COMPLETE, this.onImportComplete_, false, this);
if (this.config['zipFile']) {
importer.startImport(this.config['zipFile'].getContent());
} else {
importer.startImport([this.config['file'].getContent(), this.config['file2'].getContent()]);
}
}
/**
* Success callback for importing data. Adds the areas to Area Manager
*
* @param {goog.events.Event} event
* @private
*/
onImportComplete_(event) {
var importer = /** @type {Importer} */ (event.target);
var features = /** @type {!Array<ol.Feature>} */ (importer.getData() || []);
importer.dispose();
this.processFeatures(features);
this.close();
}
} |
JavaScript | class AddJob extends ReactWidget {
constructor(script, script_path) {
super();
this.addClass('ReactWidget');
this.script=script;
this.script_path=script_path;
}
render() {
return <Component script={this.script} script_path={this.script_path}/>;
}
} |
JavaScript | class Asserter_Tensor_NumberArray {
/**
*
*
* @param {number} acceptableDifferenceRate
* How many difference (in ratio) between the tensor and numberArray (per element) is acceptable. Because floating-point
* accumulated error of float32 (GPU) and float64 (CPU) is different, a little difference should be allowed. Otherwise,
* the comparison may hardly to pass this check. Default is 0.4 (i.e. 40% difference is allowed).
*/
constructor( acceptableDifferenceRate = 0.4 ) {
this.acceptableDifferenceRate = acceptableDifferenceRate;
this.comparator = Asserter_Tensor_NumberArray.ElementComparator.bind( this );
}
/**
*
* @param {tf.tensor} tensor
* The tf.tensor to be checked.
*
* @param {number[]} numberArray
* The number to be compared against tensor's data.
*
* @param {string} prefixMsg
* The text to be displayed at the beginning when comparison failed.
*
* @param {string} tensorName
* The text to be displayed for the tensor when comparison failed.
*
* @param {string} numberArrayName
* The text to be displayed for the numberArray when comparison failed.
*
* @param {string} postfixMsg
* The text to be displayed at the tail when comparison failed.
*/
assert( tensor, numberArray, prefixMsg, tensorName, numberArrayName, postfixMsg ) {
let tensorDataArray = null;
if ( tensor ) {
tensorDataArray = tensor.dataSync();
}
// Check both null or non-null.
tf.util.assert( ( tensorDataArray == null ) == ( numberArray == null ),
`${prefixMsg} ${tensorName} ( ${tensorDataArray} ) and ${numberArrayName} ( ${numberArray} ) should be both null or non-null. ${postfixMsg}` );
if ( !tensorDataArray )
return; // Since null, no element need to be compared futher.
// Check both length.
tf.util.assert( tensorDataArray.length == numberArray.length,
`${prefixMsg} ${tensorName} length ( ${tensorDataArray.length} ) should be ( ${numberArray.length} ). ${postfixMsg}` );
this.numberArray = numberArray; // For ElementComparator() to access.
// Check both elements.
//
// Note: Array.every() seems faster than for-loop.
tf.util.assert( tensorDataArray.every( this.comparator ),
`${prefixMsg} ${tensorName}[ ${this.elementIndex} ] `
+ `( ${tensorDataArray[ this.elementIndex ]} ) should be ( ${numberArray[ this.elementIndex ]} ) `
+ `( ${tensorDataArray} ) should be ( ${numberArray} ). `
+ `${postfixMsg}` );
//!!! (2021/08/10 Remarked) Old Codes.
// `PointDepthPoint output${i}[ ${elementIndex} ] ( ${outputArray[ elementIndex ]} ) should be ( ${outputArrayRef[ elementIndex ]} ) `
// +`( ${outputArray} ) should be ( ${outputArrayRef} ). `
// + `${parametersDescription}` );
}
/**
* @param {Asserter_Tensor_NumberArray} this
* - The this.numberArray[] and this.acceptableDifferenceRate will be read by this method.
* - The this.elementIndex will be set by this method.
*/
static ElementComparator( value, index ) {
let valueRef = this.numberArray[ this.elementIndex = index ];
let delta = Math.abs( value - valueRef );
let valueAbs = Math.abs( value );
let valueRefAbs = Math.abs( valueRef );
// Ratio to the smaller one.
//
// When one of two compared values is zero, it will always be failed if compare to the larger value (got 100% delteRate).
let deltaRateBase = Math.min( valueAbs, valueRefAbs );
let deltaRate;
if ( deltaRateBase > 0 ) // Avoid divided by zero.
deltaRate = delta / deltaRateBase; // Using ratio so that the difference will not to large even if value is large.
else
deltaRate = delta;
if ( deltaRate <= this.acceptableDifferenceRate )
return true;
return false;
}
} |
JavaScript | class EnhancerError extends Error {
constructor(message) {
super(message);
this.name = 'EnhancerError';
}
} |
JavaScript | class LabelCustomization {
/**
* Constructs a new <code>LabelCustomization</code>.
* Custom text for shipping labels.
* @alias module:client/models/LabelCustomization
* @class
*/
constructor() {
}
/**
* Constructs a <code>LabelCustomization</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:client/models/LabelCustomization} obj Optional instance to populate.
* @return {module:client/models/LabelCustomization} The populated <code>LabelCustomization</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new LabelCustomization();
if (data.hasOwnProperty('CustomTextForLabel')) {
obj['CustomTextForLabel'] = CustomTextForLabel.constructFromObject(data['CustomTextForLabel']);
}
if (data.hasOwnProperty('StandardIdForLabel')) {
obj['StandardIdForLabel'] = StandardIdForLabel.constructFromObject(data['StandardIdForLabel']);
}
}
return obj;
}
/**
* @member {module:client/models/CustomTextForLabel} CustomTextForLabel
*/
'CustomTextForLabel' = undefined;
/**
* @member {module:client/models/StandardIdForLabel} StandardIdForLabel
*/
'StandardIdForLabel' = undefined;
} |
JavaScript | class IllustrationMessageType extends DataType {
static isValid(value) {
return !!IllustrationMessageTypes[value];
}
} |
JavaScript | class SearchBar extends Component {
constructor(props) {
super(props);
this.state = { term: '' };
this.onInputChange = this.onInputChange.bind(this);
//binds local this with global this
this.onFormSubmit = this.onFormSubmit.bind(this);
}// constructor to initialize local component state
onInputChange(event) {
console.log(event.target.value);
this.setState({ term: event.target.value });
}// onchange event, change state.term
onFormSubmit(event){
event.preventDefault(); //don't submit by default
this.props.fetchWeather(this.state.term);
this.setState({ term: '' });
}// on submit, calls action creator with state.term as an argument
render() {
return (
<form onSubmit={this.onFormSubmit} className="input-group">
<input
placeholder="Get a five-day forecast in your favorite cities"
className="form-control"
value={this.state.term}
onChange={this.onInputChange} />
<span className="input-group-btn">
<button type="submit" className="btn btn-secondary">Submit</button>
</span>
</form> //form has its advantages
);
}
} |
JavaScript | class TrapThemeStarfinder extends D20TrapTheme {
/**
* @inheritdoc
*/
get name() {
return 'Starfinder Generic';
}
/**
* @inheritdoc
*/
activateEffect(effect) {
let character = getObj('character', effect.victim.get('represents'));
let effectResults = effect.json;
// Automate trap attack/save mechanics.
Promise.resolve()
.then(() => {
effectResults.character = character;
if(character) {
if(effectResults.attack)
if(effectResults.attackVs === 'ACM')
return this._doTrapCombatManeuver(character, effectResults);
else if(effectResults.attackVs === 'EAC')
return this._doTrapEACAttack(character, effectResults);
else if(effectResults.attackVs === 'starship AC')
return this._doTrapStarshipACAttack(character, effectResults);
else if(effectResults.attackVs === 'starship TL')
return this._doTrapStarshipTLAttack(character, effectResults);
else
return this._doTrapKACAttack(character, effectResults);
else if(effectResults.save && effectResults.saveDC)
return this._doTrapSave(character, effectResults);
}
return effectResults;
})
.then(effectResults => {
let html = TrapThemeStarfinder.htmlTrapActivation(effectResults);
effect.announce(html.toString(TrapTheme.css));
})
.catch(err => {
sendChat('TrapTheme: ' + this.name, '/w gm ' + err.message);
log(err.stack);
});
}
/**
* Does a trap's Combat Maneuver roll.
* @private
*/
_doTrapCombatManeuver(character, effectResults) {
return Promise.all([
this.getACM(character),
TrapTheme.rollAsync('1d20 + ' + effectResults.attack)
])
.then(tuple => {
let ac = tuple[0] || 10;
let roll = tuple[1];
effectResults.ac = ac;
effectResults.roll = roll;
effectResults.trapHit = roll.total >= ac;
return effectResults;
});
}
/**
* Does a trap's attack vs Energy AC.
* @private
*/
_doTrapEACAttack(character, effectResults) {
return Promise.all([
this.getEAC(character),
TrapTheme.rollAsync('1d20 + ' + effectResults.attack)
])
.then(tuple => {
let ac = tuple[0] || 10;
let roll = tuple[1];
effectResults.ac = ac;
effectResults.roll = roll;
effectResults.trapHit = roll.total >= ac;
return effectResults;
});
}
/**
* Does a trap's attack vs Kinetic AC.
* @private
*/
_doTrapKACAttack(character, effectResults) {
return Promise.all([
this.getKAC(character),
TrapTheme.rollAsync('1d20 + ' + effectResults.attack)
])
.then(tuple => {
let ac = tuple[0] || 10;
let roll = tuple[1];
effectResults.ac = ac;
effectResults.roll = roll;
effectResults.trapHit = roll.total >= ac;
return effectResults;
});
}
/**
* Does a trap's attack vs starship AC.
* @private
*/
_doTrapStarshipACAttack(character, effectResults) {
return Promise.all([
this.getStarshipAC(character),
TrapTheme.rollAsync('1d20 + ' + effectResults.attack)
])
.then(tuple => {
let ac = tuple[0] || 10;
let roll = tuple[1];
effectResults.ac = ac;
effectResults.roll = roll;
effectResults.trapHit = roll.total >= ac;
return effectResults;
});
}
/**
* Does a trap's attack vs starship TL.
* @private
*/
_doTrapStarshipTLAttack(character, effectResults) {
return Promise.all([
this.getStarshipTL(character),
TrapTheme.rollAsync('1d20 + ' + effectResults.attack)
])
.then(tuple => {
let ac = tuple[0] || 10;
let roll = tuple[1];
effectResults.ac = ac;
effectResults.roll = roll;
effectResults.trapHit = roll.total >= ac;
return effectResults;
});
}
/**
* Gets the Combat Maneuver Defense for a character.
* @param {Character} character
* @return {Promise<number>}
*/
getACM(character) {
let sheet = getOption('sheet');
let attrName = getOption('acm');
if(sheet && SHEET_ATTRS[sheet])
attrName = SHEET_ATTRS[sheet].acm
if(attrName)
return TrapTheme.getSheetAttr(character, attrName);
else
return Promise.reject(new Error('Please provide name of the attribute for ACM in the One-Click options.'));
}
/**
* @inheritdoc
*/
getEAC(character) {
let sheet = getOption('sheet');
let attrName = getOption('eac');
if(sheet && SHEET_ATTRS[sheet])
attrName = SHEET_ATTRS[sheet].eac;
if(attrName)
return TrapTheme.getSheetAttr(character, attrName);
else
return Promise.reject(new Error('Please provide name of the attribute for EAC in the One-Click options.'));
}
/**
* @inheritdoc
*/
getKAC(character) {
let sheet = getOption('sheet');
let attrName = getOption('kac');
if(sheet && SHEET_ATTRS[sheet])
attrName = SHEET_ATTRS[sheet].kac;
if(attrName)
return TrapTheme.getSheetAttr(character, attrName);
else
return Promise.reject(new Error('Please provide name of the attribute for KAC in the One-Click options.'));
}
/**
* @inheritdoc
*/
getStarshipAC(character) {
let sheet = getOption('sheet');
let attrName = getOption('starshipAC');
if(sheet && SHEET_ATTRS[sheet])
attrName = SHEET_ATTRS[sheet].starshipAC;
if(attrName)
return TrapTheme.getSheetAttr(character, attrName);
else
return Promise.reject(new Error('Please provide name of the attribute for starship AC in the One-Click options.'));
}
/**
* @inheritdoc
*/
getStarshipTL(character) {
let sheet = getOption('sheet');
let attrName = getOption('starshipTL');
if(sheet && SHEET_ATTRS[sheet])
attrName = SHEET_ATTRS[sheet].starshipTL;
if(attrName)
return TrapTheme.getSheetAttr(character, attrName);
else
return Promise.reject(new Error('Please provide name of the attribute for starship TL in the One-Click options.'));
}
/**
* @inheritdoc
*/
getPassivePerception(character) {
return this.getPerceptionModifier(character)
.then(value => {
return value + 10;
});
}
/**
* Gets the Perception modifier for a character.
* @param {Character} character
* @return {Promise<number>}
*/
getPerceptionModifier(character) {
let sheet = getOption('sheet');
let attrName = getOption('perceptionModifier');
if(sheet && SHEET_ATTRS[sheet])
attrName = SHEET_ATTRS[sheet].perceptionModifier;
if(attrName)
return TrapTheme.getSheetAttr(character, attrName);
else
return Promise.reject(new Error('Please provide name of the attribute ' +
'for the perception modifier in the One-Click options.'));
}
/**
* @inheritdoc
*/
getSaveBonus(character, saveName) {
let sheet = getOption('sheet');
let key = saveName + 'SaveModifier';
let attrName = getOption(key);
if(sheet && SHEET_ATTRS[sheet])
attrName = SHEET_ATTRS[sheet][key];
if(attrName)
return TrapTheme.getSheetAttr(character, attrName);
else
return Promise.reject('Please provide name of the attribute for ' +
saveName + ' save modifier in the One-Click options.');
}
/**
* @inheritdoc
*/
getThemeProperties(trapToken) {
let result = super.getThemeProperties(trapToken);
let trapEffect = (new TrapEffect(trapToken)).json;
let save = _.find(result, item => {
return item.id === 'save';
});
save.options = [ 'none', 'fort', 'ref', 'will' ];
result.splice(1, 0, {
id: 'attackVs',
name: 'Attack vs',
desc: 'If the trap makes an attack roll, what AC does it target?',
value: trapEffect.attackVs || 'KAC',
options: ['KAC', 'EAC', 'ACM', "starship AC", "starship TL"]
});
return result;
}
/**
* Produces the HTML for a trap activation message for most d20 systems.
* @param {object} effectResults
* @return {HtmlBuilder}
*/
static htmlTrapActivation(effectResults) {
let content = new HtmlBuilder('div');
// Add the flavor message.
content.append('.paddedRow trapMessage', effectResults.message);
if(effectResults.character) {
var row = content.append('.paddedRow');
row.append('span.bold', 'Target:');
row.append('span', effectResults.character.get('name'));
// Add the attack roll message.
if(effectResults.attack) {
let rollResult = D20TrapTheme.htmlRollResult(effectResults.roll, '1d20 + ' + effectResults.attack);
let row = content.append('.paddedRow')
if(effectResults.attackVs === 'ACM') {
row.append('span.bold', 'Maneuver roll:');
row.append('span', rollResult);
row.append('span', ' vs ACM ' + effectResults.ac);
}
else if(effectResults.attackVs === 'EAC') {
row.append('span.bold', 'Attack roll:');
row.append('span', rollResult);
row.append('span', ' vs EAC ' + effectResults.ac);
}
else if(effectResults.attackVs === 'starship AC') {
row.append('span.bold', 'Attack roll:');
row.append('span', rollResult);
row.append('span', ' vs starship AC ' + effectResults.ac);
}
else if(effectResults.attackVs === 'starship TL') {
row.append('span.bold', 'Attack roll:');
row.append('span', rollResult);
row.append('span', ' vs starship TL ' + effectResults.ac);
}
else {
row.append('span.bold', 'Attack roll:');
row.append('span', rollResult);
row.append('span', ' vs KAC ' + effectResults.ac);
}
}
// Add the saving throw message.
if(effectResults.save) {
let rollResult = D20TrapTheme.htmlRollResult(effectResults.roll, '1d20 + ' + effectResults.saveBonus);
let saveMsg = new HtmlBuilder('.paddedRow');
saveMsg.append('span.bold', effectResults.save.toUpperCase() + ' save:');
saveMsg.append('span', rollResult);
saveMsg.append('span', ' vs DC ' + effectResults.saveDC);
// If the save result is a secret, whisper it to the GM.
if(effectResults.hideSave)
sendChat('Admiral Ackbar', '/w gm ' + saveMsg.toString(TrapTheme.css));
else
content.append(saveMsg);
}
// Add the hit/miss message.
if(effectResults.trapHit) {
let row = content.append('.paddedRow');
row.append('span.hit', 'HIT! ');
if(effectResults.damage)
row.append('span', 'Damage: [[' + effectResults.damage + ']]');
else
row.append('span', 'You fall prey to the ' + (effectResults.type || 'trap') + '\'s effects!');
}
else {
let row = content.append('.paddedRow');
row.append('span.miss', 'MISS! ');
if(effectResults.damage && effectResults.missHalf)
row.append('span', 'Half damage: [[floor((' + effectResults.damage + ')/2)]].');
}
}
return TrapTheme.htmlTable(content, '#a22', effectResults);
}
/**
* @inheritdoc
*/
modifyTrapProperty(trapToken, argv) {
super.modifyTrapProperty(trapToken, argv);
let trapEffect = (new TrapEffect(trapToken)).json;
let prop = argv[0];
let params = argv.slice(1);
if(prop === 'attackVs')
trapEffect.attackVs = params[0];
trapToken.set('gmnotes', JSON.stringify(trapEffect));
}
/**
* @inheritdoc
*/
passiveSearch(trap, charToken) {
let passiveEnabled = getOption('enablePassivePerception') === '1';
if(passiveEnabled)
super.passiveSearch(trap, charToken);
}
} |
JavaScript | class NodoExp
{
constructor(tipo,valor)
{
this.tipo=tipo
this.valor=valor
}
getValor()
{
}
} |
JavaScript | class CustomCardSlide extends Component {
state = {
open: false,
};
showModal = () => {
this.setState({ open: true });
};
hideModal = () => this.setState({ open: false });
render() {
const { open } = this.state;
const { index } = this.props;
const numImagesAvailable = 130;
const collectionID = 3348877;
let imageWidth = 200 + Math.floor(Math.random() * 60) * 20;
//let imageHeight = imageWidth;
let randomNumber = Math.floor(Math.random() * numImagesAvailable) * 10;
return (
<Slide index={index}>
<div style={{ padding: 6 }}>
<Image
fluid
src={`https://source.unsplash.com/collection/${collectionID}/${imageWidth}x${imageWidth}/?sig=${randomNumber}`}
rounded
bordered
/>
</div>
</Slide>
);
}
} |
JavaScript | class AnClient {
/**@param {string} serv serv path root, e.g. 'http://localhost/jsample'
*/
constructor(urlRoot) {
this.cfg = {
connId: null,
verbose: 5,
defaultServ: urlRoot
}; // aes = new AES();
}
/**Get port url of the port.
* @param {string} port the port name
* @return the url
*/
servUrl(port) {
// This is a common error in jeasy frame
if (port === undefined || port === null) {
console.error("Port is null!");
return;
} // Protocol can't visited when debugging, but working:
// console.log(Protocol.Port);
// console.log("Protocol.Port[" + port + "] : " + Protocol.Port[port]);
var ulr;
if (_protocol_js__WEBPACK_IMPORTED_MODULE_2__["Protocol"].Port[port] !== undefined) ulr = this.cfg.defaultServ + '/' + _protocol_js__WEBPACK_IMPORTED_MODULE_2__["Protocol"].Port[port]; // + '?conn=' + this.cfg.connId;
else ulr = this.cfg.defaultServ + '/' + port; // + '?conn=' + this.cfg.connId;
if (this.cfg.connId) ulr += '?conn=' + this.cfg.connId;
return ulr;
}
/** initialize with url and default connection id
* @param {stirng} urlRoot root url
* @param {string} connId connection Id
* @retun {An} this */
init(urlRoot, connId) {
this.cfg.cconnId = connId;
this.cfg.defaultServ = urlRoot;
return this;
}
/** Understand the prots' name of the calling app's.<br>
* As jclient defined the basice ports, more ports extension shoould been understood by the API lib.
* This function must been callded to extned port's names.
* @param {string} new Ports
* @return {An} this */
understandPorts(newPorts) {
Object.assign(_protocol_js__WEBPACK_IMPORTED_MODULE_2__["Protocol"].Port, newPorts);
return this;
}
opts(options) {
_protocol_js__WEBPACK_IMPORTED_MODULE_2__["Protocol"].opts(options);
}
port(name) {
return _protocol_js__WEBPACK_IMPORTED_MODULE_2__["Protocol"].Port[name];
}
/**Login to jserv
* @param {string} usrId
* @param {string} pswd
* @param {function} onLogin on login ok handler
* @param {function} on failed
*/
login(usrId, pswd, onLogin, onError) {
// byte[] iv = AESHelper.getRandom();
// String iv64 = AESHelper.encode64(iv);
// String tk64 = AESHelper.encrypt(uid, pswdPlain, iv);
// console.log('An.login(' + usrId + ', ' + pswd + ', ...)');
let iv = aes.getIv128();
let cpwd = aes.encrypt(usrId, pswd, iv);
let req = _protocol_js__WEBPACK_IMPORTED_MODULE_2__["Protocol"].formatSessionLogin(usrId, cpwd, aes.bytesToB64(iv));
let An = this;
this.post(req,
/**@param {object} resp
* code: "ok"
* data: Object { uid: "admin", ssid: "3sjUJk2JszDm", "user-name": "admin" }
* port: "session"
*/
function (resp) {
// var sessionClient = new SessionClient(resp.data, iv, true);
var sessionClient = new SessionClient(resp.body[0].ssInf, iv, true);
sessionClient.An = An;
if (typeof onLogin === "function") onLogin(sessionClient);else console.log(sessionClient);
}, onError);
}
/**Check Response form jserv
* @param {any} resp
*/
static checkResponse(resp) {
if (typeof resp === "undefined" || resp === null || resp.length < 2) return "err_NA";else return false;
}
/**Post a request, using Ajax.
* @param {AnsonMsg} jreq
* @param {function} onOk
* @param {function} onErr
* @param {object} ajaxOpts */
post(jreq, onOk, onErr, ajaxOpts) {
if (jreq === undefined) {
console.error('jreq is null');
return;
}
if (jreq.port === undefined || jreq.port == '') {
// TODO docs...
console.error('Port is null - you probably created a requesting AnsonMsg with "new [User|Query|...]Req()".\n', 'Creating a new request message can mainly throught one of 2 way:\n', 'Way 1: Using a jclient helper, like those in jeasy-html.js/EasyModal.save().\n', 'Way 2: Using a ssClient request API, e.g. ssClient.delete().', 'TODO docs...');
return;
}
var url = this.servUrl(jreq.port);
var async = true;
if (ajaxOpts !== undefined && ajaxOpts !== null) {
async = ajaxOpts.async !== false;
}
var self = this;
jquery__WEBPACK_IMPORTED_MODULE_0___default.a.ajax({
type: 'POST',
// url: this.cfg.defaultServ + "/query.serv?page=" + pgIx + "&size=" + pgSize,
url: url,
contentType: "application/json; charset=utf-8",
crossDomain: true,
async: async,
//xhrFields: { withCredentials: true },
data: JSON.stringify(jreq),
success: function (resp) {
// response Content-Type = application/json;charset=UTF-8
if (typeof resp === 'string') {
// why?
resp = JSON.parse(resp);
} // code != ok
if (self.cfg.verbose >= 5) {
console.debug(_protocol_js__WEBPACK_IMPORTED_MODULE_2__["Protocol"].MsgCode);
}
if (resp.code !== _protocol_js__WEBPACK_IMPORTED_MODULE_2__["Protocol"].MsgCode.ok) {
if (typeof onErr === "function") onErr(resp.code, resp);else console.error(resp); // code == ok
} else {
if (typeof onOk === "function") onOk(resp);else console.log(resp);
}
},
error: function (resp) {
if (typeof onErr === "function") {
console.error("ajax error:", url);
onErr(_protocol_js__WEBPACK_IMPORTED_MODULE_2__["Protocol"].MsgCode.exIo, resp);
} else {
console.error("ajax error:", url);
console.error("req", jreq);
console.error("response", resp);
}
}
});
} // TODO moved to semantic resultset?
/** Get the cols from jserv's rows
* (response from port returning AnsonMsg<AnsonResp>)
* @param {AnsonMsg<AnsonResp>} resp
* @param {ix} the rs index
* @return {array} array of column names */
respCols(resp, ix) {
if (ix === null || ix === undefined) ix = 0; // colnames: {TEXT: [2, "text"], VALUE: [1, "value"]}
var colIx = resp !== null && resp !== undefined && resp.code === "ok" ? resp.body[0].rs[0].colnames : [];
var cols = new Array(colIx.length);
Object.keys(colIx).forEach(function (k, ix) {
// Design Memo: java Resultset index start from 1.
cols[colIx[k][0] - 1] = colIx[k][1];
});
return cols;
}
/** Get the rows from jserv's rows.
* (response from port returning AnsonMsg<AnsonResp>)
* @param {AnsonMsg<AnsonResp>} resp
* @param {ix} the rs index
* @return {array} array of rows */
respRows(resp, ix) {
if (ix === null || ix === undefined) ix = 0;
return resp !== null && resp !== undefined && resp.code === "ok" // ? resp.data.rs[ix].slice(1) : [];
? resp.body[0].rs[0].results : [];
}
/** Get the objects from jserv's rows (response from port returning SResultsets)
* @param {AnsonMsg<AnsonResp>} resp
* @param {int} start start to splice
* @param {int} len max length
* @return {array} array of objects<br>
* e.g [ [col1: cell1], ...] */
respObjs(resp, start, len) {
var cols = this.respCols(resp); // start from 0
if (typeof start !== 'number') start = 0;
if (typeof len !== 'number') // len = resp.data.rs[0].length - 1;
len = resp.body[0].rs[0].results.length;else len = Math.min(len, resp.body[0].rs[0].results.length);
if (resp.body[0].rs[0].results) {
return resp.body[0].rs[0].results.splice(start, len);
}
}
} |
JavaScript | class SessionClient {
static get ssInfo() {
return "ss-info";
}
/**Create SessionClient with credential information or load from localStorage.<br>
* Because of two senarios of login / home page integration, there are 2 typical useses:<br>
* Use Case 1 (persisted): logged in, then create a client with response,
* save in local storage, then load it in new page.<br>
* Use Case 1 (not persisted): logged in, then create a client with response,
* user's app handled the object, then provided to other functions,<br>
* typicall a home.vue component.<br>
* <p><b>Note</b></p>
* <p>Local storage may be sometimes confusing if not familiar with W3C standars.<br>
* The local storage can't be cross domain referenced. It's can not been loaded by home page
* if you linked from login page like this, as showed by this example in login.vue:</p>
* <p>window.top.location = response.home</p>
* <p>One recommended practice is initializing home.vue with login credential
* by login.vue, in app.vue.</p>
* <p>But this design makes home page and login component integrated. It's not
* friedly to application pattern like a port page with login which is independent
* to the system background home page.</p>
* <p>How should this pattern can be improved is open for discussion.
* If your are interested in this subject, leave any comments in wiki page please.</p>
* @param {object} ssInf login response form server: {ssid, uid}
* @param {byte[]} iv iv used for cipher when login.
* @param {boolean} dontPersist don't save into local storage.
*/
constructor(ssInf, iv, dontPersist) {
if (ssInf) {
// logged in, create from credential
this.ssInf = ssInf; // try tolerate easyUI trouble
if (typeof iv === 'string') {
// really not expected
;
} else {
this.ssInf.iv = aes.bytesToB64(iv);
}
if (!dontPersist) {
var infStr = JSON.stringify(this.ssInf);
localStorage.setItem(SessionClient.ssInfo, infStr);
}
} else {
// jumped, create from local storage
var sstr = localStorage.getItem(SessionClient.ssInfo);
if (sstr) {
this.ssInf = JSON.parse(sstr);
this.ssInf.iv = aes.b64ToBytes(this.ssInf.iv);
} else console.error("Can't find credential in local storage. SessionClient creating failed.");
}
this.an = an;
}
get userInfo() {
return this.ssInf;
}
consumeNotifies() {
if (this.ssInf) {
return this.ssInf['_notifies_'];
}
}
/**Get a header the jserv can verify successfully.
* This method is not recommended used directly.
* @param {Object} act user's action for logging<br>
* {func, cate, cmd, remarks};
* @return the logged in header */
getHeader(act) {
var header = _protocol_js__WEBPACK_IMPORTED_MODULE_2__["Protocol"].formatHeader(this.ssInf);
if (typeof act === 'object') {
header.userAct(act);
} else {
header.userAct({
func: 'ext',
cmd: 'unknow',
cate: 'ext',
remarks: 'raw header'
});
}
return header;
}
setPswd(oldPswd, newPswd, opts) {
var usrId = this.ssInf.uid;
var iv_tok = aes.getIv128();
var iv_new = aes.getIv128();
var iv_old = aes.getIv128(); // var tk = aes.encrypt(usrId, pswd, iv_tok);
var tk = this.ssInf.ssid;
var key = this.ssInf.ssid; // FIXME
var newPswd = aes.encrypt(newPswd, key, iv_new);
var oldPswd = aes.encrypt(oldPswd, key, iv_old);
var body = new _protocol_js__WEBPACK_IMPORTED_MODULE_2__["SessionReq"](usrId, tk, aes.bytesToB64(iv_tok)) // tk and iv_tok shouldn't bee used
.a('pswd').md('pswd', newPswd).md('iv_pswd', aes.bytesToB64(iv_new)).md('oldpswd', oldPswd).md('iv_old', aes.bytesToB64(iv_old));
var jmsg = new _protocol_js__WEBPACK_IMPORTED_MODULE_2__["AnsonMsg"](_protocol_js__WEBPACK_IMPORTED_MODULE_2__["Protocol"].Port.session, this.getHeader(), body);
if (opts === undefined) {
opts = {};
}
this.an.post(jmsg, opts.onok, opts.onerror);
return this;
}
/**Post the request message (AnsonMsg with body of subclass of AnsonBody).
* @param {AnsonMsg} jmsg request message
* @param {function} onOk
* @param {function} onError
*/
commit(jmsg, onOk, onError) {
this.an.post(jmsg, onOk, onError);
}
/**Post the request message (AnsonMsg with body of subclass of AnsonBody) synchronously.
* @param {AnsonMsg} jmsg request message
* @param {function} onOk
* @param {function} onError
*/
commitSync(jmsg, onOk, onError) {
this.an.post(jmsg, onOk, onError, {
async: false
});
}
/**
* create a query message.
* @param {string} conn connection id
* @param {string} maintbl target table
* @param {string} alias target table alias
* @param {Object} pageInf<br>
* page: page index, -1 for no paging<br>
* size: page size, default 20, -1 for no paging
* @param {Object} act user's action for logging<br>
* {func, cate, cmd, remarks};
* @return {AnsonMsg} the request message
*/
query(conn, maintbl, alias, pageInf, act) {
var qryItem = new _protocol_js__WEBPACK_IMPORTED_MODULE_2__["QueryReq"](conn, maintbl, alias, pageInf);
var header = _protocol_js__WEBPACK_IMPORTED_MODULE_2__["Protocol"].formatHeader(this.ssInf);
if (typeof act === 'object') {
this.usrAct(act.func, act.cate, act.cmd, act.remarks);
} else {
act = {
func: 'query',
cmd: 'select',
cate: 'r',
remarks: 'session query'
};
}
var header = this.getHeader(act);
var jreq = new _protocol_js__WEBPACK_IMPORTED_MODULE_2__["AnsonMsg"](_protocol_js__WEBPACK_IMPORTED_MODULE_2__["Protocol"].Port.query, header, qryItem);
return jreq;
}
update(conn, maintbl, pk, nvs) {
if (this.currentAct === undefined || this.currentAct.func === undefined) console.error("jclient is designed to support user updating log natively, User action with function Id shouldn't ignored.", "To setup user's action information, call ssClient.usrAct().");
if (pk === undefined) {
console.error("To update a table, {pk, v} must presented.", pk);
return;
}
var upd = new _protocol_js__WEBPACK_IMPORTED_MODULE_2__["UpdateReq"](conn, maintbl, pk);
upd.a = _protocol_js__WEBPACK_IMPORTED_MODULE_2__["Protocol"].CRUD.u;
this.currentAct.cmd = 'update';
var jmsg = this.userReq(conn, _protocol_js__WEBPACK_IMPORTED_MODULE_2__["Protocol"].Port.update, upd, this.currentAct);
if (nvs !== undefined) {
if (Array.isArray(nvs)) upd.nv(nvs);else console.error("updating nvs must be an array of name-value.", nvs);
}
return jmsg;
}
insert(conn, maintbl, nvs) {
if (this.currentAct === undefined || this.currentAct.func === undefined) console.error("jclient is designed to support user updating log natively, User action with function Id shouldn't ignored.", "To setup user's action information, call ssClient.usrAct().");
var ins = new _protocol_js__WEBPACK_IMPORTED_MODULE_2__["InsertReq"](conn, maintbl); // ins.a = Protocol.CRUD.c;
this.currentAct.cmd = 'insert';
var jmsg = this.userReq(conn, _protocol_js__WEBPACK_IMPORTED_MODULE_2__["Protocol"].Port.insert, ins, this.currentAct);
if (nvs !== undefined) {
if (Array.isArray(nvs)) ins.valus(nvs);else console.error("updating nvs must be an array of name-value.", nvs);
}
return jmsg;
}
delete(conn, maintbl, pk) {
if (this.currentAct === undefined || this.currentAct.func === undefined) console.error("jclient is designed to support user updating log natively, User action with function Id shouldn't ignored.", "To setup user's action information, call ssClient.usrAct().");
if (pk === undefined) {
console.error("To delete a table, {pk, v} must presented.", pk);
return;
}
if (maintbl === undefined || maintbl === null || maintbl === "") {
console.error("To delete a table, maintbl must presented.");
return;
}
var upd = new _protocol_js__WEBPACK_IMPORTED_MODULE_2__["UpdateReq"](conn, maintbl, pk);
upd.a = _protocol_js__WEBPACK_IMPORTED_MODULE_2__["Protocol"].CRUD.d;
this.currentAct.cmd = 'delete';
var jmsg = this.userReq(conn, // port = update, it's where the servlet handling this.
_protocol_js__WEBPACK_IMPORTED_MODULE_2__["Protocol"].Port.update, upd, this.currentAct);
return jmsg;
}
/**Create a user request AnsonMsg.
* @param {string} conn connection id
* @param {string} port
* @param {Protocol.UserReq} bodyItem request body, created by like: new jvue.UserReq(conn, tabl).
* @param {Object} act action, optional.
* @return {AnsonMsg<AnUserReq>} AnsonMsg */
userReq(conn, port, bodyItem, act) {
var header = _protocol_js__WEBPACK_IMPORTED_MODULE_2__["Protocol"].formatHeader(this.ssInf);
if (typeof act === 'object') {
header.userAct = act;
this.usrAct(act.func, act.cate, act.cmd, act.remarks);
}
return new _protocol_js__WEBPACK_IMPORTED_MODULE_2__["AnsonMsg"](port, header, bodyItem);
}
/**Set user's current action to be logged.
* @param {string} funcId curent function id
* @param {string} cate category flag
* @param {string} cmd
* @param {string} remarks
* @return {SessionClient} this */
usrAct(funcId, cate, cmd, remarks) {
if (this.currentAct === undefined) this.currentAct = {};
Object.assign(this.currentAct, {
func: funcId,
cate: cate,
cmd: cmd,
remarks: remarks
});
return this;
}
/**Set user's current action to be logged.
* @param {string} cmd user's command, e.g. 'save'
* @return {SessionClient} this */
usrCmd(cmd) {
if (this.currentAct === undefined) this.currentAct = {};
this.currentAct.cmd = cmd;
return this;
}
commit(jmsg, onOk, onErr) {
an.post(jmsg, onOk, onErr);
}
} |
JavaScript | class Inseclient {
commit(jmsg, onOk, onErr) {
an.post(jmsg, onOk, onErr);
}
} |
JavaScript | class CheapClient {
constructor(ssclient, cheaport) {
this.connId = null;
if (typeof cheaport === 'string') this.cheaport = cheaport;else this.cheaport = _cheap_req_js__WEBPACK_IMPORTED_MODULE_0__["CheapReq"].port;
this.jclient = ssclient;
this.cheapReq = _cheap_req_js__WEBPACK_IMPORTED_MODULE_0__["chpEnumReq"];
this.conn = function (conn) {
this.connId = conn;
};
}
/**Load a task's workflow nodes joined with instances.
* @param {string} wfId
* @param {object} opts<br>
* opts.taskId: task id<br>
*/
loadFlow(wfId, opts) {
// this.cmdArgs = [wfId, taskId];
var cheapReq = new _cheap_req_js__WEBPACK_IMPORTED_MODULE_0__["CheapReq"](wfId).a(this.cheapReq.load).taskId(opts.taskId);
var jmsg = this.jclient.userReq(this.connId, engports.cheapflow, cheapReq);
this.jclient.commit(jmsg, opts.onok, function (c, d) {
if (typeof opts.onerror === 'function') opts.onerror(c, d);else EasyMsger.error(c, d);
});
return this;
}
/**Load commands
* @param {string} wfId
* @param {object} opts<br>
* opts.taskId: task id<br>
* opts.nodeId: node Id<br>
* opts.usrId: user Id<br>
*/
loadCmds(wfId, opts) {
if (typeof wfId !== 'string' || typeof opts.nodeId !== 'string') {
console.error('Parameters invalid: wfId, opts.nodeId', wfId, opts);
return;
}
var cheapReq = new _cheap_req_js__WEBPACK_IMPORTED_MODULE_0__["CheapReq"](wfId).a(this.cheapReq.nodeCmds).nodeId(opts.nodeId).usrId(opts.usrId).taskId(opts.taskId); // optional - not used
var jmsg = this.jclient.userReq(this.connId, engports.cheapflow, cheapReq);
this.jclient.commit(jmsg, opts.onok, function (c, d) {
if (typeof opts.onerror === 'function') opts.onerror(c, d);else EasyMsger.error(c, d);
});
return this;
}
/**Post a workflow starting request.
* @param {CheapReq} cheapReq the request body
* @param {object} opts options<br>
* opts.taskId {string}: (Optional) task id (bussiness form record id)<br>
* opts.onok {function}: on ok callback<br>
* @return {CheapClient} this
*/
start(cheapReq, opts) {
cheapReq.a(this.cheapReq.start) // this.cheapReq is the req enum
.taskId(opts.taskId);
var jmsg = this.jclient.userReq(this.connId, engports.cheapflow, cheapReq);
this.jclient.commit(jmsg, opts.onok, function (c, d) {
if (typeof opts.onerror === 'function') opts.onerror(c, d);else if (c === _cheap_req_js__WEBPACK_IMPORTED_MODULE_0__["CheapCode"].err_rights) EasyMsger.alert(EasyMsger.m.cheap_no_rights);else EasyMsger.error(c, d);
});
return this;
}
step(cheapBody, opts) {
cheapBody.a(this.cheapReq.cmd);
var jmsg = this.jclient.userReq(this.connId, engports.cheapflow, cheapBody);
this.jclient.commit(jmsg, opts.onok, opts.onerror);
}
rights(wfid, taskId, currentNodeId, usrId, opts) {
var req = new _cheap_req_js__WEBPACK_IMPORTED_MODULE_0__["CheapReq"](this.jclient, this.cheaport).a(this.cheapReq.load).arg('wfId', wfid).arg('taskId', taskId).arg('currentNode', currentNodeId).arg('usrId', usrId);
this.jclient.commit(req, opts.onok);
}
} |
JavaScript | class Protocol {
/**Globally set this client's options.
* @param {object} options<br>
* options.noNull no null value <br>
* options.noBoolean no boolean value<br>
*/
static opts(options) {
if (options) {
if (options.noNull !== undefined) Protocol.valOptions.noNull = options.noNull === true || options.noNull === 'true';
if (options.noBoolean !== undefined) Protocol.valOptions.noBoolean = options.noBoolean === true || options.noBoolean === 'true';
Protocol.valOptions = Object.assign(Protocol.valOptions, options);
}
}
/**Format login request message.
* @param {string} uid
* @param {string} tk64 password cypher
* @param {string} iv64
* @return login request message
*/
static formatSessionLogin(uid, tk64, iv64) {
var body = new SessionReq(uid, tk64, iv64);
body.a = 'login';
return new AnsonMsg(Protocol.Port.session, null, body);
}
static formatHeader(ssInf) {
return new AnHeader(ssInf.ssid, ssInf.uid);
}
static rs2arr(rs) {
return AnsonResp.rs2arr(rs);
}
static nv2cell(nv) {
return [nv.name, nv.value];
}
static nvs2row(nvs) {
var row = [];
if (nvs) {
for (var ix = 0; ix < nvs.length; ix++) row.push(this.nv2cell(nvs[ix]));
}
return row;
}
/** convert [{name, value}, ...] to [n1, n2, ...]
* @param {Array} [n-v, ...]
* @return {Array} [n1, n2, ...]
*/
static nvs2cols(nvArr) {
var cols = [];
if (nvArr) {
for (var ix = 0; ix < nvArr.length; ix++) {
if (nvArr[ix].name) {
cols.push(nvArr[ix].name);
} else cols.push(ix);
}
}
return cols;
}
/** convert [[{name, value}]] to [[[name, value]]]
* @param {Array} 2d array of n-v pairs
* @return {Array} 3d array that can be used by server as nv rows
*/
static nvs2rows(nvs) {
var rows = [];
if (nvs) {
for (var ix = 0; ix < nvs.length; ix++) // Ix.nvn = 0; Ix.nvv = 1
// rows.push([nvs[ix].name, nvs[ix].value]);
rows.push(this.nvs2row(nvs[ix]));
}
return rows;
}
} |
JavaScript | class Survey extends Component {
constructor(props) {
super();
this.state = {
submitProgress: 0,
selected: prepareSubmission(props.datas),
numSelected: 0,
pageID: 0,
stepID: 0,
onReasoning: false,
msg: '',
workerid: ''
};
}
buttonAction() {
if (this.state.pageID >= 2) {
this.setState(prevState =>
Object.assign(prevState, {
numSelected: 0,
submitProgress: 1,
pageID: 3
})
);
const success = msg =>
this.setState(prevState =>
Object.assign(prevState, { submitProgress: 2, msg })
);
const fail = msg =>
this.setState(prevState =>
Object.assign(prevState, { submitProgress: 3, msg })
);
submitResponse(
{ data: this.state.selected, workerid: this.state.workerid },
success,
fail
);
//submit selected
} else if (!this.state.onReasoning) {
this.setState(prevState =>
Object.assign(prevState, {
numSelected: 0,
onReasoning: true,
stepID: prevState.stepID + 1
})
);
} else {
this.setState(prevState =>
Object.assign(prevState, {
numSelected: 0,
pageID: prevState.pageID + 1,
stepID: prevState.stepID + 1
})
);
}
window.scrollTo(0, 0);
}
reasoningAction = data => (type, choice) => {
// console.log(data, this.state.selected);
const pageID = this.state.pageID;
this.setState(prevState => {
if (
has(prevState, ['selected', pageID, data, 'topic']) +
has(prevState, ['selected', pageID, data, 'text']) +
has(prevState, ['selected', pageID, data, 'title']) ===
2 &&
!has(prevState, ['selected', pageID, data, type])
) {
set(prevState, 'numSelected', prevState.numSelected + 1);
}
set(prevState, ['selected', pageID, data, type], choice);
return prevState;
});
};
selectAction = data => choice => {
// console.log(data, this.state.selected);
const pageID = this.state.pageID;
const result = get(this.state, ['selected', pageID, data, 'choice']);
this.setState(prevState => {
if (result == null) {
set(prevState, 'numSelected', prevState.numSelected + 1);
}
set(prevState, ['selected', pageID, data, 'choice'], choice);
return prevState;
});
};
handleChange = event => {
this.setState({ workerid: event.target.value });
};
render() {
const { classes } = this.props;
const { pageID, stepID } = this.state;
const selectable = this.props.datas[pageID]
? this.state.numSelected < this.props.datas[pageID].length
: false;
const inSubmissionPage = pageID >= 2;
const submissionSent = this.state.submitProgress === 1;
const submissionSucceed = this.state.submitProgress === 2;
const failed = this.state.submitProgress === 3;
const renderSubmissionState = submitProgress => {
switch (submitProgress) {
case 1:
return (
<Fade
in={!submissionSucceed}
style={{ transitionDelay: submissionSucceed ? '0ms' : '800ms' }}
unmountOnExit
>
<CircularProgress />
</Fade>
);
case 2:
return (
<h1 className="App-title">
{'Success! MTurk Code: ' + this.state.msg}
<br />
{'Thanks for helping us on this survey!'}
</h1>
);
case 3:
return (
<h1 className="App-title">
{
'You did not follow the instruction and your response is not valid. We are sorry that we cannot pay you:('
}
</h1>
);
default:
return null;
}
};
const conditionalRendering = pageID => {
switch (pageID) {
case 0:
return (
<div>
{this.props.datas[0].map(data => (
<ImgChoiceType
onReasoning={this.state.onReasoning}
data={data.img}
key={`${pageID}.${data.id}`}
onClick={this.selectAction(data.id)}
reasoning={this.reasoningAction(data.id)}
/>
))}
</div>
);
case 1:
return (
<div>
{this.props.datas[1].map(data => (
<TextChoiceType
data={data.content}
key={`${pageID}.${data.id}`}
onClick={this.selectAction(data.id)}
/>
))}
</div>
);
case 2:
return (
<div>
<FormControl
className={classes.formControl}
aria-describedby="name-helper-text"
>
<InputLabel htmlFor="name-helper">MTURK Work ID</InputLabel>
<Input
id="name-helper"
value={this.state.workerid}
onChange={this.handleChange}
/>
<FormHelperText
id="name-helper-text"
style={{ cursor: 'pointer' }}
onClick={() => {
window.open('https://worker.mturk.com', '_blank');
}}
>
Click here for the shortcut to your Amazon MTurk Dashboard
</FormHelperText>
</FormControl>
</div>
);
case 3:
return (
<div className={classes.placeholder}>
{renderSubmissionState(this.state.submitProgress)}
</div>
);
default:
return null;
}
};
return (
<div>
<Instruction stepID={stepID}/>
{conditionalRendering(pageID)}
<Button
size="large"
disabled={selectable || submissionSucceed || submissionSent || failed}
variant="raised"
color="primary"
onClick={this.buttonAction.bind(this)}
className={classes.button}
>
{inSubmissionPage ? 'Submit' : 'Next'}
</Button>
</div>
);
}
} |
JavaScript | class GetRespository {
/**
* @description Find all scenarios for a specific request.
* @param {object} request Request.
* @return {object} Returns a scenario for the method GET
*/
findData(request) {
const path = request.url;
const method = request.method;
const db = Data.db();
const data = db[method === 'HEAD' ? '_head' : '_get'];
const scenarioProvider = new ScenarioProvider(path, data, request.headers, request.cookies, id());
const endpoint = scenarioProvider.isInDB();
return endpoint ? scenarioProvider.getScenario(endpoint) : negaBodies.notFound;
}
} |
JavaScript | class VirtualFiles {
constructor () {
this.descriptors = new ArrayIndex()
}
get (fd) {
return this.descriptors.get((fd - STDIO_CAP - 1) / 2)
}
open (contents) {
const idx = this.descriptors.insert(new VirtualFile(contents))
return 2 * idx + 1 + STDIO_CAP
}
close (path, fd, cb) {
this.descriptors.delete((fd - STDIO_CAP - 1) / 2)
return process.nextTick(cb, 0)
}
read (path, fd, buffer, len, offset, cb) {
const virtualFile = this.get(fd)
if (!virtualFile) return cb(dwebfuse.EBADF)
return virtualFile.read(buffer, len, offset, cb)
}
} |
JavaScript | class ImageProductController {
/**
* Show a list of all imageproducts.
* GET imageproducts
*
* @param {object} ctx
* @param {Request} ctx.request
* @param {Response} ctx.response
* @param {View} ctx.view
*/
async index ({ request, response, view }) {
}
/**
* Create/save a new imageproduct.
* POST imageproducts
*
* @param {object} ctx
* @param {Request} ctx.request
* @param {Response} ctx.response
*/
async store ({ request, response }) {
try {
const {product_id} = request.all()
const product = await Product.findBy('id', product_id)
const photos = request.file('file',{
size: '3mb'
})
if(photos){
await photos.moveAll(Helpers.tmpPath('photos'), (file) =>{
return{
name: `${product.name.toLowerCase().slice(0,10).replace(" ","_")}_${product.id}_${Date.now()}_${file.clientName.slice(-12)}`.toLowerCase().replace(" ","_")
}
})
if(!photos.movedAll()){
return photos.errors()
}
await Promise.all(
photos.movedList().map(item=> Image.create({product_id:product.id, path:item.fileName}))
)
}
return response.send({message:'Image Saved!'})
} catch (error) {
return response.status(400).send(error.message)
}
}
/**
* Display a single imageproduct.
* GET imageproducts/:id
*
* @param {object} ctx
* @param {Request} ctx.request
* @param {Response} ctx.response
* @param {View} ctx.view
*/
async show ({ params, request, response, view }) {
try {
const image = await Image.find(params.id)
if(!image){
return response.status(404).send({message:'Image not found!'})
}
return response.download(`tmp/photos/${image.path}`)
} catch (error) {
return response.status(400).send({message:error.message})
}
}
/**
* Update imageproduct details.
* PUT or PATCH imageproducts/:id
*
* @param {object} ctx
* @param {Request} ctx.request
* @param {Response} ctx.response
*/
async update ({ params, request, response }) {
}
/**
* Delete a imageproduct with id.
* DELETE imageproducts/:id
*
* @param {object} ctx
* @param {Request} ctx.request
* @param {Response} ctx.response
*/
async destroy ({ params, request, response }) {
try {
const image = await Image.find(params.id)
if(!image){
return response.status(404).send({message:'Image not found!'})
}
let imagePath = Helpers.tmpPath(`photos/${image.path}`)
if(!imagePath){
return response.status(404).send({message:'Image not found!'})
}
await fs.unlink(imagePath, err=>{
if(!err){
image.delete()
}
})
return response.status(204).send()
} catch (error) {
console.log(error)
return response.status(400).send({message:error.message})
}
}
} |
JavaScript | class Track {
constructor (instance, conf, defaultConf, data, dataParser) {
this.dispatch = dispatch('mouseover', 'mouseout')
this.parseData = dataParser
this.loadData(data, instance)
this.conf = getConf(conf, defaultConf, this.meta, instance)
this.conf.colorValue = buildColorValue(
this.conf.color,
this.conf.cmin,
this.conf.cmax,
this.conf.logScale,
this.conf.logScaleBase
)
this.scale = buildScale(
this.conf.cmin,
this.conf.cmax,
this.conf.outerRadius - this.conf.innerRadius,
this.conf.logScale,
this.conf.logScaleBase
)
}
loadData (data, instance) {
const result = this.parseData(data, instance._layout.summary())
this.data = result.data
this.meta = result.meta
}
render (instance, parentElement, name) {
parentElement.select('.' + name).remove()
const track = parentElement.append('g')
.attr('class', name)
.attr('data-name', name)
.attr('z-index', this.conf.zIndex)
const datumContainer = this.renderBlock(track, this.data, instance._layout, this.conf)
if (this.conf.axes && this.conf.axes.length > 0) {
renderAxes(datumContainer, this.conf, instance, this.scale)
}
const selection = this.renderDatum(datumContainer, this.conf, instance._layout)
if (this.conf.tooltipContent) {
registerTooltip(this, instance, selection, this.conf)
}
registerHighlight(this, instance, selection, this.conf)
selection.on('mouseover', (d, i) => {
this.dispatch.call('mouseover', this, d)
if (this.conf.tooltipContent) {
instance.clipboard.attr('value', this.conf.tooltipContent(d))
}
})
selection.on('mouseout', (d, i) => {
this.dispatch.call('mouseout', this, d)
})
Object.keys(this.conf.events).forEach((eventName) => {
const conf = this.conf
selection.on(eventName, function (d, i, nodes) { conf.events[eventName](d, i, nodes, event) })
})
return this
}
renderBlock (parentElement, data, layout, conf) {
const block = parentElement.selectAll('.block')
.data(data)
.enter().append('g')
.attr('class', 'block')
.attr(
'transform',
(d) => `rotate(${layout.blocks[d.key].start * 360 / (2 * Math.PI)})`
)
if (conf.backgrounds) {
block.selectAll('.background')
.data((d) => {
return conf.backgrounds.map((background) => {
return {
start: background.start || conf.cmin,
end: background.end || conf.cmax,
angle: layout.blocks[d.key].end - layout.blocks[d.key].start,
color: background.color,
opacity: background.opacity
}
})
})
.enter().append('path')
.attr('class', 'background')
.attr('fill', (background) => background.color)
.attr('opacity', (background) => background.opacity || 1)
.attr('d', arc()
.innerRadius((background) => {
return conf.direction === 'in'
? conf.outerRadius - this.scale(background.start)
: conf.innerRadius + this.scale(background.start)
})
.outerRadius((background) => {
return conf.direction === 'in'
? conf.outerRadius - this.scale(background.end)
: conf.innerRadius + this.scale(background.end)
})
.startAngle(0)
.endAngle((d) => d.angle)
)
}
return block
}
theta (position, block) {
return position / block.len * (block.end - block.start)
}
x (d, layout, conf) {
const height = this.scale(d.value)
const r = conf.direction === 'in'
? conf.outerRadius - height : conf.innerRadius + height
const angle = this.theta(d.position, layout.blocks[d.block_id]) - Math.PI / 2
return r * Math.cos(angle)
}
y (d, layout, conf) {
const height = this.scale(d.value)
const r = conf.direction === 'in'
? conf.outerRadius - height : conf.innerRadius + height
const angle = this.theta(d.position, layout.blocks[d.block_id]) - Math.PI / 2
return r * Math.sin(angle)
}
} |
JavaScript | class RuleItem {
constructor(key) {
if (!key) throw new Error("No key for item provided.");
this.key = key;
this.weight = 1;
this.hardeness = 0;
this.isArmor = false;
this.isWeapon = false;
this.isShield = false;
this.isRanged = false;
this.health = 1;
}
toJson() {
return {
key: this.key,
health: this.health,
};
}
static fromJson(json) {
const item = new RuleItem(json.key);
item.health = json.health;
return item;
}
} |
JavaScript | class User{
/**
* creates a new user with name and id
* @constructor
* @param {String} name the name of the User
* @param {String} id the id of the User
* @param {Connection} connection the user's session
*/
constructor(name, id, connection){
this.name = name;
this.id = id;
this.connection = connection;
this.ready = false;
}
/**
* Sends messages to session
* @param {String} string the string to be sent
*/
send(string){
this.connection.send(string);
}
} |
JavaScript | class MDCIconToggleController extends BaseComponent {
static get require() {
return {
ngModelCtrl: '?ngModel',
};
}
static get bindings() {
return bindings;
}
static get name() {
return 'mdcIconToggle';
}
static get $inject() {
return ['$element'];
}
constructor(...args) {
super(...args);
this.$element.addClass(BASE_CLASSNAME);
this.$element.attr('tabindex', 0);
this.$element.ready(() => {
this.ripple_ = this.initRipple_();
});
}
get iconEl_() {
const sel = this.iconInnerSelector;
return sel ? angular.element(this.$element[0].querySelector(sel)) : this.$element;
}
initRipple_() {
this.root_ = this.$element[0];
const adapter = Object.assign(MDCRipple.createAdapter(this), {
isUnbounded: () => true,
isSurfaceActive: () => this.foundation_.isKeyboardActivated(),
});
const foundation = new MDCRippleFoundation(adapter);
return new MDCRipple(this.$element[0], foundation);
}
getDefaultFoundation() {
return new MDCIconToggleFoundation({
addClass: (className) => this.iconEl_.addClass(className),
removeClass: (className) => this.iconEl_.removeClass(className),
registerInteractionHandler: (type, handler) => this.$element.on(type, handler),
deregisterInteractionHandler: (type, handler) => this.$element.off(type, handler),
setText: (text) => this.iconEl_.text(text),
getTabIndex: () => /* number */ this.$element.attr('tabindex'),
setTabIndex: (tabIndex) => this.$element.attr('tabindex', tabIndex),
getAttr: (name, value) => this[directiveNormalize(name)],
setAttr: (name, value) => {
this[directiveNormalize(name)] = value;
this.$element.attr(name, value);
},
rmAttr: (name) => {
this[directiveNormalize(name)] = undefined;
this.$element.removeAttr(name);
},
notifyChange: (evtData) => {
this.$element.triggerHandler(CHANGE_EVENT, evtData);
if (this.ngModelCtrl) {
this.ngModelCtrl.$setViewValue(this.foundation_.isOn(), CHANGE_EVENT);
}
},
});
}
$postLink() {
this.foundation_ = this.getDefaultFoundation();
this.foundation_.init();
if (!this.foundation_.toggleOnData_.cssClass && !this.foundation_.toggleOffData_.cssClass) {
// if no cssClass specified, assume material-icons
this.$element.addClass('material-icons');
}
// this.ripple_ = this.initRipple_(); // this should work, but it's disabled until mdc-ripple is wrapped
this.foundation_.toggle(this.ngModel === undefined ? this.ariaPressed === 'true' : this.ngModel);
this.foundation_.setDisabled(this.ngDisabled);
}
get on() {
return this.foundation_.isOn();
}
get disabled() {
return this.foundation_.isDisabled();
}
$onChanges(changesObj) {
if (this.foundation_) {
if (changesObj.ngDisabled) {
this.foundation_.setDisabled(this.ngDisabled);
}
if (changesObj.ngModel) {
this.foundation_.toggle(this.ngModel);
}
let notRefreshed = true;
for (const key in changesObj) {
// check all the bound string attributes for changes, but only refresh if a single change is found
if (notRefreshed && changesObj.hasOwnProperty(key) && STRING_BINDINGS.indexOf(key) >= 0) {
this.foundation_.refreshToggleData();
this.foundation_.toggle(!!this.ngModel);
notRefreshed = false;
}
}
}
}
$onDestroy() {
if (this.ripple_) {
this.ripple_.destroy();
}
if (this.foundation_) {
this.foundation_.destroy();
}
}
} |
JavaScript | class FunctionCode {
/**
* Inline code for function.
*
* @param code The actual function code.
* @returns code object with inline code.
* @stability stable
*/
static fromInline(code) {
return new InlineCode(code);
}
/**
* Code from external file for function.
*
* @param options the options for the external file.
* @returns code object with contents from file.
* @stability stable
*/
static fromFile(options) {
return new FileCode(options);
}
} |
JavaScript | class InlineCode extends FunctionCode {
constructor(code) {
super();
this.code = code;
}
render() {
return this.code;
}
} |
JavaScript | class FileCode extends FunctionCode {
constructor(options) {
super();
this.options = options;
}
render() {
return fs.readFileSync(this.options.filePath, { encoding: 'utf-8' });
}
} |
JavaScript | class MemeGenerator extends Component {
constructor() {
super();
this.state = {
topText: "",
bottomText: "",
randomImg: "",
allMemeImgs: []
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
//single api call saved to prop -->allMemeImgs
componentDidMount() {
fetch("https://api.imgflip.com/get_memes")
.then(response => response.json())
.then(response => {
const { memes } = response.data;
// console.log(memes);
this.setState({
allMemeImgs: memes
});
});
}
handleChange(event) {
const { value, name } = event.target;
this.setState({
[name]: value
});
}
//preventDefault so it doesnt refresh our page
handleSubmit(event) {
event.preventDefault();
const randNum = Math.floor(Math.random() * this.state.allMemeImgs.length);
const randMemeImg = this.state.allMemeImgs[randNum].url;
//set 'randomImg' to the '.url' of the random item
this.setState({
randomImg: randMemeImg
});
}
render() {
// console.log(this.state.randomImg);
return (
<div>
<form onSubmit={this.handleSubmit}>
<button className="button5">Generate</button>
<br />
<input
type="text"
name="topText"
value={this.state.topText}
placeholder="Input something"
onChange={this.handleChange}
/>
<br />
<input
type="text"
value={this.state.bottomText}
name="bottomText"
placeholder="Input something"
onChange={this.handleChange}
/>
</form>
{/* <div> */}
<h2>{this.state.topText}</h2>
<h2>{this.state.bottomText}</h2>
<img src={this.state.randomImg} alt="" />
{/* </div> */}
</div>
);
}
} |
JavaScript | class Version {
constructor(full) {
this.full = full;
this.major = full.split('.')[0];
this.minor = full.split('.')[1];
this.patch = full.split('.').slice(2).join('.');
}
} |
JavaScript | class NoSubscriptionProgramError extends common_1.CustomError {
/** @private */
constructor(channelId) {
super(`Channel ${channelId} does not have a subscription program`);
}
} |
JavaScript | class BenchmarkRatiosRequest {
/**
* Constructs a new <code>BenchmarkRatiosRequest</code>.
* @alias module:model/BenchmarkRatiosRequest
* @param ids {Array.<String>} Benchmark Identifiers. Reference the helper endpoint **_/id-list** to get a sample list of valid identifiers.
* @param metrics {Array.<String>} Requested List of FactSet Market Aggregates (FMA) or ratios. provided the below complete metrics list. |metric item|Description|category|periodicity |:---|:---|:---|:---| |GROSS_MARGIN|Gross Margin|Profitability (%)|NTMA, LTMA, STMA, LTM, QTR, 0, 1, 2 |OPER_INC_SALES|Operating Margin|Profitability (%)|LTM, QTR |NET_MGN|Net Margin|Profitability (%)|NTMA, LTMA, STMA, LTM, QTR, 0, 1, 2 |EBIT_MARGIN|EBIT Margin|Profitability (%)| NTMA, LTMA, STMA, LTM, QTR, 0, 1, 2 |EBITDA_MARGIN|EBITDA Margin|Profitability (%)|NTMA, LTMA, STMA, LTM, QTR, 0, 1, 2 |ROA|Return on Assets|Profitability (%)|LTM |ROE|Return on Equity|Profitability (%)|NTMA, LTMA, LTM, 0, 1, 2 |ROIC|Return on Invested Capital|Profitability (%)| LTM |FCF_MGN|Free Cash Flow Margin|Profitability (%)|LTM, QTR |PE|Price/Earnings|Valuation|NTMA, LTMA, STMA, LTM, QTR, 0, 1, 2 |PEX|Price/Earnings (excl negatives)|Valuation|LTM |PSALES|Price/Sales|Valuation|NTMA, LTMA, STMA, LTM, QTR, 0, 1, 2 |PBK|Price/Book Value|Valuation|NTMA, LTMA, LTM, 0, 1, 2 |PCF|Price/Cash Flow|Valuation|NTMA, LTMA, LTM, 0, 1, 2 |PCFX|Price/Cash Flow (excl negatives)|Valuation|LTM |PFCF|Price/Free Cash Flow|Valuation|NTMA, LTMA, LTM, 0, 1, 2 |EVAL_EBIT|Enterprise Value/EBIT|Valuation|NTMA, LTMA, LTM, 0, 1, 2 |EVAL_EBITDA|Enterprise Value/EBITDA|Valuation|NTMA, LTMA, LTM, 0, 1, 2 |EVAL_SALES|Enterprise Value/Sales|Valuation|NTMA, LTMA, LTM, 0, 1, 2 |NDEBT_EBITDA|Net Debt/EBITDA|Coverage|NTMA, LTMA, LTM, 0, 1, 2 |NDEBT_EBITDA_MIN_CAPEX|Net Debt/(EBITDA-Capex)|Coverage|LTM |DEBT_EBITDA|Total Debt/EBITDA|Coverage|LTM |DEBT_EBIT|Total Debt/EBIT|Coverage|LTM |EBIT_INT_EXP|EBIT/Interest Expense (Int. Coverage)|Coverage|LTM |EBITDA_INT_EXP|EBITDA/Interest Expense|Coverage|LTM |OPER_CF_INT_EXP|CFO/Interest Expense|Coverage|LTM |LTD_EBITDA|LT Debt/EBITDA|Coverage|LTM |NDEBT_FFO|Net Debt/FFO|Coverage|LTM |LTD_FFO|LT Debt/FFO|Coverage|LTM |FCF_DEBT|FCF/Total Debt|Coverage|LTM |OPER_CF_DEBT|CFO/Total Debt|Coverage|LTM |LTD_EQ|LT Debt/Total Equity|Leverage(%)|LTM |LTD_TCAP|LT Debt/Total Capital|Leverage(%)|LTM |LTD_ASSETS|LT Debt/Total Assets|Leverage(%)|LTM |DEBT_ASSETS|Total Debt/Total Assets|Leverage(%)|LTM |DEBT_EQ|Total Debt/Total Equity|Leverage(%)|LTM |NDEBT_TCAP|Net Debt/Total Capital|Leverage(%)|LTM |DEBT_TCAP|Total Debt/Total Capital|Leverage(%)|LTM
*/
constructor(ids, metrics) {
BenchmarkRatiosRequest.initialize(this, ids, metrics);
}
/**
* Initializes the fields of this object.
* This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins).
* Only for internal use.
*/
static initialize(obj, ids, metrics) {
obj['ids'] = ids;
obj['metrics'] = metrics;
}
/**
* Constructs a <code>BenchmarkRatiosRequest</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/BenchmarkRatiosRequest} obj Optional instance to populate.
* @return {module:model/BenchmarkRatiosRequest} The populated <code>BenchmarkRatiosRequest</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new BenchmarkRatiosRequest();
if (data.hasOwnProperty('ids')) {
obj['ids'] = ApiClient.convertToType(data['ids'], ['String']);
}
if (data.hasOwnProperty('startDate')) {
obj['startDate'] = ApiClient.convertToType(data['startDate'], 'String');
}
if (data.hasOwnProperty('endDate')) {
obj['endDate'] = ApiClient.convertToType(data['endDate'], 'String');
}
if (data.hasOwnProperty('periodicity')) {
obj['periodicity'] = Periodicity.constructFromObject(data['periodicity']);
}
if (data.hasOwnProperty('metrics')) {
obj['metrics'] = ApiClient.convertToType(data['metrics'], ['String']);
}
if (data.hasOwnProperty('frequency')) {
obj['frequency'] = Frequency.constructFromObject(data['frequency']);
}
if (data.hasOwnProperty('currency')) {
obj['currency'] = ApiClient.convertToType(data['currency'], 'String');
}
}
return obj;
}
} |
JavaScript | class PeticionesService {
/**
* @typedef {Object} Peticion
* @property {number} id - De sólo lectura. Se genera automáticamente en la Base de Datos para peticiones nuevas.
* @property {number} codigo - Lo mismo que id, se añade para mantener consistencia con otras entidades.
* @property {Object} proceso - Proceso al que pertenece la petición
* @property {Proceso} proceso.valor - Su valor actual.
* @property {string} proceso.display - Cómo debe ser representado.
* @property {Object} solicitante - Persona que realiza la petición.
* @property {Persona} solicitante.valor - Su valor actual.
* @property {string} solicitante.display - Cómo debe ser representado.
* @property {string} tipoSolicitud1 - Primer tipo de solicitud.
* @property {string} tipoSolicitud2 - Segundo tipo de solicitud.
* @property {string} observaciones - Observaciones.
* @property {Object} informacionExtra - Información adicional relacionada con la petición.
* @property {string} estadoInterno - Estado final de la petición.
* @property {Object} estado - Estado actual de la petición.
* @property {Object} estado.valor - Su valor actual.
* @property {string} estado.display - Cómo debe representarse.
* @property {Object} fechaCreacion - Fecha de creación de la petición.
* @property {Date} fechaCreacion.valor - Su valor actual.
* @property {string} fechaCreacion.display - Cómo debe representarse esta fecha.
* @property {Object} fechaNecesaria - Fecha necesaria de la petición.
* @property {Date} fechaNecesaria.valor - Su valor actual.
* @property {string} fechaNecesaria.display - Cómo debe representarse esta fecha.
*
* @property {Object[]} actividades - Lista de autorizadores que ya aprobaron o rechazaron esta solicitud.
* @property {Object} actividades[0].autorizador - Datos del autorizador
* @property {Object} actividades[0].autorizador.valor - Su valor actual
* @property {string} actividades[0].autorizador.display - Cómo debe ser representado.
* @property {Object} actividades[0].estado - Estado de esta actividad.
* @property {string} actividades[0].estado.valor - Su valor actual.
* @property {string} actividades[0].estado.display - Cómo debe ser representado.
* @property {Object} actividades[0].fecha - Fecha en que realizó la autorización.
* @property {Date} actividades[0].fecha.valor - Su valor actual.
* @property {string} actividades[0].fecha.display - Cómo debe representarse esta fecha.
*
* @property {Adjunto[]} adjuntos - Lista de adjuntos de la petición.
*
* @property {number} cantidadActividadesCompletadas - Número de actividades realizadas para la petición.
* @property {number} cantidadActividadesTotales - Número total de actividades requeridas por la petición.
* @property {number} cantidadAdjuntos - Número total de adjuntos de la petición.
* @property {number} cantidadMensajes - Número total de mensajes de la petición.
*
* @property {string} enlaceOrigen - Enlace a la aplicación desde donde se generó la petición.
*
*/
/**
* @param $q - Servicio de Angular para utilizar Promesas
* @param $http - Servicio de Angular para hacer llamadas HTTP
* @param EtiquetasService
* @param PersonalService
* @param SesionService
* @param AppConfig - Contiene la configuración del app.
*
**/
constructor($q, $http, EtiquetasService, PersonalService, SesionService, AppConfig) {
// Constantes del servicio
/** @private */
this.ENDPOINT = '/peticiones';
this.ENDPOINT_TIPOS_SOLICITUD = '/tipos_solicitud';
this.ENDPOINT_APROBAR = `${this.ENDPOINT}/autorizar`;
this.ENDPOINT_RECHAZAR = `${this.ENDPOINT}/rechazar`;
/** @private */
this.$q = $q;
/** @private */
this.$http = $http;
/** @private */
this.etiquetasService = EtiquetasService;
/** @private */
this.personalService = PersonalService;
/** @private */
this.AppConfig = AppConfig;
/** @type {Peticion[]} */
this.peticiones = [];
/** @private */
this.ordenActivo = null;
/** @private */
this.filtrosBusqueda = null;
SesionService.obtenerUsuarioAutenticado()
.then(usuario => {
/** @private */
this.usuario = usuario;
});
}
reiniciarEstado() {
this.peticiones = [];
this.ordenActivo = null;
this.filtrosBusqueda = null;
}
/**
* Le aplica algunas transformaciones a una petición recibida del API. Añade los permisos de edición y también le
* agrega una propiedad para facilitar la visualización de varias de sus propiedaddes.
*
* @param {Object} entidad - Representa una petición recibida del API
* @param {Etiqueta[]} etiquetas - Listado de etiquetas existentes. Se usan para mostrar el estado.
* @returns {Peticion} - La misma entidad, con las transformaciones mencionadas.
*/
procesarEntidadRecibida(entidad, etiquetas) {
let peticionProcesada = {
codigo: entidad.id
};
for (let prop in entidad) {
if (prop === 'proceso') {
peticionProcesada[prop] = {
valor: entidad[prop],
display: entidad[prop] ? entidad[prop].evento : ''
};
} else if (prop === 'solicitante') {
const personaProcesada = entidad[prop] ? this.personalService.procesarPersonaRecibida(entidad[prop]) : null;
peticionProcesada[prop] = {
valor: personaProcesada,
display: personaProcesada ? personaProcesada.nombreApellidos : ''
};
} else if (prop === 'fechaCreacion' || prop === 'fechaNecesaria') {
const fechaNecesariaObj = entidad[prop] ? new Date(Date.parse(entidad[prop])) : null;
peticionProcesada[prop] = {
valor: fechaNecesariaObj,
display: fechaNecesariaObj ? format(fechaNecesariaObj, this.AppConfig.formatoFechas) : ''
};
} else if (prop === 'fechaUltimoMensaje') {
const fechaObj = entidad[prop] ? new Date(Date.parse(entidad[prop])) : null;
peticionProcesada[prop] = {
valor: fechaObj,
display: fechaObj ? format(fechaObj, `${this.AppConfig.formatoFechas} HH:mm:ss`) : ''
};
} else if (prop === 'informacionExtra') {
const info = entidad.informacionExtra;
peticionProcesada[prop] = this._procesarInformacionExtra(info);
} else if (prop === 'estado') {
const etiqueta = find(etiquetas, etiqueta => {
return etiqueta.estado === entidad[prop] && etiqueta.proceso.valor.id === entidad.proceso.id;
});
let descripcion = etiqueta ? etiqueta.descripcion : '';
if (isNil(etiqueta)) {
switch (entidad.estadoInterno) {
case AUTORIZACION_APROBADA:
descripcion = this.AppConfig.etiquetaPorDefectoAutorizada;
break;
case AUTORIZACION_RECHAZADA:
descripcion = this.AppConfig.etiquetaPorDefectoRechazada;
break;
case AUTORIZACION_PENDIENTE:
if (entidad.estado === '0') {
descripcion = this.AppConfig.etiquetaPorDefectoPendiente;
} else {
descripcion = this.AppConfig.etiquetaPorDefectoEnRevision;
}
break;
case AUTORIZACION_ANULADA:
descripcion = this.AppConfig.etiquetaPorDefectoAnulada;
break;
}
}
peticionProcesada[prop] = {
valor: entidad[prop],
display: descripcion
};
} else if (prop === 'actividades') {
peticionProcesada[prop] = map(entidad[prop], (actividad, indice) => {
return this._procesarActividad(actividad, indice, entidad.cantidadActividadesTotales);
});
} else if (prop === 'peticionQueAnula' || prop === 'peticionAnulacion') {
peticionProcesada[prop] = entidad[prop];
if (!isNil(peticionProcesada[prop])) {
peticionProcesada[prop].informacionExtra = this._procesarInformacionExtra(peticionProcesada[prop].informacionExtra);
}
} else {
peticionProcesada[prop] = entidad[prop];
}
}
peticionProcesada.displayOrden = `${entidad.cantidadActividadesCompletadas}/${entidad.cantidadActividadesTotales}`;
peticionProcesada.displayTipoSolicitud = entidad.tipoSolicitud1;
if (!isNil(entidad.tipoSolicitud2)) {
peticionProcesada.displayTipoSolicitud = `${peticionProcesada.displayTipoSolicitud}-${entidad.tipoSolicitud2}`;
}
if (entidad.proceso.aplicacion.id === this.AppConfig.idCalendarios && !isNil(peticionProcesada.fechaNecesaria.valor)) {
const usuario = entidad.solicitante.nInterno;
const anno = peticionProcesada.fechaNecesaria.valor.getFullYear();
peticionProcesada.enlaceOrigen = this.AppConfig.urlEnlaceCalendarios.replace('<usuario>', usuario).replace('<anno>', anno);
}
peticionProcesada.editable = false;
peticionProcesada.eliminable = false;
return peticionProcesada;
}
_procesarInformacionExtra(info) {
let resultado = Object.keys(info).length > 0 ? {} : null;
for (let key in info) {
//Obtener palabras y capitalizar letra inicial
const arregloPalabras = lowerCase(key).split(' ');
forEach(arregloPalabras, (palabra, indice) => {
arregloPalabras[indice] = capitalize(palabra);
});
//Obtener valor del campo
let valorProcesado = info[key];
//Los campos tipo fecha deben tener contenido en su nombre clave el fragmento fecha
if(includes(key, 'fecha')) {
//Procesar fecha
const fecha = toDate(info[key]);
if (!isNaN(fecha)) {
let formato = this.AppConfig.formatoFechas;
if ( !(fecha.getHours() === 0 && fecha.getMinutes() === 0) && !(fecha.getHours() === 23 && fecha.getMinutes() === 59) ) {
formato = `${formato} HH:mm`;
}
valorProcesado = format(info[key], formato);
}
}
resultado[key] = {
valor: valorProcesado,
label: join(arregloPalabras, ' ')
};
}
return resultado;
}
_procesarActividad(actividad, indice, totalActividades) {
let actividadProcesada = {
codigo: actividad.actividad
};
for (let prop in actividad) {
if (prop === 'autorizador') {
const personaProcesada = actividad[prop] ? this.personalService.procesarPersonaRecibida(actividad[prop]) : null;
actividadProcesada[prop] = {
valor: personaProcesada,
display: personaProcesada ? personaProcesada.nombreApellidos : ''
};
} else if (prop === 'fecha') {
const fechaNecesariaObj = actividad[prop] ? new Date(Date.parse(actividad[prop])) : null;
actividadProcesada[prop] = {
valor: fechaNecesariaObj,
display: fechaNecesariaObj ? format(fechaNecesariaObj, `${this.AppConfig.formatoFechas} HH:mm`) : ''
};
} else if (prop === 'estado') {
actividadProcesada[prop] = {
valor: actividad[prop],
display: actividad[prop] === AUTORIZACION_APROBADA ? ETIQUETA_OK_DESC : ETIQUETA_NOK_DESC
};
} else {
actividadProcesada[prop] = actividad[prop];
}
actividadProcesada.displayOrden = `${indice+1}/${totalActividades}`;
}
return actividadProcesada;
}
/**
* Devuelve una petición dado su código
* @param {number} codigo
* @return {Promise.<Peticion>} - Se resuelve con la petición correspondiente a ese id.
*/
obtener(codigo) {
return this.$q.all([
this.$http.get(`${this.ENDPOINT}/${codigo}`),
this.etiquetasService.obtenerTodos()
]).then(resultado => {
const peticion = this.procesarEntidadRecibida(resultado[0].data, resultado[1]);
let indiceExistente = findIndex(this.peticiones, ['codigo', codigo]);
if (indiceExistente > -1) {
this.peticiones[indiceExistente] = peticion;
}
return peticion;
});
}
/**
* Devuelve una lista de peticiones. Utiliza paginación porque la cantidad total de peticiones puede llegar a ser
* considerable.
*
* @param {boolean} peticionesPropias - Verdadero si lo que se desean son las peticiones propias.
* @param {number} pagina - Página que se desea.
* @param {[string, string]} orden - Cómo deben estar ordenados los resultados.
* @param filtro - Se puede usar para filtrar los resultados por varios campos.
* @param {number} elementosPorPagina - Cantidad de peticiones que se desea recibir en una página.
* @param {boolean} persistirResultado
* @param {boolean} batch
* @return {Promise.<Peticion[]>} - Se resuelve con el arreglo de peticiones que corresponden a una página determinada.
*/
obtenerTodos(peticionesPropias, pagina, orden, filtro, elementosPorPagina, persistirResultado, batch) {
let cambioOrden = false;
const guardarCambios = isNil(persistirResultado) || persistirResultado;
if (guardarCambios) {
if (!isNil(orden) && (isNil(this.ordenActivo) || orden[0] !== this.ordenActivo[0] || orden[1] !== this.ordenActivo[1])) {
this.ordenActivo = orden;
cambioOrden = true;
}
if (!isUndefined(filtro)) {
this.filtrosBusqueda = filtro;
}
}
if(get(filtro, 'elementosExportar')) {
assign(this.filtrosBusqueda, { elementosExportar: filtro.elementosExportar });
} else {
if(get(this.filtrosBusqueda, 'elementosExportar')) {
delete this.filtrosBusqueda.elementosExportar;
}
}
return this._obtenerServidor(peticionesPropias, pagina, cambioOrden, this.filtrosBusqueda, elementosPorPagina, persistirResultado, batch);
}
obtenerTiposSolicitud() {
return this.$http.get(this.ENDPOINT_TIPOS_SOLICITUD)
.then(response => {
return response.data;
});
}
aprobar(peticiones, paginaActual) {
return this._cambiarEstadoPeticiones(peticiones, {}, paginaActual, this.ENDPOINT_APROBAR, AUTORIZACION_APROBADA);
}
rechazar(peticiones, paginaActual) {
return this._cambiarEstadoPeticiones(peticiones, {}, paginaActual, this.ENDPOINT_RECHAZAR, AUTORIZACION_RECHAZADA);
}
_actualizarPeticiones(peticiones, respuestaServidor, paginaActual, accion) {
return this.etiquetasService.obtenerTodos()
.then(etiquetas => {
let pagina = paginaActual;
const fin = paginaActual * this.AppConfig.elementosPorPagina;
const inicio = fin - this.AppConfig.elementosPorPagina;
const totalPaginas = Math.ceil(this.peticiones.length / this.AppConfig.elementosPorPagina);
let actualizarPagina = false;
if (peticiones.length !== respuestaServidor.length) {
actualizarPagina = true;
} else {
forEach(respuestaServidor, resultado => {
const indicePeticion = findIndex(this.peticiones, ['id', resultado.id]);
if (this._sigueSiendoVisible(resultado)) {
const peticionCorrespondiente = this.peticiones[indicePeticion];
peticionCorrespondiente.actividades.push(
this._procesarActividad({
actividad: peticionCorrespondiente.cantidadActividadesCompletadas + 1,
autorizador: this.usuario,
estado: accion,
fecha: new Date().toISOString().replace('Z', '')
}, peticionCorrespondiente.cantidadActividadesCompletadas, peticionCorrespondiente.cantidadActividadesTotales)
);
const objHidratado = assign({},
omit(resultado, ['solicitante', 'proceso', 'peticionQueAnula', 'peticionAnulacion']),
{proceso: peticionCorrespondiente.proceso.valor, solicitante: peticionCorrespondiente.solicitante.valor}
);
assign(peticionCorrespondiente, this.procesarEntidadRecibida( objHidratado, etiquetas) );
} else {
this.peticiones.splice(indicePeticion, 1);
if (pagina < totalPaginas) {
actualizarPagina = true;
}
}
});
if (inicio >= this.peticiones.length) {
if (paginaActual > 1) {
pagina -= 1;
actualizarPagina = true;
} else {
return {
peticiones: [],
pagina
}
}
}
}
if (actualizarPagina) {
return this.obtenerTodos(false, pagina, undefined, undefined)
.then(peticionesPagina => {
return {
peticiones: peticionesPagina,
pagina
}
});
} else {
return {
peticiones: this.peticiones.slice(inicio, fin),
pagina
}
}
});
}
_sigueSiendoVisible(peticion) {
if (peticion.estadoInterno === AUTORIZACION_PENDIENTE) {
return this.usuario.esGestor && !get(this.filtrosBusqueda, 'idRol');
} else {
return isNil(this.filtrosBusqueda) || !this.filtrosBusqueda.estadosInternos || includes(this.filtrosBusqueda.estadosInternos, peticion.estadoInterno);
}
}
/**
* Elimina una petición de la lista
*
* @param {Peticion} peticion
*/
eliminarEntidad(peticion) {
let indiceExistente = findIndex(this.peticiones, ['id', peticion.id]);
if (indiceExistente > -1) {
this.peticiones.splice(indiceExistente, 1);
}
}
/**
* Actualiza una petición existente. Sólo se llama al API si los datos de la petición cambiaron.
*
* @param {Peticion} peticion
* @return {Promise<Peticion>} - Se resuelve con la petición actualizada.
*/
editar(peticion) {
let error;
const indicePeticionCambiada = findIndex(this.peticiones, ['id', peticion.id]);
if (indicePeticionCambiada < 0) {
return this.$q.reject();
}
const peticionCorrespondiente = this.peticiones[indicePeticionCambiada];
if (peticion.observaciones !== peticionCorrespondiente.observaciones) {
const datosAEnviar = {
'id': peticion.id,
'proceso': peticion.proceso.valor.id,
'estado': peticion.estado.valor,
'fechaCreacion': procesarFechaAEnviar(peticion.fechaCreacion.valor),
'fechaNecesaria': procesarFechaAEnviar(peticion.fechaNecesaria.valor),
'observaciones': peticion.observaciones,
'solicitante': peticion.solicitante.valor.nInterno
};
return this.$http.put(`${this.ENDPOINT}/${peticion.id}`, datosAEnviar)
.then(response => {
peticionCorrespondiente.observaciones = peticion.observaciones;
return peticionCorrespondiente;
})
.catch(response => {
error = response;
// Si en el servidor no se encontró una entidad con este código, o ya no tiene permiso para editarla,
// se quita de la lista local
if (response && (response.status === 404 || response.status === 401) ) {
this.eliminarEntidad(peticion);
} else if (get(response, 'error.errorCode') === PROPIEDAD_NO_EDITABLE) {
// Este error se da por problemas de sincronización, es necesario volver a pedir la petición
return this.obtener(peticion.id);
}
})
.then(peticion => {
if (!error) {
return peticion;
} else {
throw error;
}
});
} else {
return this.$q.reject();
}
}
_cambiarEstadoPeticiones(peticiones, dataExtra, paginaActual, endpoint, accion) {
const ids = map(peticiones, peticion => {
return peticion.id
});
if (ids.length > 0) {
let error = false;
let peticionesConError, peticionesExitosas = [];
return this.$http.post(endpoint, assign({}, {ids}, dataExtra))
.then(response => {
return this._actualizarPeticiones(peticiones, response.data, paginaActual, accion);
})
.catch(response => {
error = true;
if (get(response, 'error.errorCode') === ACTUALIZACION_EN_BULTO_CON_ERRORES) {
peticionesConError = response.error.fallos;
peticionesExitosas = response.error.exitos;
return this._actualizarPeticiones(peticiones, response.error.exitos, paginaActual, accion);
} else {
throw response;
}
})
.then(resultado => {
if (!error) {
return resultado;
} else {
throw {
peticiones: resultado.peticiones,
pagina: resultado.pagina,
peticionesExitosas,
peticionesConError
}
}
});
} else {
return this.$q.reject();
}
}
/**
* Devuelve una lista de peticiones del servidor
*
* @param {boolean} peticionesPropias - Verdadero si lo que se desean son las peticiones propias.
* @param {number} pagina - Página que se desea.
* @param {boolean} cambioOrden - Verdadero si el orden de las peticiones fue cambiado.
* @param filtro - Se puede usar para filtrar los resultados por varios campos.
* @param {number} elementosPorPagina - Cantidad de peticiones que se desea recibir en una página.
* @param {boolean} persistirResultado
* @param {boolean} batch
* @return {Promise.<Peticion[]>} - Se resuelve con el arreglo de peticiones que corresponden a una página determinada.
*/
_obtenerServidor(peticionesPropias, pagina, cambioOrden, filtro, elementosPorPagina, persistirResultado, batch) {
let totalPeticiones = 0;
const paginaActual = !isNil(pagina) ? pagina : 1;
const fin = paginaActual * this.AppConfig.elementosPorPagina;
const inicio = fin - this.AppConfig.elementosPorPagina;
const guardarCambios = isNil(persistirResultado) || persistirResultado;
let ordenarPor;
if (guardarCambios && cambioOrden) {
this.peticiones = [];
}
if (!isNil(this.ordenActivo)) {
let campoAOrdenar = this.ordenActivo[0];
campoAOrdenar = campoAOrdenar.split('.')[0]; // Se hace esto por si el campo por el que se ordena es 'fecha.valor', por ejemplo
// El API interpreta como orden descendente si se pasa el parámetros con un - delante, ejemplo: -fecha
ordenarPor = `${this.ordenActivo[1] === 'desc' ? '-' : ''}${campoAOrdenar}`;
}
let params = {
paginaActual,
elementosPorPagina: !isNil(elementosPorPagina) ? elementosPorPagina : this.AppConfig.elementosPorPagina,
ordenarPor,
peticionesPropias,
batch
};
return this.$q.all([
this.$http.get(this.ENDPOINT, { params: assign(params, filtro) }),
this.etiquetasService.obtenerTodos()
]).then(resultado => {
const peticiones = map(resultado[0].data, peticion => {
return this.procesarEntidadRecibida(peticion, resultado[1]);
});
if (guardarCambios) {
totalPeticiones = resultado[0].metadata.cantidadTotal;
this._procesarResultadosPaginados(peticiones, totalPeticiones, inicio);
}
return peticiones;
});
}
/**
* Añade una página de peticiones obtenidas del API al arreglo total de peticiones, en la posición que le corresponde.
* @param {Peticion[]} resultados - Representa una página de peticiones.
* @param {number} total - Total de peticiones existentes.
* @param {number} inicio - Posición inicial del arreglo donde se debe insertar la página.
* @private
*/
_procesarResultadosPaginados(resultados, total, inicio) {
this.peticiones = [];
this.peticiones.push(...fill(Array(total), undefined));
forEach(resultados, (peticion, index) => {
this.peticiones[index + inicio] = peticion;
});
}
} |
JavaScript | class UrbackupServer {
#isLoggedIn = false;
#lastLogId = new Map();
#password;
#semaphore = new Semaphore(1);
#sessionId = '';
#url;
#username;
/**
* @class
* @param {Object} [params] - (Optional) An object containing parameters.
* @param {string} [params.url] - (Optional) Server's URL. Must include protocol, hostname and port. Defaults to http://127.0.0.1:55414.
* @param {string} [params.username] - (Optional) Username used to log in. Defaults to empty string. Anonymous login is used if userneme is empty.
* @param {string} [params.password] - (Optional) Password used to log in. Defaults to empty string.
* @example <caption>Connect locally to the built-in server without password</caption>
* const server = new UrbackupServer();
* @example <caption>Connect locally with password</caption>
* const server = new UrbackupServer({ url: 'http://127.0.0.1:55414', username: 'admin', password: 'secretpassword'});
* @example <caption>Connect over the network</caption>
* const server = new UrbackupServer({ url: 'https://192.168.0.2:443', username: 'admin', password: 'secretpassword'});
*/
constructor ({ url = 'http://127.0.0.1:55414', username = '', password = '' } = {}) {
this.#url = new URL(url);
this.#url.pathname = 'x';
this.#username = username;
this.#password = password;
}
/**
* This method is not meant to be used outside the class.
* Used internally to clear session ID and logged-in flag.
*/
#clearLoginStatus () {
this.#sessionId = '';
this.#isLoggedIn = false;
}
/**
* This method is not meant to be used outside the class.
* Used internally to make API call to the server.
*
* @param {string} action - Action.
* @param {Object} [bodyParams] - Action parameters.
* @returns {Object} Response body text parsed as JSON.
*/
async #fetchJson (action = '', bodyParams = {}) {
this.#url.searchParams.set('a', action);
if (this.#sessionId.length > 0) {
bodyParams.ses = this.#sessionId;
}
const response = await fetch(this.#url, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json; charset=UTF-8'
},
body: new URLSearchParams(bodyParams)
});
if (response?.ok === true) {
return response.json();
} else {
throw new Error('Fetch request did not end normally, response was unsuccessful (status not in the range 200-299)');
}
}
/**
* This method is not meant to be used outside the class.
* Used internally to hash user password.
*
* @param {string} salt - PBKDF2 salt value as stored on the server.
* @param {number} rounds - PBKDF2 iterations number.
* @param {string} randomKey - Random key generated by the server for each session.
* @returns {string} Hashed password.
*/
async #hashPassword (salt = '', rounds = 10000, randomKey = '') {
/**
* @param {string} password - Password.
* @returns {Buffer} Derived key.
*/
function pbkdf2Async (password) {
return new Promise((resolve, reject) => {
crypto.pbkdf2(password, salt, rounds, 32, 'sha256', (error, key) => {
return error ? reject(error) : resolve(key);
});
});
}
let passwordHash = crypto.createHash('md5').update(salt + this.#password, 'utf8').digest();
let derivedKey;
if (rounds > 0) {
derivedKey = await pbkdf2Async(passwordHash);
}
passwordHash = crypto.createHash('md5').update(randomKey + (rounds > 0 ? derivedKey.toString('hex') : passwordHash), 'utf8').digest('hex');
return passwordHash;
}
/**
* This method is not meant to be used outside the class.
* Used internally to log in to the server.
* If username is empty then anonymous login method is used.
*
* @returns {boolean} Boolean true if logged in successfuly or was already logged in.
*/
async #login () {
// Use semaphore to prevent race condition with login status i.e. this.#sessionId
// eslint-disable-next-line no-unused-vars
const [value, release] = await this.#semaphore.acquire();
try {
if (this.#isLoggedIn === true && this.#sessionId.length > 0) {
return true;
}
if (this.#username.length === 0) {
const anonymousLoginResponse = await this.#fetchJson('login');
if (anonymousLoginResponse?.success === true) {
this.#sessionId = anonymousLoginResponse.session;
this.#isLoggedIn = true;
return true;
} else {
this.#clearLoginStatus();
throw new Error('Anonymous login failed');
}
} else {
const saltResponse = await this.#fetchJson('salt', { username: this.#username });
if (typeof saltResponse?.salt === 'string') {
this.#sessionId = saltResponse.ses;
const hashedPassword = await this.#hashPassword(saltResponse.salt, saltResponse.pbkdf2_rounds, saltResponse.rnd);
const userLoginResponse = await this.#fetchJson('login', { username: this.#username, password: hashedPassword });
if (userLoginResponse?.success === true) {
this.#isLoggedIn = true;
return true;
} else {
// invalid password
this.#clearLoginStatus();
throw new Error('Login failed: invalid username or password');
}
} else {
// invalid username
this.#clearLoginStatus();
throw new Error('Login failed: invalid username or password');
}
}
} finally {
release();
}
}
/**
* This method is not meant to be used outside the class.
* Used internally to map client name to client ID.
*
* @param {string} clientName - Client's name.
* @returns {number} Client's ID. 0 (zero) when no matching clients found.
*/
async #getClientId (clientName) {
if (typeof clientName === 'undefined') {
throw new Error('API call error: missing or invalid parameters');
}
const defaultReturnValue = 0;
const clients = await this.getClients({ includeRemoved: true });
const clientId = clients.find(client => client.name === clientName)?.id;
return typeof clientId === 'undefined' ? defaultReturnValue : clientId;
}
/**
* This method is not meant to be used outside the class.
* Used internally to map client ID to client name.
*
* @param {string} clientId - Client's ID.
* @returns {string} Client's name. Empty string when no matching clients found.
*/
async #getClientName (clientId) {
if (typeof clientId === 'undefined') {
throw new Error('API call error: missing or invalid parameters');
}
const defaultReturnValue = '';
const clients = await this.getClients({ includeRemoved: true });
const clientName = clients.find(client => client.id === clientId)?.name;
return typeof clientName === 'undefined' ? defaultReturnValue : clientName;
}
/**
* This method is not meant to be used outside the class.
* Used internally to map group name to group ID.
* WARNING: return value can conflict with default group ID, which is also 0 (zero).
*
* @param {string} groupName - Group name. Must be different than '', which is default group name.
* @returns {number} Group ID. 0 (zero) when no matching clients found. That can conflict with default group ID, which is also 0.
*/
async #getGroupId (groupName) {
if (typeof groupName === 'undefined' || groupName === '') {
throw new Error('API call error: missing or invalid parameters');
}
const defaultReturnValue = 0;
const groups = await this.getGroups();
const groupId = groups.find(group => group.name === groupName)?.id;
return typeof groupId === 'undefined' ? defaultReturnValue : groupId;
}
/**
* Retrieves server identity.
*
* @returns {string} Server identity.
* @example <caption>Get server identity</caption>
* server.getServerIdentity().then(data => console.log(data));
*/
async getServerIdentity () {
const login = await this.#login();
if (login === true) {
const statusResponse = await this.#fetchJson('status');
if (typeof statusResponse?.server_identity === 'string') {
return statusResponse.server_identity;
} else {
throw new Error('API response error: missing values');
}
} else {
throw new Error('Login failed: unknown reason');
}
}
/**
* Retrieves a list of users.
*
* @returns {Array} Array of objects representing users. Empty array when no users found.
* @example <caption>Get all users</caption>
* server.getUsers().then(data => console.log(data));
*/
async getUsers () {
const login = await this.#login();
if (login === true) {
const usersResponse = await this.#fetchJson('settings', { sa: 'listusers' });
if (Array.isArray(usersResponse?.users)) {
return usersResponse.users;
} else {
throw new Error('API response error: missing values');
}
} else {
throw new Error('Login failed: unknown reason');
}
}
/**
* Retrieves a list of groups.
* By default, UrBackup clients are added to a group id 0 with name '' (empty string).
*
* @returns {Array} Array of objects representing groups. Empty array when no groups found.
* @example <caption>Get all groups</caption>
* server.getGroups().then(data => console.log(data));
*/
async getGroups () {
const login = await this.#login();
if (login === true) {
const settingsResponse = await this.#fetchJson('settings');
if (Array.isArray(settingsResponse?.navitems?.groups)) {
return settingsResponse.navitems.groups;
} else {
throw new Error('API response error: missing values');
}
} else {
throw new Error('Login failed: unknown reason');
}
}
/**
* Adds a new group.
*
* @param {Object} params - (Required) An object containing parameters.
* @param {string} params.groupName - (Required) Group name, case sensitive. UrBackup clients are added to a group id 0 with name '' (empty string) by default. Defaults to undefined.
* @returns {boolean} When successfull, Boolean true. Boolean false when adding was not successfull, for example group already exists.
* @example <caption>Add new group</caption>
* server.addGroup({groupName: 'prod'}).then(data => console.log(data));
*/
async addGroup ({ groupName } = {}) {
if (typeof groupName === 'undefined') {
throw new Error('API call error: missing or invalid parameters');
}
// Possible UrBackup bug: server does not allow adding multiple groups with the same name, but allows '' (empty string) which is the same as default group name
if (groupName === '') {
return false;
}
const login = await this.#login();
if (login === true) {
const response = await this.#fetchJson('settings', { sa: 'groupadd', name: groupName });
if ('add_ok' in response || 'already_exists' in response) {
return response?.add_ok === true;
} else {
throw new Error('API response error: missing values');
}
} else {
throw new Error('Login failed: unknown reason');
}
}
/**
* Removes group.
* All clients in this group will be re-assigned to the default group.
* Using group ID should be preferred to group name for repeated method calls.
*
* @param {Object} params - (Required) An object containing parameters.
* @param {number} params.groupId - (Required if groupName is undefined) Group ID. Must be greater than 0. Takes precedence if both ```groupId``` and ```groupName``` are defined. Defaults to undefined.
* @param {string} params.groupName - (Required if groupId is undefined) Group name, case sensitive. Must be different than '' (empty string). Ignored if both ```groupId``` and ```groupName``` are defined. Defaults to undefined.
* @returns {boolean} When successfull, Boolean true. Boolean false when removing was not successfull. Due to UrBackup bug, it returns ```true``` when called with non-existent ```groupId```.
* @example <caption>Remove group</caption>
* server.removeGroup({groupId: 1}).then(data => console.log(data));
* server.removeGroup({groupName: 'prod'}).then(data => console.log(data));
*/
async removeGroup ({ groupId, groupName } = {}) {
if (typeof groupId === 'undefined' && typeof groupName === 'undefined') {
throw new Error('API call error: missing or invalid parameters');
}
if (groupId === 0 || groupName === '') {
return false;
}
const login = await this.#login();
if (login === true) {
let mappedGroupId;
if (typeof groupId === 'undefined') {
mappedGroupId = await this.#getGroupId(groupName);
if (mappedGroupId === 0) {
return false;
}
}
const response = await this.#fetchJson('settings', { sa: 'groupremove', id: groupId ?? mappedGroupId });
// Possible UrBackup bug: server returns delete_ok:true for non-existent group ID
return response?.delete_ok === true;
} else {
throw new Error('Login failed: unknown reason');
}
}
/**
* Retrieves a list of clients.
* Matches all clients by default, including clients marked for removal.
*
* @param {Object} [params] - (Optional) An object containing parameters.
* @param {string} [params.groupName] - (Optional) Group name, case sensitive. By default, UrBackup clients are added to group id 0 with name '' (empty string). Defaults to undefined, which matches all groups.
* @param {boolean} [params.includeRemoved] - (Optional) Whether or not clients pending deletion should be included. Defaults to true.
* @returns {Array} Array of objects representing clients matching search criteria. Empty array when no matching clients found.
* @example <caption>Get all clients</caption>
* server.getClients().then(data => console.log(data));
* @example <caption>Get all clients, but skip clients marked for removal</caption>
* server.getClients({includeRemoved: false}).then(data => console.log(data));
* @example <caption>Get all clients belonging to a specific group</caption>
* server.getClients({groupName: 'office'}).then(data => console.log(data));
*/
async getClients ({ groupName, includeRemoved = true } = {}) {
const returnValue = [];
const login = await this.#login();
if (login === true) {
const statusResponse = await this.#fetchJson('status');
if (Array.isArray(statusResponse?.status)) {
for (const client of statusResponse.status) {
if (typeof groupName !== 'undefined' && groupName !== client.groupname) {
continue;
}
if (includeRemoved === false && client.delete_pending === '1') {
continue;
}
returnValue.push({ id: client.id, name: client.name, group: client.groupname, deletePending: client.delete_pending });
}
return returnValue;
} else {
throw new Error('API response error: missing values');
}
} else {
throw new Error('Login failed: unknown reason');
}
}
/**
* Adds a new client.
*
* @param {Object} params - (Required) An object containing parameters.
* @param {string} params.clientName - (Required) Client's name, case sensitive. Defaults to undefined.
* @returns {boolean} When successfull, Boolean true. Boolean false when adding was not successfull, for example client already exists.
* @example <caption>Add new client</caption>
* server.addClient({clientName: 'laptop2'}).then(data => console.log(data));
*/
async addClient ({ clientName } = {}) {
if (typeof clientName === 'undefined') {
throw new Error('API call error: missing or invalid parameters');
}
if (clientName === '') {
return false;
}
const login = await this.#login();
if (login === true) {
const addClientResponse = await this.#fetchJson('add_client', { clientname: clientName });
if (addClientResponse?.ok === true) {
return addClientResponse.added_new_client === true;
} else {
throw new Error('API response error: missing values');
}
} else {
throw new Error('Login failed: unknown reason');
}
}
/**
* This method is not meant to be used outside the class.
* Used internally to mark/unmark client as ready for removal.
* Using client ID should be preferred to client name for repeated method calls.
*
* @param {Object} params - (Required) An object containing parameters.
* @param {number} params.clientId - (Required if clientName is undefined) Client's ID. Must be greater than 0. Takes precedence if both ```clientId``` and ```clientName``` are defined. Defaults to undefined.
* @param {string} params.clientName - (Required if clientId is undefined) Client's name, case sensitive. Ignored if both ```clientId``` and ```clientName``` are defined. Defaults to undefined.
* @param {boolean} params.stopRemove - {Required) Whether it's 'remove' or 'cancel remove' operation.
* @returns {boolean} When successfull, Boolean true. Boolean false when stopping was not successfull.
*/
async #removeClientCommon ({ clientId, clientName, stopRemove } = {}) {
if ((typeof clientId === 'undefined' && typeof clientName === 'undefined') || clientId <= 0 || typeof stopRemove === 'undefined') {
throw new Error('API call error: missing or invalid parameters');
}
if (clientName === '') {
return false;
}
const returnValue = false;
const login = await this.#login();
if (login === true) {
let mappedClientId;
if (typeof clientId === 'undefined') {
mappedClientId = await this.#getClientId(clientName);
if (mappedClientId === 0) {
return returnValue;
}
}
const apiCallParameters = { remove_client: clientId ?? mappedClientId };
if (stopRemove === true) {
apiCallParameters.stop_remove_client = true;
}
const statusResponse = await this.#fetchJson('status', apiCallParameters);
if (Array.isArray(statusResponse?.status)) {
return statusResponse.status.find(client => client.id === (clientId ?? mappedClientId))?.delete_pending === (stopRemove === true ? '0' : '1');
} else {
throw new Error('API response error: missing values');
}
} else {
throw new Error('Login failed: unknown reason');
}
}
/**
* Marks the client for removal.
* Actual removing happens during the cleanup in the cleanup time window. Until then, this operation can be reversed with ```cancelRemoveClient``` method.
* Using client ID should be preferred to client name for repeated method calls.
* WARNING: removing clients will also delete all their backups.
*
* @param {Object} params - (Required) An object containing parameters.
* @param {number} params.clientId - (Required if clientName is undefined) Client's ID. Must be greater than 0. Takes precedence if both ```clientId``` and ```clientName``` are defined. Defaults to undefined.
* @param {string} params.clientName - (Required if clientId is undefined) Client's name, case sensitive. Ignored if both ```clientId``` and ```clientName``` are defined. Defaults to undefined.
* @returns {boolean} When successfull, Boolean true. Boolean false when removing was not successfull.
* @example <caption>Remove client</caption>
* server.removeClient({clientId: 1}).then(data => console.log(data));
* server.removeClient({clientName: 'laptop2'}).then(data => console.log(data));
*/
async removeClient ({ clientId, clientName } = {}) {
const returnValue = await this.#removeClientCommon({ clientId, clientName, stopRemove: false });
return returnValue;
}
/**
* Unmarks the client as ready for removal.
* Using client ID should be preferred to client name for repeated method calls.
*
* @param {Object} params - (Required) An object containing parameters.
* @param {number} params.clientId - (Required if clientName is undefined) Client's ID. Must be greater than 0. Takes precedence if both ```clientId``` and ```clientName``` are defined. Defaults to undefined.
* @param {string} params.clientName - (Required if clientId is undefined) Client's name, case sensitive. Ignored if both ```clientId``` and ```clientName``` are defined. Defaults to undefined.
* @returns {boolean} When successfull, Boolean true. Boolean false when stopping was not successfull.
* @example <caption>Stop the server from removing a client by ID</caption>
* server.cancelRemoveClient({clientId: 1}).then(data => console.log(data));
* @example <caption>Stop the server from removing a client by name</caption>
* server.cancelRemoveClient({clientName: 'laptop2'}).then(data => console.log(data));
*/
async cancelRemoveClient ({ clientId, clientName } = {}) {
const returnValue = await this.#removeClientCommon({ clientId: clientId, clientName: clientName, stopRemove: true });
return returnValue;
}
/**
* Retrieves a list of client discovery hints, also known as extra clients.
*
* @returns {Array} Array of objects representing client hints. Empty array when no matching client hints found.
* @example <caption>Get extra clients</caption>
* server.getClientHints().then(data => console.log(data));
*/
async getClientHints () {
const login = await this.#login();
if (login === true) {
const statusResponse = await this.#fetchJson('status');
if (Array.isArray(statusResponse?.extra_clients)) {
return statusResponse.extra_clients;
} else {
throw new Error('API response error: missing values');
}
} else {
throw new Error('Login failed: unknown reason');
}
}
/**
* Adds a new client discovery hint, also known as extra client.
* Discovery hints are a way of improving client discovery in local area networks.
*
* @param {Object} params - (Required) An object containing parameters.
* @param {string} params.address - (Required) Client's IP address or hostname, case sensitive. Defaults to undefined.
* @returns {boolean} When successful, Boolean true. Boolean false when adding was not successful.
* @example <caption>Add new extra client</caption>
* server.addClientHint({address: '192.168.100.200'}).then(data => console.log(data));
*/
async addClientHint ({ address } = {}) {
if (typeof address === 'undefined' || address === '') {
throw new Error('API call error: missing or invalid parameters');
};
const login = await this.#login();
if (login === true) {
const statusResponse = await this.#fetchJson('status', { hostname: address });
if (Array.isArray(statusResponse?.extra_clients)) {
return statusResponse.extra_clients.some(extraClient => extraClient.hostname === address);
} else {
throw new Error('API response error: missing values');
}
} else {
throw new Error('Login failed: unknown reason');
}
}
/**
* Removes specific client discovery hint, also known as extra client.
*
* @param {Object} params - (Required) An object containing parameters.
* @param {string} params.address - (Required) Client's IP address or hostname, case sensitive. Defaults to undefined.
* @returns {boolean} When successful, Boolean true. Boolean false when removing was not successful.
* @example <caption>Remove extra client</caption>
* server.removeClientHint({address: '192.168.100.200'}).then(data => console.log(data));
*/
async removeClientHint ({ address } = {}) {
if (typeof address === 'undefined' || address === '') {
throw new Error('API call error: missing or invalid parameters');
};
let returnValue = false;
const login = await this.#login();
if (login === true) {
const extraClients = await this.getClientHints();
if (Array.isArray(extraClients)) {
const matchingClient = extraClients.find(extraClient => extraClient.hostname === address);
if (typeof matchingClient !== 'undefined') {
const statusResponse = await this.#fetchJson('status', { hostname: matchingClient.id, remove: true });
if (Array.isArray(statusResponse?.extra_clients)) {
if (typeof statusResponse.extra_clients.find(extraClient => extraClient.hostname === address) === 'undefined') {
returnValue = true;
}
} else {
throw new Error('API response error: missing values');
}
}
return returnValue;
} else {
throw new Error('API response error: missing values');
}
} else {
throw new Error('Login failed: unknown reason');
}
}
/**
* Retrieves client settings.
* Matches all clients by default, but ```clientId``` or ```clientName``` can be used to request settings for one particular client.
* Clients marked for removal are not excluded.
*
* @param {Object} [params] - (Optional) An object containing parameters.
* @param {number} [params.clientId] - (Optional) Client's ID. Must be greater than zero. Takes precedence if both ```clientId``` and ```clientName``` are defined. Defaults to undefined, which matches all clients if ```clientName``` is also undefined.
* @param {string} [params.clientName] - (Optional) Client's name, case sensitive. Ignored if both ```clientId``` and ```clientName``` are defined. Defaults to undefined, which matches all clients if ```clientId``` is also undefined.
* @returns {Array} Array with objects represeting client settings. Empty array when no matching client found.
* @example <caption>Get settings for all clients</caption>
* server.getClientSettings().then(data => console.log(data));
* @example <caption>Get settings for a specific client only</caption>
* server.getClientSettings({clientName: 'laptop1'}).then(data => console.log(data));
* server.getClientSettings({clientId: 3}).then(data => console.log(data));
*/
async getClientSettings ({ clientId, clientName } = {}) {
if (clientId <= 0) {
throw new Error('API call error: missing or invalid parameters');
}
const returnValue = [];
if (clientName === '') {
return returnValue;
}
const login = await this.#login();
if (login === true) {
const clientIds = [];
const allClients = await this.getClients({ includeRemoved: true });
if (allClients.some(client => typeof client.id === 'undefined')) {
throw new Error('API response error: missing values');
}
if (typeof clientId === 'undefined') {
for (const client of allClients) {
if (typeof clientName === 'undefined') {
clientIds.push(client.id);
} else {
if (client.name === clientName) {
clientIds.push(client.id);
break;
}
}
}
} else {
// need to make sure that given clientId really exists bacause 'clientsettings' API call returns settings even when called with invalid ID
if (allClients.some(client => client.id === clientId)) {
clientIds.push(clientId);
}
}
for (const id of clientIds) {
const settingsResponse = await this.#fetchJson('settings', { sa: 'clientsettings', t_clientid: id });
if (typeof settingsResponse?.settings === 'object') {
returnValue.push(settingsResponse.settings);
} else {
throw new Error('API response error: missing values');
}
}
return returnValue;
} else {
throw new Error('Login failed: unknown reason');
}
}
/**
* Changes one specific element of client settings.
* A list of settings can be obtained with ```getClientSettings``` method.
* Using client ID should be preferred to client name for repeated method calls.
*
* @param {Object} params - (Required) An object containing parameters.
* @param {number} params.clientId - (Required if clientName is undefined) Client's ID. Must be greater than 0. Takes precedence if both ```clientId``` and ```clientName``` are defined. Defaults to undefined.
* @param {string} params.clientName - (Required if clientId is undefined) Client's name, case sensitive. Ignored if both ```clientId``` and ```clientName``` are defined. Defaults to undefined.
* @param {string} params.key - (Required) Settings element to change. Defaults to undefined.
* @param {string|number|boolean} params.newValue - (Required) New value for settings element. Defaults to undefined.
* @returns {boolean} When successful, Boolean true. Boolean false when save request was unsuccessful or invalid key/value.
* @example <caption>Set directories to backup to be optional by default</caption>
* server.setClientSettings({clientName: 'laptop1', key: 'backup_dirs_optional', newValue: true}).then(data => console.log(data));
* server.setClientSettings({clientId: 3, key: 'backup_dirs_optional', newValue: true}).then(data => console.log(data));
*/
async setClientSettings ({ clientId, clientName, key, newValue } = {}) {
if ((typeof clientId === 'undefined' && typeof clientName === 'undefined') || clientId <= 0 || typeof key === 'undefined' || typeof newValue === 'undefined') {
throw new Error('API call error: missing or invalid parameters');
}
let returnValue = false;
if (clientName === '') {
return returnValue;
}
const login = await this.#login();
if (login === true) {
const clientSettings = await this.getClientSettings(typeof clientId === 'undefined' ? { clientName: clientName } : { clientId: clientId });
if (Array.isArray(clientSettings) && clientSettings.length > 0) {
if (Object.keys(clientSettings[0]).includes(key)) {
clientSettings[0][key] = newValue;
clientSettings[0].overwrite = true;
clientSettings[0].sa = 'clientsettings_save';
clientSettings[0].t_clientid = clientSettings[0].clientid;
const saveSettingsResponse = await this.#fetchJson('settings', clientSettings[0]);
if (typeof saveSettingsResponse?.saved_ok === 'boolean') {
returnValue = saveSettingsResponse.saved_ok === true;
} else {
throw new Error('API response error: missing values');
}
}
return returnValue;
} else {
throw new Error('API response error: missing values');
}
} else {
throw new Error('Login failed: unknown reason');
}
}
/**
* Retrieves authentication key for a specified client.
* Using client ID should be preferred to client name for repeated method calls.
*
* @param {Object} params - (Required) An object containing parameters.
* @param {number} params.clientId - (Required if clientName is undefined) Client's ID. Must be greater than 0. Takes precedence if both ```clientId``` and ```clientName``` are defined. Defaults to undefined.
* @param {string} params.clientName - (Required if clientId is undefined) Client's name, case sensitive. Ignored if both ```clientId``` and ```clientName``` are defined. Defaults to undefined.
* @returns {string} Client's authentication key. Empty string when no matching clients found.
* @example <caption>Get authentication key for a specific client</caption>
* server.getClientAuthkey({clientName: 'laptop1'}).then(data => console.log(data));
* server.getClientAuthkey({clientId: 3}).then(data => console.log(data));
*/
async getClientAuthkey ({ clientId, clientName } = {}) {
if ((typeof clientId === 'undefined' && typeof clientName === 'undefined') || clientId <= 0) {
throw new Error('API call error: missing or invalid parameters');
}
let returnValue = '';
if (clientName === '') {
return returnValue;
}
const login = await this.#login();
if (login === true) {
const clientSettings = await this.getClientSettings(typeof clientId === 'undefined' ? { clientName: clientName } : { clientId: clientId });
if (Array.isArray(clientSettings)) {
if (clientSettings.length > 0) {
if (typeof clientSettings[0]?.internet_authkey === 'string') {
returnValue = clientSettings[0].internet_authkey.toString();
}
}
return returnValue;
} else {
throw new Error('API response error: missing values');
}
} else {
throw new Error('Login failed: unknown reason');
}
}
/**
* Retrieves backup status.
* Matches all clients by default, including clients marked for removal.
* Client name or client ID can be passed as an argument in which case only that one client's status is returned.
*
* @param {Object} [params] - (Optional) An object containing parameters.
* @param {number} [params.clientId] - (Optional) Client's ID. Must be greater than 0. Takes precedence if both ```clientId``` and ```clientName``` are defined. Defaults to undefined, which matches all clients if ```clientId``` is also undefined.
* @param {string} [params.clientName] - (Optional) Client's name, case sensitive. Ignored if both ```clientId``` and ```clientName``` are defined. Defaults to undefined, which matches all clients if ```clientName``` is also undefined.
* @param {boolean} [params.includeRemoved] - (Optional) Whether or not clients pending deletion should be included. Defaults to true.
* @returns {Array} Array of objects with status info for matching clients. Empty array when no matching clients found.
* @example <caption>Get status for all clients</caption>
* server.getStatus().then(data => console.log(data));
* @example <caption>Get status for all clients, but skip clients marked for removal</caption>
* server.getStatus({includeRemoved: false}).then(data => console.log(data));
* @example <caption>Get status for a specific client only</caption>
* server.getStatus({clientName: 'laptop1'}).then(data => console.log(data));
* server.getStatus({clientId: 3}).then(data => console.log(data));
*/
async getStatus ({ clientId, clientName, includeRemoved = true } = {}) {
const defaultReturnValue = [];
if (clientName === '') {
return defaultReturnValue;
}
const login = await this.#login();
if (login === true) {
const statusResponse = await this.#fetchJson('status');
if (Array.isArray(statusResponse?.status)) {
if (typeof clientId === 'undefined' && typeof clientName === 'undefined') {
if (includeRemoved === false) {
return statusResponse.status.filter(client => client.delete_pending !== '1');
} else {
return statusResponse.status;
}
} else {
const clientStatus = statusResponse.status.find(client => typeof clientId !== 'undefined' ? client.id === clientId : client.name === clientName);
if (typeof clientStatus !== 'undefined') {
return (includeRemoved === false && clientStatus.delete_pending === '1') ? defaultReturnValue : [clientStatus];
} else {
return defaultReturnValue;
}
}
} else {
throw new Error('API response error: missing values');
}
} else {
throw new Error('Login failed: unknown reason');
}
}
/**
* Retrieves storage usage.
* Matches all clients by default, but ```clientName``` OR ```clientId``` can be used to request usage for one particular client.
* Using client ID should be preferred to client name for repeated method calls.
*
* @param {Object} [params] - (Optional) An object containing parameters.
* @param {number} [params.clientId] - (Optional) Client's ID. Must be greater than 0. Takes precedence if both ```clientId``` and ```clientName``` are defined. Defaults to undefined, which matches all clients if ```clientId``` is also undefined.
* @param {string} [params.clientName] - (Optional) Client's name, case sensitive. Ignored if both ```clientId``` and ```clientName``` are defined. Defaults to undefined, which matches all clients if ```clientName``` is also undefined.
* @returns {Array} Array of objects with storage usage info for each client. Empty array when no matching clients found.
* @example <caption>Get usage for all clients</caption>
* server.getUsage().then(data => console.log(data));
* @example <caption>Get usage for a specific client only</caption>
* server.getUsage({clientName: 'laptop1'}).then(data => console.log(data));
* server.getUsage({clientId: 3}).then(data => console.log(data));
*/
async getUsage ({ clientId, clientName } = {}) {
const defaultReturnValue = [];
if (clientName === '') {
return defaultReturnValue;
}
const login = await this.#login();
if (login === true) {
const usageResponse = await this.#fetchJson('usage');
if (Array.isArray(usageResponse?.usage)) {
if (typeof clientId === 'undefined' && typeof clientName === 'undefined') {
return usageResponse.usage;
} else {
let mappedClientName;
if (typeof clientId !== 'undefined') {
// usage response does not contain a property with client ID so translation to client name is needed
mappedClientName = await this.#getClientName(clientId);
}
return usageResponse.usage.find(client => typeof clientId !== 'undefined' ? client.name === mappedClientName : client.name === clientName) ?? defaultReturnValue;
}
} else {
throw new Error('API response error: missing values');
}
} else {
throw new Error('Login failed: unknown reason');
}
}
/**
* Retrieves a list of current and/or past activities.
* Matches all clients by default, but ```clientName``` or ```clientId``` can be used to request activities for one particular client.
* By default this method returns only activities that are currently in progress and skips last activities.
*
* @param {Object} [params] - (Optional) An object containing parameters.
* @param {number} [params.clientId] - (Optional) Client's ID. Takes precedence if both ```clientId``` and ```clientName``` are defined. Defaults to undefined, which matches all clients if ```clientId``` is also undefined.
* @param {string} [params.clientName] - (Optional) Client's name, case sensitive. Ignored if both ```clientId``` and ```clientName``` are defined. Defaults to undefined, which matches all clients if ```clientName``` is also undefined.
* @param {boolean} [params.includeCurrent] - (Optional) Whether or not currently running activities should be included. Defaults to true.
* @param {boolean} [params.includePast] - (Optional) Whether or not past activities should be included. Defaults to false.
* @returns {Object} Object with activities info in two separate arrays (one for current and one for past activities). Object with empty arrays when no matching clients/activities found.
* @example <caption>Get current (in progress) activities for all clients</caption>
* server.getActivities().then(data => console.log(data));
* @example <caption>Get past activities for all clients</caption>
* server.getActivities({includeCurrent: false, includePast: true}).then(data => console.log(data));
* @example <caption>Get current (in progress) activities for a specific client only</caption>
* server.getActivities({clientName: 'laptop1'}).then(data => console.log(data));
* server.getActivities({clientId: 3}).then(data => console.log(data));
* @example <caption>Get all activities for a specific client only</caption>
* server.getActivities({clientName: 'laptop1', includeCurrent: true, includePast: true}).then(data => console.log(data));
* server.getActivities({clientId: '3', includeCurrent: true, includePast: true}).then(data => console.log(data));
*/
async getActivities ({ clientId, clientName, includeCurrent = true, includePast = false } = {}) {
const returnValue = { current: [], past: [] };
if (clientName === '') {
return returnValue;
}
if (includeCurrent === false && includePast === false) {
return returnValue;
}
const login = await this.#login();
if (login === true) {
const activitiesResponse = await this.#fetchJson('progress');
if (Array.isArray(activitiesResponse?.progress) && Array.isArray(activitiesResponse?.lastacts)) {
if (includeCurrent === true) {
if (typeof clientId === 'undefined' && typeof clientName === 'undefined') {
returnValue.current = activitiesResponse.progress;
} else {
returnValue.current = activitiesResponse.progress.filter(activity => typeof clientId !== 'undefined' ? activity.clientid === clientId : activity.name === clientName);
}
}
if (includePast === true) {
if (typeof clientId === 'undefined' && typeof clientName === 'undefined') {
returnValue.past = activitiesResponse.lastacts;
} else {
returnValue.past = activitiesResponse.lastacts.filter(activity => typeof clientId !== 'undefined' ? activity.clientid === clientId : activity.name === clientName);
}
}
return returnValue;
} else {
throw new Error('API response error: missing values');
}
} else {
throw new Error('Login failed: unknown reason');
}
}
/**
* Stops one activity.
* A list of current activities can be obtained with ```getActivities``` method.
* Using client ID should be preferred to client name for repeated method calls.
*
* @param {Object} params - (Required) An object containing parameters.
* @param {number} params.clientId - (Required if clientName is undefined) Client's ID. Must be greater than 0. Takes precedence if both ```clientId``` and ```clientName``` are defined. Defaults to undefined.
* @param {string} params.clientName - (Required if clientId is undefined) Client's name, case sensitive. Ignored if both ```clientId``` and ```clientName``` are defined. Defaults to undefined.
* @param {number} params.activityId - (Required) Activity ID. Defaults to undefined.
* @returns {boolean} When successful, Boolean true. Boolean false when stopping was not successful.
* @example <caption>Stop activity</caption>
* server.stopActivity({clientName: 'laptop1', activityId: 42}).then(data => console.log(data));
* server.stopActivity({clientId: 3, activityId: 42}).then(data => console.log(data));
*/
async stopActivity ({ clientId, clientName, activityId } = {}) {
if ((typeof clientId === 'undefined' && typeof clientName === 'undefined') || clientId <= 0 || typeof activityId === 'undefined' || activityId <= 0) {
throw new Error('API call error: missing or invalid parameters');
}
if (clientName === '') {
return false;
}
const login = await this.#login();
if (login === true) {
let mappedClientId;
if (typeof clientId === 'undefined' && typeof clientName !== 'undefined') {
mappedClientId = await this.#getClientId(clientName);
}
if ((typeof clientId !== 'undefined' && clientId > 0) || (typeof mappedClientId !== 'undefined' && mappedClientId > 0)) {
const activitiesResponse = await this.#fetchJson('progress', { stop_clientid: clientId ?? mappedClientId, stop_id: activityId });
if (Array.isArray(activitiesResponse?.progress) && Array.isArray(activitiesResponse?.lastacts)) {
return true;
} else {
throw new Error('API response error: missing values');
}
} else {
return false;
}
} else {
throw new Error('Login failed: unknown reason');
}
}
/**
* Retrieves a list of file and/or image backups for a specific client.
* Using client ID should be preferred to client name for repeated method calls.
*
* @param {Object} params - (Required) An object containing parameters.
* @param {number} params.clientId - (Required if clientName is undefined) Client's ID. Must be greater than 0. Takes precedence if both ```clientId``` and ```clientName``` are defined. Defaults to undefined.
* @param {string} params.clientName - (Required if clientId is undefined) Client's name, case sensitive. Ignored if both ```clientId``` and ```clientName``` are defined. Defaults to undefined.
* @param {boolean} [params.includeFileBackups] - (Optional) Whether or not file backups should be included. Defaults to true.
* @param {boolean} [params.includeImageBackups] - (Optional) Whether or not image backups should be included. Defaults to true.
* @returns {Object} Object with backups info. Object with empty arrays when no matching clients/backups found.
* @example <caption>Get all backups for a specific client</caption>
* server.getBackups({clientName: 'laptop1'}).then(data => console.log(data));
* server.getBackups({clientId: 3}).then(data => console.log(data));
* @example <caption>Get image backups for a specific client</caption>
* server.getBackups({clientName: 'laptop1', includeFileBackups: false}).then(data => console.log(data));
* @example <caption>Get file backups for a specific client</caption>
* server.getBackups({clientName: 'laptop1', includeImageBackups: false}).then(data => console.log(data));
*/
async getBackups ({ clientId, clientName, includeFileBackups = true, includeImageBackups = true } = {}) {
if ((typeof clientId === 'undefined' && typeof clientName === 'undefined') || clientId <= 0 || (includeFileBackups === false && includeImageBackups === false)) {
throw new Error('API call error: missing or invalid parameters');
}
const returnValue = { file: [], image: [] };
if (clientName === '') {
return returnValue;
}
const login = await this.#login();
if (login === true) {
let mappedClientId;
if (typeof clientId === 'undefined' && typeof clientName !== 'undefined') {
mappedClientId = await this.#getClientId(clientName);
}
if ((typeof clientId !== 'undefined' && clientId > 0) || (typeof mappedClientId !== 'undefined' && mappedClientId > 0)) {
const backupsResponse = await this.#fetchJson('backups', { sa: 'backups', clientid: clientId ?? mappedClientId });
if (Array.isArray(backupsResponse?.backup_images) && Array.isArray(backupsResponse?.backups)) {
if (includeFileBackups === true) {
returnValue.file = backupsResponse.backups;
}
if (includeImageBackups === true) {
returnValue.image = backupsResponse.backup_images;
}
return returnValue;
} else {
throw new Error('API response error: missing values');
}
} else {
throw new Error('API response error: missing values');
}
} else {
throw new Error('Login failed: unknown reason');
}
}
/**
* This method is not meant to be used outside the class.
* Starts a backup job.
* Using client ID should be preferred to client name for repeated method calls.
*
* @param {Object} params - (Required) An object containing parameters.
* @param {number} params.clientId - (Required if clientName is undefined) Client's ID. Must be greater than 0. Takes precedence if both ```clientId``` and ```clientName``` are defined. Defaults to undefined.
* @param {string} params.clientName - (Required if clientId is undefined) Client's name, case sensitive. Ignored if both ```clientId``` and ```clientName``` are defined. Defaults to undefined.
* @param {string} params.backupType - (Required) backup type, case sensitive. Defaults to undefined.
* @returns {boolean} When successful, Boolean true. Boolean false when starting was not successful.
*/
async #startBackupCommon ({ clientId, clientName, backupType } = {}) {
const backupTypes = ['full_file', 'incr_file', 'full_image', 'incr_image'];
if ((typeof clientId === 'undefined' && typeof clientName === 'undefined') || clientId <= 0 || !backupTypes.includes(backupType)) {
throw new Error('API call error: missing or invalid parameters');
}
if (clientName === '') {
return false;
}
const login = await this.#login();
if (login === true) {
let mappedClientId;
if (typeof clientId === 'undefined' && typeof clientName !== 'undefined') {
mappedClientId = await this.#getClientId(clientName);
}
if ((typeof clientId !== 'undefined' && clientId > 0) || (typeof mappedClientId !== 'undefined' && mappedClientId > 0)) {
const backupResponse = await this.#fetchJson('start_backup', { start_client: clientId ?? mappedClientId, start_type: backupType });
if (Array.isArray(backupResponse.result) && backupResponse.result.filter(element => Object.keys(element).includes('start_ok')).length !== 1) {
return !!backupResponse.result[0].start_ok;
} else {
throw new Error('API response error: missing values');
}
} else {
return false;
}
} else {
throw new Error('Login failed: unknown reason');
}
}
/**
* Starts full file backup.
* Using client ID should be preferred to client name for repeated method calls.
*
* @param {Object} params - (Required) An object containing parameters.
* @param {number} params.clientId - (Required if clientName is undefined) Client's ID. Must be greater than 0. Takes precedence if both ```clientId``` and ```clientName``` are defined. Defaults to undefined.
* @param {string} params.clientName - (Required if clientId is undefined) Client's name, case sensitive. Ignored if both ```clientId``` and ```clientName``` are defined. Defaults to undefined.
* @returns {boolean} When successful, Boolean true. Boolean false when starting was not successful.
* @example <caption>Start backup</caption>
* server.startFullFileBackup({clientName: 'laptop1').then(data => console.log(data));
* server.startFullFileBackup({clientId: 3).then(data => console.log(data));
*/
async startFullFileBackup ({ clientId, clientName } = {}) {
const returnValue = await this.#startBackupCommon({ clientId: clientId, clientName: clientName, backupType: 'full_file' });
return returnValue;
}
/**
* Starts incremental file backup.
* Using client ID should be preferred to client name for repeated method calls.
*
* @param {Object} params - (Required) An object containing parameters.
* @param {number} params.clientId - (Required if clientName is undefined) Client's ID. Must be greater than 0. Takes precedence if both ```clientId``` and ```clientName``` are defined. Defaults to undefined.
* @param {string} params.clientName - (Required if clientId is undefined) Client's name, case sensitive. Ignored if both ```clientId``` and ```clientName``` are defined. Defaults to undefined.
* @returns {boolean} When successful, Boolean true. Boolean false when starting was not successful.
* @example <caption>Start backup</caption>
* server.startIncrementalFileBackup({clientName: 'laptop1').then(data => console.log(data));
* server.startIncrementalFileBackup({clientId: 3).then(data => console.log(data));
*/
async startIncrementalFileBackup ({ clientId, clientName } = {}) {
const returnValue = await this.#startBackupCommon({ clientId: clientId, clientName: clientName, backupType: 'incr_file' });
return returnValue;
}
/**
* Starts full image backup.
* Using client ID should be preferred to client name for repeated method calls.
*
* @param {Object} params - (Required) An object containing parameters.
* @param {number} params.clientId - (Required if clientName is undefined) Client's ID. Must be greater than 0. Takes precedence if both ```clientId``` and ```clientName``` are defined. Defaults to undefined.
* @param {string} params.clientName - (Required if clientId is undefined) Client's name, case sensitive. Ignored if both ```clientId``` and ```clientName``` are defined. Defaults to undefined.
* @returns {boolean} When successful, Boolean true. Boolean false when starting was not successful.
* @example <caption>Start backup</caption>
* server.startFullImageBackup({clientName: 'laptop1').then(data => console.log(data));
* server.startFullImageBackup({clientId: 3).then(data => console.log(data));
*/
async startFullImageBackup ({ clientId, clientName } = {}) {
const returnValue = await this.#startBackupCommon({ clientId: clientId, clientName: clientName, backupType: 'full_image' });
return returnValue;
}
/**
* Starts incremental image backup.
* Using client ID should be preferred to client name for repeated method calls.
*
* @param {Object} params - (Required) An object containing parameters.
* @param {number} params.clientId - (Required if clientName is undefined) Client's ID. Must be greater than 0. Takes precedence if both ```clientId``` and ```clientName``` are defined. Defaults to undefined.
* @param {string} params.clientName - (Required if clientId is undefined) Client's name, case sensitive. Ignored if both ```clientId``` and ```clientName``` are defined. Defaults to undefined.
* @returns {boolean} When successful, Boolean true. Boolean false when starting was not successful.
* @example <caption>Start backup</caption>
* server.startIncrementalImageBackup({clientName: 'laptop1').then(data => console.log(data));
* server.startIncrementalImageBackup({clientId: 3).then(data => console.log(data));
*/
async startIncrementalImageBackup ({ clientId, clientName } = {}) {
const returnValue = await this.#startBackupCommon({ clientId: clientId, clientName: clientName, backupType: 'incr_image' });
return returnValue;
}
/**
* Retrieves live logs.
* Server logs are requested by default, but ```clientName``` or ```clientId``` can be used to request logs for one particular client.
* Instance property is being used internally to keep track of log entries that were previously requested.
* When ```recentOnly``` is set to true, then only recent (unfetched) logs are requested.
* Using client ID should be preferred to client name for repeated method calls.
*
* @param {Object} [params] - (Optional) An object containing parameters.
* @param {number} [params.clientId] - (Optional) Client's ID. Takes precedence if both ```clientId``` and ```clientName``` are defined. Defaults to undefined, which means server logs will be requested if ```clientId``` is also undefined.
* @param {string} [params.clientName] - (Optional) Client's name, case sensitive. Ignored if both ```clientId``` and ```clientName``` are defined. Defaults to undefined, which means server logs will be requested if ```clientName``` is also undefined.
* @param {boolean} [params.recentOnly] - (Optional) Whether or not only recent (unfetched) entries should be requested. Defaults to false.
* @returns {Array} Array of objects representing log entries. Empty array when no matching clients or logs found.
* @example <caption>Get server logs</caption>
* server.getLiveLog().then(data => console.log(data));
* @example <caption>Get logs for a specific client only</caption>
* server.getLiveLog({clientName: 'laptop1'}).then(data => console.log(data));
* server.getLiveLog({clientId: 3}).then(data => console.log(data));
* @example <caption>Get logs for a specific client only, but skip previously fetched logs</caption>
* server.getLiveLog({clientName: 'laptop1', recentOnly: true}).then(data => console.log(data));
*/
async getLiveLog ({ clientId, clientName, recentOnly = false } = {}) {
let returnValue = [];
if (clientName === '') {
return returnValue;
}
const login = await this.#login();
if (login === true) {
let mappedClientId;
if (typeof clientId === 'undefined' && typeof clientName !== 'undefined') {
mappedClientId = await this.#getClientId(clientName);
}
if (clientId === 0 || mappedClientId === 0) {
// fail early to distinguish this case bacause 0 (zero) is a valid parameter value for 'livelog' call which should be used when both clientId and clientName are undefined
return returnValue;
}
// Use semaphore to prevent race condition with this.#lastLogId
// eslint-disable-next-line no-unused-vars
const [value, release] = await this.#semaphore.acquire();
try {
const logResponse = await this.#fetchJson('livelog', { clientid: clientId ?? mappedClientId ?? 0, lastid: recentOnly === false ? 0 : this.#lastLogId.get(clientId) });
if (Array.isArray(logResponse.logdata)) {
const lastId = logResponse.logdata.slice(-1)[0]?.id;
if (typeof lastId !== 'undefined') {
this.#lastLogId.set(clientId, lastId);
}
returnValue = logResponse.logdata;
} else {
throw new Error('API response error: missing values');
}
} finally {
release();
}
return returnValue;
} else {
throw new Error('Login failed: unknown reason');
}
}
/**
* Retrieves general settings.
*
* @returns {Object} Object with general settings.
* @example <caption>Get general settings</caption>
* server.getGeneralSettings().then(data => console.log(data));
*/
async getGeneralSettings () {
const login = await this.#login();
if (login === true) {
const settingsResponse = await this.#fetchJson('settings', { sa: 'general' });
if (typeof settingsResponse?.settings === 'object') {
return settingsResponse.settings;
} else {
throw new Error('API response error: missing values');
}
} else {
throw new Error('Login failed: unknown reason');
}
}
/**
* Changes one specific element of general settings.
* A list of settings can be obtained with ```getGeneralSettings``` method.
*
* @param {Object} params - (Required) An object containing parameters.
* @param {string} params.key - (Required) Settings element to change. Defaults to undefined.
* @param {string|number|boolean} params.newValue - (Required) New value for settings element. Defaults to undefined.
* @returns {boolean} When successful, Boolean true. Boolean false when save request was unsuccessful or invalid key/value.
* @example <caption>Disable image backups</caption>
* server.setGeneralSettings({key: 'no_images', newValue: true}).then(data => console.log(data));
*/
async setGeneralSettings ({ key, newValue } = {}) {
if (typeof key === 'undefined' || typeof newValue === 'undefined') {
throw new Error('API call error: missing or invalid parameters');
}
const login = await this.#login();
if (login === true) {
const settings = await this.getGeneralSettings();
if (Object.keys(settings).includes(key)) {
settings[key] = newValue;
settings.sa = 'general_save';
const saveSettingsResponse = await this.#fetchJson('settings', settings);
if (typeof saveSettingsResponse?.saved_ok === 'boolean') {
return saveSettingsResponse.saved_ok;
} else {
throw new Error('API response error: missing values');
}
} else {
return false;
}
} else {
throw new Error('Login failed: unknown reason');
}
}
} |
JavaScript | class Index {
//
// Constructor.
/**
* @constructor
* @param {Collection} collection Collection to which this index is
* associated.
* @param {string} field Name of the field to be index.
* @param {Connection} connection Collection in which it's stored.
*/
constructor(collection, field, connection) {
//
// Protected properties.
this._collection = null;
this._connected = false;
this._connection = null;
this._data = {};
this._field = null;
this._resourcePath = null;
this._skipSave = false;
this._subLogicErrors = null;
/**
* This methods provides a proper value for string auto-castings.
*
* @method toString
* @returns {string} Returns a simple string identifying this index.
*/
this.toString = () => {
return `index:${this._field}`;
};
//
// Shortcuts.
this._field = field;
this._collection = collection;
this._connection = connection;
//
// Main path.
this._resourcePath = `${this._collection.name()}/${this._field}.idx`;
//
// Sub-logics.
this._subLogicErrors = new errors_sl_dfdb_1.SubLogicErrors(this);
}
//
// Public methods.
/**
* This method takes a document and adds into this index if it contains the
* index field.
*
* @method addDocument
* @param {DBDocument} doc Document to be indexed.
* @returns {Promise<void>} Return a promise that gets resolved when the
* operation finishes.
*/
addDocument(doc) {
//
// This anonymous function takes a value for a index entry and adds the
// given document ID to it.
const addValue = (value) => {
//
// Value should be indexed in lower case for case-insensitive search.
value = `${value}`.toLowerCase();
//
// Is it a new index value?
if (typeof this._data[value] === 'undefined') {
this._data[value] = [doc._id];
}
else {
//
// Is it already indexed for this value?
if (this._data[value].indexOf(doc._id) < 0) {
this._data[value].push(doc._id);
this._data[value].sort();
}
}
};
//
// Restarting error messages.
this._subLogicErrors.resetError();
//
// Building promise to return.
return new es6_promise_1.Promise((resolve, reject) => {
//
// Parsing object for the right field.
const jsonPathValues = jsonpath({ json: doc, path: `\$.${this._field}` });
//
// Is it connected and is it the required field present?
if (this._connected && typeof jsonPathValues[0] !== 'undefined') {
//
// If it's an array, each element should be indexes separately.
if (Array.isArray(jsonPathValues[0])) {
//
// Indexing each value.
jsonPathValues[0].forEach((value) => {
if (typeof value !== 'object') {
addValue(value);
}
});
//
// Saving data on file.
this.save()
.then(resolve)
.catch(reject);
}
else if (typeof jsonPathValues[0] === 'object' && jsonPathValues[0] !== null) {
//
// At this point, if the value is an object, it cannot be
// indexed and should be treated as an error.
this._subLogicErrors.setLastRejection(new rejection_dfdb_1.Rejection(rejection_codes_dfdb_1.RejectionCodes.NotIndexableValue));
reject(this._subLogicErrors.lastRejection());
}
else {
//
// Indexing field's value.
addValue(jsonPathValues[0]);
//
// Saving data on file.
this.save()
.then(resolve)
.catch(reject);
}
}
else if (!this._connected) {
this._subLogicErrors.setLastRejection(new rejection_dfdb_1.Rejection(rejection_codes_dfdb_1.RejectionCodes.IndexNotConnected));
reject(this._subLogicErrors.lastRejection());
}
else {
//
// IF the required field isn't present, the given document is
// ignored.
resolve();
}
});
}
/**
* Creating an index object doesn't mean it is connected to physical
* information, this method does that.
* It connects and loads information from the physical storage in zip file.
*
* @method connect
* @returns {Promise<void>} Return a promise that gets resolved when the
* operation finishes.
*/
connect() {
//
// Restarting error messages.
this._subLogicErrors.resetError();
//
// Building promise to return.
return new es6_promise_1.Promise((resolve, reject) => {
//
// Is it connected?
if (!this._connected) {
//
// Setting default data.
this._data = {};
//
// Retrieving data from zip.
this._connection.loadFile(this._resourcePath)
.then((results) => {
//
// Did it return any data?
if (results.error) {
//
// Setting as connected.
this._connected = true;
//
// Forcing to save.
this._connected = true;
//
// Physically saving data.
this.save()
.then(resolve)
.catch(reject);
}
else {
//
// Sanitization.
results.data = results.data ? results.data : '';
//
// Parsing data.
results.data.split('\n')
.filter(line => line != '')
.forEach(line => {
const pieces = line.split('|');
const key = pieces.shift();
this._data[key] = pieces;
});
//
// Setting as connected.
this._connected = true;
resolve();
}
});
}
else {
//
// If it's not connected, nothing is done.
resolve();
}
});
}
/**
* This method saves current data and then closes this index.
*
* @method close
* @returns {Promise<void>} Return a promise that gets resolved when the
* operation finishes.
*/
close() {
//
// Restarting error messages.
this._subLogicErrors.resetError();
//
// Building promise to return.
return new es6_promise_1.Promise((resolve, reject) => {
//
// Is it connected?
if (this._connected) {
//
// Saving data on file.
this.save()
.then(() => {
//
// Freeing memory
this._data = {};
//
// Disconnecting this index.
this._connected = false;
resolve();
})
.catch(reject);
}
else {
//
// If it's not connected, nothing is done.
resolve();
}
});
}
/**
* This method removes this index from its connection and erases all
* traces of it.
*
* @method drop
* @returns {Promise<void>} Return a promise that gets resolved when the
* operation finishes.
*/
drop() {
//
// Restarting error messages.
this._subLogicErrors.resetError();
//
// Building promise to return.
return new es6_promise_1.Promise((resolve, reject) => {
//
// Is it connected?
if (this._connected) {
this._connection.removeFile(this._resourcePath)
.then(() => {
// no need to ask collection to forget this index because it's the
// collection's responsibillity to invoke this method and then
// forget it.
this._connected = false;
resolve();
})
.catch(reject);
}
else {
//
// If it's not connected, nothing is done.
resolve();
}
});
}
/**
* Provides a way to know if there was an error in the last operation.
*
* @method error
* @returns {boolean} Returns TRUE when there was an error.
*/
error() {
//
// Forwarding to sub-logic.
return this._subLogicErrors.error();
}
/**
* This method searches for document IDs associated to a certain value or
* piece of value.
*
* @method find
* @param {ConditionsList} conditions List of conditions to check.
* @returns {Promise<string[]>} Returns a promise that gets resolve when the
* search completes. In the promise it returns the list of found document IDs.
*/
find(conditions) {
//
// Restarting error messages.
this._subLogicErrors.resetError();
//
// Building promise to return.
return new es6_promise_1.Promise((resolve, reject) => {
//
// Selecting only those conditions that apply to this index.
const conditionsToUse = [];
conditions.forEach((cond) => {
if (this._field === cond.field()) {
conditionsToUse.push(cond);
}
});
//
// Initializing a list of findings.
let findings = [];
//
// Checking every index value becuase the one being search may be
// equal or contained in it.
Object.keys(this._data).forEach((indexValue) => {
//
// Check all conditions against current value.
let allValid = true;
conditionsToUse.forEach((cond) => {
allValid = allValid && cond.validate(indexValue);
});
//
// Does current condition applies?
if (allValid) {
//
// Adding IDs.
findings = findings.concat(this._data[indexValue]);
}
});
//
// Removing duplicates.
findings = Array.from(new Set(findings));
//
// Finishing and returning found IDs.
resolve(findings);
});
}
/**
* Provides access to the error message registed by the last operation.
*
* @method lastError
* @returns {string|null} Returns an error message.
*/
lastError() {
//
// Forwarding to sub-logic.
return this._subLogicErrors.lastError();
}
/**
* Provides access to the rejection registed by the last operation.
*
* @method lastRejection
* @returns {Rejection} Returns an rejection object.
*/
lastRejection() {
//
// Forwarding to sub-logic.
return this._subLogicErrors.lastRejection();
}
/**
* This method unindexes a document from this index.
*
* @method removeDocument
* @param {string} id ID of the documento to remove.
* @returns {Promise<void>} Return a promise that gets resolved when the
* operation finishes.
*/
removeDocument(id) {
//
// Restarting error messages.
this._subLogicErrors.resetError();
//
// Building promise to return.
return new es6_promise_1.Promise((resolve, reject) => {
//
// Checking each indexed value because it may point to the document
// to remove.
Object.keys(this._data).forEach(key => {
//
// Does it have it?
const idx = this._data[key].indexOf(id);
if (idx > -1) {
this._data[key].splice(idx, 1);
}
//
// If current value is empty, it should get forgotten.
if (this._data[key].length === 0) {
delete this._data[key];
}
});
//
// Saving changes.
this.save()
.then(resolve)
.catch(reject);
});
}
/**
* When the physical file saving is trigger by a later action, this method
* avoids next file save attempt for this sequence.
*
* @method skipSave
*/
skipSave() {
this._skipSave = true;
}
/**
* This method removes all data of this index.
*
* @method truncate
* @returns {Promise<void>} Return a promise that gets resolved when the
* operation finishes.
*/
truncate() {
//
// Restarting error messages.
this._subLogicErrors.resetError();
//
// Building promise to return.
return new es6_promise_1.Promise((resolve, reject) => {
//
// Is it connected?
if (this._connected) {
//
// Freeing memory.
this._data = {};
//
// Saving changes.
this.save()
.then(resolve)
.catch(reject);
}
else {
//
// If it's not connected, nothing is done.
resolve();
}
});
}
//
// Protected methods.
/**
* This method triggers the physical saving of this index file.
*
* @protected
* @method save
* @returns {Promise<void>} Return a promise that gets resolved when the
* operation finishes.
*/
save() {
//
// Building promise to return.
return new es6_promise_1.Promise((resolve, reject) => {
let data = [];
//
// Converting data into a list of strings that can be physically
// stored.
Object.keys(this._data).forEach(key => {
data.push(`${key}|${this._data[key].join('|')}`);
});
//
// Saving file.
this._connection.updateFile(this._resourcePath, data.join('\n'), this._skipSave)
.then((results) => {
//
// Skipped once.
this._skipSave = false;
resolve();
})
.catch(reject);
});
}
} |
JavaScript | class Champernowne {
/**
* Get the nth digit of the Champernowne constant,
* counting the first zero before the decimal place as digit one.
*
* @param int n must be 1 or greater
* @return int
*/
getDigit(n) {
if (typeof n !== 'number' || n % 1 !== 0 || n <= 0) {
return Infinity;
}
let d = 0; // digit count of the number at position n
let count = 0; // running tally of total characters needed
do {
d++;
count += this.getNumChars(d);
} while(n > count);
let pivotChar = count - this.getNumChars(d);
let offset = Math.ceil((n - pivotChar) / d);
let number = offset + (d === 1 ? 0 : 10 ** (d - 1)) - 1;
let numOffset = n - ((pivotChar + 1) + ((offset - 1) * d));
return ('' + number)[numOffset];
}
/**
* Get the number of characters that are needed
* to represent the entire range of n-digit numbers.
*
* e.g. for 3-digit numbers, 2700 characters are needed
*
* Assumes base 10.
*
* @param int n number of digits
* @return int number of characters needed
*/
getNumChars(n) {
let range = (10 ** n);
if (n > 1) { range -= (10 ** (n - 1)); }
return range * n;
}
/**
* Naively build the Champernowne string to test
*
* @param int n
* @return int
*/
testDigit(n) {
let s = '';
let i = -1;
while(s.length < n) { s += ++i; }
return s.slice(n - 1, n);
}
/**
* Compare the digit returned by naively building the string
* vs the digit returned from the algorithm.
*
* Tests the first n digits.
*
* @param int n number of digits to test
* @return void
*/
testCorrectness(n) {
console.log(`Running tests for first ${n} digits...`);
let testDigit, getDigit;
for (let i = 1; i < n; i++) {
testDigit = this.testDigit(i);
getDigit = this.getDigit(i);
if (testDigit !== getDigit) {
throw `Digit ${i} should be ${testDigit} but got ${getDigit}`;
}
}
console.log('All tests pass!');
}
/**
* Test the speed of the algorithm alone.
* Processes the first n digits and returns the time it took.
*
* @param int n the number of digits to test
* @return void
*/
testSpeed(n) {
console.log(`Speed test. Processing ${n} positions.`);
console.time('took');
for (let i = 1; i < n; i++) {
this.getDigit(i);
}
console.timeEnd('took');
}
} |
JavaScript | class TtsPage extends Component {
/**
* Default Constructor
* @param {*} props Inbound Properties
*/
constructor(props) {
super(props);
if (this.props.ttsContent) {
// Split Content Text with newline
this.state = {
toolbar_msg: TOOLBAR_MSG_INIT
, ttsContents: this.props.ttsContent.trim().split(/\r?\n/)
, speechSpeed: DEFAULT_SPEECH_SPEED
, isPostingTts: false
, errorTitle: ''
, errorContent: ''
};
} else {
this.state = {
toolbar_msg: TOOLBAR_MSG_INIT
, ttsContents: []
, speechSpeed: DEFAULT_SPEECH_SPEED
, isPostingTts: false
, errorTitle: ''
, errorContent: ''
};
}
this.handleReset = this.handleReset.bind(this);
this.handleBackHome = this.handleBackHome.bind(this);
this.handlePlay = this.handlePlay.bind(this);
this.handlePlayAll = this.handlePlayAll.bind(this);
this.handleUpdateItem = this.handleUpdateItem.bind(this);
this.handleMoveItem = this.handleMoveItem.bind(this);
this.handleErrorDialogCancel = this.handleErrorDialogCancel.bind(this);
this.processTtsContent = this.processTtsContent.bind(this);
this.processTtsError = this.processTtsError.bind(this);
this.playVoice = this.playVoice.bind(this);
}
/**
* Reset all state values to the default ones
*/
resetAll() {
if (this.props.ttsContent) {
// Split Content Text with newline
this.setState({
ttsContents: this.props.ttsContent.trim().split(/\r?\n/)
, speechSpeed: DEFAULT_SPEECH_SPEED
, isPostingTts: false
, errorTitle: ''
, errorContent: ''
});
} else {
this.setState({
ttsContents: []
, speechSpeed: DEFAULT_SPEECH_SPEED
, isPostingTts: false
, errorTitle: ''
, errorContent: ''
});
}
}
/**
* Event Handler of requesting Back Home
* @param {*} _event
*/
handleBackHome(_event) {
this.resetAll();
this.props.onBackToHome();
}
/**
* Event Handler of requesting Reset
* @param {*} _event
*/
handleReset(_event) {
this.resetAll();
}
/**
* Event Handler of requesting TTS on the given text and playing the TTS voice
* @param {*} _event Event of this handler
* @param {*} _sentence Text to be converted to Speech
*/
handlePlay(_event, _sentence) {
if (this.state.isPostingTts) {
// Posting to TTS in progress
console.log('Posting to TTS in progress rejects a new coming request.');
this.setState({
errorTitle: '語音轉換異常'
, errorContent: '語音轉換進行中,請稍候。'
});
} else {
this.setState({
isPostingTts: true
});
callVoiceRss(
VOICE_RSS_API_KEY
, this.props.lang
, _sentence
, Math.floor(this.state.speechSpeed / 5.0) - 10
, this.processTtsContent
, this.processTtsError
);
}
}
/**
* Event Handler of requesting TTS on all texts and playing the TTS voice
* @param {*} _event Event of this handler
*/
handlePlayAll(_event) {
this.playFromArray(this.state.ttsContents.slice());
}
/**
* Request TTS of all the given texts until the buffer is over limit
* @param {*} arrContents Array of given texts
*/
playFromArray(arrContents) {
var voiceContent = "";
if (typeof arrContents !== undefined && arrContents !== null && arrContents.length > 0) {
while (arrContents.length > 0 &&
countBytes(voiceContent + "\n" + arrContents[0]) <= VOICE_BYTE_LIMIT) {
voiceContent += "\n" + arrContents.shift();
}
}
if (voiceContent.trim() !== "") {
callVoiceRss(
VOICE_RSS_API_KEY
, this.props.lang
, voiceContent
, Math.floor(this.state.speechSpeed / 5.0) - 10
, (_response) => {
if (typeof _response !== undefined && _response !== null) {
var respData = _response.data;
if (respData.startsWith("ERROR")) {
console.log("Speech can't be played. Please try next time.");
console.log(respData);
this.setState({
isPostingTts: false
, errorTitle: '語音轉換異常'
, errorContent: JSON.stringify(respData)
});
} else {
let playResult = this.playVoice(respData);
if (!playResult) {
console.log("Speech can't be played. Please try next time.");
this.setState({
isPostingTts: false
, errorTitle: '播放語音異常'
, errorContent: '播放語音異常,請重試。'
});
} else {
this.playFromArray(arrContents);
}
}
} else {
console.log("Speech can't be played. Please try next time.");
this.setState({
isPostingTts: false
, errorTitle: '語音轉換異常'
, errorContent: '語音播放異常,請重試。'
});
}
}
, (_error) => {
console.log(_error);
this.setState({
isPostingTts: false
, errorTitle: '語音轉換異常'
, errorContent: JSON.stringify(_error)
});
}
);
}
}
/**
* Event Handler of Updating text content of a List Item
* @param {*} _event Event of this handler
* @param {*} _idx Index value of the List Item in the List
*/
handleUpdateItem(_event, _idx) {
this.setState(prevState => {
const arrContent = prevState.ttsContents.map((item, idx) => {
if (idx === _idx) {
return _event.target.value;
} else {
return item;
}
});
return {
ttsContents: arrContent
};
});
}
/**
* Event Handler of moving text content of a List Item along the List
* @param {*} _event Event of this handler
* @param {*} _idx Current Index value of the List Item in the List
* @param {*} _step Step to move. Positive to down. Negative to up.
*/
handleMoveItem(_event, _idx, _step) {
if (_idx + _step < 0 || _idx + _step >= this.state.ttsContents.length) {
console.log("Invalid Movement.");
return; // Invalid movement
} else {
var thisValue = this.state.ttsContents[_idx];
var nextValue = this.state.ttsContents[_idx + _step];
this.setState(prevState => {
const arrContent = prevState.ttsContents.map((item, idx) => {
if (idx === _idx) {
return nextValue;
} else if (idx === (_idx + _step)) {
return thisValue;
} else {
return item;
}
});
return {
ttsContents: arrContent
};
});
}
}
/**
* Function routine when TTS Content Response is successfully received
* @param {*} _response Response Object
*/
processTtsContent(_response) {
if (typeof _response !== undefined && _response !== null) {
var respData = _response.data;
if (respData.startsWith("ERROR")) {
console.log("Speech can't be played. Please try next time.");
console.log(respData);
this.setState({
isPostingTts: false
, errorTitle: '語音轉換異常'
, errorContent: JSON.stringify(respData)
});
} else {
let playResult = this.playVoice(respData);
if (!playResult) {
console.log("Speech can't be played. Please try next time.");
this.setState({
isPostingTts: false
, errorTitle: '播放語音異常'
, errorContent: '播放語音異常,請重試。'
});
}
}
} else {
console.log("Speech can't be played. Please try next time.");
this.setState({
isPostingTts: false
, errorTitle: '語音轉換異常'
, errorContent: '語音播放異常,請重試。'
});
}
this.setState({
isPostingTts: false
});
}
/**
* Function routine when an error happens in processing TTS Content
* @param {*} _error Error Object
*/
processTtsError(_error) {
console.log(_error);
this.setState({
isPostingTts: false
, errorTitle: '語音轉換異常'
, errorContent: JSON.stringify(_error)
});
}
/**
* Play the given voice content
* @param {*} _voiceContent Voice Content encoded in Base 64
*/
playVoice(_voiceContent) {
var audio = document.querySelector("#audioPlayback");
if (!audio.src || audio.paused || audio.ended) {
audio.src = _voiceContent;
audio.load();
var playPromise = audio.play();
if (playPromise !== undefined) {
playPromise.then(function() {
console.log("Automatic playback started!");
}).catch(function(error) {
console.log(error);
this.setState({
isPostingTts: false
, errorTitle: '播放語音異常'
, errorContent: JSON.stringify(error)
});
});
} else {
console.log("audio returns undefined.");
this.setState({
isPostingTts: false
, errorTitle: '播放語音異常'
, errorContent: '未能返回語音。'
});
}
return playPromise;
} else {
console.log("audio element is not available.");
this.setState({
isPostingTts: false
, errorTitle: '播放語音異常'
, errorContent: '未能產生語音元件。'
});
}
return null;
}
/**
* Event Handler of cancelling an error dialog box
* @param {*} _event Event of this handler
*/
handleErrorDialogCancel(_event) {
if (this.state.errorTitle.length > 0) {
this.setState({
errorTitle: ''
, errorContent: ''
});
}
}
/**
* React JS Render function
*/
render() {
return(
<Page renderToolbar={() =>
<Toolbar>
<div className="left">
<ToolbarButton onClick={this.handleBackHome}><i className="zmdi zmdi-home"></i></ToolbarButton>
</div>
<div className="center" onClick={this.handlePlayAll}>
{ this.state.toolbar_msg }<i className="zmdi zmdi-play-circle"></i>
</div>
<div className="right">
<ToolbarButton onClick={this.handleReset}><i className="zmdi zmdi-refresh"></i></ToolbarButton>
</div>
</Toolbar>
}>
<Modal isOpen={this.state.isPostingTts}>
<p>Loading ...</p>
<ProgressCircular indeterminate />
</Modal>
<AlertDialog
isOpen={this.state.errorTitle.length > 0}
onCancel={this.handleErrorDialogCancel}
cancelable
>
<div className="alert-dialog-title"
onClick={this.handleErrorDialogCancel}
><b>{this.state.errorTitle}</b></div>
<div className="alert-dialog-content">{this.state.errorContent}</div>
<div className="alert-dialog-footer">
<Button onClick={this.handleErrorDialogCancel} className="alert-dialog-button">Ok</Button>
</div>
</AlertDialog>
<Row>
<Col width="20%" verticalAlign="center" style={{ 'textAlign': "right" }}>
<i className="zmdi zmdi-bike" />Slow
</Col>
<Col width="60^">
<Range modifier="material"
style={{width: "100%"}}
value={this.state.speechSpeed}
onChange={(event) => this.setState({speechSpeed: parseInt(event.target.value)})}
/>
</Col>
<Col width="20%" verticalAlign="center" style={{ 'textAlign': "left" }}>
<i className="zmdi zmdi-airplane" />Fast
</Col>
</Row>
<Row><Col>
<audio id="audioPlayback" controls src=""></audio>
</Col></Row>
<Row><Col>
<List
dataSource={ this.state.ttsContents }
renderRow={(row, idx) => (
<ListItem key={"contentItem-" + idx} modifier={idx === this.state.ttsContents.length - 1 ? 'longdivider' : null}>
<div className="left" onClick={(_event) => { this.handlePlay(_event, row); }}>
<i className="zmdi zmdi-play-circle" style={{"fontSize": "1.5em"}}></i>
</div>
<div className="center">
<Input type="text" modifier='transparent' style={{ 'width': "100%" }} value={row} onChange={(_event) => this.handleUpdateItem(_event, idx)} float></Input>
</div>
<div className="right">
<i className="zmdi zmdi-caret-up-circle" style={{"fontSize": "1.5em"}} onClick={(_event) => {this.handleMoveItem(_event, idx, -1)}}></i>
<i className="zmdi zmdi-caret-down-circle" style={{"fontSize": "1.5em"}} onClick={(_event) => {this.handleMoveItem(_event, idx, 1)}}></i>
</div>
</ListItem>
)}
/>
</Col></Row>
</Page>
);
}
} |
JavaScript | class SearchForm extends Component {
render() {
return (
<div className='search-form'>
<h2 className='text-center'>Search for a Movie</h2>
<form>
<div className='form-group'>
<input
type='text'
className='form-control'
ref='title'
placeholder="Search..."
/>
</div>
<button className="btn btn-primary">Search</button>
</form>
</div>
)
}
} |
JavaScript | class RoleSearch extends RoleLandmark {
/**
* @returns {boolean}
*/
static get abstract() {
return false
}
} |
JavaScript | class Session {
// Generates a new session
constructor() {
this.key = uuid(),
this.timestamp = Date.now();
}
} |
JavaScript | class CompositeMember extends Node {
constructor(member, module, location) {
super();
this.type = 'composite-member';
this.member = member;
this.module = module;
this.location = location;
}
transpile() {
return `import * as ${this.member.transpile()} from ${this.module.transpile()};`;
}
compile(o) {
return this.sourceNode(o.file, 'import * as').
add(this.member.compile(o)).
add(this.module.compile(o));
}
} |
JavaScript | class PersistentState extends BasePlugin {
constructor(hotInstance) {
super(hotInstance);
/**
* Instance of {@link Storage}.
*
* @type {Storage}
*/
this.storage = void 0;
}
/**
* Check if the plugin is enabled in the Handsontable settings.
*
* @returns {Boolean}
*/
isEnabled() {
return !!this.hot.getSettings().persistentState;
}
/**
* Enable plugin for this Handsontable instance.
*/
enablePlugin() {
if (this.enabled) {
return;
}
if (!this.storage) {
this.storage = new Storage(this.hot.rootElement.id);
}
this.addHook('persistentStateSave', (key, value) => this.saveValue(key, value));
this.addHook('persistentStateLoad', (key, saveTo) => this.loadValue(key, saveTo));
this.addHook('persistentStateReset', () => this.resetValue());
super.enablePlugin();
}
/**
* Disable plugin for this Handsontable instance.
*/
disablePlugin() {
this.storage = void 0;
super.disablePlugin();
}
/**
* Updates the plugin to use the latest options you have specified.
*/
updatePlugin() {
this.disablePlugin();
this.enablePlugin();
super.updatePlugin();
}
/**
* Load value from localStorage.
*
* @param {String} key Key string.
* @param {Object} saveTo Saved value from browser local storage.
*/
loadValue(key, saveTo) {
saveTo.value = this.storage.loadValue(key);
}
/**
* Save data to localStorage.
*
* @param {String} key Key string.
* @param {Mixed} value Value to save.
*/
saveValue(key, value) {
this.storage.saveValue(key, value);
}
/**
* Reset given data or all data from localStorage.
*
* @param {String} key [optional] Key string.
*/
resetValue(key) {
if (typeof key === 'undefined') {
this.storage.resetAll();
} else {
this.storage.reset(key);
}
}
/**
* Destroy plugin instance.
*/
destroy() {
super.destroy();
}
} |
JavaScript | class FlashSourceBuffer extends videojs.EventTarget {
constructor(mediaSource) {
super();
let encodedHeader;
// Start off using the globally defined value but refine
// as we append data into flash
this.chunkSize_ = FlashConstants.BYTES_PER_CHUNK;
// byte arrays queued to be appended
this.buffer_ = [];
// the total number of queued bytes
this.bufferSize_ = 0;
// to be able to determine the correct position to seek to, we
// need to retain information about the mapping between the
// media timeline and PTS values
this.basePtsOffset_ = NaN;
this.mediaSource = mediaSource;
// indicates whether the asynchronous continuation of an operation
// is still being processed
// see https://w3c.github.io/media-source/#widl-SourceBuffer-updating
this.updating = false;
this.timestampOffset_ = 0;
// TS to FLV transmuxer
this.segmentParser_ = new flv.Transmuxer();
this.segmentParser_.on('data', this.receiveBuffer_.bind(this));
encodedHeader = window.btoa(
String.fromCharCode.apply(
null,
Array.prototype.slice.call(
this.segmentParser_.getFlvHeader()
)
)
);
this.mediaSource.swfObj.vjs_appendBuffer(encodedHeader);
this.one('updateend', () => {
this.mediaSource.tech_.trigger('loadedmetadata');
});
Object.defineProperty(this, 'timestampOffset', {
get() {
return this.timestampOffset_;
},
set(val) {
if (typeof val === 'number' && val >= 0) {
this.timestampOffset_ = val;
this.segmentParser_ = new flv.Transmuxer();
this.segmentParser_.on('data', this.receiveBuffer_.bind(this));
// We have to tell flash to expect a discontinuity
this.mediaSource.swfObj.vjs_discontinuity();
// the media <-> PTS mapping must be re-established after
// the discontinuity
this.basePtsOffset_ = NaN;
}
}
});
Object.defineProperty(this, 'buffered', {
get() {
if (!this.mediaSource ||
!this.mediaSource.swfObj ||
!('vjs_getProperty' in this.mediaSource.swfObj)) {
return videojs.createTimeRange();
}
let buffered = this.mediaSource.swfObj.vjs_getProperty('buffered');
if (buffered && buffered.length) {
buffered[0][0] = toDecimalPlaces(buffered[0][0], 3);
buffered[0][1] = toDecimalPlaces(buffered[0][1], 3);
}
return videojs.createTimeRanges(buffered);
}
});
// On a seek we remove all text track data since flash has no concept
// of a buffered-range and everything else is reset on seek
this.mediaSource.player_.on('seeked', () => {
removeCuesFromTrack(0, Infinity, this.metadataTrack_);
removeCuesFromTrack(0, Infinity, this.inbandTextTrack_);
});
}
/**
* Append bytes to the sourcebuffers buffer, in this case we
* have to append it to swf object.
*
* @link https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer/appendBuffer
* @param {Array} bytes
*/
appendBuffer(bytes) {
let error;
let chunk = 512 * 1024;
let i = 0;
if (this.updating) {
error = new Error('SourceBuffer.append() cannot be called ' +
'while an update is in progress');
error.name = 'InvalidStateError';
error.code = 11;
throw error;
}
this.updating = true;
this.mediaSource.readyState = 'open';
this.trigger({ type: 'update' });
// this is here to use recursion
let chunkInData = () => {
this.segmentParser_.push(bytes.subarray(i, i + chunk));
i += chunk;
if (i < bytes.byteLength) {
scheduleTick(chunkInData);
} else {
scheduleTick(this.segmentParser_.flush.bind(this.segmentParser_));
}
};
chunkInData();
}
/**
* Reset the parser and remove any data queued to be sent to the SWF.
*
* @link https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer/abort
*/
abort() {
this.buffer_ = [];
this.bufferSize_ = 0;
this.mediaSource.swfObj.vjs_abort();
// report any outstanding updates have ended
if (this.updating) {
this.updating = false;
this.trigger({ type: 'updateend' });
}
}
/**
* Flash cannot remove ranges already buffered in the NetStream
* but seeking clears the buffer entirely. For most purposes,
* having this operation act as a no-op is acceptable.
*
* @link https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer/remove
* @param {Double} start start of the section to remove
* @param {Double} end end of the section to remove
*/
remove(start, end) {
removeCuesFromTrack(start, end, this.metadataTrack_);
removeCuesFromTrack(start, end, this.inbandTextTrack_);
this.trigger({ type: 'update' });
this.trigger({ type: 'updateend' });
}
/**
* Receive a buffer from the flv.
*
* @param {Object} segment
* @private
*/
receiveBuffer_(segment) {
// create an in-band caption track if one is present in the segment
createTextTracksIfNecessary(this, this.mediaSource, segment);
addTextTrackData(this, segment.captions, segment.metadata);
// Do this asynchronously since convertTagsToData_ can be time consuming
scheduleTick(() => {
let flvBytes = this.convertTagsToData_(segment);
if (this.buffer_.length === 0) {
scheduleTick(this.processBuffer_.bind(this));
}
if (flvBytes) {
this.buffer_.push(flvBytes);
this.bufferSize_ += flvBytes.byteLength;
}
});
}
/**
* Append a portion of the current buffer to the SWF.
*
* @private
*/
processBuffer_() {
let chunk;
let i;
let length;
let binary;
let b64str;
let startByte = 0;
let appendIterations = 0;
let startTime = +(new Date());
let appendTime;
if (!this.buffer_.length) {
if (this.updating !== false) {
this.updating = false;
this.trigger({ type: 'updateend' });
}
// do nothing if the buffer is empty
return;
}
do {
appendIterations++;
// concatenate appends up to the max append size
chunk = this.buffer_[0].subarray(startByte, startByte + this.chunkSize_);
// requeue any bytes that won't make it this round
if (chunk.byteLength < this.chunkSize_ ||
this.buffer_[0].byteLength === startByte + this.chunkSize_) {
startByte = 0;
this.buffer_.shift();
} else {
startByte += this.chunkSize_;
}
this.bufferSize_ -= chunk.byteLength;
// base64 encode the bytes
binary = '';
length = chunk.byteLength;
for (i = 0; i < length; i++) {
binary += String.fromCharCode(chunk[i]);
}
b64str = window.btoa(binary);
// bypass normal ExternalInterface calls and pass xml directly
// IE can be slow by default
this.mediaSource.swfObj.CallFunction(
'<invoke name="vjs_appendBuffer"' +
'returntype="javascript"><arguments><string>' +
b64str +
'</string></arguments></invoke>'
);
appendTime = (new Date()) - startTime;
} while (this.buffer_.length &&
appendTime < FlashConstants.TIME_PER_TICK);
if (this.buffer_.length && startByte) {
this.buffer_[0] = this.buffer_[0].subarray(startByte);
}
if (appendTime >= FlashConstants.TIME_PER_TICK) {
// We want to target 4 iterations per time-slot so that gives us
// room to adjust to changes in Flash load and other externalities
// such as garbage collection while still maximizing throughput
this.chunkSize_ = Math.floor(this.chunkSize_ * (appendIterations / 4));
}
// We also make sure that the chunk-size doesn't drop below 1KB or
// go above 1MB as a sanity check
this.chunkSize_ = Math.max(
FlashConstants.MIN_CHUNK,
Math.min(this.chunkSize_, FlashConstants.MAX_CHUNK));
// schedule another append if necessary
if (this.bufferSize_ !== 0) {
scheduleTick(this.processBuffer_.bind(this));
} else {
this.updating = false;
this.trigger({ type: 'updateend' });
}
}
/**
* Turns an array of flv tags into a Uint8Array representing the
* flv data. Also removes any tags that are before the current
* time so that playback begins at or slightly after the right
* place on a seek
*
* @private
* @param {Object} segmentData object of segment data
*/
convertTagsToData_(segmentData) {
let segmentByteLength = 0;
let tech = this.mediaSource.tech_;
let targetPts = 0;
let i;
let j;
let segment;
let filteredTags = [];
let tags = this.getOrderedTags_(segmentData);
// Establish the media timeline to PTS translation if we don't
// have one already
if (isNaN(this.basePtsOffset_) && tags.length) {
this.basePtsOffset_ = tags[0].pts;
}
// Trim any tags that are before the end of the end of
// the current buffer
if (tech.buffered().length) {
targetPts = tech.buffered().end(0) - this.timestampOffset;
}
// Trim to currentTime if it's ahead of buffered or buffered doesn't exist
targetPts = Math.max(targetPts, tech.currentTime() - this.timestampOffset);
// PTS values are represented in milliseconds
targetPts *= 1e3;
targetPts += this.basePtsOffset_;
// skip tags with a presentation time less than the seek target
for (i = 0; i < tags.length; i++) {
if (tags[i].pts >= targetPts) {
filteredTags.push(tags[i]);
}
}
if (filteredTags.length === 0) {
return;
}
// concatenate the bytes into a single segment
for (i = 0; i < filteredTags.length; i++) {
segmentByteLength += filteredTags[i].bytes.byteLength;
}
segment = new Uint8Array(segmentByteLength);
for (i = 0, j = 0; i < filteredTags.length; i++) {
segment.set(filteredTags[i].bytes, j);
j += filteredTags[i].bytes.byteLength;
}
return segment;
}
/**
* Assemble the FLV tags in decoder order.
*
* @private
* @param {Object} segmentData object of segment data
*/
getOrderedTags_(segmentData) {
let videoTags = segmentData.tags.videoTags;
let audioTags = segmentData.tags.audioTags;
let tag;
let tags = [];
while (videoTags.length || audioTags.length) {
if (!videoTags.length) {
// only audio tags remain
tag = audioTags.shift();
} else if (!audioTags.length) {
// only video tags remain
tag = videoTags.shift();
} else if (audioTags[0].dts < videoTags[0].dts) {
// audio should be decoded next
tag = audioTags.shift();
} else {
// video should be decoded next
tag = videoTags.shift();
}
tags.push(tag.finalize());
}
return tags;
}
} |
JavaScript | class SKUPrepInstructions {
/**
* Constructs a new <code>SKUPrepInstructions</code>.
* Labeling requirements and item preparation instructions to help you prepare items for shipment to Amazon's fulfillment network.
* @alias module:client/models/SKUPrepInstructions
* @class
*/
constructor() {
}
/**
* Constructs a <code>SKUPrepInstructions</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:client/models/SKUPrepInstructions} obj Optional instance to populate.
* @return {module:client/models/SKUPrepInstructions} The populated <code>SKUPrepInstructions</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new SKUPrepInstructions();
if (data.hasOwnProperty('SellerSKU')) {
obj['SellerSKU'] = ApiClient.convertToType(data['SellerSKU'], 'String');
}
if (data.hasOwnProperty('ASIN')) {
obj['ASIN'] = ApiClient.convertToType(data['ASIN'], 'String');
}
if (data.hasOwnProperty('BarcodeInstruction')) {
obj['BarcodeInstruction'] = BarcodeInstruction.constructFromObject(data['BarcodeInstruction']);
}
if (data.hasOwnProperty('PrepGuidance')) {
obj['PrepGuidance'] = PrepGuidance.constructFromObject(data['PrepGuidance']);
}
if (data.hasOwnProperty('PrepInstructionList')) {
obj['PrepInstructionList'] = PrepInstructionList.constructFromObject(data['PrepInstructionList']);
}
if (data.hasOwnProperty('AmazonPrepFeesDetailsList')) {
obj['AmazonPrepFeesDetailsList'] = AmazonPrepFeesDetailsList.constructFromObject(data['AmazonPrepFeesDetailsList']);
}
}
return obj;
}
/**
* The seller SKU of the item.
* @member {String} SellerSKU
*/
'SellerSKU' = undefined;
/**
* The Amazon Standard Identification Number (ASIN) of the item.
* @member {String} ASIN
*/
'ASIN' = undefined;
/**
* @member {module:client/models/BarcodeInstruction} BarcodeInstruction
*/
'BarcodeInstruction' = undefined;
/**
* @member {module:client/models/PrepGuidance} PrepGuidance
*/
'PrepGuidance' = undefined;
/**
* @member {module:client/models/PrepInstructionList} PrepInstructionList
*/
'PrepInstructionList' = undefined;
/**
* @member {module:client/models/AmazonPrepFeesDetailsList} AmazonPrepFeesDetailsList
*/
'AmazonPrepFeesDetailsList' = undefined;
} |
JavaScript | class NetworkConfiguration {
/**
* Create a NetworkConfiguration.
* @property {string} [subnetId] The ARM resource identifier of the virtual
* network subnet which the Compute Nodes of the Pool will join. This is of
* the form
* /subscriptions/{subscription}/resourceGroups/{group}/providers/{provider}/virtualNetworks/{network}/subnets/{subnet}.
* The virtual network must be in the same region and subscription as the
* Azure Batch Account. The specified subnet should have enough free IP
* addresses to accommodate the number of Compute Nodes in the Pool. If the
* subnet doesn't have enough free IP addresses, the Pool will partially
* allocate Nodes and a resize error will occur. The 'MicrosoftAzureBatch'
* service principal must have the 'Classic Virtual Machine Contributor'
* Role-Based Access Control (RBAC) role for the specified VNet. The
* specified subnet must allow communication from the Azure Batch service to
* be able to schedule Tasks on the Nodes. This can be verified by checking
* if the specified VNet has any associated Network Security Groups (NSG). If
* communication to the Nodes in the specified subnet is denied by an NSG,
* then the Batch service will set the state of the Compute Nodes to
* unusable. For Pools created with virtualMachineConfiguration only ARM
* virtual networks ('Microsoft.Network/virtualNetworks') are supported, but
* for Pools created with cloudServiceConfiguration both ARM and classic
* virtual networks are supported. If the specified VNet has any associated
* Network Security Groups (NSG), then a few reserved system ports must be
* enabled for inbound communication. For Pools created with a virtual
* machine configuration, enable ports 29876 and 29877, as well as port 22
* for Linux and port 3389 for Windows. For Pools created with a cloud
* service configuration, enable ports 10100, 20100, and 30100. Also enable
* outbound connections to Azure Storage on port 443. For more details see:
* https://docs.microsoft.com/en-us/azure/batch/batch-api-basics#virtual-network-vnet-and-firewall-configuration
* @property {string} [dynamicVNetAssignmentScope] The scope of dynamic vnet
* assignment. Possible values include: 'none', 'job'
* @property {object} [endpointConfiguration] The configuration for endpoints
* on Compute Nodes in the Batch Pool. Pool endpoint configuration is only
* supported on Pools with the virtualMachineConfiguration property.
* @property {array} [endpointConfiguration.inboundNATPools] The maximum
* number of inbound NAT Pools per Batch Pool is 5. If the maximum number of
* inbound NAT Pools is exceeded the request fails with HTTP status code 400.
* @property {object} [publicIPAddressConfiguration] The Public IPAddress
* configuration for Compute Nodes in the Batch Pool. Public IP configuration
* property is only supported on Pools with the virtualMachineConfiguration
* property.
* @property {string} [publicIPAddressConfiguration.provision] The default
* value is BatchManaged. Possible values include: 'batchManaged',
* 'userManaged', 'noPublicIPAddresses'
* @property {array} [publicIPAddressConfiguration.ipAddressIds] The number
* of IPs specified here limits the maximum size of the Pool - 50 dedicated
* nodes or 20 low-priority nodes can be allocated for each public IP. For
* example, a pool needing 150 dedicated VMs would need at least 3 public IPs
* specified. Each element of this collection is of the form:
* /subscriptions/{subscription}/resourceGroups/{group}/providers/Microsoft.Network/publicIPAddresses/{ip}.
*/
constructor() {
}
/**
* Defines the metadata of NetworkConfiguration
*
* @returns {object} metadata of NetworkConfiguration
*
*/
mapper() {
return {
required: false,
serializedName: 'NetworkConfiguration',
type: {
name: 'Composite',
className: 'NetworkConfiguration',
modelProperties: {
subnetId: {
required: false,
serializedName: 'subnetId',
type: {
name: 'String'
}
},
dynamicVNetAssignmentScope: {
required: false,
serializedName: 'dynamicVNetAssignmentScope',
type: {
name: 'Enum',
allowedValues: [ 'none', 'job' ]
}
},
endpointConfiguration: {
required: false,
serializedName: 'endpointConfiguration',
type: {
name: 'Composite',
className: 'PoolEndpointConfiguration'
}
},
publicIPAddressConfiguration: {
required: false,
serializedName: 'publicIPAddressConfiguration',
type: {
name: 'Composite',
className: 'PublicIPAddressConfiguration'
}
}
}
}
};
}
} |
JavaScript | class MockClient {
/**
* Create the client and use the given fixture to simulate the connection
* to the server
* @param {string} host the host to connect to
* @param {number} port the port to connect to
* @param {string} fixture the path to the fixture containing the simulated
* connection
* @param listener a callback that will be called when the connection
* has been simulated completely
*/
create(host, port, fixture, listener) {
// read fixture
let lines = fs.readFileSync(fixture).toString("ASCII").split("\n");
lines = lines.map(line => line.trim());
while (lines[lines.length - 1] === "") {
lines.pop();
}
// simulate messages from the client
function sendClientMessage(socket) {
while (true) {
let str = lines[0];
if (str.match(/^C:/)) {
socket.write(str.substring(3) + "\r\n");
lines.shift();
} else {
break;
}
}
}
this.socket = new net.Socket();
let lineStream = new LineStream();
lineStream.on("data", buf => {
while (lines.length > 0) {
let str = lines[0];
if (str.match(/^S:/)) {
expect(buf.toString("ASCII")).toBe(str.substring(3) + "\r\n");
lines.shift();
} else {
break;
}
}
if (lines.length > 0) {
sendClientMessage(this.socket);
} else {
listener();
}
});
this.socket.pipe(lineStream);
this.socket.connect(port, host);
}
close() {
this.socket.end();
}
} |
JavaScript | class ParseLines extends Transform {
constructor(options, divider) {
super(options);
this.divider = divider || '|';
}
_transform(line, _enc, done) {
const data = line.split(this.divider).reduce(_createPatientReducer, {});
this.push(data);
done();
}
} |
JavaScript | class List {
/**
* Get null or iterable Object and make List sequentially.
* @param {null|object} data - The data of iteable object.
*/
constructor(data = null) {
this.list = new OldList(data);
this.classname = 'List';
}
// Capacity
/**
* Get the number of elements.
* @return {number} the number of elements.
*/
size() {
return this.list.size();
}
/**
* Make sure the list is empty.
* @return {boolean} if list is empty, true.
*/
empty() {
return this.list.empty();
}
// Element Access
/**
* Get the first element of list.
* @return {boolean|*} false if list is empty, else return the first element.
*/
front() {
return this.list.front();
}
/**
* Get the last element of list.
* @return {boolean|*} false if list is empty, else return the last element.
*/
back() {
return this.list.back();
}
// iterable node
/**
* Get the first Node of list.<br>
* Can use getNext method for next node.<br>
* if list is empty, return null.
* @return {null|Node} The first Node of list.
*/
begin() {
return this.list.begin();
}
/**
* Get the back end of list, nil.<br>
* For check of end.<br>
* Or use getPrev method for before node:last node of list.
* @return {Node} nil
*/
end() {
return this.list.end();
}
/**
* Get the last node of list.<br>
* Use the getPrev method for next node.<br>
* If list is empty, return null.
* @returns {null|Node} last node of list.
*/
rbegin() {
return this.list.rbegin();
}
/**
* Get the front end of list, rnil<br>
* For check of the end of reverse iterator.<br>
* Use getNext method for get first node of list.
* @returns {Node} rnil.
*/
rend() {
return this.list.rend();
}
// Modifiers
/**
* Make list empty.
*/
clear() {
return this.list.clear();
}
/**
* Insert new data in front of given node and return present node like c++ stl.
* @param {Node} node - In front of this node, the data is inserted.
* @param {*} data - The data to insert list.
* @returns {boolean|Node} - If node is not Node object, return false, else return this node.
*/
insert(variableName='', dataStates=[], visualizeDatas=[], executingCode='', node, data) {
// array, object, js_dsal의 class만 deepcopy하자
const newdataStates = dataStates.map(n => {
if (n.value.classname !== undefined) {
return {...n, value: n.value.copy()}
} else if (typeof n.value === 'object') {
return {...n, value: JSON.parse(JSON.stringify(n))};
} else {
return n;
}
})
visualizeDatas.push({dataStates: newdataStates, executingCode: executingCode.trim(), containerState: {object: this.copy(), method: 'insert', params: [data]}});
return this.list.insert(node, data);
}
/**
* Erase this node and return the next node.
* @param {*} node - The node which is removed from list.
* @returns {boolean|Node} - If node is not Node object, return false, else return the next node.
*/
erase(node) {
return this.list.erase(node);
}
/**
* The data is added to end of list.
* @param {*} data - the data of list.
*/
pushBack(variableName='', dataStates=[], visualizeDatas=[], executingCode='', data) {
// array, object, js_dsal의 class만 deepcopy하자
const newdataStates = dataStates.map(n => {
if (n.value.classname !== undefined) {
return {...n, value: n.value.copy()}
} else if (typeof n.value === 'object') {
return {...n, value: JSON.parse(JSON.stringify(n))};
} else {
return n;
}
})
visualizeDatas.push({dataStates: newdataStates, executingCode: executingCode.trim(), containerState: {object: this.copy(), method: 'pushBack', params: [data]}});
this.list.pushBack(data);
}
/**
* The data is added to front of list.
* @param {*} data - the data of list.
*/
pushFront(variableName='', dataStates=[], visualizeDatas=[], executingCode='', data) {
// array, object, js_dsal의 class만 deepcopy하자
const newdataStates = dataStates.map(n => {
if (n.value.classname !== undefined) {
return {...n, value: n.value.copy()}
} else if (typeof n.value === 'object') {
return {...n, value: JSON.parse(JSON.stringify(n))};
} else {
return n;
}
})
visualizeDatas.push({dataStates: newdataStates, executingCode: executingCode.trim(), containerState: {object: this.copy(), method: 'pushFront', params: [data]}});
this.list.pushFront(data);
}
/**
* The data is removed from end of list.
* @returns {boolean} false it the list is empty.
*/
popBack(variableName='', dataStates=[], visualizeDatas=[], executingCode='') {
// array, object, js_dsal의 class만 deepcopy하자
const newdataStates = dataStates.map(n => {
if (n.value.classname !== undefined) {
return {...n, value: n.value.copy()}
} else if (typeof n.value === 'object') {
return {...n, value: JSON.parse(JSON.stringify(n))};
} else {
return n;
}
})
visualizeDatas.push({dataStates: newdataStates, executingCode: executingCode.trim(), containerState: {object: this.copy(), method: 'popBack', params: []}});
return this.list.popBack();
}
/**
* The data is removed from front of list.
* @returns {boolean} false it the list is empty.
*/
popFront(variableName='', dataStates=[], visualizeDatas=[], executingCode='') {
// array, object, js_dsal의 class만 deepcopy하자
const newdataStates = dataStates.map(n => {
if (n.value.classname !== undefined) {
return {...n, value: n.value.copy()}
} else if (typeof n.value === 'object') {
return {...n, value: JSON.parse(JSON.stringify(n))};
} else {
return n;
}
})
visualizeDatas.push({dataStates: newdataStates, executingCode: executingCode.trim(), containerState: {object: this.copy(), method: 'popFront', params: []}});
return this.list.popFront();
}
// Operations
/**
* Compare iterable object with this list.
* @param {Object} data - iterable object.
* @returns {boolean} - true if the data and index is same in list and iterable object.
*/
compare(data) {
return this.list.compare(data);
}
/**
* Insert elements of iterable object in list where the front of given node.
* @param {Node} node - Elements of data are inserted in front of this node.
* @param {Object} data - iterable object
* @returns {boolean} If elements are well inserted, return true.
*/
splice(node, data) {
return this.list.splice(node, data);
}
/**
* sort the list by compare function.
* Basically quick sort, but can choose merge sort.
* @param {function} comp - compare function
* @param {string} sorting - sort mode
*/
sort(comp = (n1, n2) => n1 < n2, sorting = 'quicksort') {
return this.list.sort(comp, sorting)
}
/**
* Merge this list and data(iterable object) by sequential order.<br>
* @param {Object} data - sortable iterable object.
* @param {function} compare - inequality function.
* @return {boolean} check well merged.
*/
merge(data, compare = (d1, d2) => d1 < d2) {
return this.list.merge(data, compare)
}
/**
* Reverse the list.
*/
reverse() {
this.list.reverse();
}
// javascript iterator
/**
* Iterator of this list.
* return the value of Nodes.
* @returns {Object} {value, done}
*/
[Symbol.iterator]() {
let node = null;
const start = this.begin();
const end = this.end();
const iterator = {
next() {
if (node === null) {
node = start;
if (node === null) {
return { value: undefined, done: true };
}
return { value: node.getData(), done: false };
}
node = node.getNext();
if (node === end) {
return { value: undefined, done: true };
}
return { value: node.getData(), done: false };
},
};
return iterator;
}
toString() {
return this.list.toString();
}
// new method
copy() {
return new List(this.list);
}
make = (data) => new List(data);
} |
JavaScript | class DynamicString {
constructor(str) {
this._str = str;
this._mods = [];
}
_addOffset(idx, ofs) {
this._mods.push({ idx, ofs });
}
get(start, end) {
// Adjust the offsets relative to all applied changes.
for (const mod of this._mods) {
if (start >= mod.idx) {
start += mod.ofs;
end += mod.ofs;
}
}
return this._str.substring(start, end);
}
sub(start, end, sub) {
// Adjust the offsets relative to all applied changes.
for (const mod of this._mods) {
if (start >= mod.idx) {
start += mod.ofs;
end += mod.ofs;
}
}
const repl = this._str.substring(0, start) + sub + this._str.substring(end);
const origLength = end - start;
if (sub.length !== origLength)
this._addOffset(end, sub.length - origLength);
this._str = repl;
}
toString() {
return this._str;
}
} |
JavaScript | class PyProxyIterableMethods {
/**
* This translates to the Python code ``iter(obj)``. Return an iterator
* associated to the proxy. See the documentation for `Symbol.iterator
* <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/iterator>`_.
*
* Present only if the proxied Python object is iterable (i.e., has an
* ``__iter__`` method).
*
* This will be used implicitly by ``for(let x of proxy){}``.
*
* @returns {Iterator<Py2JsResult, Py2JsResult, any>} An iterator for the proxied Python object.
*/
[Symbol.iterator]() {
let ptrobj = _getPtr(this);
let token = {};
let iterptr;
try {
iterptr = Module._PyObject_GetIter(ptrobj);
} catch (e) {
Module.fatal_error(e);
}
let result = iter_helper(iterptr, token);
Module.finalizationRegistry.register(result, [iterptr, undefined], token);
return result;
}
} |
JavaScript | class PyProxyAwaitableMethods {
/**
* This wraps __pyproxy_ensure_future and makes a function that converts a
* Python awaitable to a promise, scheduling the awaitable on the Python
* event loop if necessary.
* @private
*/
_ensure_future() {
let ptrobj = _getPtr(this);
let resolveHandle;
let rejectHandle;
let promise = new Promise((resolve, reject) => {
resolveHandle = resolve;
rejectHandle = reject;
});
let resolve_handle_id = Module.hiwire.new_value(resolveHandle);
let reject_handle_id = Module.hiwire.new_value(rejectHandle);
let errcode;
try {
errcode = Module.__pyproxy_ensure_future(
ptrobj,
resolve_handle_id,
reject_handle_id
);
} catch (e) {
Module.fatal_error(e);
} finally {
Module.hiwire.decref(reject_handle_id);
Module.hiwire.decref(resolve_handle_id);
}
if (errcode === -1) {
Module._pythonexc2js();
}
return promise;
}
/**
* Runs ``asyncio.ensure_future(awaitable)``, executes
* ``onFulfilled(result)`` when the ``Future`` resolves successfully,
* executes ``onRejected(error)`` when the ``Future`` fails. Will be used
* implictly by ``await obj``.
*
* See the documentation for
* `Promise.then
* <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then>`_
*
* Present only if the proxied Python object is `awaitable
* <https://docs.python.org/3/library/asyncio-task.html?highlight=awaitable#awaitables>`_.
*
* @param {Function} onFulfilled A handler called with the result as an
* argument if the awaitable succeeds.
* @param {Function} onRejected A handler called with the error as an
* argument if the awaitable fails.
* @returns {Promise} The resulting Promise.
*/
then(onFulfilled, onRejected) {
let promise = this._ensure_future();
return promise.then(onFulfilled, onRejected);
}
/**
* Runs ``asyncio.ensure_future(awaitable)`` and executes
* ``onRejected(error)`` if the future fails.
*
* See the documentation for
* `Promise.catch
* <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch>`_.
*
* Present only if the proxied Python object is `awaitable
* <https://docs.python.org/3/library/asyncio-task.html?highlight=awaitable#awaitables>`_.
*
* @param {Function} onRejected A handler called with the error as an
* argument if the awaitable fails.
* @returns {Promise} The resulting Promise.
*/
catch(onRejected) {
let promise = this._ensure_future();
return promise.catch(onRejected);
}
/**
* Runs ``asyncio.ensure_future(awaitable)`` and executes
* ``onFinally(error)`` when the future resolves.
*
* See the documentation for
* `Promise.finally
* <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally>`_.
*
* Present only if the proxied Python object is `awaitable
* <https://docs.python.org/3/library/asyncio-task.html?highlight=awaitable#awaitables>`_.
*
*
* @param {Function} onFinally A handler that is called with zero arguments
* when the awaitable resolves.
* @returns {Promise} A Promise that resolves or rejects with the same
* result as the original Promise, but only after executing the
* ``onFinally`` handler.
*/
finally(onFinally) {
let promise = this._ensure_future();
return promise.finally(onFinally);
}
} |
JavaScript | class PyBuffer {
constructor() {
/**
* The offset of the first entry of the array. For instance if our array
* is 3d, then you will find ``array[0,0,0]`` at
* ``pybuf.data[pybuf.offset]``
* @type {number}
*/
this.offset;
/**
* If the data is readonly, you should not modify it. There is no way
* for us to enforce this, but it may cause very weird behavior.
* @type {boolean}
*/
this.readonly;
/**
* The format string for the buffer. See `the Python documentation on
* format strings
* <https://docs.python.org/3/library/struct.html#format-strings>`_.
* @type {string}
*/
this.format;
/**
* How large is each entry (in bytes)?
* @type {number}
*/
this.itemsize;
/**
* The number of dimensions of the buffer. If ``ndim`` is 0, the buffer
* represents a single scalar or struct. Otherwise, it represents an
* array.
* @type {number}
*/
this.ndim;
/**
* The total number of bytes the buffer takes up. This is equal to
* ``buff.data.byteLength``.
* @type {number}
*/
this.nbytes;
/**
* The shape of the buffer, that is how long it is in each dimension.
* The length will be equal to ``ndim``. For instance, a 2x3x4 array
* would have shape ``[2, 3, 4]``.
* @type {number[]}
*/
this.shape;
/**
* An array of of length ``ndim`` giving the number of elements to skip
* to get to a new element in each dimension. See the example definition
* of a ``multiIndexToIndex`` function above.
* @type {number[]}
*/
this.strides;
/**
* The actual data. A typed array of an appropriate size backed by a
* segment of the WASM memory.
*
* The ``type`` argument of :any:`PyProxy.getBuffer`
* determines which sort of ``TypedArray`` this is. By default
* :any:`PyProxy.getBuffer` will look at the format string to determine the most
* appropriate option.
* @type {TypedArray}
*/
this.data;
/**
* Is it C contiguous?
* @type {boolean}
*/
this.c_contiguous;
/**
* Is it Fortran contiguous?
* @type {boolean}
*/
this.f_contiguous;
throw new TypeError("PyBuffer is not a constructor");
}
/**
* Release the buffer. This allows the memory to be reclaimed.
*/
release() {
if (this._released) {
return;
}
// Module.bufferFinalizationRegistry.unregister(this);
try {
Module._PyBuffer_Release(this._view_ptr);
Module._PyMem_Free(this._view_ptr);
} catch (e) {
Module.fatal_error(e);
}
this._released = !!1;
this.data = null;
}
} |
JavaScript | class IPValidationRule extends ValidationRule {
/**
* The class constructor.
*
* @param {?string[]} [params] An array of strings containing some additional parameters the validation should take care of.
*
* @throws {InvalidArgumentException} If an invalid array of parameters is given.
* @throws {InvalidArgumentException} If an invalid IP version is given.
*/
constructor(params) {
super(params);
/**
* @type {?string} [_version] A string containing the accepted IP version, by default both IPv4 and IPv6 are accepted.
*
* @protected
*/
this._version = null;
if ( Array.isArray(params) && params.length > 0 ){
if ( params[0] !== '4' && params[0] !== '6' ){
throw new InvalidArgumentException('Invalid IP version.', 1);
}
this._version = params[0];
}
}
/**
* Validates a given value.
*
* @param {*} value The value to validate, usually a string, however, no type validation is performed allowing to pass an arbitrary value.
* @param {Validator} validator An instance of the "Validator" class representing the validator this rule is used in.
* @param {Object.<string, *>} params An object containing all the parameters being validated by the validator this rule is used in.
*
* @returns {boolean} If validation passes will be returned "true".
*/
validate(value, validator, params){
let valid = false;
if ( value !== '' && typeof value === 'string' ){
if ( !valid && ( this._version === null || this._version === '4' ) ){
// Check if the string being validated is a valid IPv4.
const IPV4Regex = new RegExp('^(?=.*[^\\.]$)((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.?){4}$');
valid = IPV4Regex.test(value);
}
if ( !valid && ( this._version === null || this._version === '6' ) ){
// Check if the string is a valid IPv6.
const IPV6Regex = new RegExp('((^\\s*((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\\s*$)|(^\\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:)))(%.+)?\\s*$))', 'g');
valid = IPV6Regex.test(value);
}
}
return valid;
}
/**
* Returns the error message that should be returned whenever this validation rule fails.
*
* @returns {string} A string containing the error message.
*/
getMessage() {
let message;
switch ( this._version ){
case '4': {
message = 'Field {fieldName} must contains a valid IPv4 address.';
}break;
case '6': {
message = 'Field {fieldName} must contains a valid IPv6 address.';
}break;
default: {
message = 'Field {fieldName} must contains a valid IP address.';
}break;
}
return message;
}
} |
JavaScript | class PackageJson {
/**
* Initialize PackageJson
* @param {string} pkgPath - The path of package.json.
* @param {Object} json - The parsed content of package.json.
*/
constructor(pkgPath, json) {
this._path = pkgPath;
this._json = assign({}, json);
}
/**
* Return true if the given module is listed in
* `dependencies`.
* @param {string} moduleName
* @return {boolean}
*/
hasDep(moduleName) {
const deps = this.get('dependencies');
return deps.hasOwnProperty(moduleName);
}
/**
* Return true if the given module is listed in
* `devDependencies`.
* @param {string} moduleName
* @return {boolean}
*/
hasDevDep(moduleName) {
const devDeps = this.get('devDependencies');
return devDeps.hasOwnProperty(moduleName);
}
/**
* Return true if the given module is listed in
* `peerDependencies`.
* @param {string} moduleName
* @return {boolean}
*/
hasPeerDep(moduleName) {
const peerDeps = this.get('peerDependencies');
return peerDeps.hasOwnProperty(moduleName);
}
/**
* Get the value of the specified key.
* If the key doesn't exist, 'defaultValue' is returned.
* @param {string} key
* @param {*} defaultValue - Returned if the key is not found.
* @return {*} The value of the key.
*/
get(key, defaultValue = {}) {
return this._json[key] || defaultValue;
}
/**
* Get the {@link FileInfo} instance of the package.json file.
* @return {FileInfo}
*/
getFileInfo() {
return FileInfo.asDev(this._path);
}
} |
JavaScript | class Vector4 {
/**
* Creates a Vector4 object from the given floats.
* @param x x value of the vector
* @param y y value of the vector
* @param z z value of the vector
* @param w w value of the vector
*/
constructor(
/** x value of the vector */
x,
/** y value of the vector */
y,
/** z value of the vector */
z,
/** w value of the vector */
w) {
this.x = x;
this.y = y;
this.z = z;
this.w = w;
}
/**
* Returns the string with the Vector4 coordinates.
* @returns a string containing all the vector values
*/
toString() {
return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
}
/**
* Returns a JSON representation of this vector. This is necessary due to the way
* Actors detect changes on components like the actor's transform. They do this by adding
* properties for observation, and we don't want these properties serialized.
*/
toJSON() {
return {
x: this.x,
y: this.y,
z: this.z,
w: this.w,
};
}
/**
* Returns the string "Vector4".
* @returns "Vector4"
*/
getClassName() {
return "Vector4";
}
/**
* Returns the Vector4 hash code.
* @returns a unique hash code
*/
getHashCode() {
let hash = this.x || 0;
hash = (hash * 397) ^ (this.y || 0);
hash = (hash * 397) ^ (this.z || 0);
hash = (hash * 397) ^ (this.w || 0);
return hash;
}
// Operators
/**
* Returns a new array populated with 4 elements : the Vector4 coordinates.
* @returns the resulting array
*/
asArray() {
const result = new Array();
this.toArray(result, 0);
return result;
}
/**
* Populates the given array from the given index with the Vector4 coordinates.
* @param array array to populate
* @param index index of the array to start at (default: 0)
* @returns the Vector4.
*/
toArray(array, index) {
if (index === undefined) {
index = 0;
}
array[index] = this.x;
array[index + 1] = this.y;
array[index + 2] = this.z;
array[index + 3] = this.w;
return this;
}
/**
* Adds the given vector to the current Vector4.
* @param otherVector the vector to add
* @returns the updated Vector4.
*/
addInPlace(otherVector) {
this.x += otherVector.x;
this.y += otherVector.y;
this.z += otherVector.z;
this.w += otherVector.w;
return this;
}
/**
* Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
* @param otherVector the vector to add
* @returns the resulting vector
*/
add(otherVector) {
return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
}
/**
* Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
* @param otherVector the vector to add
* @param result the vector to store the result
* @returns the current Vector4.
*/
addToRef(otherVector, result) {
result.x = this.x + otherVector.x;
result.y = this.y + otherVector.y;
result.z = this.z + otherVector.z;
result.w = this.w + otherVector.w;
return this;
}
/**
* Subtract in place the given vector from the current Vector4.
* @param otherVector the vector to subtract
* @returns the updated Vector4.
*/
subtractInPlace(otherVector) {
this.x -= otherVector.x;
this.y -= otherVector.y;
this.z -= otherVector.z;
this.w -= otherVector.w;
return this;
}
/**
* Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
* @param otherVector the vector to add
* @returns the new vector with the result
*/
subtract(otherVector) {
return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
}
/**
* Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
* @param otherVector the vector to subtract
* @param result the vector to store the result
* @returns the current Vector4.
*/
subtractToRef(otherVector, result) {
result.x = this.x - otherVector.x;
result.y = this.y - otherVector.y;
result.z = this.z - otherVector.z;
result.w = this.w - otherVector.w;
return this;
}
/**
* Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
*/
/**
* Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
* @param x value to subtract
* @param y value to subtract
* @param z value to subtract
* @param w value to subtract
* @returns new vector containing the result
*/
subtractFromFloats(x, y, z, w) {
return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
}
/**
* Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
* @param x value to subtract
* @param y value to subtract
* @param z value to subtract
* @param w value to subtract
* @param result the vector to store the result in
* @returns the current Vector4.
*/
subtractFromFloatsToRef(x, y, z, w, result) {
result.x = this.x - x;
result.y = this.y - y;
result.z = this.z - z;
result.w = this.w - w;
return this;
}
/**
* Returns a new Vector4 set with the current Vector4 negated coordinates.
* @returns a new vector with the negated values
*/
negate() {
return new Vector4(-this.x, -this.y, -this.z, -this.w);
}
/**
* Multiplies the current Vector4 coordinates by scale (float).
* @param scale the number to scale with
* @returns the updated Vector4.
*/
scaleInPlace(scale) {
this.x *= scale;
this.y *= scale;
this.z *= scale;
this.w *= scale;
return this;
}
/**
* Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
* @param scale the number to scale with
* @returns a new vector with the result
*/
scale(scale) {
return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
}
/**
* Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
* @param scale the number to scale with
* @param result a vector to store the result in
* @returns the current Vector4.
*/
scaleToRef(scale, result) {
result.x = this.x * scale;
result.y = this.y * scale;
result.z = this.z * scale;
result.w = this.w * scale;
return this;
}
/**
* Scale the current Vector4 values by a factor and add the result to a given Vector4
* @param scale defines the scale factor
* @param result defines the Vector4 object where to store the result
* @returns the unmodified current Vector4
*/
scaleAndAddToRef(scale, result) {
result.x += this.x * scale;
result.y += this.y * scale;
result.z += this.z * scale;
result.w += this.w * scale;
return this;
}
/**
* Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
* @param otherVector the vector to compare against
* @returns true if they are equal
*/
equals(otherVector) {
return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
}
/**
* Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
* @param otherVector vector to compare against
* @param epsilon (Default: very small number)
* @returns true if they are equal
*/
equalsWithEpsilon(otherVector, epsilon = _1.Epsilon) {
return otherVector
&& _1.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
&& _1.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
&& _1.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
&& _1.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
}
/**
* Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
* @param x x value to compare against
* @param y y value to compare against
* @param z z value to compare against
* @param w w value to compare against
* @returns true if equal
*/
equalsToFloats(x, y, z, w) {
return this.x === x && this.y === y && this.z === z && this.w === w;
}
/**
* Multiplies in place the current Vector4 by the given one.
* @param otherVector vector to multiple with
* @returns the updated Vector4.
*/
multiplyInPlace(otherVector) {
this.x *= otherVector.x;
this.y *= otherVector.y;
this.z *= otherVector.z;
this.w *= otherVector.w;
return this;
}
/**
* Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
* @param otherVector vector to multiple with
* @returns resulting new vector
*/
multiply(otherVector) {
return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
}
/**
* Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
* @param otherVector vector to multiple with
* @param result vector to store the result
* @returns the current Vector4.
*/
multiplyToRef(otherVector, result) {
result.x = this.x * otherVector.x;
result.y = this.y * otherVector.y;
result.z = this.z * otherVector.z;
result.w = this.w * otherVector.w;
return this;
}
/**
* Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
* @param x x value multiply with
* @param y y value multiply with
* @param z z value multiply with
* @param w w value multiply with
* @returns resulting new vector
*/
multiplyByFloats(x, y, z, w) {
return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
}
/**
* Returns a new Vector4 set with the division result of the current Vector4 by the given one.
* @param otherVector vector to devide with
* @returns resulting new vector
*/
divide(otherVector) {
return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
}
/**
* Updates the given vector "result" with the division result of the current Vector4 by the given one.
* @param otherVector vector to devide with
* @param result vector to store the result
* @returns the current Vector4.
*/
divideToRef(otherVector, result) {
result.x = this.x / otherVector.x;
result.y = this.y / otherVector.y;
result.z = this.z / otherVector.z;
result.w = this.w / otherVector.w;
return this;
}
/**
* Divides the current Vector3 coordinates by the given ones.
* @param otherVector vector to devide with
* @returns the updated Vector3.
*/
divideInPlace(otherVector) {
return this.divideToRef(otherVector, this);
}
/**
* Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
* @param other defines the second operand
* @returns the current updated Vector4
*/
minimizeInPlace(other) {
if (other.x < this.x) {
this.x = other.x;
}
if (other.y < this.y) {
this.y = other.y;
}
if (other.z < this.z) {
this.z = other.z;
}
if (other.w < this.w) {
this.w = other.w;
}
return this;
}
/**
* Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
* @param other defines the second operand
* @returns the current updated Vector4
*/
maximizeInPlace(other) {
if (other.x > this.x) {
this.x = other.x;
}
if (other.y > this.y) {
this.y = other.y;
}
if (other.z > this.z) {
this.z = other.z;
}
if (other.w > this.w) {
this.w = other.w;
}
return this;
}
/**
* Gets a new Vector4 from current Vector4 floored values
* @returns a new Vector4
*/
floor() {
return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
}
/**
* Gets a new Vector4 from current Vector3 floored values
* @returns a new Vector4
*/
fract() {
return new Vector4(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z), this.w - Math.floor(this.w));
}
// Properties
/**
* Returns the Vector4 length (float).
* @returns the length
*/
length() {
return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
}
/**
* Returns the Vector4 squared length (float).
* @returns the length squared
*/
lengthSquared() {
return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
}
// Methods
/**
* Normalizes in place the Vector4.
* @returns the updated Vector4.
*/
normalize() {
const len = this.length();
if (len === 0) {
return this;
}
return this.scaleInPlace(1.0 / len);
}
/**
* Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
* @returns this converted to a new vector3
*/
toVector3() {
return new _1.Vector3(this.x, this.y, this.z);
}
/**
* Returns a new Vector4 copied from the current one.
* @returns the new cloned vector
*/
clone() {
return new Vector4(this.x, this.y, this.z, this.w);
}
/**
* Updates the current Vector4 with the given one coordinates.
* @param source the source vector to copy from
* @returns the updated Vector4.
*/
copyFrom(source) {
this.x = source.x;
this.y = source.y;
this.z = source.z;
this.w = source.w;
return this;
}
/**
* Updates the current Vector4 coordinates with the given floats.
* @param x float to copy from
* @param y float to copy from
* @param z float to copy from
* @param w float to copy from
* @returns the updated Vector4.
*/
copyFromFloats(x, y, z, w) {
this.x = x;
this.y = y;
this.z = z;
this.w = w;
return this;
}
/**
* Updates the current Vector4 coordinates with the given floats.
* @param x float to set from
* @param y float to set from
* @param z float to set from
* @param w float to set from
* @returns the updated Vector4.
*/
set(x, y, z, w) {
return this.copyFromFloats(x, y, z, w);
}
/**
* Copies the given float to the current Vector3 coordinates
* @param v defines the x, y, z and w coordinates of the operand
* @returns the current updated Vector3
*/
setAll(v) {
this.x = this.y = this.z = this.w = v;
return this;
}
// Statics
/**
* Returns a new Vector4 set from the starting index of the given array.
* @param array the array to pull values from
* @param offset the offset into the array to start at
* @returns the new vector
*/
static FromArray(array, offset) {
if (!offset) {
offset = 0;
}
return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
}
/**
* Updates the given vector "result" from the starting index of the given array.
* @param array the array to pull values from
* @param offset the offset into the array to start at
* @param result the vector to store the result in
*/
static FromArrayToRef(array, offset, result) {
result.x = array[offset];
result.y = array[offset + 1];
result.z = array[offset + 2];
result.w = array[offset + 3];
}
/**
* Updates the given vector "result" from the starting index of the given Float32Array.
* @param array the array to pull values from
* @param offset the offset into the array to start at
* @param result the vector to store the result in
*/
static FromFloatArrayToRef(array, offset, result) {
Vector4.FromArrayToRef(array, offset, result);
}
/**
* Updates the given vector "result" coordinates from the given floats.
* @param x float to set from
* @param y float to set from
* @param z float to set from
* @param w float to set from
* @param result the vector to the floats in
*/
static FromFloatsToRef(x, y, z, w, result) {
result.x = x;
result.y = y;
result.z = z;
result.w = w;
}
/**
* Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
* @returns the new vector
*/
static Zero() {
return new Vector4(0.0, 0.0, 0.0, 0.0);
}
/**
* Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
* @returns the new vector
*/
static One() {
return new Vector4(1.0, 1.0, 1.0, 1.0);
}
/**
* Returns a new normalized Vector4 from the given one.
* @param vector the vector to normalize
* @returns the vector
*/
static Normalize(vector) {
const result = Vector4.Zero();
Vector4.NormalizeToRef(vector, result);
return result;
}
/**
* Updates the given vector "result" from the normalization of the given one.
* @param vector the vector to normalize
* @param result the vector to store the result in
*/
static NormalizeToRef(vector, result) {
result.copyFrom(vector);
result.normalize();
}
/**
* Returns a vector with the minimum values from the left and right vectors
* @param left left vector to minimize
* @param right right vector to minimize
* @returns a new vector with the minimum of the left and right vector values
*/
static Minimize(left, right) {
const min = left.clone();
min.minimizeInPlace(right);
return min;
}
/**
* Returns a vector with the maximum values from the left and right vectors
* @param left left vector to maximize
* @param right right vector to maximize
* @returns a new vector with the maximum of the left and right vector values
*/
static Maximize(left, right) {
const max = left.clone();
max.maximizeInPlace(right);
return max;
}
/**
* Returns the distance (float) between the vectors "value1" and "value2".
* @param value1 value to calulate the distance between
* @param value2 value to calulate the distance between
* @return the distance between the two vectors
*/
static Distance(value1, value2) {
return Math.sqrt(Vector4.DistanceSquared(value1, value2));
}
/**
* Returns the squared distance (float) between the vectors "value1" and "value2".
* @param value1 value to calulate the distance between
* @param value2 value to calulate the distance between
* @return the distance between the two vectors squared
*/
static DistanceSquared(value1, value2) {
const x = value1.x - value2.x;
const y = value1.y - value2.y;
const z = value1.z - value2.z;
const w = value1.w - value2.w;
return (x * x) + (y * y) + (z * z) + (w * w);
}
/**
* Returns a new Vector4 located at the center between the vectors "value1" and "value2".
* @param value1 value to calulate the center between
* @param value2 value to calulate the center between
* @return the center between the two vectors
*/
static Center(value1, value2) {
const center = value1.add(value2);
center.scaleInPlace(0.5);
return center;
}
/**
* Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
* This methods computes transformed normalized direction vectors only.
* @param vector the vector to transform
* @param transformation the transformation matrix to apply
* @returns the new vector
*/
static TransformNormal(vector, transformation) {
const result = Vector4.Zero();
Vector4.TransformNormalToRef(vector, transformation, result);
return result;
}
/**
* Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
* This methods computes transformed normalized direction vectors only.
* @param vector the vector to transform
* @param transformation the transformation matrix to apply
* @param result the vector to store the result in
*/
static TransformNormalToRef(vector, transformation, result) {
const m = transformation.m;
const x = (vector.x * m[0]) + (vector.y * m[4]) + (vector.z * m[8]);
const y = (vector.x * m[1]) + (vector.y * m[5]) + (vector.z * m[9]);
const z = (vector.x * m[2]) + (vector.y * m[6]) + (vector.z * m[10]);
result.x = x;
result.y = y;
result.z = z;
result.w = vector.w;
}
/**
* Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
* This methods computes transformed normalized direction vectors only.
* @param x value to transform
* @param y value to transform
* @param z value to transform
* @param w value to transform
* @param transformation the transformation matrix to apply
* @param result the vector to store the results in
*/
static TransformNormalFromFloatsToRef(x, y, z, w, transformation, result) {
const m = transformation.m;
result.x = (x * m[0]) + (y * m[4]) + (z * m[8]);
result.y = (x * m[1]) + (y * m[5]) + (z * m[9]);
result.z = (x * m[2]) + (y * m[6]) + (z * m[10]);
result.w = w;
}
} |
JavaScript | class ObservableService {
constructor(__observableProvider) {
this.__observableProvider = __observableProvider;
}
get __observable() {
if (!(this.____observable)) {
if ((typeof this.__observableProvider.getObservable) !== 'function') {
throw new Error("The property '_observableProvider' must have a method" +
" 'getObservable()'");
}
this.____observable = this.__observableProvider.getObservable();
}
return this.____observable;
}
subscribe(observer) {
return this.__observable.subscribe(observer);
}
} |
JavaScript | class ServiceBillingPlans {
/**
* Create a ServiceBillingPlans.
* @member {boolean} [canSelectTrialPlan] Can customer select trial plan for
* that service (if it exists)?
* @member {string} [lastTrialPlanExpirationTime] Expiration time of the last
* selected trial plan. Will be null if trial plan was not used.
* @member {object} [currentBillingPeriod]
* @member {string} [currentBillingPeriod.startTime] Inclusive start of the
* period
* @member {string} [currentBillingPeriod.endTime] Exclusive end of the
* period.
* @member {object} [currentBillingPeriod.byAccount]
* @member {number} [currentBillingPeriod.byAccount.count] Number of
* instances of the billing plan.
* @member {object} [currentBillingPeriod.byAccount.plan]
* @member {string} [currentBillingPeriod.byAccount.plan.id] The Billing Plan
* ID
* @member {string} [currentBillingPeriod.byAccount.plan.version] Version of
* the Billing Plan schema
* @member {number} [currentBillingPeriod.byAccount.plan.priceBucket] Price
* bucket of the billing plan. Free plans start with 0, paid plans have
* higher price buckets
* @member {string} [currentBillingPeriod.byAccount.plan.service] Name of the
* service that the plan applies to. Possible values include: 'Build',
* 'Push', 'Test'
* @member {object} [currentBillingPeriod.byAccount.plan.limits]
* @member {object} [currentBillingPeriod.byAccount.plan.attributes]
*/
constructor() {
}
/**
* Defines the metadata of ServiceBillingPlans
*
* @returns {object} metadata of ServiceBillingPlans
*
*/
mapper() {
return {
required: false,
serializedName: 'ServiceBillingPlans',
type: {
name: 'Composite',
className: 'ServiceBillingPlans',
modelProperties: {
canSelectTrialPlan: {
required: false,
serializedName: 'canSelectTrialPlan',
type: {
name: 'Boolean'
}
},
lastTrialPlanExpirationTime: {
required: false,
serializedName: 'lastTrialPlanExpirationTime',
type: {
name: 'String'
}
},
currentBillingPeriod: {
required: false,
serializedName: 'currentBillingPeriod',
type: {
name: 'Composite',
className: 'BillingPeriod'
}
}
}
}
};
}
} |
JavaScript | class ROI {
/* @constructor
* @param{Scoord} scoord spatial coordinates
* @param{Object} properties qualititative evaluations
*/
constructor(options) {
if (!('scoord' in options)) {
console.error('spatial coordinates are required for ROI')
}
this.scoord = options.scoord;
this.properties = options.properties ? options.properties : {};
}
} |
JavaScript | class SafariAuthenticator extends Authenticator {
/**
* @constructor
*/
constructor () {
super()
this._authData = new AuthData()
this.hasUserData = false
// TODO: Hardcoded for now. Can we do it any better than that?
this.endpoints = Auth0env.ENDPOINTS
}
/**
* A link for login external to the Alpheios components.
* @returns null for client side login
*/
loginUrl () {
return null
}
/**
* A link for logout external to the Alpheios components.
* @returns null for client side login
*/
logoutUrl () {
return null
}
getEndPoints () {
return new Promise((resolve, reject) => {
if (this.hasUserData) {
// User data has been retrieved
resolve(this.endpoints)
} else {
reject('No user data has been retrieved yet') // eslint-disable-line prefer-promise-reject-errors
}
})
}
/**
* Returns an authentication data along with an expiration data.
* Is used to obtain user information and set expiration timeout
* if user has already been authenticated previously.
* @return {Promise<AuthData> | Promise<Error>}
*/
session () {
return new Promise((resolve, reject) => {
if (this._authData.isAuthenticated) {
resolve(this._authData)
} else {
reject(new Error('Not authenticated'))
}
})
}
/**
* @typedef SafariAuthData
* @property {string} userId - A user ID (`sub` in Auth0).
* @property {string} userName - A full name of the user.
* @property {string} userNickname - A user's nickname.
* @property {string} accessToken - An access token of the user.
* @property {Date} accessTokenExpiresIn - A date and time when access token expires.
*/
/**
* Authenticates user with an Auth0.
* @param {SafariAuthData} authData - A user auth data.
* @returns {Promise | Promise<Error>} Is resolved with an empty promise in case of success and
* is rejected with an error in case of failure.
*/
authenticate (authData) {
return new Promise((resolve, reject) => {
// Check the validity of user data. All required fields must be available
if (!authData.userId || !authData.userName || !authData.userNickname || !authData.accessToken) {
reject(new Error('Some of the required parameters (userId, userNae, userNickname, accessToken) are missing'))
}
this._authData.userId = authData.userId
this._authData.userName = authData.userName
this._authData.userNickname = authData.userNickname
this._authData.accessToken = authData.accessToken
this._authData.expirationDateTime = authData.accessTokenExpiresIn
this.hasUserData = true
this._authData.isAuthenticated = true
this._authData.hasSessionExpired = false
resolve()
})
}
/**
* @typedef UserProfileData
* @property {string} name - A full name of the user.
* @property {string} nickname - A user's nickname.
* @property {string} sub - A user ID.
*/
/**
* Retrieves user profile information.
* This function can be used by third-party libraries to retrieve user profile data.
* One example of such use is a UserDataManager which is used by the word list controller.
* @return {Promise<UserProfileData>|Promise<Error>} - Resolved with user profile data
* in case of success or rejected with an error in case of failure.
*/
getProfileData () {
return new Promise((resolve, reject) => {
if (this.hasUserData) {
// User data has been retrieved
resolve(this._authData)
} else {
reject('No user profile data is available yet') // eslint-disable-line prefer-promise-reject-errors
}
})
}
/**
* Retrieves user information (an access token currently).
* @return {Promise<string>|Promise<Error>} - Resolved with an access token
* in case of success or rejected with an error in case of failure.
*/
getUserData () {
return new Promise((resolve, reject) => {
if (this.hasUserData) {
// User data has been retrieved
resolve(this._authData.accessToken)
} else {
reject('No user data has been retrieved yet') // eslint-disable-line prefer-promise-reject-errors
}
})
}
get iFrameURL () {
return Auth0env.ALPHEIOS_DOMAIN || ''
}
/**
* Logs the user out
*/
logout () {
return new Promise((resolve, reject) => {
// Erase user data
this.hasUserData = false
this._authData.erase()
resolve()
})
}
} |
JavaScript | class Format {
number(value) {
return this.formatNumber(value, {});
}
round(value, decimalPlaces=0) {
const intlOptions = {
style: 'decimal',
maximumFractionDigits: decimalPlaces,
minimumFractionDigits: decimalPlaces,
};
return this.formatNumber(value, intlOptions);
}
currency(value, currencyCode) {
const intlOptions = { style: 'currency', currency: currencyCode, maximumFractionDigits: 2 };
return this.formatNumber(value, intlOptions);
}
percent(value, decimalPlaces=0) {
const intlOptions = {
style: 'percent',
maximumFractionDigits: decimalPlaces,
minimumFractionDigits: decimalPlaces,
};
return this.formatNumber(value, intlOptions);
}
date(value) {
return this.formatDateTime(value, {});
}
dateTime(value) {
const intlOptions = { year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric' };
return this.formatDateTime(value, intlOptions);
}
time(value) {
const intlOptions = { hour: 'numeric', minute: 'numeric', second: 'numeric' };
return this.formatDateTime(value, intlOptions);
}
// Return true if a valid number, this excludes Infinity and NaN
isNumber(n) {
return (!isNaN(parseFloat(n)) && isFinite(n));
}
// Format a date, date/time or time value with Intl.DateTimeFormat()
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat
formatDateTime(dateTime, options) {
// Fallback to data in original format.
// As of 2020 this would most likely happen on older iOS.
if (window.Intl === undefined) {
return dateTime;
}
// Make sure a value exists
if (dateTime === null || dateTime === '') {
return null;
}
// Return formatted date/time in the user's local language
try {
if (dateTime instanceof Date) {
return new Intl.DateTimeFormat(navigator.language, options).format(dateTime);
} else if (/^\d{4}-\d{2}-\d{2}$/.test(dateTime)) {
// Basic date without timezone (YYYY-MM-DD)
const nums = dateTime.split('-').map(function(n) { return parseInt(n, 10); });
const date = new Date(nums[0], nums[1] - 1, nums[2]);
return new Intl.DateTimeFormat(navigator.language, options).format(date);
} else {
// Assume JavaScript `Date` object can parse the date.
// In the future a new Temporal may be used instead:
// https://tc39.es/proposal-temporal/docs/
const localDate = new Date(dateTime);
return new Intl.DateTimeFormat(navigator.language, options).format(localDate);
}
} catch (e) {
// If Error log to console and return 'Error' text
console.warn('Error formatting Date/Time Value:');
console.log(navigator.language);
console.log(options);
console.log(dateTime);
console.log(e);
return 'Error';
}
}
// Format a numeric value with Intl.NumberFormat()
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat
formatNumber(value, options) {
// Check for a valid number
if (value === null || value === '') {
return null;
}
if (!this.isNumber(value)) {
console.warn('Warning value specified in DateFormsJS function formatNumber() is not a number:');
console.log(value);
return value;
}
// Fallback to data in original format.
// As of 2020 this would most likely happen on older iOS.
if (window.Intl === undefined) {
return value;
}
// Return formatted number/currency/percent/etc in the user's local language
try {
return new Intl.NumberFormat(navigator.language, options).format(value);
} catch (e) {
// If Error log to console and return 'Error' text
console.warn('Error formatting Numeric Value:');
console.log(navigator.language);
console.log(options);
console.log(value);
console.log(e);
return 'Error';
}
}
} |
JavaScript | class AtlasAttachmentLoader {
constructor(atlas) {
this.atlas = atlas;
}
newRegionAttachment(skin, name, path) {
let region = this.atlas.findRegion(path);
if (!region)
throw new Error("Region not found in atlas: " + path + " (region attachment: " + name + ")");
region.renderObject = region;
let attachment = new RegionAttachment(name);
attachment.setRegion(region);
return attachment;
}
newMeshAttachment(skin, name, path) {
let region = this.atlas.findRegion(path);
if (!region)
throw new Error("Region not found in atlas: " + path + " (mesh attachment: " + name + ")");
region.renderObject = region;
let attachment = new MeshAttachment(name);
attachment.region = region;
return attachment;
}
newBoundingBoxAttachment(skin, name) {
return new BoundingBoxAttachment(name);
}
newPathAttachment(skin, name) {
return new PathAttachment(name);
}
newPointAttachment(skin, name) {
return new PointAttachment(name);
}
newClippingAttachment(skin, name) {
return new ClippingAttachment(name);
}
} |
JavaScript | class APIS {
constructor() {
this.credentials = null
}
// ----------------- INSTALLER
install() {
const apis = this
Vue.mixin({
beforeCreate() {
this.$api = apis
},
})
}
// ----------------- UTILS
__get_cookie(key) {
return Object.fromEntries(document.cookie.split('; ').map(cd => cd.split('=')))[key]
}
// ----------------- INNER API CALLERS
async __auth_user_api(endpoint, method, data, headers, data_format = 'json') {
headers = headers ?? {}
const options = { method, headers }
if (data) {
headers['Content-type'] = {
'json': 'application/json',
'text': 'text/plain'
}[data_format] ?? data_format
options.body = data_format == 'json' ? JSON.stringify(data) : data
}
const url = ["/api/auth", endpoint].join('/')
const resp = await fetch(url, options)
if (!resp.ok) throw new Error(await resp.text())
if (resp.headers.get('content-type').includes('application/json')) return await resp.json()
return await resp.text()
}
async __users_roles_api(endpoint, method, data, headers, data_format = 'json') {
headers = headers ?? {}
const options = { method, headers }
if (data) {
headers['Content-type'] = {
'json': 'application/json',
'text': 'text/plain'
}[data_format] ?? data_format
options.body = data_format == 'json' ? JSON.stringify(data) : data
}
const url = ["/api/auth", "admin", endpoint].join('/')
const resp = await fetch(url, options)
if (!resp.ok) throw new Error(await resp.text())
if (resp.headers.get('content-type').includes('application/json')) return await resp.json()
return await resp.text()
}
async __admin_users_api(endpoint, method, data, headers, data_format = 'json') {
headers = headers ?? {}
const options = { method, headers }
if (data) {
headers['Content-type'] = {
'json': 'application/json',
'text': 'text/plain'
}[data_format] ?? data_format
options.body = data_format == 'json' ? JSON.stringify(data) : data
}
const url = ["/api/auth", "admin", endpoint].join('/')
const resp = await fetch(url, options)
if (!resp.ok) throw new Error(await resp.text())
if (resp.headers.get('content-type').includes('application/json')) return await resp.json()
return await resp.text()
}
async __auth_api(endpoint, method, data, headers, data_format = 'json') {
headers = headers ?? {}
const options = { method, headers }
if (data) {
headers['Content-type'] = {
'json': 'application/json',
'text': 'text/plain'
}[data_format] ?? data_format
options.body = data_format == 'json' ? JSON.stringify(data) : data
}
const url = ["/api/auth", endpoint].join('/')
const resp = await fetch(url, options)
if (!resp.ok) throw new Error(await resp.text())
if (resp.headers.get('content-type').includes('application/json')) return await resp.json()
return await resp.text()
}
// ----------------- EXTERNAL CALLERS
auth = {
connected: () => {
const headers = null
return this.__auth_api("connect", "get", null, headers, null)
},
connect: (data = null) => {
const headers = null
return this.__auth_api("connect", "post", data, headers, "json")
},
get_token: () => {
const headers = null
return this.__auth_api("token", "get", null, headers, null)
},
change_password: (data = null) => {
const headers = null
return this.__auth_api("pass", "post", data, headers, "json")
},
user: {
disconnect: () => {
const headers = null
return this.__auth_user_api("connect", "delete", null, headers, null)
},
get: () => {
const headers = null
return this.__auth_user_api("", "get", null, headers, null)
},
is_admin: () => {
const headers = null
return this.__auth_user_api("is_admin", "get", null, headers, null)
},
},
admin: {
users: {
create: (data = null) => {
const headers = null
return this.__admin_users_api("create", "post", data, headers, "json")
},
delete: (conn) => {
const headers = null
return this.__admin_users_api("user/" + conn, "delete", null, headers, null)
},
list: () => {
const headers = null
return this.__admin_users_api("list", "get", null, headers, null)
},
roles: {
add: (conn, role) => {
const headers = null
return this.__users_roles_api("role/" + conn + "/" + role, "put", null, headers, null)
},
delete: (conn, role) => {
const headers = null
return this.__users_roles_api("role/" + conn + "/" + role, "delete", null, headers, null)
},
},
},
},
}
keys = {
}
} |
JavaScript | class NunjucksFileLinter extends FileLinter
{
/**
* @param {object|undefined} rules
* @param {object|undefined} options
* @param {nunjucks.EntityRenderer} entityRenderer
*/
constructor(rules, options, entityRenderer)
{
super(rules, options);
// Check params
assertParameter(this, 'entityRenderer', entityRenderer, true, EntityRenderer);
// Assign
const opts = options || {};
this._linter = new NunjucksLinter(entityRenderer, opts);
this._glob = opts.glob || ['/*.j2', '/examples/*.j2'];
}
/**
* @inheritDoc
*/
static get injections()
{
return { 'parameters': ['linter/NunjucksFileLinter.rules', 'linter/NunjucksFileLinter.options', EntityRenderer] };
}
/**
* @inheritDoc
*/
static get className()
{
return 'linter/NunjucksFileLinter';
}
} |
JavaScript | class GameData {
constructor() {
this._key = false;
this._intervalHandle = false;
this._extraData = false;
}
/**
* Activate periodic updates.
*
* @returns {GameData} self, for chaining
*/
enable() {
this.disable(); // cancel if currently active
const delay = this._key ? KEY_DELAY_MSECS : DEFAULT_DELAY_MSECS;
this._intervalHandle = setInterval(() => {
this._asyncUpdate();
}, delay);
return this;
}
/**
* Cancel periodic updates, if active.
*
* @returns {GameData} self, for chaining
*/
disable() {
if (this._intervalHandle) {
clearInterval(this._intervalHandle);
this._intervalHandle = false;
}
return this;
}
/**
* Enable streamer overlay mode, faster updates and includes player names.
* Caller must call enable() to reset timer!!
*
* @param {string} key
* @returns {GameData} self, for chaining
*/
setStreamerOverlayKey(key) {
assert(typeof key === "string");
assert(key.length > 0);
this._key = key;
return this;
}
/**
* Add 'extra' data component. Overwrites existing if present.
*
* NOTE: not persisted across save/load, caller must re-register if needed.
*
* @param {string} key
* @param {?} value - anything JSON serializable
* @returns {GameData} self, for chaining
*/
addExtra(key, value) {
if (!this._extraData) {
this._extraData = {};
}
this._extraData[key] = value;
return this;
}
_syncUpdate() {
const data = this._createGameDataShell();
for (const updator of UPDATORS) {
updator(data);
}
this._post(data);
}
_asyncUpdate() {
const data = this._createGameDataShell();
const updators = [...UPDATORS];
const doNextUpdatorOrPost = () => {
const updator = updators.shift();
if (!updator) {
this._post(data);
return;
}
process.nextTick(doNextUpdatorOrPost);
};
process.nextTick(doNextUpdatorOrPost);
}
_createGameDataShell() {
const data = {
timestamp: Date.now() / 1000,
players: world.TI4.getAllPlayerDesks().map((desk) => {
return { color: desk.colorName };
}),
};
// Streamer data includes player names.
if (this._key) {
for (const playerDesk of world.TI4.getAllPlayerDesks()) {
const playerData = data.players[playerDesk.index];
const player = world.getPlayerBySlot(playerDesk.playerSlot);
playerData.steamName = player ? player.getName() : "-";
}
}
if (this._extraData) {
data.extra = this._extraData;
}
return data;
}
_getUrl() {
const host = this._key === "localhost" ? LOCALHOST : DEFAULT_HOST;
const path = this._key ? "postkey" : "posttimestamp";
const urlArgs = [`timestamp=${world.TI4.config.timestamp}`];
if (this._key) {
urlArgs.push(`key=${this._key}`);
}
return `http://${host}/${path}?${urlArgs.join("&")}`;
}
_post(data) {
const url = this.getUrl();
const fetchOptions = {
body: JSON.stringify(data),
method: "POST",
};
const promise = fetch(url, fetchOptions);
promise.then((res) => console.log(JSON.stringify(res.json())));
}
} |
JavaScript | class Child extends React.Component {
render() {
return <div />;
}
} |
JavaScript | class MediumEventView extends BaseEventItem {
render() {
const { event } = this.props;
return (
<TouchableOpacity
disabled={!_.isFunction(this.props.onPress)}
onPress={this.onPress}
key={event.id}
>
<Card styleName="horizontal">
<EventImage styleName="medium-portrait rounded-corners" event={event} />
<View styleName="content pull-left space-between rounded-corners">
<Subtitle numberOfLines={3} >{event.name}</Subtitle>
<View styleName="horizontal stretch space-between v-center">
<Caption>
{formatDate(event.startTime)}
</Caption>
<Button
styleName="tight clear"
onPress={this.action}
>
<Icon name="add-event" />
</Button>
</View>
</View>
</Card>
</TouchableOpacity>
);
}
} |
JavaScript | class LocalDevModelClient extends ModelClient{
fetch(modelPath) {
if (!modelPath) {
const err = `Fetching model rejected for path: ${modelPath}`;
return Promise.reject(new Error(err));
}
// Either the API host has been provided or we make an absolute request relative to the current host
const apihostPrefix = this._apiHost || '';
const url = `${apihostPrefix}${modelPath}`;
return fetch(url, {
credentials: 'same-origin',
headers: {
'Authorization': process.env.REACT_APP_AEM_AUTHORIZATION_HEADER
}
}).then((response) => {
if ((response.status >= 200) && (response.status < 300)) {
return response.json() ;
}
return Promise.reject(response);
}).catch((error) => {
return Promise.reject(error);
});
}
} |
JavaScript | class GUI_pages_class {
constructor() {
this.Base_pages = new Base_pages_class();
this.Helper = new Helper_class();
}
render_main_pages() {
document.getElementById('pages_base').innerHTML = template;
this.render_pages();
this.set_events();
}
set_events() {
var _this = this;
document.getElementById('pages_base').addEventListener('click', function (event) {
var target = event.target;
/*if (target.id == 'insert_page') {
//new page
app.State.do_action(
new app.Actions.Insert_page_action()
);
}
else */if (target.id == 'page_up') {
//move page up
app.State.do_action(
new app.Actions.Reorder_page_action(config.page.id, 1)
);
}
else if (target.id == 'page_down') {
//move page down
app.State.do_action(
new app.Actions.Reorder_page_action(config.page.id, -1)
);
}
else if (target.id == 'delete') {
//delete layer
app.State.do_action(
new app.Actions.Delete_page_action(target.dataset.id)
);
}
else if (target.id == 'page_name') {
//select page
const activePage = config.page ? config.page.id : -1;
if (target.dataset.id == activePage)
return;
app.State.do_action(
new app.Actions.Select_page_action(target.dataset.id)
);
}
});
}
/**
* renders pages list
*/
render_pages() {
var target_id = 'pages';
var pages = config.pages.concat().sort(
//sort function
(a, b) => a.order - b.order
);
document.getElementById(target_id).innerHTML = '';
var html = '';
const activePage = config.page ? config.page.id : -1;
for (var i in pages) {
var value = pages[i];
if (value.id == activePage)
html += '<div class="item active">';
else
html += '<div class="item">';
html += ' <span class="delete" id="delete" data-id="' + value.id + '" title="Delete"></span>';
html += ' <span class="page_num" title="Page Number">' + value.label + '</span>';
html += ' <span class="page_name"><img id="page_name" data-id="' + value.id + '" src="' + value.thumbnail + '"></span>';
html += ' <div class="clear"></div>';
html += '</div>';
}
//register
document.getElementById(target_id).innerHTML = html;
}
} |
JavaScript | class ClientResolver {
constructor(reportBusyWhile) {
this.reportBusyWhile = reportBusyWhile;
this.clients = new Map();
this.memoizedClients = new Map();
this.emitter = new atom_1.Emitter();
this.subscriptions = new atom_1.CompositeDisposable();
this.tsserverInstancePerTsconfig = atom.config.get("atom-typescript")
.tsserverInstancePerTsconfig;
// This is just here so TypeScript can infer the types of the callbacks when using "on" method
// tslint:disable-next-line:member-ordering
this.on = this.emitter.on.bind(this.emitter);
this.diagnosticHandler = (serverPath, type) => (result) => {
const filePath = isConfDiagBody(result) ? result.configFile : result.file;
if (filePath) {
this.emitter.emit("diagnostics", {
type,
serverPath,
filePath,
diagnostics: result.diagnostics,
});
}
};
}
async restartAllServers() {
await this.reportBusyWhile("Restarting servers", () => Promise.all(Array.from(this.getAllClients()).map(client => client.restartServer())));
}
async get(pFilePath) {
const memo = this.memoizedClients.get(pFilePath);
if (memo)
return memo;
const client = this._get(pFilePath);
this.memoizedClients.set(pFilePath, client);
try {
return await client;
}
catch (e) {
this.memoizedClients.delete(pFilePath);
throw e;
}
}
dispose() {
this.emitter.dispose();
this.subscriptions.dispose();
this.memoizedClients.clear();
this.clients.clear();
}
async _get(pFilePath) {
const { pathToBin, version } = await resolveBinary_1.resolveBinary(pFilePath, "tsserver");
const tsconfigPath = this.tsserverInstancePerTsconfig
? ts.findConfigFile(pFilePath, f => ts.sys.fileExists(f))
: undefined;
let tsconfigMap = this.clients.get(pathToBin);
if (!tsconfigMap) {
tsconfigMap = new Map();
this.clients.set(pathToBin, tsconfigMap);
}
const client = tsconfigMap.get(tsconfigPath);
if (client)
return client;
const newClient = new client_1.TypescriptServiceClient(pathToBin, version, this.reportBusyWhile);
tsconfigMap.set(tsconfigPath, newClient);
this.subscriptions.add(newClient.on("configFileDiag", this.diagnosticHandler(pathToBin, "configFileDiag")), newClient.on("semanticDiag", this.diagnosticHandler(pathToBin, "semanticDiag")), newClient.on("syntaxDiag", this.diagnosticHandler(pathToBin, "syntaxDiag")), newClient.on("suggestionDiag", this.diagnosticHandler(pathToBin, "suggestionDiag")));
return newClient;
}
*getAllClients() {
for (const tsconfigMap of this.clients.values()) {
yield* tsconfigMap.values();
}
}
} |
JavaScript | class FishBody extends SwimmerAbstractBody {
/**
* @constructor
* @param scale {number} - Scale of the environment
* @param motors_torque {number}
* @param density {number} - Density of the agent's body.
* @param nb_steps_outside_water {number}
*/
constructor(scale, motors_torque=80, density, nb_steps_outside_water=600) {
super(scale, motors_torque, density, nb_steps_outside_water);
this.TORQUE_PENALTY = 0.00035;
this.AGENT_WIDTH = HULL_BOTTOM_WIDTH / this.SCALE;
this.AGENT_HEIGHT = 18 / this.SCALE;
this.AGENT_CENTER_HEIGHT = 9 / this.SCALE;
this.remove_reward_on_head_angle = true;
this.fins = [];
this.tail = null;
}
draw(world, init_x, init_y){
let vertices;
let rjd;
let joint_motor;
// HULL
let hull_fd = new b2.FixtureDef();
hull_fd.shape = new b2.PolygonShape();
vertices = [];
for(let vertex of HULL_POLYGON){
vertices.push(new b2.Vec2(vertex[0] / this.SCALE, vertex[1] / this.SCALE));
}
hull_fd.shape.Set(vertices, HULL_POLYGON.length);
hull_fd.density = this.DENSITY;
hull_fd.friction = 0.1;
hull_fd.filter.categoryBits = 0x20;
hull_fd.filter.maskBits = 0x000F; // 0.99 bouncy
let hull_bd = new b2.BodyDef();
hull_bd.type = b2.Body.b2_dynamicBody;
hull_bd.position.Set(init_x, init_y);
let hull = world.CreateBody(hull_bd);
hull.CreateFixture(hull_fd);
hull.color1 = "#806682"; // [0.5, 0.4, 0.9]
hull.color2 = "#4D4D80";
hull.SetUserData(new CustomBodyUserData(true, false, "head"));
this.body_parts.push(hull);
this.reference_head_object = hull;
// BODY_P1
let body_p1_x = init_x - 35 / 2 / this.SCALE - 16 / 2 / this.SCALE;
let body_p1_fd = new b2.FixtureDef();
body_p1_fd.shape = new b2.PolygonShape();
vertices = [];
for(let vertex of BODY_P1){
vertices.push(new b2.Vec2(vertex[0] / this.SCALE, vertex[1] / this.SCALE));
}
body_p1_fd.shape.Set(vertices, BODY_P1.length);
body_p1_fd.density = this.DENSITY;
body_p1_fd.restitution = 0.0;
body_p1_fd.filter.categoryBits = 0x20;
body_p1_fd.filter.maskBits = 0x000F; // 0.99 bouncy
let body_p1_bd = new b2.BodyDef();
body_p1_bd.type = b2.Body.b2_dynamicBody;
body_p1_bd.position.Set(body_p1_x, init_y);
let body_p1 = world.CreateBody(body_p1_bd);
body_p1.CreateFixture(body_p1_fd);
body_p1.color1 = "#806682"; // [0.5, 0.4, 0.9]
body_p1.color2 = "#4D4D80";
body_p1.SetUserData(new CustomBodyUserData(true, false, "body"));
this.body_parts.push(body_p1);
// Revolute joint between HULL and BODY_P1
rjd = new b2.RevoluteJointDef();
rjd.Initialize(hull, body_p1, new b2.Vec2(init_x - 35 / 2 / this.SCALE, init_y));
rjd.enableMotor = true;
rjd.enableLimit = true;
rjd.maxMotorTorque = this.MOTORS_TORQUE;
rjd.motorSpeed = 1;
rjd.lowerAngle = -0.1 * Math.PI;
rjd.upperAngle = 0.2 * Math.PI;
joint_motor = world.CreateJoint(rjd);
joint_motor.SetUserData(new CustomMotorUserData("neck", SPEED, true, 0.0, body_p1));
this.motors.push(joint_motor);
// BODY_P2
let body_p2_x = body_p1_x - 16 / 2 / this.SCALE - 16 / 2 / this.SCALE;
let body_p2_fd = new b2.FixtureDef();
body_p2_fd.shape = new b2.PolygonShape();
vertices = [];
for(let vertex of BODY_P2){
vertices.push(new b2.Vec2(vertex[0] / this.SCALE, vertex[1] / this.SCALE));
}
body_p2_fd.shape.Set(vertices, BODY_P2.length);
body_p2_fd.density = this.DENSITY;
body_p2_fd.restitution = 0.0;
body_p2_fd.filter.categoryBits = 0x20;
body_p2_fd.filter.maskBits = 0x000F;
let body_p2_bd = new b2.BodyDef();
body_p2_bd.type = b2.Body.b2_dynamicBody;
body_p2_bd.position.Set(body_p2_x, init_y);
let body_p2 = world.CreateBody(body_p2_bd);
body_p2.CreateFixture(body_p2_fd);
body_p2.color1 = "#806682"; // [0.5, 0.4, 0.9]
body_p2.color2 = "#4D4D80";
body_p2.SetUserData(new CustomBodyUserData(true, false, "body"));
this.body_parts.push(body_p2);
// Revolute joint between BODY_P1 and BODY_P2
rjd = new b2.RevoluteJointDef();
rjd.Initialize(body_p1, body_p2, new b2.Vec2(body_p1_x - 16 / 2 / this.SCALE, init_y));
rjd.enableMotor = true;
rjd.enableLimit = true;
rjd.maxMotorTorque = this.MOTORS_TORQUE;
rjd.motorSpeed = 1;
rjd.lowerAngle = -0.15 * Math.PI;
rjd.upperAngle = 0.15 * Math.PI;
joint_motor = world.CreateJoint(rjd);
joint_motor.SetUserData(new CustomMotorUserData("hip", SPEED, true, 0.0, body_p2));
this.motors.push(joint_motor);
// BODY_P3 - TAIL
let body_p3_x = body_p2_x - 16 / 2 / this.SCALE - 8 / 2 / this.SCALE;
let body_p3_fd = new b2.FixtureDef();
body_p3_fd.shape = new b2.PolygonShape();
vertices = [];
for(let vertex of BODY_P3){
vertices.push(new b2.Vec2(vertex[0] / this.SCALE, vertex[1] / this.SCALE));
}
body_p3_fd.shape.Set(vertices, BODY_P3.length);
body_p3_fd.density = this.DENSITY;
body_p3_fd.restitution = 0.0;
body_p3_fd.filter.categoryBits = 0x20;
body_p3_fd.filter.maskBits = 0x000F;
let body_p3_bd = new b2.BodyDef();
body_p3_bd.type = b2.Body.b2_dynamicBody;
body_p3_bd.position.Set(body_p3_x, init_y);
let body_p3 = world.CreateBody(body_p3_bd);
body_p3.CreateFixture(body_p3_fd);
body_p3.color1 = "#806682"; // [0.5, 0.4, 0.9]
body_p3.color2 = "#4D4D80";
body_p3.SetUserData(new CustomBodyUserData(true, false, "body"));
this.body_parts.push(body_p3);
this.tail = body_p3;
// Revolute joint between BODY_P2 and BODY_P3
rjd = new b2.RevoluteJointDef();
rjd.Initialize(body_p2, body_p3, new b2.Vec2(body_p2_x - 16 / 2 / this.SCALE, init_y));
rjd.enableMotor = true;
rjd.enableLimit = true;
rjd.maxMotorTorque = this.MOTORS_TORQUE;
rjd.motorSpeed = 1;
rjd.lowerAngle = -0.3 * Math.PI;
rjd.upperAngle = 0.3 * Math.PI;
joint_motor = world.CreateJoint(rjd);
joint_motor.SetUserData(new CustomMotorUserData("knee", SPEED, true, 0.0, body_p3));
this.motors.push(joint_motor);
// FINS
let fin_fd = new b2.FixtureDef();
fin_fd.shape = new b2.PolygonShape();
vertices = [];
for(let vertex of FIN){
vertices.push(new b2.Vec2(vertex[0] / this.SCALE, vertex[1] / this.SCALE));
}
fin_fd.shape.Set(vertices, FIN.length);
fin_fd.density = this.DENSITY;
fin_fd.restitution = 0.0;
fin_fd.filter.categoryBits = 0x20;
fin_fd.filter.maskBits = 0x000F;
let fin_positions = [
[init_x, init_y - 22 / 2 / this.SCALE + 0.2],
];
let fin_angle = -0.2 * Math.PI;
let middle_fin_x_distance = Math.sin(fin_angle) * 20 / 2 / this.SCALE;
let middle_fin_y_distance = Math.cos(fin_angle) * 20 / 2 / this.SCALE;
for(let fin_pos of fin_positions){
let current_fin_x = fin_pos[0] + middle_fin_x_distance;
let current_fin_y = fin_pos[1] - middle_fin_y_distance;
let fin_bd = new b2.BodyDef();
fin_bd.type = b2.Body.b2_dynamicBody;
fin_bd.position.Set(current_fin_x, current_fin_y);
let fin = world.CreateBody(fin_bd);
fin.CreateFixture(fin_fd);
fin.color1 = "#806682"; // [0.5, 0.4, 0.9]
fin.color2 = "#4D4D80";
fin.SetUserData(new CustomBodyUserData(true, false, "fin"));
this.body_parts.push(fin);
this.fins.push(fin);
// Revolute joint between HULL and FIN
rjd = new b2.RevoluteJointDef();
rjd.Initialize(hull, fin, new b2.Vec2(fin_pos[0], fin_pos[1]));
rjd.enableMotor = true;
rjd.enableLimit = true;
rjd.maxMotorTorque = this.MOTORS_TORQUE;
rjd.motorSpeed = 1;
rjd.lowerAngle = -0.3 * Math.PI;
rjd.upperAngle = 0.2 * Math.PI;
joint_motor = world.CreateJoint(rjd);
joint_motor.SetUserData(new CustomMotorUserData("shoulder", SPEED, true, 0.0, fin));
this.motors.push(joint_motor);
}
}
} |
JavaScript | class TwingTemplate {
constructor(environment) {
this._environment = environment;
this.parents = new Map();
this.aliases = new TwingContext();
this.blockHandlers = new Map();
this.macroHandlers = new Map();
}
get environment() {
return this._environment;
}
/**
* @returns {TwingSource}
*/
get source() {
return this._source;
}
/**
* Returns the template name.
*
* @returns {string} The template name
*/
get templateName() {
return this.source.getName();
}
get isTraitable() {
return true;
}
/**
* Returns the parent template.
*
* @param {any} context
*
* @returns {Promise<TwingTemplate|false>} The parent template or false if there is no parent
*/
getParent(context = {}) {
if (this.parent) {
return Promise.resolve(this.parent);
}
return this.doGetParent(context)
.then((parent) => {
if (parent === false || parent instanceof TwingTemplate) {
if (parent instanceof TwingTemplate) {
this.parents.set(parent.source.getName(), parent);
}
return parent;
}
// parent is a string
if (!this.parents.has(parent)) {
return this.loadTemplate(parent)
.then((template) => {
this.parents.set(parent, template);
return template;
});
}
else {
return this.parents.get(parent);
}
});
}
/**
* Returns template blocks.
*
* @returns {Promise<TwingTemplateBlocksMap>} A map of blocks
*/
getBlocks() {
if (this.blocks) {
return Promise.resolve(this.blocks);
}
else {
return this.getTraits().then((traits) => {
this.blocks = merge(traits, new Map([...this.blockHandlers.keys()].map((key) => [key, [this, key]])));
return this.blocks;
});
}
}
/**
* Displays a block.
*
* @param {string} name The block name to display
* @param {any} context The context
* @param {TwingOutputBuffer} outputBuffer
* @param {TwingTemplateBlocksMap} blocks The active set of blocks
* @param {boolean} useBlocks Whether to use the active set of blocks
*
* @returns {Promise<void>}
*/
displayBlock(name, context, outputBuffer, blocks, useBlocks) {
return this.getBlocks().then((ownBlocks) => {
let blockHandler;
if (useBlocks && blocks.has(name)) {
blockHandler = blocks.get(name)[0].blockHandlers.get(blocks.get(name)[1]);
}
else if (ownBlocks.has(name)) {
blockHandler = ownBlocks.get(name)[0].blockHandlers.get(ownBlocks.get(name)[1]);
}
if (blockHandler) {
return blockHandler(context, outputBuffer, blocks);
}
else {
return this.getParent(context).then((parent) => {
if (parent) {
return parent.displayBlock(name, context, outputBuffer, merge(ownBlocks, blocks), false);
}
else if (blocks.has(name)) {
throw new TwingErrorRuntime(`Block "${name}" should not call parent() in "${blocks.get(name)[0].templateName}" as the block does not exist in the parent template "${this.templateName}".`, -1, blocks.get(name)[0].source);
}
else {
throw new TwingErrorRuntime(`Block "${name}" on template "${this.templateName}" does not exist.`, -1, this.source);
}
});
}
});
}
/**
* Displays a parent block.
*
* @param {string} name The block name to display from the parent
* @param {any} context The context
* @param {TwingOutputBuffer} outputBuffer
* @param {TwingTemplateBlocksMap} blocks The active set of blocks
*
* @returns {Promise<void>}
*/
displayParentBlock(name, context, outputBuffer, blocks) {
return this.getTraits().then((traits) => {
if (traits.has(name)) {
return traits.get(name)[0].displayBlock(traits.get(name)[1], context, outputBuffer, blocks, false);
}
else {
return this.getParent(context).then((template) => {
if (template !== false) {
return template.displayBlock(name, context, outputBuffer, blocks, false);
}
else {
throw new TwingErrorRuntime(`The template has no parent and no traits defining the "${name}" block.`, -1, this.source);
}
});
}
});
}
/**
* Renders a parent block.
*
* @param {string} name The block name to display from the parent
* @param {*} context The context
* @param {TwingOutputBuffer} outputBuffer
* @param {TwingTemplateBlocksMap} blocks The active set of blocks
*
* @returns {Promise<string>} The rendered block
*/
renderParentBlock(name, context, outputBuffer, blocks) {
outputBuffer.start();
return this.getBlocks().then((blocks) => {
return this.displayParentBlock(name, context, outputBuffer, blocks).then(() => {
return outputBuffer.getAndClean();
});
});
}
/**
* Renders a block.
*
* @param {string} name The block name to display
* @param {any} context The context
* @param {TwingOutputBuffer} outputBuffer
* @param {TwingTemplateBlocksMap} blocks The active set of blocks
* @param {boolean} useBlocks Whether to use the active set of blocks
*
* @return {Promise<string>} The rendered block
*/
renderBlock(name, context, outputBuffer, blocks = new Map(), useBlocks = true) {
outputBuffer.start();
return this.displayBlock(name, context, outputBuffer, blocks, useBlocks).then(() => {
return outputBuffer.getAndClean();
});
}
/**
* Returns whether a block exists or not in the active context of the template.
*
* This method checks blocks defined in the active template or defined in "used" traits or defined in parent templates.
*
* @param {string} name The block name
* @param {any} context The context
* @param {TwingTemplateBlocksMap} blocks The active set of blocks
*
* @return {Promise<boolean>} true if the block exists, false otherwise
*/
hasBlock(name, context, blocks = new Map()) {
if (blocks.has(name)) {
return Promise.resolve(true);
}
else {
return this.getBlocks().then((blocks) => {
if (blocks.has(name)) {
return Promise.resolve(true);
}
else {
return this.getParent(context).then((parent) => {
if (parent) {
return parent.hasBlock(name, context);
}
else {
return false;
}
});
}
});
}
}
/**
* @param {string} name The name of the macro
*
* @return {Promise<boolean>}
*/
hasMacro(name) {
// @see https://github.com/twigphp/Twig/issues/3174 as to why we don't check macro existence in parents
return Promise.resolve(this.macroHandlers.has(name));
}
/**
* @param name The name of the macro
*/
getMacro(name) {
return this.hasMacro(name).then((hasMacro) => {
if (hasMacro) {
return this.macroHandlers.get(name);
}
else {
return null;
}
});
}
loadTemplate(templates, line = null, index = 0) {
let promise;
if (typeof templates === 'string') {
promise = this.environment.loadTemplate(templates, index, this.source);
}
else if (templates instanceof TwingTemplate) {
promise = Promise.resolve(templates);
}
else {
promise = this.environment.resolveTemplate([...templates.values()], this.source);
}
return promise.catch((e) => {
if (e.getTemplateLine() !== -1) {
throw e;
}
if (line) {
e.setTemplateLine(line);
}
throw e;
});
}
/**
* Returns template traits.
*
* @returns {Promise<TwingTemplateBlocksMap>} A map of traits
*/
getTraits() {
if (this.traits) {
return Promise.resolve(this.traits);
}
else {
return this.doGetTraits().then((traits) => {
this.traits = traits;
return traits;
});
}
}
doGetTraits() {
return Promise.resolve(new Map());
}
display(context, blocks = new Map(), outputBuffer) {
if (!outputBuffer) {
outputBuffer = new TwingOutputBuffer();
}
if (context === null) {
throw new TypeError('Argument 1 passed to TwingTemplate::display() must be an iterator, null given');
}
if (!isMap(context)) {
context = iteratorToMap(context);
}
context = new TwingContext(this.environment.mergeGlobals(context));
return this.getBlocks().then((ownBlocks) => this.displayWithErrorHandling(context, outputBuffer, merge(ownBlocks, blocks)));
}
displayWithErrorHandling(context, outputBuffer, blocks = new Map()) {
return this.doDisplay(context, outputBuffer, blocks).catch((e) => {
if (e instanceof TwingError) {
if (!e.getSourceContext()) {
e.setSourceContext(this.source);
}
}
else {
e = new TwingErrorRuntime(`An exception has been thrown during the rendering of a template ("${e.message}").`, -1, this.source, e);
}
throw e;
});
}
render(context, outputBuffer) {
if (!outputBuffer) {
outputBuffer = new TwingOutputBuffer();
}
let level = outputBuffer.getLevel();
outputBuffer.start();
return this.display(context, undefined, outputBuffer)
.then(() => {
return outputBuffer.getAndClean();
})
.catch((e) => {
while (outputBuffer.getLevel() > level) {
outputBuffer.endAndClean();
}
throw e;
});
}
doGetParent(context) {
return Promise.resolve(false);
}
callMacro(template, name, outputBuffer, args, lineno, context, source) {
let getHandler = (template) => {
if (template.macroHandlers.has(name)) {
return Promise.resolve(template.macroHandlers.get(name));
}
else {
return template.getParent(context).then((parent) => {
if (parent) {
return getHandler(parent);
}
else {
return null;
}
});
}
};
return getHandler(template).then((handler) => {
if (handler) {
return handler(outputBuffer, ...args);
}
else {
throw new TwingErrorRuntime(`Macro "${name}" is not defined in template "${template.templateName}".`, lineno, source);
}
});
}
traceableMethod(method, lineno, source) {
return function () {
return method.apply(null, arguments).catch((e) => {
if (e instanceof TwingError) {
if (e.getTemplateLine() === -1) {
e.setTemplateLine(lineno);
e.setSourceContext(source);
}
}
else {
throw new TwingErrorRuntime(`An exception has been thrown during the rendering of a template ("${e.message}").`, lineno, source, e);
}
throw e;
});
};
}
traceableRenderBlock(lineno, source) {
return this.traceableMethod(this.renderBlock.bind(this), lineno, source);
}
traceableRenderParentBlock(lineno, source) {
return this.traceableMethod(this.renderParentBlock.bind(this), lineno, source);
}
traceableHasBlock(lineno, source) {
return this.traceableMethod(this.hasBlock.bind(this), lineno, source);
}
concatenate(object1, object2) {
if (isNullOrUndefined(object1)) {
object1 = '';
}
if (isNullOrUndefined(object2)) {
object2 = '';
}
return String(object1) + String(object2);
}
get cloneMap() {
return cloneMap;
}
get compare() {
return compare;
}
get constant() {
return (name, object) => {
return constant(this, name, object);
};
}
get convertToMap() {
return iteratorToMap;
}
get count() {
return count;
}
get createRange() {
return createRange;
}
get ensureTraversable() {
return ensureTraversable;
}
get get() {
return (object, property) => {
if (isMap(object) || isPlainObject(object)) {
return get(object, property);
}
};
}
get getAttribute() {
return getAttribute;
}
get include() {
return (context, outputBuffer, templates, variables, withContext, ignoreMissing, line) => {
return include(this, context, outputBuffer, templates, variables, withContext, ignoreMissing).catch((e) => {
if (e.getTemplateLine() === -1) {
e.setTemplateLine(line);
}
throw e;
});
};
}
get isCountable() {
return isCountable;
}
get isIn() {
return isIn;
}
get iterate() {
return iterate;
}
get merge() {
return merge;
}
get parseRegExp() {
return parseRegex;
}
get Context() {
return TwingContext;
}
get Markup() {
return TwingMarkup;
}
get RuntimeError() {
return TwingErrorRuntime;
}
get SandboxSecurityError() {
return TwingSandboxSecurityError;
}
get SandboxSecurityNotAllowedFilterError() {
return TwingSandboxSecurityNotAllowedFilterError;
}
get SandboxSecurityNotAllowedFunctionError() {
return TwingSandboxSecurityNotAllowedFunctionError;
}
get SandboxSecurityNotAllowedTagError() {
return TwingSandboxSecurityNotAllowedTagError;
}
get Source() {
return TwingSource;
}
} |
JavaScript | class Map {
constructor(savedMap) {
this.name = savedMap.name;
this.id = savedMap.id;
this._key = savedMap._key;
this.board = savedMap.board;
this.floor = savedMap.floors;
this.playerSpawn = savedMap.playerSpawn;
this.playerSpawns = savedMap.playerSpawns;
this.monsterSpawns = savedMap.monsterSpawns;
this.objects = savedMap.objects;
// 0 : void
// 1 : Ground
// 2 : Wall
this.nbSpawn = savedMap.playerSpawns.length;
}
overview() {
return {
id: this.id,
name: this.name,
nbSpawn: this.nbSpawn,
};
}
get() {
return {
...this.overview(),
board: this.board,
floor: this.floor,
playerSpawn: this.playerSpawn,
playerSpawns: this.playerSpawns,
monsterSpawns: this.monsterSpawns,
};
}
isWalkable({ x, y }) {
if (x > this.board.dimX - 1 || x < 0 || y > this.board.dimY - 1 || y < 0) {
return false;
}
return this.floor[x][y] == 1;
}
isFlyable({ x, y }) {
if (x > this.board.dimX - 1 || x < 0 || y > this.board.dimY - 1 || y < 0) {
return false;
}
return this.floor[x][y] !== 2;
}
} |
JavaScript | class DiligordFixture {
added() {
// `this.id` and `this.$iApi` and `this.$vApp` are automatically made available on this object
console.log(this.id, this.$iApi, this.$vApp);
// you can also create a custom component using the helper `extend` function and put it anywhere on the page, even outside the R4MP container
// the helper function will add references to this fixture and `$iApi` to the extended component
const component = this.extend({
render: function(h) {
return h(
'p',
{
style: {
marginTop: '80px',
fontWeight: 'bold',
color: '#34495e',
fontSize: '20pt',
textAlign: 'center'
}
},
[this.firstName, ' ', this.lastName, ' aka ', this.alias]
);
},
data: function() {
return {
firstName: 'Walter',
lastName: 'White',
alias: 'Heisenberg'
};
}
});
// and put it on the page
document.querySelector('.ramp-app').after(component.$el);
// this life hook is called when the fixture is added to R4MP, and now it's possible to open our panel
this.$iApi.panel.register(dpanel).open();
}
// TEMP CODE FOR SAMPLE
// will allow an outside caller to update the fixture
doAThing(text) {
// too dumb do figure out how to get text on the fixture panels. vue hates me.
console.log('EVENTS API SAMPLE: dillygord got this data from gazebo', text);
}
} |
JavaScript | class Card extends Component {
// componentDidMount() {
// const body = document.querySelector('BODY');
// body.addEventListener('click', this.inputBlur)
// // setTimeout(() => {
// // document.querySelector('.card-container').style.animation = null;
// // }, 1000);
// }
// componentWillUnmount() {
// const body = document.querySelector('BODY');
// body.removeEventListener('click', this.inputBlur)
// }
// inputBlur = (e) => {
// if (e.target.nodeName !== "INPUT" && !(e.target.classList.contains("form-button-update-error"))) {
// console.log(e.target.nodeName !== "INPUT" && e.target.classList.contains("form-button-update"));
// document.querySelectorAll("INPUT[type=text]").forEach(input => input.disabled=true)
// document.querySelectorAll(".svg-flex").forEach(svg => svg.classList.remove("svg-edit-active"))
// document.querySelectorAll(".form-buttons-update").forEach(formButtons => formButtons.style.display="none")
// }
// }
scrollToCard = () => {
const card = document.getElementById(`${this.props.props.deck.cards[this.props.props.score]._id}`);
const input = document.querySelectorAll(`.input-${this.props.props.deck.cards[this.props.props.score]._id}`);
const svg = document.getElementById(`svg-${this.props.props.deck.cards[this.props.props.score]._id}`);
const formButtons = document.querySelector(`.form-buttons-update-${this.props.props.deck.cards[this.props.props.score]._id}`);
formButtons.style.display="flex";
svg.classList.toggle("svg-edit-active")
input.forEach(input=>input.disabled=false)
card.scrollIntoView({behavior: "smooth", block: "center", inline: "nearest"});
}
render(props) {
return (
<div className="bounds card--detail">
{/* Check to see if there are flashcards in deck */}
{ (this.props.props.amountOfCards <= 0)
? (<p>There are no flashcards in this deck</p>)
: (
<StyleRoot>
<div className="card-container" style={this.props.props.fade}>
<div className="card-quiz" onClick={this.props.props.flipCard}>
<div className="edit-card-icons">
{
(this.props.props.authenticatedUserId === this.props.props.authorId)
? <svg onClick={this.scrollToCard} className="svg-icon-edit" viewBox="0 0 20 20">
<path className="svg-icon-edit" fill="none" d="M19.404,6.65l-5.998-5.996c-0.292-0.292-0.765-0.292-1.056,0l-2.22,2.22l-8.311,8.313l-0.003,0.001v0.003l-0.161,0.161c-0.114,0.112-0.187,0.258-0.21,0.417l-1.059,7.051c-0.035,0.233,0.044,0.47,0.21,0.639c0.143,0.14,0.333,0.219,0.528,0.219c0.038,0,0.073-0.003,0.111-0.009l7.054-1.055c0.158-0.025,0.306-0.098,0.417-0.211l8.478-8.476l2.22-2.22C19.695,7.414,19.695,6.941,19.404,6.65z M8.341,16.656l-0.989-0.99l7.258-7.258l0.989,0.99L8.341,16.656z M2.332,15.919l0.411-2.748l4.143,4.143l-2.748,0.41L2.332,15.919z M13.554,7.351L6.296,14.61l-0.849-0.848l7.259-7.258l0.423,0.424L13.554,7.351zM10.658,4.457l0.992,0.99l-7.259,7.258L3.4,11.715L10.658,4.457z M16.656,8.342l-1.517-1.517V6.823h-0.003l-0.951-0.951l-2.471-2.471l1.164-1.164l4.942,4.94L16.656,8.342z"></path>
</svg>
: null
}
{/* Checks if hint exists*/}
{/* (this.props.props.deck.cards[this.props.props.score]["hint"] === undefined && this.props.props.isFlipped === true) */}
{/* (this.props.props.deck.cards[0].hint == undefined) */}
{
(this.props.props.isFlipped || this.props.props.deck.cards[this.props.props.score].hint === undefined)
? (null)
: <button className="show-hint hint-card" onClick={this.props.props.showHint}><svg className="svg-icon-hint" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path className="svg-icon-hint" d="M22 8.51v1.372h-2.538c.02-.223.038-.448.038-.681 0-.237-.017-.464-.035-.69h2.535zm-10.648-6.553v-1.957h1.371v1.964c-.242-.022-.484-.035-.726-.035-.215 0-.43.01-.645.028zm5.521 1.544l1.57-1.743 1.019.918-1.603 1.777c-.25-.297-.593-.672-.986-.952zm-10.738.952l-1.603-1.777 1.019-.918 1.57 1.743c-.392.28-.736.655-.986.952zm-1.597 5.429h-2.538v-1.372h2.535c-.018.226-.035.454-.035.691 0 .233.018.458.038.681zm9.462 9.118h-4c-.276 0-.5.224-.5.5s.224.5.5.5h4c.276 0 .5-.224.5-.5s-.224-.5-.5-.5zm0 2h-4c-.276 0-.5.224-.5.5s.224.5.5.5h4c.276 0 .5-.224.5-.5s-.224-.5-.5-.5zm.25 2h-4.5l1.188.782c.154.138.38.218.615.218h.895c.234 0 .461-.08.615-.218l1.187-.782zm3.75-13.799c0 3.569-3.214 5.983-3.214 8.799h-1.989c-.003-1.858.87-3.389 1.721-4.867.761-1.325 1.482-2.577 1.482-3.932 0-2.592-2.075-3.772-4.003-3.772-1.925 0-3.997 1.18-3.997 3.772 0 1.355.721 2.607 1.482 3.932.851 1.478 1.725 3.009 1.72 4.867h-1.988c0-2.816-3.214-5.23-3.214-8.799 0-3.723 2.998-5.772 5.997-5.772 3.001 0 6.003 2.051 6.003 5.772z"/></svg></button>
}
</div>
<h3 className="card--question">{this.props.props.deck.cards[this.props.props.score][this.props.props.sideOfCard]}</h3>
<div className="card--hint">
{ (this.props.props.hint == null)
? (
<div className="grid-66">
<h3 className="card--hint"> </h3>
</div>
)
: (
<div className="grid-66">
<h3 className="card--hint">{this.props.props.deck.cards[this.props.props.score][this.props.props.hint]}</h3>
</div>
)
}
</div>
</div>
</div>
</StyleRoot>
)
}
<div className="card-options">
{/* instead of rendering next and previous as null change class so you can gray out buttons */}
{/* Checks if at the beginning of deck*/}
{
(this.props.props.score > 0)
? <button className="previous-card" onClick={this.props.props.previousCard}> ← </button>
: <button className="previous-card-disabled" onClick={this.props.props.previousCard}> ← </button>
}
<button className="flip-card" onClick={this.props.props.flipCard}><svg className="svg-icon-flip" viewBox="0 0 20 20">
<path fill="none" d="M3.254,6.572c0.008,0.072,0.048,0.123,0.082,0.187c0.036,0.07,0.06,0.137,0.12,0.187C3.47,6.957,3.47,6.978,3.484,6.988c0.048,0.034,0.108,0.018,0.162,0.035c0.057,0.019,0.1,0.066,0.164,0.066c0.004,0,0.01,0,0.015,0l2.934-0.074c0.317-0.007,0.568-0.271,0.56-0.589C7.311,6.113,7.055,5.865,6.744,5.865c-0.005,0-0.01,0-0.015,0L5.074,5.907c2.146-2.118,5.604-2.634,7.971-1.007c2.775,1.912,3.48,5.726,1.57,8.501c-1.912,2.781-5.729,3.486-8.507,1.572c-0.259-0.18-0.618-0.119-0.799,0.146c-0.18,0.262-0.114,0.621,0.148,0.801c1.254,0.863,2.687,1.279,4.106,1.279c2.313,0,4.591-1.1,6.001-3.146c2.268-3.297,1.432-7.829-1.867-10.101c-2.781-1.913-6.816-1.36-9.351,1.058L4.309,3.567C4.303,3.252,4.036,3.069,3.72,3.007C3.402,3.015,3.151,3.279,3.16,3.597l0.075,2.932C3.234,6.547,3.251,6.556,3.254,6.572z"></path>
</svg></button>
{/* Checks if at the end of deck*/}
{
(this.props.props.score < this.props.props.amountOfCards-1)
? <button className="next-card" onClick={this.props.props.nextCard}> → </button>
: <button className="next-card-disabled" onClick={this.props.props.nextCard}> → </button>
}
</div>
<p className="centered">{this.props.props.score+1}/{this.props.props.amountOfCards}</p>
</div>
)
}
} |
JavaScript | class Cart extends Component {
// constructor () {
// super()
// this.state = { quantity: 1 }
// }
componentDidMount () {
this.props.getItems(this.props.info.id)
// so important make this cart id alive!!!
// this.props.addItems(1, {stockId: 9, quantity: 12});
// this.props.removeItems(5);
// this.props.getItems(5)
}
handleChange = item => {
console.log('insisde handleChange==== item:?>>> ', item)
this.props.updateQuantity(item)
}
handleCheckout = () => {
this.props.history.push('/checkout')
}
render () {
let totalBag = 0
const items = this.props.items || []
return (
<div className='spacer'>
{items.length === 0 || !items ? (
<div className='outline'>
<div className='empty_cart'>
<h3>{this.props.user.username} BAG</h3>
<p>Your bag is empty, but it doesn't have to be!</p>
<Link to='/products'>
<button type='button'> GO TO HOME PAGE FOR SOME SWEETS!</button>
</Link>
</div>
</div>
) : (
<div className='outline'>
<div className='cart_container'>
<h3>{this.props.user.username} BAG</h3>
<table id='cart_table'>
<tbody>
<tr>
<th> ITEM </th>
<th> QUANTITY </th>
<th> UNIT PRICE </th>
<th> ITEM TOTAL</th>
</tr>
{items.map(item => {
let product
if (this.props.products) {
;[product] = this.props.products.filter(
product => product.id === item.stockId
)
}
totalBag += (item.quantity * product.price * 100) / 100
return (
<tr key={item.id}>
<td>{product.name}</td>
<td>
<input
type='input'
defaultValue={item.quantity}
onChange={evt => {
item.quantity = Number(evt.target.value)
}}
/>
<button
onClick={() => {
this.handleChange(item)
}}
>
{' '}
edit{' '}
</button>
</td>
<td>{product.price}</td>
<td>{(item.quantity * product.price * 100) / 100}</td>
<button
onClick={() => {
this.props.removeItems(item.id)
}}
>
remove
</button>
</tr>
)
})}
</tbody>
</table>
<div className='checkOut'>Total Bag ${totalBag}</div>
<button
type='button'
onClick={() => {
this.handleCheckout()
}}
>
{' '}
CHECKOUT
</button>
</div>
</div>
)}
</div>
)
}
} |
JavaScript | class RopePoint {
//integrates motion equations per node without taking into account relationship
//with other nodes...
static integrate(point, gravity, dt, previousFrameDt) {
if (!point.isFixed) {
point.velocity = Vector2.sub(point.pos, point.oldPos);
point.oldPos = { ...point.pos };
//drastically improves stability
let timeCorrection = previousFrameDt != 0.0 ? dt / previousFrameDt : 0.0;
let accel = Vector2.add(gravity, { x: 0, y: point.mass });
const velCoef = timeCorrection * point.damping;
const accelCoef = Math.pow(dt, 2);
point.pos.x += point.velocity.x * velCoef + accel.x * accelCoef;
point.pos.y += point.velocity.y * velCoef + accel.y * accelCoef;
} else {
point.velocity = Vector2.zero();
point.oldPos = { ...point.pos };
}
}
//apply constraints related to other nodes next to it
//(keeps each node within distance)
static constrain(point) {
if (point.next) {
const delta = Vector2.sub(point.next.pos, point.pos);
const len = Vector2.mag(delta);
const diff = len - point.distanceToNextPoint;
const normal = Vector2.normalized(delta);
if (!point.isFixed) {
point.pos.x += normal.x * diff * 0.25;
point.pos.y += normal.y * diff * 0.25;
}
if (!point.next.isFixed) {
point.next.pos.x -= normal.x * diff * 0.25;
point.next.pos.y -= normal.y * diff * 0.25;
}
}
if (point.prev) {
const delta = Vector2.sub(point.prev.pos, point.pos);
const len = Vector2.mag(delta);
const diff = len - point.distanceToNextPoint;
const normal = Vector2.normalized(delta);
if (!point.isFixed) {
point.pos.x += normal.x * diff * 0.25;
point.pos.y += normal.y * diff * 0.25;
}
if (!point.prev.isFixed) {
point.prev.pos.x -= normal.x * diff * 0.25;
point.prev.pos.y -= normal.y * diff * 0.25;
}
}
}
constructor(initialPos, distanceToNextPoint) {
this.pos = initialPos;
this.distanceToNextPoint = distanceToNextPoint;
this.isFixed = false;
this.oldPos = { ...initialPos };
this.velocity = Vector2.zero();
this.mass = 1.0;
this.damping = 1.0;
this.prev = null;
this.next = null;
}
} |
JavaScript | class SortedArray extends Array{
// Construct a new SortedArray. Uses Array.sort to sort
// the input collection, if any; the sort may be unstable.
constructor(){
let values = null;
let valuesEqual = null;
let comparator = null;
let reversedComparator = null;
// new SortedArray(comparator)
if(arguments.length === 1 &&
typeof(arguments[0]) === "function"
){
comparator = arguments[0];
// new SortedArray(comparator, valuesEqual)
}else if(arguments.length === 2 &&
typeof(arguments[0]) === "function" &&
typeof(arguments[1]) === "function"
){
comparator = arguments[0];
valuesEqual = arguments[1];
// new SortedArray(values, comparator?, valuesEqual?)
}else{
values = arguments[0];
comparator = arguments[1];
valuesEqual = arguments[2];
}
if(comparator && typeof(comparator) !== "function"){
// Verify comparator input
throw new TypeError("Comparator argument must be a function.");
}
if(valuesEqual && typeof(valuesEqual) !== "function"){
// Verify comparator input
throw new TypeError("Value equality argument must be a function.");
}
// new SortedArray(length, cmp?, eq?) - needed by some inherited methods
if(typeof(values) === "number"){
if(!Number.isInteger(values) || values < 0){
throw new RangeError("Invalid array length");
}
super(values);
// new SortedArray(SortedArray, cmp?, eq?) - same or unspecified comparator
}else if(values instanceof SortedArray && (
!comparator || values.comparator === comparator
)){
super();
super.push(...values);
comparator = values.comparator;
reversedComparator = values.reversedComparator;
if(!valuesEqual) valuesEqual = values.valuesEqual;
// new SortedArray(Array, cmp?, eq?)
}else if(Array.isArray(values)){
super();
super.push(...values);
super.sort(comparator || DefaultComparator);
if(values instanceof SortedArray && !valuesEqual){
valuesEqual = values.valuesEqual;
}
// new SortedArray(iterable, cmp?, eq?)
}else if(values && typeof(values[Symbol.iterator]) === "function"){
super();
for(let value of values) super.push(value);
super.sort(comparator || DefaultComparator);
// new SortedArray(object with length, cmp?, eq?) - e.g. `arguments`
}else if(values && typeof(values) === "object" &&
Number.isFinite(values.length)
){
super();
for(let i = 0; i < values.length; i++) super.push(values[i]);
super.sort(comparator || DefaultComparator);
// new SortedArray()
// new SortedArray(comparator)
// new SortedArray(comparator, valuesEqual)
}else if(!values){
super();
// new SortedArray(???)
}else{
throw new TypeError(
"Unhandled values input type. Expected an iterable."
);
}
this.valuesEqual = valuesEqual || SameValueZero;
this.comparator = comparator || DefaultComparator;
this.reversedComparator = reversedComparator;
}
// Construct a SortedArray with elements given as arguments.
static of(...values){
return new SortedArray(values);
}
// Construct a SortedArray from assumed-sorted arguments.
static ofSorted(...values){
const array = new SortedArray();
Array.prototype.push.apply(array, values);
return array;
}
// Construct a SortedArray from the given inputs.
static from(values, comparator, valuesEqual){
return new SortedArray(values, comparator, valuesEqual);
}
// Construct a SortedArray from assumed-sorted values.
static fromSorted(values, comparator, valuesEqual){
const array = new SortedArray(null, comparator, valuesEqual);
if(Array.isArray(values)){
Array.prototype.push.apply(array, values);
}else{
for(let value of values) Array.prototype.push.call(array, value);
}
return array;
}
/// SortedArray methods
// Insert a value into the list.
insert(value){
const index = this.lastInsertionIndexOf(value);
this.splice(index, 0, value);
return this.length;
}
// Insert an iterable of assumed-sorted values into the list
// This will typically be faster than calling `insert` in a loop.
insertSorted(values){
// Optimized implementation for arrays and array-like objects
if(values && typeof(values) === "object" &&
Number.isFinite(values.length)
){
// Exit immediately if the values array is empty
if(values.length === 0){
return this.length;
}
// If the last element in the input precedes the first element
// in the array, the input can be prepended in one go.
const lastInsertionIndex = this.lastInsertionIndexOf(
values[values.length - 1]
);
if(lastInsertionIndex === 0){
this.unshift(...values);
return this.length;
}
// If the first element would go in the same place in the array
// as the last element, then it can be spliced in all at once.
const firstInsertionIndex = this.lastInsertionIndexOf(values[0]);
if(firstInsertionIndex === lastInsertionIndex){
this.splice(firstInsertionIndex, 0, ...values);
return this.length;
}
// Array contents must be interlaced
let insertIndex = 0;
for(let valIndex = 0; valIndex < values.length; valIndex++){
const value = values[valIndex];
insertIndex = this.lastInsertionIndexOf(value, insertIndex);
// If this element was at the end of the array, then every other
// element of the input is too and they can be appended at once.
if(insertIndex === this.length && valIndex < values.length - 1){
this.push(...values.slice(valIndex));
return this.length;
}else{
this.splice(insertIndex++, 0, value);
}
}
return this.length;
// Generalized implementation for any iterable
}else if(values && typeof(values[Symbol.iterator]) === "function"){
let insertIndex = 0;
for(let value of values){
insertIndex = this.lastInsertionIndexOf(value, insertIndex);
this.splice(insertIndex++, 0, value);
}
return this.length;
// Produce an error if the input isn't an acceptable type.
}else{
throw new TypeError("Expected an iterable list of values.");
}
}
// Remove the first matching value.
// Returns true if a matching element was found and removed,
// or false if no matching element was found.
remove(value){
const index = this.indexOf(value);
if(index >= 0){
this.splice(index, 1);
return true;
}else{
return false;
}
}
// Remove the last matching value.
// Returns true if a matching element was found and removed,
// or false if no matching element was found.
removeLast(value){
const index = this.lastIndexOf(value);
if(index >= 0){
this.splice(index, 1);
return true;
}else{
return false;
}
}
// Remove all matching values.
// Returns the removed elements as a new SortedArray.
removeAll(value){
let index = this.firstInsertionIndexOf(value);
const removed = new SortedArray();
removed.valuesEqual = this.valuesEqual;
removed.comparator = this.comparator;
removed.reversedComparator = this.reversedComparator;
while(index < this.length &&
this.comparator(this[index], value) === 0
){
if(this.valuesEqual(this[index], value)){
Array.prototype.push.call(removed, this[index]);
this.splice(index, 1);
}else{
index++;
}
}
return removed;
}
// Get all equal values.
// Returns the equivalent elements as a new SortedArray.
getEqualValues(value){
let index = this.firstInsertionIndexOf(value);
const equal = new SortedArray();
equal.valuesEqual = this.valuesEqual;
equal.comparator = this.comparator;
equal.reversedComparator = this.reversedComparator;
while(index < this.length &&
this.comparator(this[index], value) === 0
){
if(this.valuesEqual(this[index], value)){
Array.prototype.push.call(equal, this[index]);
}
index++;
}
return equal;
}
// Returns the index of the first equal element,
// or the index that such an element should
// be inserted at if there is no equal element.
firstInsertionIndexOf(value, fromIndex, endIndex){
const from = (typeof(fromIndex) !== "number" || fromIndex !== fromIndex ?
0 : (fromIndex < 0 ? Math.max(0, this.length + fromIndex) : fromIndex)
);
const end = (typeof(endIndex) !== "number" || endIndex !== endIndex ?
this.length : (endIndex < 0 ? this.length + endIndex :
Math.min(this.length, endIndex)
)
);
let min = from - 1;
let max = end;
while(1 + min < max){
const mid = min + Math.floor((max - min) / 2);
const cmp = this.comparator(value, this[mid]);
if(cmp > 0) min = mid;
else max = mid;
}
return max;
}
// Returns the index of the last equal element,
// or the index that such an element should
// be inserted at if there is no equal element.
lastInsertionIndexOf(value, fromIndex, endIndex){
const from = (typeof(fromIndex) !== "number" || fromIndex !== fromIndex ?
0 : (fromIndex < 0 ? Math.max(0, this.length + fromIndex) : fromIndex)
);
const end = (typeof(endIndex) !== "number" || endIndex !== endIndex ?
this.length : (endIndex < 0 ? this.length + endIndex :
Math.min(this.length, endIndex)
)
);
let min = from - 1;
let max = end;
while(1 + min < max){
const mid = min + Math.floor((max - min) / 2);
const cmp = this.comparator(value, this[mid]);
if(cmp >= 0) min = mid;
else max = mid;
}
return max;
}
// Returns the index of the first equal element, or -1 if
// there is no equal element.
indexOf(value, fromIndex){
let index = this.firstInsertionIndexOf(value, fromIndex);
if(index >= 0 && index < this.length &&
this.valuesEqual(this[index], value)
){
return index;
}
while(++index < this.length &&
this.comparator(value, this[index]) === 0
){
if(this.valuesEqual(this[index], value)) return index;
}
return -1;
}
// Returns the index of the last equal element, or -1 if
// there is no equal element.
lastIndexOf(value, fromIndex){
let index = this.lastInsertionIndexOf(value, 0, fromIndex);
if(index >= 0 && index < this.length &&
this.valuesEqual(this[index], value)
){
return index;
}
while(--index >= 0 &&
this.comparator(value, this[index]) === 0
){
if(this.valuesEqual(this[index], value)) return index;
}
return -1;
}
// Returns true when the value is contained within the
// array, and false when not.
includes(value, fromIndex){
return this.indexOf(value, fromIndex) >= 0;
}
// Get a copy of this list containing only those elements
// which satisfy a predicate function.
// The output is also a SortedArray.
filter(predicate){
if(typeof(predicate) !== "function"){
throw new TypeError("Predicate must be a function.");
}
const array = new SortedArray(null, this.comparator);
array.reversedComparator = this.reversedComparator;
for(let element of this){
if(predicate(element)) Array.prototype.push.call(array, element);
}
return array;
}
// Reverse the list. This method also inverts the comparator
// function, meaning later insertions respect the new order.
reverse(){
super.reverse();
if(this.reversedComparator){
const t = this.comparator;
this.comparator = this.reversedComparator;
this.reversedComparator = t;
}else{
const t = this.comparator;
this.reversedComparator = this.comparator;
this.comparator = (a, b) => t(b, a);
}
}
// Get a slice out of the array. Returns a SortedArray.
slice(){
const slice = Array.prototype.slice.apply(this, arguments);
slice.valuesEqual = this.valuesEqual;
slice.comparator = this.comparator;
slice.reversedComparator = this.reversedComparator;
return slice;
}
// Changes the array's comparator and re-sorts its contents.
// Uses Array.sort, which may be unstable.
sort(comparator){
comparator = comparator || DefaultComparator;
if(comparator === this.comparator) return;
this.comparator = comparator;
this.reversedComparator = null;
super.sort(comparator);
}
// Remove and/or insert elements in the array.
splice(){
const splice = Array.prototype.splice.apply(this, arguments);
splice.valuesEqual = this.valuesEqual;
splice.comparator = this.comparator;
splice.reversedComparator = this.reversedComparator;
return splice;
}
// Can these be done in a less hacky way?
concat(){
this.constructor = Array;
const array = Array.prototype.concat.apply(this, arguments);
this.constructor = SortedArray;
return array;
}
flat(){
this.constructor = Array;
const array = Array.prototype.flat.apply(this, arguments);
this.constructor = SortedArray;
return array;
}
flatMap(){
this.constructor = Array;
const array = Array.prototype.flatMap.apply(this, arguments);
this.constructor = SortedArray;
return array;
}
map(){
this.constructor = Array;
const array = Array.prototype.map.apply(this, arguments);
this.constructor = SortedArray;
return array;
}
} |
JavaScript | class NumberInput extends PureComponent {
constructor() {
super(...arguments);
const { value } = this.props;
this.state = { origValue: value };
}
/*
* @desc cache the original value before changes begin
* @since 1.0.0
*/
onFocus = e => {
const { target } = e;
const { value } = target;
this.setState({ origValue: parseInt(value, 10) });
};
/*
* @desc reset the input to its original value if the changes are invalid
* @since 1.0.0
*/
onBlur = e => {
const {
min = 0,
max = 100,
} = this.props;
const { target } = e;
const { value } = target;
if (!isValidInput(value, min, max)) {
const {
onChange,
channel = 0,
} = this.props;
const { origValue } = this.state;
onChange(origValue, false, channel);
}
};
/*
* @desc the up/down arrows have been pressed
* @since 1.0.0
*/
onMouseDownBtn = up => {
let run;
this.updating = true;
this.increment(up);
this.timeout = setTimeout(() => {
this.timer = setInterval(() => {
run = this.increment(up);
if (!run) {
this.onMouseUpBtn();
}
}, 50);
}, 100);
};
/*
* @desc stop incrementing if the arrows are no longer hovered
* @since 1.0.0
*/
onMouseLeave = () => {
this.updating = false;
this.clearTimers();
}
/*
* @desc stop incrementing if the arrows are no longer pressed
* also called each time the increment timer runs
* @since 1.0.0
*/
onMouseUpBtn = () => {
this.updating = false;
this.clearTimers();
const { value } = this.props;
this.onChange({ target: { value } });
};
/*
* @desc increment the value up
* @since 1.0.0
*/
arrowUpClick = () => {
this.onMouseDownBtn(true);
}
/*
* @desc increment the value down
* @since 1.0.0
*/
arrowDownClick = () => {
this.onMouseDownBtn();
}
/*
* @desc input slider changes potentially starting
* see "Records" note above
* @since 1.0.0
*/
onSliderDown = () => {
const { fetchRecords } = this.props;
if (fetchRecords) {
this.fetch = true;
}
this.updating = true;
}
/*
* @desc user has finished dragging the range slider control
* @since 1.0.0
*/
onSliderUp = e => {
this.fetch = false;
this.updating = false;
this.onChange(e);
}
/*
* @desc clears number input incrementing timers when changing is complete
* @since 1.0.0
*/
clearTimers() {
clearTimeout(this.timeout);
clearInterval(this.timer);
}
componentWillUnmount() {
this.clearTimers();
}
/*
* @desc increment the value up or down as the fake input number buttons are clicked
* @since 1.0.0
*/
increment = up => {
const {
value,
min = 0,
max = 100,
} = this.props;
let newValue = up ? value + 1 : value - 1;
newValue = Math.round(newValue);
if (newValue >= min && newValue <= max) {
this.onChange({ target: { value: newValue } });
return true;
}
return false;
};
/*
* @desc gets a copy of the current values for the hsl inputs
* see "Records" note above
* @since 1.0.0
*/
getRecords() {
const { sliderRecord } = this.props;
const { records } = sliderRecord;
const passedRecords = [];
records.forEach(index => {
passedRecords.push({
index,
value: parseInt(this.records[index], 10),
});
});
this.records = null;
return passedRecords;
}
/*
* @desc creates a copy of the current values for the hsl inputs
* see "Records" note above
* @since 1.0.0
*/
setRecords(value) {
const { sliderRecord } = this.props;
const { minMax } = sliderRecord;
if (minMax.includes(value)) {
const { allValues } = this.props;
const { records } = sliderRecord;
const recordValues = [];
records.forEach(index => {
recordValues[index] = allValues[index];
});
this.records = recordValues;
}
}
/*
* @desc checks if the records need to be reset after a change happens
* see "Records" note above
* @since 1.0.0
*/
checkRecords(value) {
if (!this.records) {
this.setRecords(value);
} else {
return this.getRecords();
}
return null;
}
/*
* @desc fires after the slider has been dragged, an ioncrement arrow is clicked or via direct input
* @since 1.0.0
*/
onChange = e => {
const {
onChange,
channel = 0,
} = this.props;
let records;
const { target } = e;
const { value: newValue } = target;
const clampedValue = newValue !== '' ? parseInt(newValue, 10) : newValue;
if (this.fetch) {
records = this.checkRecords(clampedValue);
}
onChange(clampedValue, this.updating, channel, records);
};
render() {
const {
slug,
unit,
label,
value,
slider,
disabled,
inputRef,
onChangeUnit,
onMouseLeave,
onMouseEnter,
min = 0,
max = 100,
channel = 0,
numbers = true,
buttons = true,
className = '',
arrowIcons = defaultIcons,
} = this.props;
const { namespace } = this.context;
const id = `${namespace}-${slug}-input-${channel}`;
// if "disabled" exists it could be a number which could be 0
const isDisabled = disabled !== undefined && disabled !== null && disabled !== false;
let extraClass = !className ? '' : `${className}`;
if (isDisabled) {
if (extraClass) {
extraClass += ' ';
}
extraClass += `${namespace}-disabled`;
}
let parsed = value;
if (value !== '') {
parsed = Math.round(parseFloat(value));
} else {
parsed = value;
}
return (
<Row
ref={inputRef}
onMouseEnter={onMouseEnter}
onMouseLeave={onMouseLeave}
className={`${extraClass}`}
>
{numbers && (
<InputWrap>
<input
id={id}
className={`${namespace}-input`}
type="number"
min={min}
max={max}
disabled={isDisabled}
value={parsed}
onFocus={this.onFocus}
onBlur={this.onBlur}
onChange={this.onChange}
/>
{buttons && (
<RangeButtons
icons={arrowIcons}
arrowUpClick={this.arrowUpClick}
arrowDownClick={this.arrowDownClick}
onMouseLeave={this.onMouseLeave}
onMouseUp={this.onMouseUpBtn}
/>
)}
</InputWrap>
)}
{slider && (
<RangeSlider
min={min}
max={max}
value={parsed}
disabled={isDisabled}
onMouseDown={this.onSliderDown}
onMouseUp={this.onSliderUp}
onChange={this.onChange}
/>
)}
{label && (
<label
className={`${namespace}-input-label`}
htmlFor={id}
>{label}</label>
)}
{unit && (
<SelectBox
isMini
prop={slug}
value={unit}
list={unitList}
onChange={onChangeUnit}
/>
)}
</Row>
);
}
} |
JavaScript | class LabeledGrid extends THREE.Object3D{
constructor( width = 200, length = 200, step = 100, upVector = [0,1,0],
color = 0x00baff, opacity = 0.2,
text = true, textColor = "#000000", textLocation = "center") {
super();
this.width = width;
this.length = length;
this.step = step;
this.color = color;
this.opacity = opacity;
this.text = text;
this.textColor = textColor;
this.textLocation = textLocation;
this.upVector = new THREE.Vector3().fromArray(upVector);
this.name = "grid";
//TODO: clean this up
this.marginSize =10;
this.stepSubDivisions = 10;
this._drawGrid();
//default grid orientation is z up, rotate if not the case
var upVector = this.upVector;
this.up = upVector;
this.lookAt(upVector);
}
_drawGrid() {
var gridGeometry, gridMaterial, mainGridZ, planeFragmentShader, planeGeometry, planeMaterial, subGridGeometry, subGridMaterial, subGridZ;
//offset to avoid z fighting
mainGridZ = -0.05;
gridGeometry = new THREE.Geometry();
gridMaterial = new THREE.LineBasicMaterial({
color: new THREE.Color().setHex(this.color),
opacity: this.opacity,
linewidth: 2,
transparent: true
});
subGridZ = -0.05;
subGridGeometry = new THREE.Geometry();
subGridMaterial = new THREE.LineBasicMaterial({
color: new THREE.Color().setHex(this.color),
opacity: this.opacity / 2,
transparent: true
});
var step = this.step;
var stepSubDivisions = this.stepSubDivisions;
var width = this.width;
var length = this.length;
var centerBased = true
if(centerBased)
{
for (var i = 0; i <= width/2; i += step/stepSubDivisions)
{
subGridGeometry.vertices.push( new THREE.Vector3(-length / 2, i, subGridZ) );
subGridGeometry.vertices.push( new THREE.Vector3(length / 2, i, subGridZ) );
subGridGeometry.vertices.push( new THREE.Vector3(-length / 2, -i, subGridZ) );
subGridGeometry.vertices.push( new THREE.Vector3(length / 2, -i, subGridZ) );
if( i%step == 0 )
{
gridGeometry.vertices.push( new THREE.Vector3(-length / 2, i, mainGridZ) );
gridGeometry.vertices.push( new THREE.Vector3(length / 2, i, mainGridZ) );
gridGeometry.vertices.push( new THREE.Vector3(-length / 2, -i, mainGridZ) );
gridGeometry.vertices.push( new THREE.Vector3(length / 2, -i, mainGridZ) );
}
}
for (var i = 0; i <= length/2; i += step/stepSubDivisions)
{
subGridGeometry.vertices.push( new THREE.Vector3(i, -width / 2, subGridZ) );
subGridGeometry.vertices.push( new THREE.Vector3(i, width / 2, subGridZ) );
subGridGeometry.vertices.push( new THREE.Vector3(-i, -width / 2, subGridZ) );
subGridGeometry.vertices.push( new THREE.Vector3(-i, width / 2, subGridZ) );
if( i%step == 0 )
{
gridGeometry.vertices.push( new THREE.Vector3(i, -width / 2, mainGridZ) );
gridGeometry.vertices.push( new THREE.Vector3(i, width / 2, mainGridZ) );
gridGeometry.vertices.push( new THREE.Vector3(-i, -width / 2, mainGridZ) );
gridGeometry.vertices.push( new THREE.Vector3(-i, width / 2, mainGridZ) );
}
}
}
else{
for (var i = -width/2; i <= width/2; i += step/stepSubDivisions)
{
subGridGeometry.vertices.push( new THREE.Vector3(-length / 2, i, subGridZ));
subGridGeometry.vertices.push( new THREE.Vector3(length / 2, i, subGridZ));
if( i%step == 0 )
{
gridGeometry.vertices.push( new THREE.Vector3(-length / 2, i, mainGridZ));
gridGeometry.vertices.push( new THREE.Vector3(length / 2, i, mainGridZ));
}
}
for (var i = -length/2; i <= length/2; i += step/stepSubDivisions)
{
subGridGeometry.vertices.push( new THREE.Vector3(i, -width / 2, subGridZ));
subGridGeometry.vertices.push( new THREE.Vector3(i, width / 2, subGridZ));
if( i%step == 0 )
{
gridGeometry.vertices.push( new THREE.Vector3(i, -width / 2, mainGridZ));
gridGeometry.vertices.push( new THREE.Vector3(i, width / 2, mainGridZ));
}
}
}
this.mainGrid = new THREE.Line(gridGeometry, gridMaterial, THREE.LinePieces);
//create sub grid geometry object
this.subGrid = new THREE.Line(subGridGeometry, subGridMaterial, THREE.LinePieces);
//create margin
var offsetWidth = width + this.marginSize;
var offsetLength = length + this.marginSize;
var marginGeometry = new THREE.Geometry();
marginGeometry.vertices.push( new THREE.Vector3(-length / 2, -width/2, subGridZ));
marginGeometry.vertices.push( new THREE.Vector3(length / 2, -width/2, subGridZ));
marginGeometry.vertices.push( new THREE.Vector3(length / 2, -width/2, subGridZ));
marginGeometry.vertices.push( new THREE.Vector3(length / 2, width/2, subGridZ));
marginGeometry.vertices.push( new THREE.Vector3(length / 2, width/2, subGridZ));
marginGeometry.vertices.push( new THREE.Vector3(-length / 2, width/2, subGridZ));
marginGeometry.vertices.push( new THREE.Vector3(-length / 2, width/2, subGridZ));
marginGeometry.vertices.push( new THREE.Vector3(-length / 2, -width/2, subGridZ));
marginGeometry.vertices.push( new THREE.Vector3(-offsetLength / 2, -offsetWidth/2, subGridZ));
marginGeometry.vertices.push( new THREE.Vector3(offsetLength / 2, -offsetWidth/2, subGridZ));
marginGeometry.vertices.push( new THREE.Vector3(offsetLength / 2, -offsetWidth/2, subGridZ));
marginGeometry.vertices.push( new THREE.Vector3(offsetLength / 2, offsetWidth/2, subGridZ));
marginGeometry.vertices.push( new THREE.Vector3(offsetLength / 2, offsetWidth/2, subGridZ));
marginGeometry.vertices.push( new THREE.Vector3(-offsetLength / 2, offsetWidth/2, subGridZ));
marginGeometry.vertices.push( new THREE.Vector3(-offsetLength / 2, offsetWidth/2, subGridZ));
marginGeometry.vertices.push( new THREE.Vector3(-offsetLength / 2, -offsetWidth/2, subGridZ));
var strongGridMaterial = new THREE.LineBasicMaterial({
color: new THREE.Color().setHex(this.color),
opacity: this.opacity*2,
linewidth: 2,
transparent: true
});
this.margin = new THREE.Line(marginGeometry, strongGridMaterial, THREE.LinePieces);
//add all grids, subgrids, margins etc
this.add( this.mainGrid );
this.add( this.subGrid );
this.add( this.margin );
this._drawNumbering();
}
toggle(toggle) {
//apply visibility settings to all children
this.traverse( function( child ) {
child.visible = toggle;
});
}
setOpacity(opacity) {
this.opacity = opacity;
this.mainGrid.material.opacity = opacity;
this.subGrid.material.opacity = opacity/2;
this.margin.material.opacity = opacity*2;
}
setColor(color) {
this.color = color;
this.mainGrid.material.color = new THREE.Color().setHex(this.color);
this.subGrid.material.color = new THREE.Color().setHex(this.color);
this.margin.material.color = new THREE.Color().setHex(this.color);
}
toggleText(toggle) {
this.text = toggle;
var labels = this.labels.children;
for (var i = 0; i < this.labels.children.length; i++) {
var label = labels[i];
label.visible = toggle;
}
}
setTextColor(color) {
this.textColor = color;
this._drawNumbering();
}
setTextLocation(location) {
this.textLocation = location;
return this._drawNumbering();
}
setUp(upVector) {
this.upVector = upVector;
this.up = upVector;
this.lookAt(upVector);
}
resize( width, length ) {
if (width && length ) {
var width = Math.max(width,10);
this.width = width;
var length = Math.max(length,10);
this.length = length;
this.step = Math.max(this.step,5);
this.remove(this.mainGrid);
this.remove(this.subGrid);
this.remove( this.margin );
//this.remove(this.plane);
return this._drawGrid();
}
}
_drawNumbering() {
var label, sizeLabel, sizeLabel2, xLabelsLeft, xLabelsRight, yLabelsBack, yLabelsFront;
var step = this.step;
this._labelStore = {};
if (this.labels != null) {
this.mainGrid.remove(this.labels);
}
this.labels = new THREE.Object3D();
var width = this.width;
var length = this.length;
var numbering = this.numbering = "centerBased";
var labelsFront = new THREE.Object3D();
var labelsSideRight = new THREE.Object3D();
if(numbering == "centerBased" )
{
for (var i = 0 ; i <= width/2; i += step)
{
var sizeLabel = this.drawTextOnPlane("" + i, 32);
var sizeLabel2 = sizeLabel.clone();
sizeLabel.position.set(length/2, -i, 0.1);
sizeLabel.rotation.z = -Math.PI / 2;
labelsFront.add( sizeLabel );
sizeLabel2.position.set(length/2, i, 0.1);
sizeLabel2.rotation.z = -Math.PI / 2;
labelsFront.add( sizeLabel2 );
}
for (var i = 0 ; i <= length/2; i += step)
{
var sizeLabel = this.drawTextOnPlane("" + i, 32);
var sizeLabel2 = sizeLabel.clone();
sizeLabel.position.set(-i, width/2, 0.1);
//sizeLabel.rotation.z = -Math.PI / 2;
labelsSideRight.add( sizeLabel );
sizeLabel2.position.set(i, width/2, 0.1);
//sizeLabel2.rotation.z = -Math.PI / 2;
labelsSideRight.add( sizeLabel2 );
}
var labelsSideLeft = labelsSideRight.clone();
labelsSideLeft.rotation.z = -Math.PI ;
//labelsSideLeft = labelsSideRight.clone().translateY(- width );
var labelsBack = labelsFront.clone();
labelsBack.rotation.z = -Math.PI ;
}
/*if (this.textLocation === "center") {
yLabelsRight.translateY(- length/ 2);
xLabelsFront.translateX(- width / 2);
} else {
yLabelsLeft = yLabelsRight.clone().translateY( -width );
xLabelsBack = xLabelsFront.clone().translateX( -length );
this.labels.add( yLabelsLeft );
this.labels.add( xLabelsBack) ;
}*/
//this.labels.add( yLabelsRight );
this.labels.add( labelsFront );
this.labels.add( labelsBack );
this.labels.add( labelsSideRight );
this.labels.add( labelsSideLeft );
//apply visibility settings to all labels
var textVisible = this.text;
this.labels.traverse( function( child ) {
child.visible = textVisible;
});
this.mainGrid.add(this.labels);
}
drawTextOnPlane(text, size) {
var canvas, context, material, plane, texture;
if (size == null) {
size = 256;
}
if(document){
canvas = document.createElement('canvas');
}else{
canvas = {}
}
var size = 128;
canvas.width = size;
canvas.height = size;
context = canvas.getContext('2d');
context.font = "18px sans-serif";
context.textAlign = 'center';
context.fillStyle = this.textColor;
context.fillText(text, canvas.width / 2, canvas.height / 2);
context.strokeStyle = this.textColor;
context.strokeText(text, canvas.width / 2, canvas.height / 2);
texture = new THREE.Texture(canvas);
texture.needsUpdate = true;
texture.generateMipmaps = true;
texture.magFilter = THREE.LinearFilter;
texture.minFilter = THREE.LinearFilter;
material = new THREE.MeshBasicMaterial({
map: texture,
transparent: true,
color: 0xffffff,
alphaTest: 0.3
});
plane = new THREE.Mesh(new THREE.PlaneBufferGeometry(size / 8, size / 8), material);
plane.doubleSided = true
plane.overdraw = true
return plane;
}
} |
JavaScript | class RouteChangeListener extends Component {
componentDidMount() {
const {history} = this.props;
// Send initially mounted route
this.sendAnalytics(history.location.pathname);
history.listen((location) => {
// Send subsequent route changes
this.sendAnalytics(location.pathname);
});
}
sendAnalytics(url) {
window.ga && ga.send('pageview', {dp: url})
}
render({children}) {
return <div>{children}</div>;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.