how to read the output of a function as an object - html

Here is the output of my function sam() in HTML:
["2020-02-14", 324.7300, 325.9800, 322.8500, 324.9500, 20028447],
["2020-02-13", 324.1900, 326.2200, 323.3500, 324.8700, 23686892],
["2020-02-12", 321.4700, 327.2200, 321.4700, 327.2000, 28432573],
["2020-02-11", 323.6000, 323.9000, 318.7100, 319.6100, 23580780],
["2020-02-10", 314.1800, 321.5500, 313.8500, 321.5500, 27337215],
I am trying to get that very output of sam() to be read as an object in this line of code below.
"data": [
sam() ],
At the moment sam() in that location keeps outputting that above sequence of dates and price numbers. I need for sam() in that location to be read so that the above sequence would be integrated into the stock chart that I am working on. If I add all of that code as a non-string into the "data"[ ], it will print out the stock chart with the dates and prices, but when I simply use the function sam() in there, it doesn't print out the chart. It only does dates and numbers

Here is the entire code that uses the sam() function. When you execute it, it will output a sequence of dates and numbers. When you copy and paste that output into the line of code near the bottom labeled "data" : [ ], it will output a nice looking stock chart using the dates and numbers. I need a function that can do the same.
<html>
<head>
<script data-require="jquery#2.1.4" data-semver="2.1.4" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script data-require="highstock#0.0.1" data-semver="0.0.1" src="http://code.highcharts.com/stock/highstock.js"></script>
<script data-require="highstock#0.0.1" data-semver="0.0.1" src="http://code.highcharts.com/stock/modules/exporting.js"></script>
<title>
How to get the array of dates between
two dates in JavaScript ?
</title>
</head>
<body style = "text-align:center;">
<div id="myData"></div>
<div id="demo"></div>
<div id="demo1"></div>
<script>var tday=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
var tmonth=["-01-","-02-","-03-","-04-","-05-","-06-","-07-","-08-","-09-","-10-","-11-","-12-"];
function GetClock(){
var d=new Date();
var nday=d.getDay(),nmonth=d.getMonth(),ndate=d.getDate(),nyear=d.getFullYear();
var nhour=d.getHours(),nmin=d.getMinutes(),nsec=d.getSeconds(),ap;
if(nhour==0){ap=" AM";nhour=12;}
else if(nhour<12){ap=" AM";}
else if(nhour==12){ap=" PM";}
else if(nhour>12){ap=" PM";nhour-=12;}
if(nmin<=9) nmin="0"+nmin;
if(nsec<=9) nsec="0"+nsec;
var clocktext=""+nyear +tmonth[nmonth] +ndate +"";
document.getElementById('clockbox').innerHTML= clocktext;
}
GetClock();
setInterval(GetClock,1000);</script>
<script>
function heavy(){
var today = new Date("2014-10-01"); //YYYY-MM-DD
var startDate = new Date("2014-10-01");
var endDate = new Date("2016-10-10" );
//YYYY-MM-DD
var getDateArray = function(start, end) {
var arr = new Array();
while (startDate < end) {
arr.push(new Date(startDate));
startDate.setDate(startDate.getDate() + 1);
}
return arr.reverse().toLocaleString().replace(new RegExp('/', 'g'), '-').replace(new RegExp("8:", 'g'), '').replace(new RegExp("00", 'g'), '').replace(new RegExp("PM", 'g'), '').replace(new RegExp("AM", 'g'), '').replace(new RegExp(",", 'g'), '').replace(new RegExp(":", 'g'), '');
}
var dateArr = getDateArray(startDate, endDate);
// Output
for (var i = 0; i < dateArr.length; i++) {
document.write( dateArr[i] );
}
}
</script>
<script>
function heavy1(){
var cars = [["2020-02-13"], ["2020-02-12"]];
var text = "";
var i;
for (i = 0; i < cars.length; i++) {
text += cars[i] + "<br>";
}
document.getElementById("demo").innerHTML = text;}
</script>
<script>
function sam(){
fetch('https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&outputsize=full&apikey=demo')
.then(function (response) {
return response.json();
})
.then(function (data) {
appendData(data);
})
.catch(function (err) {
console.log('error: ' + err);
});
function appendData(data) {
var mainContainer = document.getElementById("myData");
var arrw = ["2020-02-14",
"2020-02-13",
"2020-02-12",
"2020-02-11",
"2020-02-10",
"2020-02-07",
"2020-02-06",
"2020-02-05",
"2020-02-04",
"2020-02-03",
"2020-01-31",
"2020-01-30",
"2020-01-29",
"2020-01-28",
"2020-01-27",
"2020-01-24",
"2020-01-23",
"2020-01-22",
"2020-01-21",];
for (var i = 0; i < arrw.length; i++) {
var joe = '[' +"\""+ arrw[i]+ "\"" + "," + " " + data['Time Series (Daily)'][arrw[i]]['1. open']+"," + " " +data['Time Series (Daily)'][arrw[i]]['2. high']+"," + " " +data['Time Series (Daily)'][arrw[i]]['3. low']+","+ " " +data['Time Series (Daily)'][arrw[i]]['4. close']+","+ " " +data['Time Series (Daily)'][arrw[i]]['5. volume' ] + ']' + "," ;
document.write(joe);
}}}
</script>
<div id="container"></div>
<script>
var json = {
"dataset": {
"data": [
sam()
],
}
};
var hiJson = json.dataset.data.map(function(d) {
return [new Date(d[0]).getTime(), d[4]]
});
// Create the chart
$('#container').highcharts('StockChart', {
rangeSelector: {
selected: 1
},
title: {
text: 'MS Stock Price'
},
series: [{
name: 'MS',
data: hiJson,
tooltip: {
valueDecimals: 2
}
}]
});
</script>
</body>
</html>

Related

Ng-repeat not searching Object

Having an issue using ng-repeat for my angular object.There is no duplicate data in my object.
Table Html
<table style="border: black solid 2px;width:400px;height:auto;background-color: wheat;">
<tr>
<th>Date</th>
<th>Panels Completed</th>
</tr>
<tr ng-repeat="value in vm.displayData" >
<td style="text-align:center;border: black solid 2px;">{{value}}</td>
<td style="text-align:center;border: black solid 2px;" ng-repeat="x in value">{{x}}</td>
</tr>
</table>
Data Example:
KxRkjsAPf0ThgxBOjiE:
additionalInfo: {components: 8, framingStyle: "SIP 162", nailing:
"150x150", qty: 1, sheathing: "MGO", …}
area: "-KsDT3O8DJIGMXmmyXV_"
dimensions: {area: 0.2, height: 200, length: 1234, weight: 14,
width: 162}
id: "ID"
project: "-KqdccSuHiz__2UZ0AGX"
qa: {completed: 1511442566322, completedOperatives: {…},
diagonalHeight: 1250, diagonalLength: 1250, midHeight: 200, …}
timestamps: {created: 1509089806654, modified: 1511442566322}
type: "Ext"
Javascript(anglarJs)
vm.weekStart = weekStart;
vm.weekEnd= weekEnd;
vm.getPanelByDay = getPanelByDay;
getPanelByDay()
.then(function (data){
console.log(data);
vm.dataData = data;
console.log(vm.dataData);
});
function weekEnd(){
vm.lastDay = plusDays(vm.weekStart("2017-11-21"),5);
return vm.lastDay;
function plusDays(value, days) {
var date = new Date(value);
date.setDate(date.getDate() + days);
date.setHours(23, 59, 59,0);
return date;
function toIsoDate(value) {
var date = asDate(value);
return date.getFullYear()+"-" + ("0" + (date.getMonth()+1)).slice(-2) + "-"+ ("0" + date.getDate()).slice(-2);
function asDate(value) {
return angular.isDate(value) ? value : new Date(value);
}
}
}
}
function weekStart(value) {
if (angular.isDefined(value)) {
var date = new Date(value);
} else {
var date = new Date();
}
date.setDate(date.getDate() - dayOfWeek(date));
date.setHours(0,0,0,0);
return date;
function dayOfWeek(value) {
var date = asDate(value);
return (date.getDay() + 6) % 7;
function asDate(value) {
return angular.isDate(value) ? value : new Date(value);
}
}
function asDate(value) {
return angular.isDate(value) ? value : new Date(value);
}
function toIsoDate(value) {
var date = asDate(value);
return date.getFullYear()+"-" + ("0" + (date.getMonth()+1)).slice(-2) + "-"+ ("0" + date.getDate()).slice(-2);
function asDate(value) {
return angular.isDate(value) ? value : new Date(value);
}
}
}
function getPanelByDay(){
var todayDate = new Date("2017-11-21");
var startDay = new Date(vm.weekStart(todayDate)).getTime();
var endDay = new Date(vm.weekEnd(todayDate)).getTime();
var weeklyPanels = {};
return realDatabaseRef.child("panels").orderByChild("qa/completed").startAt(startDay).endAt(endDay).once("value").then(function(snapshot){
for(snap in snapshot){
var data = snapshot.val();
angular.forEach(data,function(info,key){
var PanelCompletedDate = toIsoDate(info.qa.completed);
if(angular.isUndefined(weeklyPanels[PanelCompletedDate])){
weeklyPanels[PanelCompletedDate] = {};
}
if(angular.isUndefined(weeklyPanels[PanelCompletedDate][key])){
weeklyPanels[PanelCompletedDate][key] = {};
}
weeklyPanels[PanelCompletedDate][key] = info;
});
}
return weeklyPanels;
})
.then(function (pa){
return pa;
});
function toIsoDate(value) {
var date = asDate(value);
return date.getFullYear() + "-" + ("0" + (date.getMonth() + 1)).slice(-2) + "-" + ("0" + date.getDate()).slice(-2);
function asDate(value) {
return angular.isDate(value) ? value : new Date(value);
}
}
}
the JS is a little bit messy, i have taken most of the functions off our current working system and then dropped them into this separate web page.I am able to see that the object that i want to to fill with data and use in the view is full of data, it is just not getting used or being deleted somewhere, but i am still stuck
Any help will be appreciated.
Maybe You should use ng-repeat-start and ng-repeat-end for nested repeat.

Piechart not being rendered when values supplied through d3.json

I am trying to read the values as specified in a JSON and based on those values creating a Piechart in d3.json. But on supplying values manually, the piechart is fully functional! The JSON file is present in the same directory as the .html file. Moreover, the var dataset is being populated with the desired values, which is verified by logging the dataset in the console. And I am not getting any error in the Chrome Browser.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Sentiments Score</title>
<script type="text/javascript" src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<div id="chart"></div>
<script type="text/javascript">
var dataset = [
{ "label": 'Neutral'},
{ "label": 'Positive'},
{ "label": 'Negative' }
];
d3.json("senti_analysis.json", function(data){
for (var i =0; i<dataset.length;i++)
{
if (dataset[i].label == 'Neutral')
{
dataset[i].count = +data.key.senti.neu;
}
else if (dataset[i].label == 'Positive') {
dataset[i].count = +data.key.senti.pos;
}
else
{
dataset[i].count = +data.key.senti.neg;
}
}
});
/*
var dataset = [{ label: 'Neutral', count: 0.45 },
{ label: 'Positive', count: 0.45 },
{ label: 'Negative', count: 0.10 }
];*/
console.log(dataset);
var w = 360;
var h = 360;
var r = Math.min(w, h) / 2;
var color = d3.scaleOrdinal(d3.schemeCategory20b);
var svg = d3.select('#chart')
.append('svg')
.attr('width', w)
.attr('height', h)
.append('g')
.attr('transform', 'translate(' + (w / 2) + ',' + (h / 2) + ')');
var arc = d3.arc()
.innerRadius(0)
.outerRadius(r);
var pie = d3.pie()
.value(function(d) { return d.count; })
.sort(null);
var path = svg.selectAll('path')
.data(pie(dataset))
.enter()
.append('path')
.attr('d', arc)
.attr('fill', function(d, i) {
return color(d.data.label);
});
</script>
</body>
The json file I am trying to read is as below:
{
"key": {
"senti": {
"neg": 0.10,
"neu": 0.45,
"pos": 0.45,
"compound": 0.784
},
"post": "I am excited to do Sentiment Analysis. I live in Tempe
and I love learning!"
}
}

How to integrate a dynamic graph in a webpage?

I am getting dynamically generated data from my Raspberry PI in .csv format and I want to make a webpage for my institute to analyze the waveform of the output . The main feature of this graph is that the graph should auto-update according to the modified data. How should I go about making this?
I am assuming that the solution you are looking for must work in HTML 5 and JavaScript where there is NO server side processing. The raspberry pi posts a file to the server.
We are using morris charts which is JavaScript library
http://morrisjs.github.io/morris.js/
Morris uses a json format
1: read the csv file
2: convert the csv data to a json object
3: initialise the chart
try this example csv data
"elapsed","value",b
"Oct-12",24,2
"Oct-13",34,22
"Oct-14",33,7
"Oct-15",22,6
"Oct-16",28,17
"Oct-17",60,15
"Oct-18",60,17
"Oct-19",70,7
"Oct-20",67,18
"Oct-21",86,18
"Oct-22",86,18
$(document).ready(function() {
$.ajax({
url: "linechartdata.csv",
success: function(data) {
processData(data)
}
});
});
function processData(data) {
var record_num = 3; // or however many elements there are in each row
var dataLines = data.split(/\r\n|\n/);
var entries = dataLines[0].split(',');
var records = [];
var headers = entries.splice(0, record_num);
console.log(dataLines.length)
for (var i = 1; i < dataLines.length; i++) {
var obj = dataLines[i].split(',');
if (obj.length == headers.length) {
var tarr = [];
for (var j = 0; j < headers.length; j++) {
//doing it this way to get strings and numbers
var field01;
var field02;
var field03;
if (j == 0) {
field01 = obj[j]
}
if (j == 1) {
field02 = obj[j]
}
if (j == 2) {
field03 = obj[j]
}
var o = {
elapsed: field01,
value: field02,
b: field03
}
records.push(o);
}
}
}
initChart(records)
}
function initChart(records) {
var chart = Morris.Line({
element: 'morris-chart-network',
data: records,
axes: false,
xkey: 'elapsed',
ykeys: ['value', 'b'],
labels: ['Download Speed', 'Upload Speed'],
yLabelFormat: function(y) {
return y.toString() + ' Mb/s';
},
gridEnabled: false,
gridLineColor: 'transparent',
lineColors: ['#5b6b79', '#a5a5a5'],
lineWidth: [2, 1],
pointSize: [0, 2],
fillOpacity: .7,
gridTextColor: '#999',
parseTime: false,
resize: true,
behaveLikeLine: true,
hideHover: 'auto'
});
};
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Morris Chart</title>
</head>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script>
<body>
<div>Morris Chart</div>
<div id="morris-chart-network" style="width:800px;height:600px">
</div>
<div>
example
</div>

Google Org Chart - Draw a chart from JSON (mysql)

I'm trying to draw an organizational chart (http://goo.gl/wgftfO) from JSON (php - mysql) but it doen'st display well.
Here is my HTML code:
<script type="text/javascript">
google.load('visualization', '1', {packages:['orgchart']});
google.setOnLoadCallback(drawChart);
function json(){
$.ajax({
type: "POST",
url: "function/ver.php",
success: function(datos){
datos = eval(datos);
for (var i=0;i<datos.length;i++){
var id = datos[i].id;
var nombre = datos[i].nombre;
var jefe = datos[i].jefe;
alert(id);
drawChart(id, nombre);
function drawChart(id, nombre) {
//alert("Id: " + id + " | Nombre: " + nombre);
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('string', 'Manager');
data.addColumn('string', 'ToolTip');
data.addRows([
[nombre, jefe, id]
]);
var chart = new google.visualization.OrgChart(document.getElementById('contenido'));
chart.draw(data, {allowHtml:true});
}
}
},
error: function(error){
alert(error);
}
});
}
</script>
</head>
<body onLoad="json()">
<div id="contenido"></div>
</body>
JSON result:
[
{
"id":"1",
"nombre":"Andrey",
"paterno":null,
"foto":"http:\/\/icons.iconarchive.com\/icons\/deleket\/face-avatars\/256\/Male-Face-G1-icon.png",
"jefe":""
},
{
"id":"2",
"nombre":"Enrique",
"paterno":null,
"foto":"http:\/\/icons.iconarchive.com\/icons\/deleket\/face-avatars\/256\/Male-Face-F3-icon.png",
"jefe":"Andrey"
},
{
"id":"3",
"nombre":"Chero",
"paterno":null,
"foto":"http:\/\/icons.iconarchive.com\/icons\/deleket\/face-avatars\/256\/Male-Face-E4-icon.png",
"jefe":"Andrey"
},
{
"id":"4",
"nombre":"Ricardo",
"paterno":null,
"foto":"http:\/\/icons.iconarchive.com\/icons\/deleket\/face-avatars\/256\/Male-Face-F3-icon.png",
"jefe":"Chero"
},
{
"id":"5",
"nombre":"Jhon",
"paterno":null,
"foto":"http:\/\/icons.iconarchive.com\/icons\/deleket\/face-avatars\/256\/Male-Face-H1-icon.png",
"jefe":"Enrique"
}
]
This displays like:
And, if i remove the alert(id) form the HTML code (in ajax), just shows the last object of the JSON:
How can i fix this?
or, is there any other option to do this chart?
Thank your for answers
The bellow code worked for me
index.html
<script type='text/javascript' src='https://www.google.com/jsapi'></script>
<script type='text/javascript' src='js/jquery.min.js'></script>
<script type='text/javascript'>
google.load('visualization', '1', { packages: ['orgchart'] });
google.setOnLoadCallback(drawChart);
function drawChart() {
$.ajax({
type: "POST",
url: "ajax/organization.php",
success: function(result){
var result = JSON.parse(result);
if ((emp_count = result.length) > 0) {
console.log(result);
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('string', 'Manager');
data.addRows(emp_count);
for (i = 0; i < emp_count; i++) {
data.setCell(i, 0, result[i].emp);
data.setCell(i, 1, result[i].manager);
}
var chart = new google.visualization.OrgChart(document.getElementById('chart_div'));
chart.draw(data, { allowHtml: true });
}
}
});
}
</script>
organization.php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'USERNAME');
define('DB_PASSWORD', 'PASSWORD');
define('DB_DATABASE', 'DATABASE_NAME');
$connection = mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD) or die(mysql_error());
$database = mysql_select_db(DB_DATABASE) or die(mysql_error());
$query=mysql_query("select emp, manager from employees") or die(mysql_error());
# Collect the results
while($obj = mysql_fetch_object($query)) {
$arr[] = $obj;
}
# JSON-encode the response
$json_response = json_encode($arr);
// # Return the response
echo $json_response;

Prototype Remove HTML?

I have the following HTML
<div id="top-right">
<span id="top-right-name">sometexthere</span> | link
</div>
And the following prototype JS
Event.observe(window, 'load', function() {
try {
if ($$('#top-right')!=null) {
var topmenu = document.getElementById('top-right');
var value = topmenu.innerHTML;
// define an array of replacements
var replacements = [
{ from: '|', to: ' ' },
{ from: '|', to: ' ' },
{ from: '|', to: ' ' },
{ from: '|', to: ' ' }
];
for (var i = 0, replacement; i < replacements.length, replacement = replacements[i]; i++) {
// replace
value = value.replace(replacement.from, replacement.to);
}
// replace the old text with the new
topmenu.innerHTML = value;
}
}
catch(ex) {
}
});
I am trying to remove the " | " after the </span> automatically onload of the this JS - but I just cant seem to do it .
Can someone assist ?
Thanks
It seems to be a syntax error somewhere, perhaps in your loading of Prototype. The below snippet worked fine for me :)
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.2/prototype.js"></script>
<div id="top-right">
<span id="top-right-name">sometexthere</span> | link
</div>
<script type="text/javascript">
Event.observe(window, 'load', function() {
try {
if ($$('#top-right')!=null) {
var topmenu = document.getElementById('top-right');
var value = topmenu.innerHTML;
// define an array of replacements
var replacements = [
{ from: '|', to: ' ' }
];
for (var i = 0, replacement; i < replacements.length, replacement = replacements[i]; i++) {
// replace
value = value.replace(replacement.from, replacement.to);
}
// replace the old text with the new
topmenu.innerHTML = value;
}
}
catch(ex) {
}
});
</script>
Edited to reflect problem