newbie: hello world using jointjs - jointjs

Hello Im trying to execute Hello world application using JointJS library as given in :
http://www.jointjs.com/tutorial#hello-world
I have downloaded joint.js and joint.css files
I have copied the code given in HelloWorld tutorial in html file and accessed it from the firefox browser (26.0)
But its not working as expected and shown in the tutorial.
Expected: Two boxes with link should come.
Actual: Nothing is coming on the browser. Ater debugging error is:
"NS_ERROR_FAILURE:" in joint.js at:
var bbox = this.el.getBBox();
code is:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="joint.css" />
<script src="joint.js"></script>
</head>
<body>
<script type="text/javascript">
var graph = new joint.dia.Graph;
var paper = new joint.dia.Paper({
el: $('#myholder'),
width: 600,
height: 200,
model: graph
});
var rect = new joint.shapes.basic.Rect({
position: { x: 100, y: 30 },
size: { width: 100, height: 30 },
attrs: { rect: { fill: 'blue' }, text: { text: 'my box', fill: 'white' } }
});
var rect2 = rect.clone();
rect2.translate(300);
var link = new joint.dia.Link({
source: { id: rect.id },
target: { id: rect2.id }
});
graph.addCells([rect, rect2, link]);
</script>
</body>
</html>
Regards
Ranganath

You're missing a holder for the paper object. Add the following right after the opening <body> tag:
<div id="myholder"></div>

You can try this code. Please add jquery.min.js lodash.min.js backbone-min.js
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="joint.css" />
<script src="joint.js"></script>
<script src="jquery.min.js"></script>
<script src="lodash.min.js"></script>
<script src="backbone-min.js"></script>
</head>
<body>
<div id="myholder"></div>
<script type="text/javascript">
var graph = new joint.dia.Graph;
var paper = new joint.dia.Paper({
el: $('#myholder'),
width: 600,
height: 200,
model: graph
});
var rect = new joint.shapes.basic.Rect({
position: { x: 100, y: 30 },
size: { width: 100, height: 30 },
attrs: { rect: { fill: 'blue' }, text: { text: 'my box', fill: 'white' } }
});
var rect2 = rect.clone();
rect2.translate(300);
var link = new joint.dia.Link({
source: { id: rect.id },
target: { id: rect2.id }
});
graph.addCells([rect, rect2, link]);
</script>
</body>

Related

Chart.js - Dynamic Data sources based on new data point entry in JSON File

can someone support me here. Im using Chart.js libary to show in realtime beacon data from backend by using an websocket client technology.
The data are sent to frontend via websocket and in a "JSON format". Every 5 Seconds a new single is sent (see picture).
My Question is can I add a new data source dynamically including a data source label on the header with the Beacon ID to filter the rssi value by beaconID in case that a new beacon-ID would be sent from the backend?
Markus
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdn.socket.io/4.5.3/socket.io.min.js"
integrity="sha384-WPFUvHkB1aHA5TDSZi6xtDgkF0wXJcIIxXhC6h8OT8EH3fC5PWro5pWJ1THjcfEi"
crossorigin="anonymous"></script>
<script src="/socket.io/socket.io.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#3.3.2"></script>
<script src="https://cdn.jsdelivr.net/npm/luxon#^2"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-luxon#^1"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-streaming#2.0.0"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels#2 "></script>
<title>Demo Plugin Streaming in Chart.js</title>
<style type="text/css">
.chartBox {
width: 600px;
}
</style>
</head>
<body>
<div class="chartBox">
<canvas id="myChart"></canvas>
</div>
<button onclick="pauseChart()">Pause Chart</button>
<script>
//setblock
const data = {
labels: [],
datasets: [{
label: [],
data: [],
backgroundColor: 'rgba(75, 192, 192, 0.2)',
borderColor: 'rgba(75, 192, 192, 1)',
borderWidth: 1
},
{
label: [],
data: [],
backgroundColor: 'rgba(ß, 0, 192, 0.2)',
borderColor: 'rgba(0, 0, 192, 1)',
borderWidth: 1
}
]
};
//config block
const config = {
type: 'line',
data,
options: {
plugins: {
streaming: {
duration: 40000,
ttl: 60000,
refresh: 1000,
frameRate: 1,
pause: false
}
},
interaction: {
intersect: false
},
scales: {
x: {
type: 'realtime',
realtime: {
// delay: 2000,
onRefresh: chart => {
}
}
},
y: {
min: -100,
max: 0,
},
},
},
};
// render init block
const myChart = new Chart(
document.getElementById('myChart'),
config
);
function pauseChart() {
if (myChart.options.plugins.streaming.pause === false) {
myChart.options.plugins.streaming.pause = true;
} else {
myChart.options.plugins.streaming.pause = false;
}
myChart.update({ delay: 0 });
};
// Listen for messages
const socket = io("http://localhost:3000");
// client-side
socket.on("JSON_Data", function (message) {
const obj = JSON.parse(message);
const dataArray = Object.values(obj);
index = dataArray[0] - 1;
addData(myChart, dataArray[0].beaconMac, dataArray[0].rssi);
});
function addData(chart, label, data) {
chart.data.labels = label
console.log(label);
console.log(data);
chart.data.datasets.forEach((dataset) => {
dataset.data.push({
x: Date.now(),
y: data,
});
});
chart.update({ delay: 0 });
}
</script>
</body>
</html>
I tried to use the "dynamicy plugin streaming" libary of chart.js and I thought this libary will support dynamically this feature that whenever a field value would change that a new data source is automatically added, but I found nothing in the documenation.
https://nagix.github.io/chartjs-plugin-streaming/master/guide/

How to FTP upload a buffer (pdf buffer) using NodeJS?

I converted a HTML to pdf using html-pdf-node, but I am not find a way to store this PDF in my server using FTP.
My Code:
const html_to_pdf = require('html-pdf-node');
const generatePDF = () => {
// The test HTML file
let content = `
<html>
<head>
<title>Test Application</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h2>Just a Test</h2>
</div>
</body>
</html>
`;
// generating the PDF
let options = {
format: 'letter',
margin: {
right: '40px',
left: '40px'
}
};
let file = { content };
html_to_pdf.generatePdf(file, options).then((pdfBuffer) => {
console.log(pdfBuffer); // This is the pdfBuffer. It works because if I send this buffer to my email as an attachment, I can open the PDF
// How can I create and store a test.pdf file inside my server using FTP connection?
});
}
Thank you
Using ftp should do it - https://www.npmjs.com/package/ftp
Installation: npm i ftp and usage something like:
const Client = require("ftp");
// snip snip some code here
html_to_pdf.generatePdf(file, options).then((pdfBuffer) => {
const c = new Client();
c.on("ready", function () {
c.put(pdfBuffer, "foo.pdf", function (err) {
if (err) throw err;
c.end();
});
});
const secureOptions = {
host: "localhost",
port: 21,
user: "TheGreatPotatoKingOfEurope",
password: "5uper_5eekrit!"
};
c.connect(secureOptions);
});

Bouncing a body from the walls of another body. Phaser3

var config = {
type: Phaser.AUTO,
width: 800,
height: 600,
backgroundColor: '#1b1464',
parent: 'phaser-example',
physics: {
default: 'matter',
matter: {
debug: true
}
},
scene: {
preload: preload,
create: create
}
};
var game = new Phaser.Game(config);
function preload ()
{
this.load.image('red', 'assets/sprites/columns-red.png');
}
function create ()
{
this.matter.world.setBounds(100, 0, 600, 400, 1).disableGravity();
console.log(this.matter.world.walls.bottom)
var circ = this.matter.add.image(200, 50, 'red');
// Change the body to a Circle with a radius of 48px
circ.setBody({
type: 'circle',
radius: 48
});
// Just make the body move around and bounce
circ.setVelocity(6, 3);
circ.setAngularVelocity(0.01);
circ.setBounce(1);
circ.setFriction(1, 0, 0);
}
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="//cdn.jsdelivr.net/npm/phaser#3.19.0/dist/phaser.js"></script>
<script src="//cdn.jsdelivr.net/npm/phaser#3.19.0/dist/phaser.min.js"></script>
</head>
There is a code according to which the ball is squared and bounces off its walls. How can I rotate this square?
I am ready to accept proposals for the implementation of this example on other phaser engines

how to add callbacks to kendo dialog actions

I've tried using the Kendo UI DialogService to call up my own component in a dialog. The issue I'm having is in using custom actions for my dialog.
Including an ng-template with custom buttons and actions somewhat defeats the purpose of using the dialogService and clutters my template with markup not directly related to it.
I've tried using code like this:
const saveAction = { text: 'Save', primary: true };
const cancelAction = { text: 'Cancel' };
const dialog = this.dialogService.open({
title: 'Edit data',
content: FormComponent,
actions: [
cancelAction,
saveAction
]
});
const form = dialog.content.instance;
form.data = data;
dialog.result.subscribe((result) => {
if (result === saveAction) {
form.save();
}
});
This will let me run a save function from my FormComponent, but won't allow me to stop the dialog from closing if the form validation is off or the save fails.
I have managed to prevent the dialog from closing after you click an action by taking a copy of the dialogs action event emitter, and replacing it with my own.
It's a hack solution to this. Hopefully Kendo will provide something better in future.
const saveAction = { text: 'Save', primary: true };
const cancelAction = { text: 'Cancel' };
const dialog = this.dialogService.open({
title: 'Edit data',
content: FormComponent,
actions: [
cancelAction,
saveAction
]
});
const form = dialog.content.instance;
form.data = data;
const actionEmitter = dialog.dialog.instance.action;
dialog.dialog.instance.action = new EventEmitter<any>();
const sub = dialog.dialog.instance.action.subscribe(action => {
// Perform any check here based on whether you want the dialog to close or not
if(form.validate()) {
// Only call this if you want the dialog to close
actionEmitter.emit(action);
}
});
dialog.result.subscribe((result) => {
sub.unsubscribe(); // clean up
if (result === saveAction) {
form.save();
}
});
You can use method 'setOptions', but I don't know why this method doesn't exist in Telerik Document: https://docs.telerik.com/kendo-ui/api/javascript/ui/dialog
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled</title>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.2.619/styles/kendo.common.min.css">
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.2.619/styles/kendo.rtl.min.css">
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.2.619/styles/kendo.default.min.css">
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.2.619/styles/kendo.mobile.all.min.css">
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2019.2.619/js/angular.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2019.2.619/js/jszip.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2019.2.619/js/kendo.all.min.js"></script>
</head>
<body>
<div id="dialog"></div>
<input type="button" value="show dialog" onclick="showDialog()" />
<script>
$("#dialog").kendoDialog({
visible: false,
content: 'first content',
actions: [{
text: "OK",
action: function (e) {
return false;
},
primary: true
}, {
text: "Cancel"
}]
});
function showDialog() {
var dialog = $("#dialog").data("kendoDialog");
dialog.setOptions({
closable: false,
content: 're-open content',
actions: [{
text: 'test1',
primary: true
},
{
text: 'test2'
}
]
});
dialog.open();
console.log(dialog.options.actions)
}
</script>
</body>
</html>

How to make a Graph on VueJS

Am trying to make a graph with data received from an API and put this on a graph (https://bl.ocks.org/mbostock/4062045) - Force-Directed Graph
However I am unsure on how this is done on VueJs or if there is a simpler tool to do this?
D3 Force-Directed Graph seems a bit complicated, maybe there is a library already that does this out of the box?
The mentioned vue-d3 package from the comment is just adding D3 to the Vue prototype so it is accessible with this.$d3.
I've tested that package but it wasn't working with my D3 version. Looks like a casing issue (D3 instead of d3). So I've added the prototype manually.
I don't know if there is an easier library for creating a force graph but please have a look at the demo below or this fiddle.
I've modified the example from your link to create a force directed graph. The demo is working but as you've mentioned it's pretty complicated.
Also binding from SVG to Vue.js model could be improved. But I couldn't find a better way to do it.
For example adding a new node on click is not working with just adding a new node to the array but this should be the goal for a Vue.js component. The SVG graph should automatically update once the data changes.
At the moment, nodes and links in Vue.js are not used in the component because I don't know how to add the updating of the graph.
If you figured out how to add the updating with the model data, please let me know. Refreshing the whole chart is pretty easy by deleting the SVG and re-create it. (see reload button)
// https://unpkg.com/vue-d3#0.1.0 --> only adds d3 to Vue.prototype but it wasn't working as expected (d3 is lower case)
Vue.prototype.$d3 = d3;
const URL = 'https://demo5147591.mockable.io/miserables'; // data copied from below link because of jsonp support
//'https://bl.ocks.org/mbostock/raw/4062045/5916d145c8c048a6e3086915a6be464467391c62/miserables.json';
//console.log(window.d3);
const d3ForceGraph = {
template: `
<div>
{{mousePosition}}
<button #click="reload">reload</button>
<svg width="600" height="600"
#mousemove="onMouseMove($event)"></svg>
</div>
`,
data() {
return {
nodes: [],
links: [],
simulation: undefined,
mousePosition: {
x: 0,
y: 0
}
}
},
mounted() {
this.loadData(); // initially load json
},
methods: {
// load data
loadData() {
this.$svg = $(this.$el).find('svg');
let svg = this.$d3.select(this.$svg.get(0)), //this.$d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height");
//console.log($(this.$el).find('svg').get(0));
this.simulation = this.$d3.forceSimulation()
.force("link", this.$d3.forceLink().id(function(d) {
return d.id;
}))
.force("charge", this.$d3.forceManyBody())
.force("center", this.$d3.forceCenter(width / 2, height / 2));
let color = this.$d3.scaleOrdinal(this.$d3.schemeCategory20);
$.getJSON(URL, (graph) => {
//d3.json("miserables.json", function(error, graph) { // already loaded
//if (error) throw error; // needs to be implemented differently
let nodes = graph.nodes;
let links = graph.links;
let link = svg.append("g")
.attr("class", "links")
.selectAll("line")
.data(links) //graph.links)
.enter().append("line")
.attr("stroke-width", function(d) {
return Math.sqrt(d.value);
});
let node = svg.append("g")
.attr("class", "nodes")
.selectAll("circle")
.data(nodes) //graph.nodes)
.enter().append("circle")
.attr("r", 5)
.attr("fill", function(d) {
return color(d.group);
})
.call(this.$d3.drag()
.on("start", this.dragstarted)
.on("drag", this.dragged)
.on("end", this.dragended));
node.append("title")
.text(function(d) {
return d.id;
});
this.simulation
.nodes(graph.nodes)
.on("tick", ticked);
this.simulation.force("link")
.links(links); //graph.links);
function ticked() {
link
.attr("x1", function(d) {
return d.source.x;
})
.attr("y1", function(d) {
return d.source.y;
})
.attr("x2", function(d) {
return d.target.x;
})
.attr("y2", function(d) {
return d.target.y;
});
node
.attr("cx", function(d) {
return d.x;
})
.attr("cy", function(d) {
return d.y;
});
}
})
},
reload() {
//console.log('reloading...');
this.$svg.empty(); // clear svg --> easiest way to re-create the force graph.
this.loadData();
},
// mouse events
onMouseMove(evt) {
//console.log(evt, this)
this.mousePosition = {
x: evt.clientX,
y: evt.clientY
}
},
// drag event handlers
dragstarted(d) {
if (!this.$d3.event.active) this.simulation.alphaTarget(0.3).restart();
d.fx = d.x;
d.fy = d.y;
},
dragged(d) {
d.fx = this.$d3.event.x;
d.fy = this.$d3.event.y;
},
dragended(d) {
if (!this.$d3.event.active) this.simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
}
}
};
new Vue({
el: '#app',
data() {
return {}
},
components: {
d3ForceGraph
}
});
.links line {
stroke: #999;
stroke-opacity: 0.6;
}
.nodes circle {
stroke: #fff;
stroke-width: 1.5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.8.0/d3.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.6/vue.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="app">
<d3-force-graph></d3-force-graph>
</div>
I answered another question on vue + d3 by providing an example of a d3 force graph with vue.js.
d3.js is now split in small modules and specific computations are isolated in small components like d3-force. SVG can be drawn in a component template like any other HTML structure.
You can use vue-d3-network
npm install vue-d3-network
see this fiddle
html:
```
<head>
<script type="text/javascript" src="https://unpkg.com/vue">
</script>
<link rel="stylesheet" type="text/css" href="https://rawgit.com/emiliorizzo/vue-d3-network/master/dist/vue-d3-network.css">
<script type="text/javascript" src="https://rawgit.com/emiliorizzo/vue-d3-network/master/dist/vue-d3-network.umd.js"></script>
</head>
<body>
<div id="app">
<d3-network :net-nodes="nodes" :net-links="links" :options="options">
</d3-network>
</div>
</body>
```
javascript:
```
var D3Network = window['vue-d3-network']
new Vue({
el: '#app',
components: {
D3Network
},
data () {
return {
nodes: [
{ id: 1, name: 'my node 1' },
{ id: 2, name: 'my node 2' },
{ id: 3, _color:'orange' },
{ id: 4 },
{ id: 5 },
{ id: 6 },
{ id: 7 },
{ id: 8 },
{ id: 9 }
],
links: [
{ sid: 1, tid: 2, _color:'red' },
{ sid: 2, tid: 8, _color:'f0f' },
{ sid: 3, tid: 4,_color:'rebeccapurple' },
{ sid: 4, tid: 5 },
{ sid: 5, tid: 6 },
{ sid: 7, tid: 8 },
{ sid: 5, tid: 8 },
{ sid: 3, tid: 8 },
{ sid: 7, tid: 9 }
],
options:
{
force: 3000,
nodeSize: 20,
nodeLabels: true,
linkWidth:5
}
}
},
})
```

Resources