Icons not Displaying on Deck.gl - javascript

I think there's an error with the data format that I using but I can't seen to solve it, at the current format no icons are displaying.
var coord = [];
export default function App({
function coordGet() {
for (let i = 0; i < IconPositions.length; i++) {
coord["ID" + i] = [{
name: "ID" + i,
address: "Address" + i,
exits: "Exits" + i,
position: [parseFloat(IconPositions[i][0]), parseFloat(IconPositions[i][1])]
}];
}
coordGet();
}
const iconVar = { data: coordGet() };
function updateLayers() {
const layers = [
new IconLayer({
id: "icon-layer",
data: iconVar.data,
pickable: true,
iconAtlas: 'https://raw.githubusercontent.com/visgl/deck.gl-data/master/website/icon-atlas.png',
iconMapping: ICON_MAPPING,
getIcon: d => 'marker',
getPosition: d => d.position,
sizeScale: 200,
getSize: d => 7,
getColor: d => [Math.sqrt(d.exits), 140, 0],
})
];
return layers;
}

Related

Display data for specific release selected in release filter at the top of page in rally dashboard

This is my code and in this the data displayed in chart is hole project data but in rally dashboard there is release filter at the top of your page. and i want my chart to show data of the the release selected by that filter and my sdk version in code is 1.33
<!DOCTYPE HTML\>
<script
src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js">
var WORKSPACE_OID = "__WORKSPACE_OID__";
var PROJECT_OID = "__PROJECT_OID__";
var PROJECT_SCOPING_UP = "__PROJECT_SCOPING_UP__";
var PROJECT_SCOPING_DOWN = "__PROJECT_SCOPING_DOWN__";
var MILS_IN_DAY = 86400000;
var DAYS_BACK = 30;
var filterChart;
var currentProjectDataSource;
var fromDate = new Date(new Date().getTime() - (MILS_IN_DAY * DAYS_BACK));
var allDefects = [];
// var currentRelease;
var onLoadAllIssues = function (result) {
// var defects = result.defects.filter(function (defect) {
// return defect.Release && defect.Release.\_refObjectName === currentRelease.Name;
// });
var labels = [];
var openDefects = [];
var closedDefects = [];
var defects = result.defects;
for (var count = 0; count < defects.length; count++) {
allDefects[allDefects.length] = defects[count];
var defect = defects[count];
labels.push(defect.CreationDate.split('T')[0]);
if (defect.ClosedDate !==null) {
closedDefects.push(defect.ClosedDate.split('T')[0]);
}
}
closedDefects.sort();
const counts = {};
labels.forEach(function (x) { counts[x] = (counts[x] || 0) + 1; });
const closedcounts = {};
closedDefects.forEach(function (x) { closedcounts[x] = (closedcounts[x] || 0) + 1; });
mychart(counts,closedcounts,labels)
};
var createCharts = function () {
var loadAllDefectsQuery = {
type: 'defect',
key: 'defects',
fetch: 'CreationDate,ClosedDate,ObjectID,FormattedID,Name,State,Priority',
order: 'CreationDate',
query: '((CreationDate != "null") OR (CreationDate > "' + dojo.date.stamp.toISOString(fromDate, { zulu: true }) +
'"))'
};
currentProjectDataSource.findAll(loadAllDefectsQuery, onLoadAllIssues);
};
var initPage = function () {
currentProjectDataSource = new rally.sdk.data.RallyDataSource(WORKSPACE_OID, PROJECT_OID, PROJECT_SCOPING_UP,
PROJECT_SCOPING_DOWN);
createCharts();
};
rally.addOnLoad(initPage);
function mychart(counts,closedcounts,labels) {
const pielable = labels;
const piedata = counts;
const closedcountsdata = closedcounts;
const data = {
datasets: [
{
label: 'Number of opened defects',
data: piedata,
},
{
label: 'Number of closed defects',
data: closedcountsdata,
}
]
};
const config = {
type: 'line',
data: data,
options: {
scales: {
x: {
min:"2022-01-01",
max:"2022-12-31",
type: 'time',
time:{
unit:'day',
},
},
y: {
beginAtZero: true,
grace: 5,
ticks: {
stepSize: 1,
},
},
},
plugins: {
legend: {
position: 'top',
},
title: {
display: true,
text: 'Defect Burndown Chart'
},
tooltip: {
yAlign: 'bottom',
titleMarginBottom: 0,
callbacks: {
title: function (context) {
return( `${context[0].label.slice(0, -13).replace(/,/g, " ")}`)
},
}
}
}
}
};
const myChart = new Chart(
document.getElementById('myChart'),
config
)
filterChart= function filterChart(date){
const year = date.value.substring(0,4);
const month = date.value.substring(5);
const lastday = (y,m)=>{
return new Date(y,m,0).getDate();
}
const startDate = `${date.value}-01`;
const endDate = `${date.value}-${lastday(year,month)}`;
myChart.config.options.scales.x.min=startDate;
myChart.config.options.scales.x.ma`your text`x=endDate;
myChart.update();
}}
</script>

Feeding Array to a Classifier

I have an issue looping through an array using a bayesian classifier function.
Here is my array:
var data = ['good', {
dry: 1,
wet: 0,
moist:0
}, 'bad', {
dry: 0,
wet: 1,
moist: 1
}, 'neutral', {
dry: 1,
wet: 1,
moist:1
}, 'good', {
dry: 1,
wet: 0,
moist: 1
}];
Here's my classifier function:
class Bayes{
constructor(...categories) {
this.categories = {};
this.categoryCounts = {};
categories.forEach(category => {
this.categories[category] = {};
this.categoryCounts[category] = 0;
});
}
train(category, dataset) {
this.categoryCounts[category]++;
Object.keys(dataset).forEach(key => {
this.categories[category][key] = (this.categories[category][key] || '') + dataset[key];
});
};
classify(dataset) {
let scores = {};
let trainingCount = Object.values(this.categoryCounts).reduce((a, b) => a + b );
Object.keys(this.categories).forEach(category => {
scores[category] = 0;
let categoryWords = this.categories[category];
let total = Object.values(categoryWords).reduce((a, b) => a + b );
Object.keys(dataset).forEach(function (key) {
let value = dataset[key];
let s = categoryWords[key] || 0.1;
let i = 0;
while(i<value){
scores[category] += Math.log(s / parseFloat(total));
i++;
}
});
let s = this.categoryCounts[category] || 0.1;
scores[category] = (s / trainingCount);
});
return scores;
};
};
Normally, to classify the data; I'll do:
var b = new Bayes('good', 'bad', 'neutral');
b.train('good', { dry: 1, wet: 0, moist:0});
b.train('bad', {dry: 0,wet: 1,moist: 1});
b.train('neutral', {dry: 1,wet: 1,moist:1});
b.train('good', {dry: 1,wet: 0,moist: 1});
console.log(b.classify({ dry: 0, wet: 1, moist: 1}));
// good: 0.5, bad: 0.25, neutral: 0.25
But when I can't figure out how to train the data by iterating through data.
I need help to feed the array dynamically as a javascript object.
if you can guarantee the data structure consistency, such as
let data = [key, value, key, value, key, value......]
const data = ['good', { dry: 1, wet: 0, moist:0}, 'neutral', {dry: 1,wet: 1,moist:1}, 'good', {dry: 1,wet: 0,moist: 1}];
// 1: chunk it
const size = 2;
const chunks = [];
while (data.length) {
chunks.push(data.splice(0, size));
}
console.log(chunks);
// 2: loop through your train
let keys = chunks.map(val=>val[0])
let deDupeKeys = [...new Set(keys)]
console.log(keys)
console.log(deDupeKeys)
// var b = new Bayes(deDupeKeys)
chunks.forEach(chunk => {
console.log(chunk[0])
console.log(chunk[1])
// b.train(chunk[0],chunk[1]);
})
Assuming the data array will have the format: data = [category, dataset, category, dataset...], a simple solution would be to loop the data array as follows and train the classifier.
for (let i = 0; i < data.length; i = i + 2) {
console.log("category : ", data[i], "dataset : ", data[i + 1]);
b.train(data[i], data[i + 1]);
}

How to clear the vue warn when I use vue-slider-component?

The issue detail:
1. I implement the feature with the vue-slider-component module, but that has a lot of warnings when I move the dots on the slider.
2. I know that the reason is that I used v-for to point to an object that will change, but I do not know how to fix this issue.
the following link is my test site:
https://jsfiddle.net/ncwv84x9/
enter image description here
My codes:
code1 (Html)
<div id="app">
<div class="box" v-for="(item,index) in columnvalue">
<label>{{item.text}}</label>
<input v-model="value[index]" />
</div>
<hr />
<br />
<vue-slider v-model="value" :order="false" :tooltip="'always'" :process="false" :marks="marks" :width="600">
<template slot="tooltip" slot-scope="{index}">
<div>{{getText(index)}}</div>
</template>
</vue-slider>
</div>
JavaScript + Vue:
new Vue({
el: '#app',
components: {
VueSlider: window['vue-slider-component']
},
data: function() {
return {
// collect the all values
columnvalue: [],
// stored disease value
pet_name: [{
text: 'dog',
index: 0
},
{
text: 'cat',
index: 1
}
],
// stored drug value
feeder_name: [{
text: 'Sam',
index: 0
}],
// from age filter
age: [
65, 100
],
test: "",
value: [],
process: dotsPos => [
[dotsPos[0], dotsPos[1], {
backgroundColor: 'pink'
}],
[dotsPos[1], dotsPos[2], {
backgroundColor: 'blue'
}],
[dotsPos[2], dotsPos[3], {
backgroundColor: 'black'
}],
],
after: {},
relations: [],
marks: {
'0': {
label: 'start',
margin: '0 0 0 10px'
},
'100': {
label: 'end',
labelStyle: {
left: '100%',
margin: '0 0 0 10px',
top: '50%',
transform: 'translateY(-50%)'
}
}
}
}
},
created: function() {
//vue instance 被 constructor 建立後,在這裡完成 data binding
let tmpArray = this.pet_name.concat(this.feeder_name);
let tmpValueArray = [];
for (i = 0; i < tmpArray.length; i++) {
tmpArray[i].index = i;
tmpValueArray.push(0);
}
this.columnvalue = tmpArray;
this.value = tmpValueArray;
},
methods: {
getText(index) {
const ani = this.columnvalue.find((v) => v.index == index).text;
this.after = {
...this.after,
[ani]: this.value[index]
}
return ani;
},
getNodeRelation() {
const indexs = this.after;
let result = [];
let result2 = [];
let placement = [];
for (obj in indexs) {
placement.push([obj, indexs[obj]]);
}
placement.sort(function(a, b) {
/* console.log(a[1]) */
return a[1] - b[1];
})
for (i = 0; i < placement.length; i++) {
if (i + 1 >= placement.length) {
break;
}
let distance = placement[i + 1][1] - placement[i][1];
let predicate = "";
if (distance > 0) {
predicate = "after";
} else if (distance == 0 && placement[i + 1][1] == 0) {
predicate = "hasUse";
} else {
predicate = "same";
}
let source = {
label: placement[i][0],
index: i
};
let target = {
label: placement[i + 1][0],
index: i
};
// store the 4-tuple reprsentations about slider
result2.push({
source: source,
target: target,
type: predicate,
days: distance
});
}
/* this.relations = "{\"relation\":" + JSON.stringify(result2)+"}" */
;
this.relations = JSON.stringify(result2);
},
getAllFilters() {
let vm = this;
let beginHas = true;
if (vm.relations.length == 0) {
vm.getNodeRelation();
beginHas = false;
}
let result = {
age: vm.age,
disease_name: vm.disease_name,
drug_name: vm.drug_name,
relation: vm.relations
};
if (!beginHas) {
vm.relations = [];
}
this.test = JSON.stringify(result);
}
},
})
I get a infinite loop error which disappears when I remove this section in getText()
this.after = {
...this.after,
[ani]: this.value[index]
}
This is because there is some reactivity triggered and re-renders the dom, which calls that function, which renders the dom and so on...

loop returning the same value

I need to replace a template array with values from another array and push it to the final result.
This is what I have tried, the problem is that I get the same value when I loop.
var pickups = [
{ address: "Lusaka, Zambia", distance: 22 },
{ address: "Ndola, Zambia", distance: 44 }
];
var template = [{ lable: "distance", data: 0 }];
var final_templates = [];
var pickup_temp = template;
for (var i = 0; i < pickups.length; i++) {
for (var m = 0; m < template.length; m++) {
if (pickup_temp[m].lable == "distance") {
pickup_temp[m].data = pickups[i].distance;
}
}
final_templates.push(pickup_temp);
}
console.log(final_templates);
Expected Result:
[[{lable: "distance", data: 22}],[{lable: "distance", data: 44}]]
Actual Result (same distance value):
[[{lable: "distance", data: 44}],[{lable: "distance", data: 44}]]
It is simpler if the code avoids for loops and just uses Array.map:
var pickups = [
{ address: "Lusaka, Zambia", distance: 22 },
{ address: "Ndola, Zambia", distance: 44 }
];
var template = [{ lable: "distance", data: 0 }];
var final = pickups.map(pick => (
template.map( item => (
{ label: item.lable, data: pick[item.lable] }
))
));
console.log(JSON.stringify(final));

How to sum duplicates in an array

I am creating a javascriptchart, which I have done succesfully but I am lot having duplicates.
Below is a sample xmlwhere I am retrieving data from to display on my Bar chart.
How do I sum the duplicate values retrieved from the xml?
xml:
<counts>
<serial>3123111</serial>
<scans>3</scans>
<prints>1</prints>
<copies>0</copies>
</counts>
<counts>
<serial>3123111</serial>
<scans>0</scans>
<prints>2</prints>
<copies>0</copies>
</counts>
<counts>
<serial>AHTSD111</serial>
<scans>0</scans>
<prints>1</prints>
<copies>2</copies>
</counts>
<counts>
<serial>AHTSD111</serial>
<scans>0</scans>
<prints>1</prints>
<copies>2</copies>
</counts>
Expected result below which I use for the barchart:
<counts>
<serial>3123111</serial>
<scans>3</scans>
<prints>3</prints>
<copies>0</copies>
</counts>
<counts>
<serial>AHTSD111</serial>
<scans>0</scans>
<prints>2</prints>
<copies>4</copies>
</counts>
Data retrieved and pushed to the Chart data, I know i have to do a loop to sum the values of scan, prints, copies for each Serial Number but I still keep getting duplicate values, I just left the code out.
$.ajax({
url: "http://localhost5/api/",
dataType: 'xml',
method: "GET",
success: function (data) {
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(data, "text/html");
data = xmlDoc.getElementsByTagName("JobCounts");
var items = [];
var serial, prints, copies, scans;
function getAsText(parent, name) {
return parent.getElementsByTagName(name)[0].textContent
}
function getAsInt(parent, name) {
return parseInt(getAsText(parent, name));
}
for (i = 0; i < data.length; i++) {
items.push({
serial: getAsText(data[i], "serial"),
prints: getAsInt(data[i], "prints"),
copies: getAsInt(data[i], "copies"),
scans: getAsInt(data[i], "scans")
});
}
items = items.reduce((a, c) => {
var same = a.find(v => v.serial == c.serial);
console.log(same);
if (same) {
same.prints += c.prints;
same.copies += c.copies;
same.scans += c.scans;
} else {
a.push(c);
}
return a;
}, []);
// "https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"
// JS chart library I am using
var chartdata = {
labels: serial,
title: "Date",
datasets: [
{
label: 'Copies',
backgroundColor: 'rgba(0,255,0,0.6)',
data: copies
}
]
};
var ctx = $("#mycanvas");
var options = {
responsive: true,
title: {
display: true,
position: "top",
text: "DashBoard",
fontSize: 12,
fontColor: "#111"
},
legend: {
display: true,
position: "bottom",
labels: {
fontSize: 9
}
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
};
var barGraph = new Chart(ctx, {
'type': 'bar',
data: chartdata,
options : options,
"categoryField": "date",
"categoryAxis": {
"autoGridCount": false,
"gridCount": chartdata.length,
"gridPosition": "start",
"labelRotation": 90,
"startOnAxis": false,
"title":"Date"
}
});
},
error: function (data) {
console.log(data);
}
});
}
Instead of storing the info in 3 different arrays, you can stored it in a single array of objects which will make it easier to merge objects that have the same serial number.
Here is what I mean:
var items = [];
function getAsText(parent, name){
return parent.getElementsByTagName(name)[0].textContent
}
function getAsInt(parent, name){
return parseInt(getAsText(parent, name));
}
for (i = 0; i < data.length; i++) {
items.push({serial: getAsText(data[i], "serial"),
prints: getAsInt(data[i], "prints"),
copies: getAsInt(data[i], "copies"),
scans: getAsInt(data[i], "scans")});
}
// Merge items with the same `serial` value;
items = items.reduce((a, c) => {
var same = a.find(v => v.serial == c.serial);
if(same){
same.prints += c.prints;
same.copies += c.copies;
same.scans += c.scans;
}else{
a.push(c);
}
return a;
}, []);
You can iterate each counts element .children, .map() each .tagName and .textContent to an object, push the object to an array, iterate the array and increment each SCANS, PRINTS, and COPIES property if SERIAL matches.
Convert JSON to elements by iterating resulting array using .forEach() and Object.entries().
let data = `<counts>
<serial>3123111</serial>
<scans>3</scans>
<prints>1</prints>
<copies>0</copies>
</counts>
<counts>
<serial>3123111</serial>
<scans>0</scans>
<prints>2</prints>
<copies>0</copies>
</counts>
<counts>
<serial>AHTSD111</serial><scans>0</scans><prints>1</prints><copies>2</copies>
</counts>
<counts>
<serial>AHTSD111</serial><scans>0</scans><prints>1</prints><copies>2</copies>
</counts>`;
let parser = new DOMParser();
let xmlDoc = parser.parseFromString(data, "text/html");
let res = [];
for (let {counts:{SERIAL, SCANS, COPIES, PRINTS}} of
[...xmlDoc.querySelectorAll("counts")]
.map(el =>
({counts:[...el.children]
.reduce((o, {tagName, textContent}) =>
Object.assign(o, {[tagName]:textContent}), {})
}))) {
let curr = res.find(({counts:{SERIAL:s}}) => s === SERIAL);
if (!curr) {
res.push({counts:{SERIAL, SCANS, COPIES, PRINTS}})
} else {
curr = curr.counts;
curr.SCANS = +curr.SCANS + +SCANS;
curr.PRINTS = +curr.PRINTS + +PRINTS;
curr.COPIES = +curr.COPIES + +COPIES;
}
}
res.forEach(o => {
let key = Object.keys(o).pop();
let parentNode = document.createElement(key);
Object.entries(o[key])
.forEach(([tagName, textContent]) => {
let childNode = document.createElement(tagName)
childNode.textContent = textContent;
parentNode.appendChild(childNode);
parentNode.appendChild(document.createElement("br"));
document.body.appendChild(parentNode);
})
document.body.appendChild(document.createElement("br"));
})

Categories