I have an api in that returns a result like:
[[{"AG":2707}],[{"AR":398}],[{"AI":28}],[{"BL":1085}],[{"BS":1318}],[{"BE":2964}],[{"GL":206}],[{"GR":845}],[{"JR":256}],[{"LU":1855}],[{"NW":297}],[{"OW":307}],[{"SH":307}],[{"SZ":1118}],[{"SO":945}],[{"SG":2029}],[{"TI":2146}],[{"TG":1038}],[{"UR":107}],[{"VS":1237}],[{"ZG":3714}],[{"ZH":8496}]]
So I want those data to display for example:
AG : {DATA.AG} => (there to be number 2707)
AR : {DATA.AR} => (there to be number 398)
I am new to react and I couldn't find a solution. What can I try next?
Actually, your data is inside an array so you cannot access it this way in an array, you should have to change your data from array type to object something like this,
const data = {
AG: 2707,
AR: 398,
AI: 28,
BL: 1085,
BS: 1318,
BE: 2964,
GL: 206,
GR: 845,
JR: 256,
LU: 1855,
NW: 297,
OW: 307,
SH: 307,
SZ: 1118,
SO: 945,
SG: 2029,
TI: 2146,
TG: 1038,
UR: 107,
VS: 1237,
ZG: 3714,
ZH: 8496,
};
console.log(data.AG)
But If you are strict to use the above data array you can do it something like,
const findVal = (key) => {
let obj = arr.find((el) => el[0][key]);
if(obj) return arr.find((el) => el[0][key])[0][key]
return -1;
}
console.log(findVal('AG'))
Related
I have trained a keras model with 6 classes for CNN Image Recognition. Then, I converted it to tensorflowjs using this command:
tensorflowjs_converter --quantization_bytes 1 --input_format=keras {saved_model_path} {target_path}
which then gives me 2 files (model.json, group1-shard1of1.bin). After adding it to my react native project and test the prediction function, it always returns the same result. I am converting my image to tensor base on this github thread:
const processImagePrediction = async (base64Image: any) => {
const fileUri = base64Image.uri;
const imgB64 = await FileSystem.readAsStringAsync(fileUri, {
encoding: FileSystem.EncodingType.Base64,
});
const imgBuffer = tf.util.encodeString(imgB64, 'base64').buffer;
const raw = new Uint8Array(imgBuffer);
let imageTensor = decodeJpeg(raw);
const scalar = tf.scalar(255);
imageTensor = tf.image.resizeNearestNeighbor(imageTensor, [224, 224]);
const tensorScaled = imageTensor.div(scalar);
//Reshaping my tensor base on my model size (224, 224)
const img = tf.reshape(tensorScaled, [1, 224, 224, 3]);
console.log("IMG: ", img);
const results = model.predict(img);
let pred = results.dataSync();
console.log("PREDICTION: ", pred);
}
I was expecting to have a different result but no matter what image I capture it always returns this result:
LOG IMG: {"dataId": {"id": 23}, "dtype": "float32", "id": 38, "isDisposedInternal": false, "kept": false, "rankType": "4", "scopeId": 6, "shape": [1, 224, 224, 3], "size": 150528, "strides": [150528, 672, 3]} LOG PREDICTION: [-7.7249579429626465, 4.73449182510376, 2.609705924987793, 20.0458927154541, -7.944214344024658, -18.101320266723633]
The numbers somehow change slightly but it retains the highest prediction (which is class number 4).
P.S. I'm new to image recognition so any tips would be appreciated.
I want to display the findMax() output in a div but im facing this problem :
'findMax' is not defined no-undef
, 'dataset' is not defined no-undef
Someone suggested that I need to use useState but I'm not sure how to make it work , I would appreciate any help !
const pricedata = {
datasets: [
{
backgroundColor: "#0000",
barPercentage: 2,
barThickness: 5,
data: [1, 10, 30, 7, 42, 12],
label: "Update in prices",
maxBarThickness: 10
},
{
backgroundColor: "#0000",
barPercentage: 2,
barThickness: 5,
data: [11, 70, 18, 17, 24, 12],
label: "Update in prices",
maxBarThickness: 10
}
]
};
function findMax(PRICES) {
if (!PRICES) {
return 0;
}
return Math.max(...PRICES);
}
pricedata.datasets.forEach((dataset) => {
dataset.maxPrice = findMax(dataset.data);
});
pricedata.datasets.forEach((dataset) => {
console.log('max price is', dataset.maxPrice);
});
return (
<div>{findMax(dataset.data)}</div>
There is no 'dataset' variable at the root level of the code. The pricedata variable contains an array called datasets. In your code when you call map, it loops over all the datasets - calling each individual one dataset. That variable name is only "scoped" to be within the map() function.
You can build the DIVs inside a map like this:
// call your findMax() on each element
const divs = pricedata.datasets.forEach((dataset,i) => (<div key={i}>{findMax(dataset.data)}</div>))
// using React, you'll need to surround the divs in a parent div
return <>{divs}</>
I want to create Excel file that consist of 2 arrays of data with ExcelJS.
I can create the Excel file:
var Excel = require('exceljs');
var workbook = new Excel.Workbook();
var sheet = workbook.addWorksheet('My Sheet', {properties:{tabColor:{argb:'FFC0000'}}});
I can add column headers:
sheet.columns = [{key:"date", header:"Date"}, {key: "quantity", header: "Quantity"}]
I got 2 arrays for these columns:
array_date = [2018-01-04, 2018-01-06, 2018-01-08, 2018-01-09]
array_quantity = [25, 32, 54, 48]
I want to combine these 2 arrays to one array like this:
var merged = [{date:"2018-01-04", quantity:25}
, {date:"2018-01-06", quantity:32}
, {date:"2018-01-08", quantity:42}
, {date:"2018-01-09", quantity:48}];
If I can combine, I able to add as row for every data:
for(i in merged){
sheet.addRow(merged[i]);
}
Then I can create the Excel File:
workbook.xlsx.writeFile("some.xlsx").then(function() {
console.log("xls file is written.");
});
How can I combine two arrays to one If they are ordered? Also, I'm wondering is this the best approach to create excel file in NodeJS?
You can create the new array with
var array_date = ["2018-01-04", "2018-01-06", "2018-01-08", "2018-01-09"];
var array_quantity = [25, 32, 54, 48];
var merged = array_date.map((date, i) => ({
date,
quantity: array_quantity[i],
}));
array_date = [2018-01-04, 2018-01-06, 2018-01-08, 2018-01-09]
array_quantity = [25, 32, 54, 48]
var merged=[];
for(var i=0;i<array_date.length;i++){
merged.push({date:array_date[i], quantity:array_quantity[i]});
}
console.log(merged);
I have an MS SQL database that contains a table with latitude/longitude positions of some devices. These positions are stored in a GEOGRAPHY field. Now I want to get these positions from my node app with Sequelize.
Here's my sequelize model definition:
db.define('StationLocation', {
StationId: { type: Sequelize.INTEGER },
Position: { type: Sequelize.GEOMETRY('POINT') }
}
)
And here's what I currently get:
{
"id":4,
"StationId":1,
"Position":{
"type":"Buffer",
"data":[
230,
16,
0,
0,
1,
12,
25,
159,
112,
57,
112,
200,
73,
64,
0,
0,
0,
128,
184,
247,
26,
64
]
}
}
How can I convert this to latitude and longitude values? Is Sequelize able to do this?
Update: In the example above, the position is this:
Latitude: 51.565924816122966
Longitude: 6.741914749145508
Here's my query:
StationLocation
.findAll({ raw: true })
.then(function(allStationLocations) {
console.dir(allStationLocations[0].coordinates); // Just for debugging
res.send(JSON.stringify(allStationLocations));
});
This translates to this SQL statement:
SELECT [id], [StationId], [Position] FROM [StationLocations] AS [StationLocation];
Proper support for MSSQL geometry and geography data types is still pending. Tedious does however provide a parser for that buffer you get as a result: Tediousjs Geoparser
As a workaround for anyone having the same problem i've created an adapter utility, it's fairly simple to use but only supports points: Sequelize MSSQL Adapter
Require and use accordingly in your model definition, more info on the snippet's description.
const adapter = require('../utils/sequelize-geodata-adapter');
module.exports = (sequelize, DataType) =>
sequelize.define('MyModel', {
// Attributes
location: {
type: DataType.GEOGRAPHY('POINT', 4326),
get: function () {
const location = this.getDataValue('location');
if (location)
return adapter.get(location);
},
set: function (value) {
if (value === undefined || value === null)
return this.setDataValue('location', value);
this.setDataValue('location', adapter.set(value));
},
validate: {
hasCoordinates: adapter.validate
}
},
...
}, {
tableName: 'MyModels'
...
});
Setter supports GeoJSON and Google-style {lat, lng} location formats, getter always returns {lat, lng} objects.
In your particular case you'll need to replace geography::Point with geometry::Point at the adapter since you are using the GEOMETRY data type. Parser is indistinct for both.
Given the following JSON response from a previous test step (request) in soapUI:
{
"AccountClosed": false,
"AccountId": 86270,
"AccountNumber": "2915",
"AccountOwner": 200000000001,
"AccountSequenceNumber": 4,
"AccountTotal": 6,
"ActiveMoneyBeltSession": true,
"CLMAccountId": "",
"CustomerName": "FRANK",
"Lines": [{
"AndWithPreviousLine": false,
"IngredientId": 10000025133,
"OrderDestinationId": 1,
"PortionTypeId": 1,
"Quantity": 1,
"QuantityAsFraction": "1",
"SentToKitchen": true,
"TariffPrice": 6,
"Id": 11258999068470003,
"OriginalRingUpTime": "2014-10-29T07:37:38",
"RingUpEmployeeName": "Andy Bean",
"Seats": []
}, {
"Amount": 6,
"Cashback": 0,
"Change": 0,
"Forfeit": 0,
"InclusiveTax": 1,
"PaymentMethodId": 1,
"ReceiptNumber": "40/1795",
"Tip": 0,
"Id": 11258999068470009,
"Seats": []
}],
"MoaOrderIdentifier": "A2915I86270",
"OutstandingBalance": 0,
"SaveAccount": false,
"ThemeDataRevision": "40",
"TrainingMode": false
}
I have the following groovy script to parse the information from the response:
import groovy.json.JsonSlurper
//Define Variables for each element on JSON Response
String AccountID, AccountClosed, AccountOwner, AccountSeqNumber, AccountTotal, ActMoneyBelt
String CLMAccountID, ThemeDataRevision, Lines, MoaOrderIdentifier, OutstandingBalance, SaveAccount, TrainingMode, CustName, AccountNumber
String AndWithPreviousLine, IngredientId, OrderDestinationId, PortionTypeId, Quantity, SentToKitchen, TariffPrice, Id, OriginalRingUpTime, RingUpEmployeeName, Seats
int AccSeqNumInt
def responseContent = testRunner.testCase.getTestStepByName("ReopenAcc").getPropertyValue("response")
// Create JsonSlurper Object to parse the response
def Response = new JsonSlurper().parseText(responseContent)
//Parse each element from the JSON Response and store in a variable
AccountClosed = Response.AccountClosed
AccountID = Response.AccountId
AccountNumber = Response.AccountNumber
AccountOwner = Response.AccountOwner
AccountSeqNumber = Response.AccountSequenceNumber
AccountTotal = Response.AccountTotal
ActMoneyBelt = Response.ActiveMoneyBeltSession
CLMAccountID = Response.CLMAccountId
CustName = Response.CustomerName
Lines = Response.Lines
/*Lines Variables*/
AndWithPreviousLine = Response.Lines.AndWithPreviousLine
IngredientId = Response.Lines.IngredientId
OrderDestinationId = Response.Lines.OrderDestinationId
PortionTypeId = Response.Lines.PortionTypeId
Quantity = Response.Lines.Quantity
SentToKitchen = Response.Lines.SentToKitchen
TariffPrice = Response.Lines.TariffPrice
Id = Response.Lines.Id
OriginalRingUpTime = Response.Lines.OriginalRingUpTime
RingUpEmployeeName = Response.Lines.RingUpEmployeeName
Seats = Response.Lines.Seats
/*End Lines Variables*/
MoaOrderIdentifier = Response.MoaOrderIdentifier
OutstandingBalance = Response.OutstandingBalance
SaveAccount = Response.SaveAccount
ThemeDataRevision = Response.ThemeDataRevision
TrainingMode = Response.TrainingMode
As you can see above there is an element (Array) called "Lines". I am looking to get the individual element value within this array. My code above when parsing the elements is returning the following:
----------------Lines Variables----------------
INFO: AndWithPreviousLine: [false, null]
INFO: IngredientId: [10000025133, null]
INFO: OrderDestinationId: [1, null]
INFO: PortionTypeId: [1, null]
INFO: Quantity: [1.0, null]
INFO: SentToKitchen: [true, null]
INFO: TariffPrice: [6.0, null]
INFO: Id: [11258999068470003, 11258999068470009]
INFO: OriginalRingUpTime: [2014-10-29T07:37:38, null]
INFO: RingUpEmployeeName: [Andy Bean, null]
INFO: Seats: [[], []]
How can i get the required element from the above, also note the the 2 different data contracts contain the same element "ID". Is there a way to differenciate between the 2.
any help appreciated, thanks.
The "Lines" in the Response can be treated as a simple list of maps.
Response["Lines"].each { println it }
[AndWithPreviousLine:false, Id:11258999068470003, IngredientId:10000025133, OrderDestinationId:1, OriginalRingUpTime:2014-10-29T07:37:38, PortionTypeId:1, Quantity:1, QuantityAsFraction:1, RingUpEmployeeName:Andy Bean, Seats:[], SentToKitchen:true, TariffPrice:6]
[Amount:6, Cashback:0, Change:0, Forfeit:0, Id:11258999068470009, InclusiveTax:1, PaymentMethodId:1, ReceiptNumber:40/1795, Seats:[], Tip:0]
The Response is just one huge map, with the Lines element a list of maps.
Using groovysh really helps here to interactively play with the data, i did the following commands after starting a "groovysh" console:
import groovy.json.JsonSlurper
t = new File("data.json").text
r = new JsonSlurper().parse(t)
r
r["Lines"]
r["Lines"][0]
etc
Edit: In response to your comment, here's a better way to get the entry with a valid AndWithPreviousLine value.
myline = r["Lines"].find{it.AndWithPreviousLine != null}
myline.AndWithPreviousLine
>>> false
myline.IngredientId
>>> 10000025133
If you use findAll instead of find you'll get an array of maps and have to index them, but for this case there's only 1 and find gives you the first whose condition is true.
By using Response["Lines"].AndWithPreviousLine [0] you're assuming AndWithPreviousLine exists on each entry, which is why you're getting nulls in your lists. If the json responses had been reversed, you'd have to use a different index of [1], so using find and findAll will work better for you than assuming the index value.