Getting error dia.ElementView: markup required from graph.fromJSON(json) - json

While doing one of my assignment where I want to draw diagram form json with help of rappidJS/JointJS. I was referring to below link
https://resources.jointjs.com/tutorial/serialization
I am getting below error
dia.ElementView: markup required
The json I am using to populate is
{
"cells": [{
"type": "standard.Rectangle",
"position": {
"x": 70,
"y": 70
},
"size": {
"width": 70,
"height": 70
},
"angle": 0,
"id": "79e30352-ad4f-417a-807a-0427d605a9f4",
"z": 1
}]
}
and the graph and paper code are as follow
var graph = new joint.dia.Graph;
var paper = new joint.dia.Paper({
width: $('.paper-container').width(),
height: $('.paper-container').height(),
gridSize: 10,
drawGrid: true,
model: graph,
interactive: {linkMove: false},
defaultLink: new joint.dia.Link({
attrs: { '.marker-target': { d: 'M 10 0 L 0 5 L 10 10 z' }}
}),
async: true
});
and the error I am getting is
Uncaught Error: dia.ElementView: markup required
at child.renderMarkup (rappid.min.js:14)
at child.render (rappid.min.js:14)
at child.e.render (rappid.min.js:14)
at child.confirmUpdate (rappid.min.js:14)
at child.updateView (rappid.min.js:14)
at child.updateViewsBatch (rappid.min.js:14)
at child.updateViewsAsync (rappid.min.js:14)
I am using Rappid 3.0 version here.

Make sure you have the cellNamespace of the graph set on creation and also have the
cellViewNamespace of the paper set.
const graph = new joint.dia.Graph({}, {cellNamespace: joint.shape});
const paper = new joint.dia.Paper({model: graph, cellViewNamespace: joint.shapes});
After that, make sure that all custom element extends are on the joint.shape object. So if you have a custom element defined like so:
const NewElement = joint.dia.Element.define("node.NewElement", {size: {width:70,height: 70},... });
Then ensure that the node.NewElement element is on the joint.shapes object like this.
joint.shapes.node = {}; joint.shapes.node.NewElement = NewElement;

Related

How to prevent duplicates being added to JSON object

Using Electron and electron-store to add files' simplified executable names and their full paths from showOpenDialog to config.json. Selecting the same file causes repeating entries in config.json. For some reason (or rather missing code), app thinks they're different paths.
function addTool() {
dialog.showOpenDialog({
title: 'Select tool executable.',
filters: [{
name: 'Tool start file',
extensions: ['exe', 'jar']
}],
properties: ['openFile']
},
(exeFromDialog) => {
var var_exeToolPath = exeFromDialog.join(); //removes square brackets
var var_toolName = path.basename(var_exeToolPath).split(/[/._-]/g)[0];
//path.basename removes path until file, split+regex takes only first part until first character (one of ._/)
const tools = appConfig.get('tools');
const newTool = [...(tools || []), {
"toolName": var_toolName,
"toolPath": var_exeToolPath
}];
appConfig.set('tools', newTool);
})
}
This is how config.json looks when you open the same file few times:
{
"winPosition": {
"x": 1497,
"y": 410,
"width": 203,
"height": 603
},
"exePOEPath": [
"C:\\Program Files (x86)\\Grinding Gear Games\\Path of Exile\\PathOfExile_x64.exe"
],
"tools": [
{
"toolName": "tool1",
"toolPath": "D:\\tool1.exe"
},
{
"toolName": "tool1",
"toolPath": "D:\\tool1.exe"
},
{
"toolName": "tool1",
"toolPath": "D:\\tool1.exe"
}
]
}
Ultimately it comes to the question How to remove duplicates from your array
This part of your code will always add the new value, it doesn't check for duplicates
const newTool = [...(tools || []), {
toolName: var_toolName,
toolPath: var_exeToolPath
}]
So it should be improved to something like the following:
newTool = newTool.filter((item, pos, self) =>
self.find(other => other.toolName === item.toolName) === item
)
I would prefer using [...new Set([newTool])] but you store Objects which are compared by reference thus duplicates cannot be eliminated by Set

How to reformat (transform) my json results with javascript?

I have a simple loop that extracts a subset of json objects from a larger dataset.
function getData(d) {
var data = {};
for (var i=0; i < d.length; i++){
data[i] = {
'date' : d[i].date,
'light' : Math.round(d[i].details.light/60),
'deep' : Math.round(d[i].details.deep/60),
'awake' : Math.round(d[i].details.awake/60),
'duration': Math.round(d[i].details.duration/60),
'quality': Math.round(d[i].details.quality*10)
};
console.log(data[i]);
};
return data;
}
getData(d);
It generates json results in the form of,
{
date: 20150809,
light: 168,
deep: 206,
awake: 64,
duration: 438,
quality: 100
}, ...
How might I get this into the desired form,
[{
"key":"light",
"date":20150809,
"value":168
},
{
"key":"deep",
"date": 20150809,
"value":206
},
{
"key":"awake",
"date":20150809,
"value":64
},
{
"key":"duration",
"date": 20150809,
"value":438
},
...
{
"key":"quality",
"date":20150809,
"value":6100
}]
My question is, how might I achieve this without iterating over the dataset five times (once for each of the 5 key types)? I assume at least a minimum of one iteration would be required. A jquery solution would be acceptable.
I'm seeking one array containing all the json objects as opposed to an associative array of nested objects.
Thanks
Suppose your data is in a array in this format :
var data = [
{
date: 20150809,
light: 168,
deep: 206,
awake: 64,
duration: 438,
quality: 100
},
{
date: 20153203,
light: 2,
deep: 21,
awake: 21,
duration: 21,
quality: 32
}
...
];
You can try something like this :
var results = [];
data.forEach(function(e) {
for (var key in e) {
if (key !== 'date')
results.push({
key : key,
date : e.date,
value : e[key]
});
}
});
Considering the object
{
date: 20150809,
light: 168,
deep: 206,
awake: 64,
duration: 438,
quality: 100
}
You want to turn each key into a object without looping through every object. I would to the following:
function convertToJson(obj){
var myJson = {};
var myKeys = obj.keys(); // return an array with the keys of the object
myJson.keys = myKeys[1];
myJson.date = myKeys[0]; // your date
myJson.value = obj.light;
... // do the same with the rest of the elements, if you don't want to loop.
return JSON.stringfy(myJson);
}
I'm no javascript guru, so I appreciate any feedback.

best way to parse nested object in AngularJS?

I'm trying to use angularjs for parsing a nested data structure returned from a remote server. I'm really stumped by this pattern because i'm trying to access the "events" data with the following function
$scope.generate_event = function(){
from_date = $scope.dts.from
to_date = $scope.dts.to
from = from_date.getFullYear()+'/'+(from_date.getMonth()+1)+'/'+from_date.getDate()
to = to_date.getFullYear()+'/'+(to_date.getMonth()+1)+'/'+to_date.getDate()
$http.get(server+'rawdata?vids='+$scope.selected_vehicle.id+'&evfields=lat,lon,f_event_time,speed&from='+from+'&to='+to)
.success(function(data){
$scope.report_data = data
$localStorage.report_data = data
$scope.generate()
})
}
Any advice or even a hint on the best approach would be great, i need this running for work and its been a month now. Thanks!
{
"rawData": {
"keys": {
"lat": ["number", "lat"],
"lon": ["number", "lon"],
"speed": ["number", "Speed [mph]"],
"code": ["number", "EVC"],
"vid": ["number", "Vehicle ID"]
},
"keys_order": ["lat", "lon", "speed", "code", "vid"],
"events": [{
"f_lon": -8.3315599999999996,
"code": 4,
"vid": 5,
"lon": -833156,
"f_lat": 51.90831,
"lat": 5190831,
"speed": 78.0
}, {
"f_lon": -8.3741599999999998,
"code": 4,
"vid": 5,
"lon": -837416,
"f_lat": 51.903979999999997,
"lat": 5190398,
"speed": 78.0
}]
}
}
UPDATE: I didnt explain the problem correctly. Here's the generate function
$scope.generate = function(){
$scope.event_config = {
title: 'Events', // chart title, legend etc
/*etc
*etc
*/
data = {}
data.series = [' Events']
data.data = []
this fucker ----->$scope.report_data.events.forEach(function(value, index, array){
o = {}
o.x = value.f_event_time
o.y = [value.lat+'/'+value.lon]
o.tooltip = value.speed
data.data.push(o)
})
$scope.event_data = data
I'm getting error 'forEach undefined'. This is supposed to generate a d3 chart but 'report_data' is intially used to store distance data from a different function for local storage. So do i need a second variable for localStorage? ie $scope.report_event = $localStorage.report_event? Can someone look at the source code if i send it?
$http.get(server+'rawdata?vids='+$scope.selected_vehicle.id+'&evfields=lat,lon,f_event_time,speed&from='+from+'&to='+to)
.success(function(data){
if (data) {
var events = data.rawData.events; // get the events json array
$scope.generate(events);
}
})
and in your controller have the declarative function like
$scope.generate = function(events) {
// your code
}
Solved it with the following
$scope.generate_report = function(){
from_date = $scope.dts.from
to_date = $scope.dts.to
from = from_date.getFullYear()+'/'+(from_date.getMonth()+1)+'/'+from_date.getDate()
to = to_date.getFullYear()+'/'+(to_date.getMonth()+1)+'/'+to_date.getDate()
$http.get(server+'vehicle/'+$scope.selected_vehicle.id+'/counters/deltas/day?from='+from+'&to='+to)
.success(function(data){
$scope.report_data = data
$localStorage.report_data = data
$scope.process()
})
$http.get(server+'rawdata?vids='+$scope.selected_vehicle.id+'&genevcodes=39,40&evfields=lat,lon,f_event_time,mph,speed,code&from='+from+'&to='+to)
.success(function(data){
if(data){
var events = data.rawData.events
}
$scope.report_event = events
$localStorage.report_event = events
$scope.generate()
})
}
just had to declare another localstorage variable for storing events from the JSON object Thanks Yannik

AS3 Object To JSON

I'm trying to convert an array of objects (nested) to JSON string.
Here is my JSON output:
[{
"Width": 570,
"SessionID": 2003404006158805,
"Price": "69,90",
"PageCount": 24,
"Pages": [{
"ID": 1,
"TemplateID": 0,
"PageType": "cover",
"TextContainers": [],
"ImageContainers": []
}, {
"ID": 2,
"TemplateID": 1001,
"PageType": "single",
"TextContainers": [],
"ImageContainers": []
}, {
"ID": 3,
"TemplateID": 0,
"PageType": "double",
"TextContainers": [],
"ImageContainers": [{
"Width": 570,
"IsBG": true,
"Brightness": 0,
"Contrast": 0,
"PosX": null,
"ScaleX": null,
"Height": 284,
"ID": -1,
"BlackWhite": 0,
"PosY": null,
"HasPhoto": false,
"ScaleY": null,
"PhotoID": null
}]
}, {
"ID": 4,
"TemplateID": 0,
"PageType": "double",
"TextContainers": [],
"ImageContainers": [{
"Width": 570,
"IsBG": true,
"Brightness": 0,
"Contrast": 0,
"PosX": null,
"ScaleX": null,
"Height": 284,
"ID": -1,
"BlackWhite": 0,
"PosY": null,
"HasPhoto": false,
"ScaleY": null,
"PhotoID": null
}]
}],
"ProductSubID": 0,
"Height": 620,
"ProductID": 0
}]
And when I'm trying to convert this string to XML (at server side) comes out like this:
<?xml version="1.0" encoding="UTF-8" ?>
<0>
<Width>570</Width>
<SessionID>2003404006158805</SessionID>
<Price>69,90</Price>
<PageCount>24</PageCount>
<Pages>
<ID>1</ID>
<TemplateID>0</TemplateID>
<PageType>cover</PageType>
</Pages>
<Pages>
<ID>2</ID>
<TemplateID>1001</TemplateID>
<PageType>single</PageType>
</Pages>
<Pages>
<ID>3</ID>
<TemplateID>0</TemplateID>
<PageType>double</PageType>
<ImageContainers>
<Width>570</Width>
<IsBG>true</IsBG>
<Brightness>0</Brightness>
<Contrast>0</Contrast>
<PosX />
<ScaleX />
<Height>284</Height>
<ID>-1</ID>
<BlackWhite>0</BlackWhite>
<PosY />
<HasPhoto>false</HasPhoto>
<ScaleY />
<PhotoID />
</ImageContainers>
</Pages>
<Pages>
<ID>4</ID>
<TemplateID>0</TemplateID>
<PageType>double</PageType>
<ImageContainers>
<Width>570</Width>
<IsBG>true</IsBG>
<Brightness>0</Brightness>
<Contrast>0</Contrast>
<PosX />
<ScaleX />
<Height>284</Height>
<ID>-1</ID>
<BlackWhite>0</BlackWhite>
<PosY />
<HasPhoto>false</HasPhoto>
<ScaleY />
<PhotoID />
</ImageContainers>
</Pages>
<ProductSubID>0</ProductSubID>
<Height>620</Height>
<ProductID>0</ProductID>
</0>
But I need it to be like:
<pages>
<page>
</page>
<page>
</page>
</pages>
This is my AS code to convert Object arrays into JSON
var Pages:Array = [];
var Books:Array = [];
var JBook:Object = new Object();
JBook.Width = Global.BOOK_WIDTH;
for(var i:Number = 0; i<Global.PAGES.length; i++)
{
var Page:PageVO = Global.PAGES[i] as PageVO;
var JPage:Object = new Object();
JPage.ID = Page.ID;
var ImageContainers:Array = [];
var TextContainers:Array = [];
var Template:TemplateVO = Page.ACTIVE_TEMPLATE;
for(var j:Number = 0; j<Template.IMAGE_CONTAINERS.length; j++)
{
var ImageContainer:ImageContainerVO = Template.IMAGE_CONTAINERS[j] as ImageContainerVO;
var JImageContainer:Object = new Object();
JImageContainer.ID = ImageContainer.ID;
ImageContainers.push(JImageContainer);
}
for (var m:Number = 0; m<Template.TEXT_CONTAINERS.length; m++)
{
var TextContainer:TextContainerVO = Template.TEXT_CONTAINERS[m] as TextContainerVO;
var JTextContainer:Object = new Object();
JTextContainer.ID = TextContainer.ID;
}
JPage.TextContainers = TextContainers;
JPage.ImageContainers = ImageContainers;
Pages.push(JPage);
}
var Photos:Array = [];
for(var p:Number = 0; p<Global.PHOTOS.length; p++ )
{
var Photo:PhotoVO = Global.PHOTOS[p] as PhotoVO;
var JPhoto:Object = new Object();
JPhoto.BMP = ImageUtils.BitmapToBase64(Photo.BMP.bitmapData);
JPhoto.UseCount = Photo.USE_COUNT;
JPhoto.ID = Photo.ID;
Photos.push(JPhoto);
}
//JBook.Photos = Photos;
JBook.Pages = Pages;
JSON = com.adobe.serialization.json.JSON.encode(Books);
Any idea why it's rendering JSON string like they are not in the same node (seperate node for every page item)?
Hope I've been clear. Thanks.
Probably the easiest way to convert from an AS3 object to a JSON string is to use the JSON class from as3corelib.
Example usage:
var jsonString:String = JSON.encode(myDataObject);
It is probably best not to write your own parser, as the as3corelib JSON parser has been worked on and used by many people, for quite some time.
EDIT: #dpcao mentioned that you don't even need an external library anymore, Adobe introduced a new JSON class available in FlashPlayer 11.
Example usage:
var jsonString:String = JSON.stringify(myDataObject);
Are you iterating through a native object? Or through an XML Object? Because if you're iterating an [XMLList][1] you should use length(), not length (they named it as a function to avoid name collections)
But honestly, use JSONLib, or [natively][2], with Flash Player 10.3 or above, use it natively. It mimics the javascript api, with JSON.parse and JSON.stringify respectively. This shouldn't be an issue with JSON serialization, you might have a bug either server side or client side with your serialization. I would suggest adding a serialize() function to each of your objects -- this makes it easier in the long run to maintain anyways. ie:
class PageVO {
function serialize():Object {
return {
ID: some_id,
Template_ID: some_template_id,
// add image containers here
}
}
}
This will make it easier to debug individual objects to see where the problem is coming from. As it looks, there's no reason why your code shouldn't work. However, there might be issues with the actionscript serialization class and not adding a variable node: i.e. serializing [], rather than { "name": value }. Try the native serializer and see what happens. (don't forget -swf-version=16)

HighCharts & MVC: How to load whole graph definition and data with JSON?

I'd like to know how it is possible to load options & data graph or whole graph structure returning a JSON object?
In particular, I'd like to dynamically create options, categories, axis, data, etc. with JSON; I think it is possible, but I only found informations describing how to load data& series, not options.
For example, I'd like to define title, xAxis, etc, returning a JSon Object:
[...]
title: {
text: 'Total fruit consumtion, grouped by gender'
},
xAxis: {
categories: []
},
[...]
In particular, I need to dynamically create a more complex graph, similar to this one: http://www.highcharts.com/demo/column-stacked-and-grouped
Thanks in advance!
With DotNet.Highcharts is possible to create the chart on the server side as you like without using JavaScript or JSON. Here is the example which you would like do with the library:
Highcharts chart = new Highcharts("chart")
.InitChart(new Chart { DefaultSeriesType = ChartTypes.Column })
.SetTitle(new Title { Text = "Total fruit consumtion, grouped by gender" })
.SetXAxis(new XAxis { Categories = new[] { "Apples", "Oranges", "Pears", "Grapes", "Bananas" } })
.SetYAxis(new YAxis
{
AllowDecimals = false,
Min = 0,
Title = new YAxisTitle { Text = "Number of fruits" }
})
.SetTooltip(new Tooltip { Formatter = "TooltipFormatter" })
.SetPlotOptions(new PlotOptions { Column = new PlotOptionsColumn { Stacking = Stackings.Normal } })
.SetSeries(new[]
{
new Series
{
Name = "John",
Data = new Data(new object[] { 5, 3, 4, 7, 2 }),
Stack = "male"
},
new Series
{
Name = "Joe",
Data = new Data(new object[] { 3, 4, 4, 2, 5 }),
Stack = "male"
},
new Series
{
Name = "Jane",
Data = new Data(new object[] { 2, 5, 6, 2, 1 }),
Stack = "female"
},
new Series
{
Name = "Janet",
Data = new Data(new object[] { 3, 0, 4, 4, 3 }),
Stack = "female"
}
});
You can find a lot of ASP.NET MVC examples here: http://dotnethighcharts.codeplex.com/releases/view/80650