how to get value from response from Microsoft cogntive services - arrays

I am making a http request to "Microsoft cogntive services" ; and I am getting a proper answer, but I am failing to get the value out of the response.
Here is my script:
'use strict';
const request = require('request');
// Replace <Subscription Key> with your valid subscription key. const subscriptionKey = 'xyz'; // here my API key
// You must use the same location in your REST call as you used to get your // subscription keys. For example, if you got your subscription keys from // westus, replace "westcentralus" in the URL below with "westus". const uriBase = 'https://westeurope.api.cognitive.microsoft.com/face/v1.0/detect';
const imageUrl =
'https://images.unsplash.com/photo-1534559529872-1a83a6cbc03d?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=56820e7b0db7b8a7f10804cd157f61ef&w=1000&q=80'
// Request parameters. const params = {
'returnFaceId': 'true',
'returnFaceLandmarks': 'false',
'returnFaceAttributes': 'age,gender,headPose,smile,facialHair,glasses,' +
'emotion,hair,makeup,occlusion,accessories,blur,exposure,noise' };
const options = {
uri: uriBase,
qs: params, // json: true, // dies nachtäglich eingefügt ev. löschen
body: '{"url": ' + '"' + imageUrl + '"}',
headers: {
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key' : subscriptionKey
} };
request.post(options, (error, response, body) => { if (error) {
console.log('Error: ', error);
return; } let jsonResponse = JSON.stringify(JSON.parse(body), null, ' '); console.log('JSON Response\n'); console.log(jsonResponse); });
and here the response that I get:
[ {
"faceId":"f469c0b3-fbb8-4238-a52a-54fd515a2bca",
"faceRectangle":{
"top":327,
"left":253,
"width":426,
"height":426
},
"faceAttributes":{
"smile":0.005,
"headPose":{
"pitch":0,
"roll":0.7,
"yaw":-4.4
},
"gender":"female",
"age":23,
"facialHair":{
"moustache":0,
"beard":0,
"sideburns":0
},
"glasses":"NoGlasses",
"emotion":{
"anger":0,
"contempt":0,
"disgust":0,
"fear":0,
"happiness":0.005,
"neutral":0.994,
"sadness":0.001,
"surprise":0
},
"blur":{
"blurLevel":"low",
"value":0
},
"exposure":{
"exposureLevel":"goodExposure",
"value":0.64
},
"noise":{
"noiseLevel":"low",
"value":0
},
"makeup":{
"eyeMakeup":true,
"lipMakeup":true
},
"accessories":[
],
"occlusion":{
"foreheadOccluded":false,
"eyeOccluded":false,
"mouthOccluded":false
},
"hair":{
"bald":0.02,
"invisible":false,
"hairColor":[
{
"color":"blond",
"confidence":0.99
},
{
"color":"gray",
"confidence":0.74
},
{
"color":"other",
"confidence":0.35
},
{
"color":"brown",
"confidence":0.31
},
{
"color":"red",
"confidence":0.15
},
{
"color":"black",
"confidence":0.06
}
]
}
} } ]
Now would I would like to do it to get the value for "faceID" or faceAttributes.gender or faceAttributes.age
I have tried that with the following commands, but I always get the following errors.
i.e.
console.log(jsonResponse.faceId);
log-message:
script.js.facedetect_node: undefined
i.e.
console.log(jsonResponse.faceId[0]);
log-message:
uncaught exception: Cannot read property '0' of undefined
i.e.
console.log(jsonResponse.faceAttributes[0]);
i.e.
console.log(jsonResponse.faceAttributes.age[0]);
log-message
TypeError: Cannot read property '0' of undefined
I guess you have already seen that I am quite a newbie - for this reason I would highly appreciate if you have an idea how I can get the mentioned values out of this json.
cu
schroedinger

Related

RSocket error 0x201 (APPLICATION_ERROR): readerIndex(1) + length(102) exceeds writerIndex(8): UnpooledSlicedByteBu

setInterval(() => {
let that = this;
this.socket && this.socket.requestResponse({
data: '' + (++index),
metadata: 'org.mvnsearch.account.AccountService.findById',
}).subscribe({
onComplete(payload) {
let account = JSON.parse(payload.data);
that.setState({
nick: account.nick
})
},
onError: (e) => {
console.log('onError', e)
}
});
}, 2000)
trying to connect to spring rsocket using reactjs. getting an error before subscribe in the javascript code shown below.
**this.socket.requestResponse({
data: '' + (++index),
metadata: 'org.mvnsearch.account.AccountService.findById',
})**
How to resolve the above issue?
If you are using rsocket routing on the backend, it is length prefixed. See https://github.com/rsocket/rsocket-demo/blob/master/src/main/js/app.js#L22-L36
// Create an instance of a client
const client = new RSocketClient({
setup: {
keepAlive: 60000,
lifetime: 180000,
dataMimeType: 'application/json',
metadataMimeType: 'message/x.rsocket.routing.v0',
},
transport: new RSocketWebSocketClient({url: url}),
});
const stream = Flowable.just({
data: '{"join": {"name": "Web"}}',
metadata: String.fromCharCode('chat/web'.length) + 'chat/web',
});
The routing specification allows multiple routes, so the encoding of a single route is unfortunately complicated by this. https://github.com/rsocket/rsocket/blob/master/Extensions/Routing.md

rn-fetch-blob Error: RNFetchBlob.fetchBlobForm failed to create request body

async postFileUpload(payload) {
const rnfetchfile = RNFetchBlob.wrap(payload.uri);
try {
console.log(
'POST',
'https://******.***.**/******/***/upload_*******_file',
{
...this.config,
'Content-Type': 'multipart/form-data',
},
[
// element with property `filename` will be transformed into `file` in form data
{
name: 'files',
filename: payload.name,
data: rnfetchfile.replace('file://file:///', 'file://'),
},
],
);
const res = await RNFetchBlob.fetch(
'POST',
'https://******.***.**/******/***/upload_*******_file',
{
...this.config,
'Content-Type': 'multipart/form-data',
},
[
// element with property `filename` will be transformed into `file` in form data
{
name: 'files',
filename: payload.name,
data: rnfetchfile.replace('file://file:///', 'file://'),
},
],
);
const response = JSON.parse(res.data);
console.log('api upload adpostimage', response);
return response;
} catch (err) {
console.log('postFileUpload', err.response, err);
Toast.show(err.response.data.message, Toast.SHORT);
throw err.response.data;
}
res throws error
in console messages are
POST https://******.***.**/******/***/upload_*******_file {Content-Type: "multipart/form-data", Authorization: "Bearer ******.***.*****"}
[{…}]
0:
name: "files"
filename: "*****.pdf"
data: "RNFetchBlob-file://Users/********/tmp/*****/B****.pdf"}
postFileUpload undefined Error: RNFetchBlob.fetchBlobForm failed to create request body
at index.js:313
at MessageQueue.__invokeCallback (MessageQueue.js:483)
at MessageQueue.js:135
at MessageQueue.__guard (MessageQueue.js:384)
at MessageQueue.invokeCallbackAndReturnFlushedQueue (MessageQueue.js:134)
at debuggerWorker.js:69
I am trying to upload a file using rn-fetch-blob and some crazy things happened
rnfetchfile.replace('file://file:///', 'file://'), because of file://file/// outputting which didn't seem right
I think this like mostly ios problem please help me out guys
as here said just use decodeURIComponent(uri)
this is my code :
const realPath = Platform.OS === 'ios' ? uri.replace('file://', '') : uri;
const data = [
{
name: 'file',
filename,
type,
data: RNFetchBlob.wrap(decodeURIComponent(realPath)),
},
{name: 'bla', data: 'bla'}
]
Try replacing the file://file:// to '' an empty string..
rnfetchfile.replace('file://file:///', '')
– #Abhishek Ghosh commented is a need trick which will work but the file will not be available in the uri.. your uploaded file wont open
I tried doing
data: decodeURIComponent(rnfetchfile.replace('file://file:///', 'file:///')
and it worked hope this helps

node.js program using mssql module - connecting to a SQL Server database fails

I've got this very simple node.js program. The program adds a record to an SQL Server database. I'm trying to code it as a synchronous operation.
It returns an error:
"config.server" property is required and must be of type string.
However the property exists and is a string.
Does anyone know why this is the case?
var AWS = require('aws-sdk');
const sql_server = require('mssql');
exports.handler = (event, context, callback) => {
console.log('Received event:', event);
var DB_status;
DB_status=Add_to_DB(event);
if (DB_status=="OK") {
var response = {
"isBase64Encoded": false,
"headers": { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' },
"statusCode": 200,
"body": "{\"result\": \"Success.\"}"
};
}
else {
var response = {
"isBase64Encoded": false,
"headers": { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' },
"statusCode": 200,
"body": "{\"result\": \"Database Error - " + DB_status + ".\"}"
};
};
callback(null,response);
}
async function Add_to_DB (event) {
let DB_status="OK";
const config = {
user: 'sa',
password: 'sapassword',
database: 'serverless-example',
server: 'serverless-example.cilqefqosmtc.ap-southeast-2.rds.amazonaws.com'
};
var sql = 'INSERT INTO UserTbl(Name,Email,Message)';
sql = sql + ' VALUES(\"' + event.name + '\",\"' + event.email + '\",\"' + event.message + '\")';
try {
let dbConn = await sql_server.connect();
let request = new sql_server.Request(dbConn);
await request.query(sql);
}
catch (err) {
// Error running our SQL Query
console.error("ERROR: Exception thrown running SQL", err);
DB_status=err;
}
return DB_status;
}
Sorry to all.
There is a typo there which I did not spot - I did not end up using the conif variable.
THanks to all for looking

Handle multipart/form-data with Serverless?

How to handle multipart/form-data with serverless-framework? v.0.5.6
Just tried this:
"requestTemplates": {
"multipart/form-data": {
"httpMethod": "$context.httpMethod",
"body": "$input.json('$')",
"queryParams": "$input.params().querystring",
"headerParams": "$input.params().header",
"headerParamNames": "$input.params().header.keySet()",
"contentTypeValue": "$input.params().header.get('Content-Type')"
},
"application/json": {
"httpMethod": "$context.httpMethod",
"body": "$input.json('$')",
"queryParams": "$input.params().querystring",
"headerParams": "$input.params().header",
"headerParamNames": "$input.params().header.keySet()",
"contentTypeValue": "$input.params().header.get('Content-Type')"
}
}
action.js:
export function respond(event, cb) {
var form = new formidable.IncomingForm();
form.parse(event, function(err, fields, files) {
if (err == null) {
var response = {
status: "true",
data: fields,
error: []
};
return cb(null, response);
} else {
console.log(err);
return cb(null, ApiErrors.errors(402, err['message'] + fields));
}
});
}
But got an error: errorMessage = "Cannot read property 'content-length' of undefined";
I've got this working with serverless by emulating http.ClientRequest and using a form parser tool like formidable.
I'm using lambda-proxy for the API Gateway event configuration.
const Stream = require('stream').Readable;
const Formidable = require('formidable');
module.exports.upload = ( e, ctx, cb ) => {
let form = new Formidable.IncomingForm();
let stream = new Stream();
stream.push( e.body );
stream.push( null );
// NOTE: You'll likely want to toLowerCase() at least 'Content-Type' header key
stream.headers = e.headers;
form.parse( stream, (err, fields, files) => {
// Work with your parsed form results here.
});
}
Well, I couldnt make it as multipart/form-data, so I used base64 string.
action.js:
export function respond(event, cb) {
//console.log('Received event:', JSON.stringify(event, null, 2));
var key = new Date().toISOString().substr(0, 10) + '/' + String(Date.now());
var contentType = event.body["data"].substr(0, event.body["data"].indexOf(';'));
if (!contentType.match(/(\.|\/)(gif|jpe?g|png)$/i)) {
return cb(null, 'invalid content type, gif, jpg, and png supported');
}
var data = new Buffer(event.body["data"].replace(/^image\/\w+;base64,/, ''),'base64');
var params = {
Bucket: 'your-bucket',
Key: key,
Body: data,
ContentEncoding: 'base64',
ContentType: contentType,
ACL: 'public-read'
};
s3.upload(params, function (err, data) {
if (err) {
console.log(err);
return cb(null, ApiErrors.errors(402, err['message']));
} else {
var response = {
status: "true",
data: {
url: urlPrefix + key
},
error: []
};
return cb(null, response);
}
});
}
RequestTemplate:
"requestTemplates": {
"application/json": {
"httpMethod": "$context.httpMethod",
"body": "$input.json('$')",
"header": "$input.params().header.get($header)",
"headerParam": "$input.params().header.keySet()",
"contentType": "$input.params().header.get('Content-Type')"
}
},

How to handle response from Express response.write() in Angular $http

I'm trying to upload a csv file using ng-file-upoad. Here is my code snippet:
Upload.upload({
url: baseUrl + '/file-upload',
data: {
file: file
}
})
.then(function(res) {
console.log('success: ===> ', res);
}, function(err) {
console.log('erroir: ===> ', err);
}, function() {
console.log('progress: ', arguments);
});
And in node environment I'm parsing the file and inserting the data in database. I don't want to close the connection. That's why I used "response.write". Here is my code snippet:
var path = req.files.file.path,
currentIndex = 0;
fs.readFile(path, 'utf8', function(err, data) {
if(err) {
// handle error
} else {
// making array (dataArray) from data
dataArray.forEach(function(eachData){
newEntry = new app.db.models.SomeCollection(eachData);
newEntry.save(function(err, data) {
if (currentIndex === dataArray.length) {
res.end('DONE!');
} else {
currentIndex++;
res.write(JSON.stringify({
total: dataArray.length,
done: currentIndex
}));
}
});
})
}
});
My question is how I will get the data I'm passing in "res.write"? I don't want to use socket for only this purpose. Am I missing something?
As already explained here:
response.send(msg) is equal to response.write(msg);response.end();
Which means, send can only be called once, write can be called many times, but you must call end yourself.
You are probably not receiving the response because response.end() is missing.
Once you end() your response you should be able to access the response data in your angular controller in the Upload.upload promise that is returned.
It's not like close a connection as you said. This is not a socket-ish like implementation (such as ws or socket.io). Once a request is made it should have a response even if it is to provide error details about that request (i.e. status 401, 403, 404, etc).
in your angular component:
...
constructor(private incrementalService: IncrementalService) {}
incrementalTest() { //activate with a button or whatnot
this.incrementalService.increment().subscribe( (result:any) => {
if (result.partialText) {
console.log(partialText); //do whatever you need to do with your partial results here!
}
})
}
your angular service:
import { HttpClient, HttpHeaders } from '#angular/common/http';
public class IncrementalService {
constructor(private http: HttpClient) {}
increment(): Observable<ArrayBuffer> {
const options = {
reportProgress: true,
responseType: 'text',
observe: 'events'
}
return this.http.request('get', 'http://someURL', { ...this.addRawHeaderOptions(), ...options});
}
private addRawHeaderOptions() {
const authHeaders = new HttpHeaders({
'Content-Type': 'application/json',
//authorization, Cache-Control: 'no-cache, Pragma:'no-cache', et al. }
return { headers: authHeaders }
}
}
Finally, your back-end service (this is express, but should work similarly for raw node):
async function(request, response) {
const increments = [ 1,2,3,4 ];
response.set('Content-Type', 'text/html');
for (const value of increments) { //contains async call - not switch-outable for a forEach.
response.write(`increment - ${value} `);
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
await delay(1000)
}
response.status(200).end()
}
browser console output when run:
increment - 1
increment - 1 increment - 2
increment - 1 increment - 2 increment - 3
increment - 1 increment - 2 increment - 3 increment - 4
!!Sorry for any typos - i had to transcribe this from a locked-down machine.

Resources