Can we query using the Hyperledger Composer Playground or can we only query using the REST API? I read the tutorial, but it only shows how to query using the REST API.
as Pronoy says, you can use REST APIs. Alternative is to set up a transaction, that calls a defined query (in queries,qry) - purely for testing and logging messages etc. Eg.
return query('selectPerson', {firstName: 'joe'} )
.then(function (results) {
for (var n = 0; n < results.length; n++) {
var person = results[n];
console.log('person is ' + (n+1) + ', object is ' + person);
console.log('person identifier is ' + person.getIdentifier());
return personRegistry.get(person.getIdentifier())
.then(function (personRecord) {
console.log('object is ' + personRecord); // all good
console.log('identifier is ' + person.getIdentifier() );
})
} // for
}) //function
You cannot do HTTP requests with the Playground, but you can test all the transactions and assets in your network. With the REST API, you can do HTTP requests plus CRUD all the transactions and assets in your network.
Related
I am searching the same text string from the chatBot which is passing this string to the azure search, but I am getting the results in a different order than the results appears in the azure search explorer from the Azure Portal.
Here is my search function for the azure search.
module.exports = function () {
global.request = require('request');
global.searchQueryStringBuilder = function (query) {
return queryString + query;
}
global.performSearchQuery = function (queryString, callback) {
request(queryString, function (error, response, body) {
if (!error && response && response.statusCode == 200) {
var result = JSON.parse(body);
callback(null, result);
} else {
callback(error, null);
}
})
}
}
even if I print the queryString in the console and paste to the chrome browser, results are the same as the explorer. So kind of frustrating whats wrongs happening on the way. :(
Thanks in advance.
Vivek
Previously I was adding the URL parameters with the normal string operation +, so it was somehow sending something extra with the query. Following way to make the URL worked well and now azure search results and the results from code are in synch.
var testUrl = global.queryString + 'api-key=' + encodeURIComponent(global['api-key']) + '&api-version=' + encodeURIComponent(global['api-version']) + '&search=' + encodeURIComponent(global.textToSearch);
I'm doing the tutorial for IBM Watson Speech-to-text. In the section "Using the WebSocket interface", subsection "Opening a connection and passing credentials", I copied the following code:
var token = watsonToken;
console.log(token); // token looks good
var wsURI = 'wss://stream.watsonplatform.net/speech-to-text/api/v1/recognize?watson-token=' +
token + '&model=es-ES_BroadbandModel';
var websocket = new WebSocket(wsURI);
websocket.onopen = function(evt) { onOpen(evt) };
websocket.onclose = function(evt) { onClose(evt) };
websocket.onmessage = function(evt) { onMessage(evt) };
websocket.onerror = function(evt) { onError(evt) };
I'm using Angular so I made a value for the token:
app.value('watsonToken', 'Ln%2FV...');
I get back an error message:
WebSocket connection to 'wss://stream.watsonplatform.net/speech-to-text/api/v1/recognize?watson-toke...&model=es-ES_BroadbandModel' failed: HTTP Authentication failed; no valid credentials available
I tried hardcoding the token:
var wsURI = 'wss://stream.watsonplatform.net/speech-to-text/api/v1/recognize?watson-token=Ln%2FV2...&model=es-ES_BroadbandModel';
Same error message.
IBM's documentation on tokens says that an expired or invalid token will return a 401 error, which I didn't get, so I presume that my token is neither expired nor invalid. Any suggestions?
I think you can see the Official Example from IBM Developers here.
The error is because the authentication does not work fine before you send the request to recognize, try to follow the same step inside this repository, like:
const QUERY_PARAMS_ALLOWED = ['model', 'X-Watson-Learning-Opt-Out', 'watson-token', 'customization_id'];
/**
* pipe()-able Node.js Readable/Writeable stream - accepts binary audio and emits text in it's `data` events.
* Also emits `results` events with interim results and other data.
* Uses WebSockets under the hood. For audio with no recognizable speech, no `data` events are emitted.
* #param {Object} options
* #constructor
*/
function RecognizeStream(options) {
Duplex.call(this, options);
this.options = options;
this.listening = false;
this.initialized = false;
}
util.inherits(RecognizeStream, Duplex);
RecognizeStream.prototype.initialize = function() {
const options = this.options;
if (options.token && !options['watson-token']) {
options['watson-token'] = options.token;
}
if (options.content_type && !options['content-type']) {
options['content-type'] = options.content_type;
}
if (options['X-WDC-PL-OPT-OUT'] && !options['X-Watson-Learning-Opt-Out']) {
options['X-Watson-Learning-Opt-Out'] = options['X-WDC-PL-OPT-OUT'];
}
const queryParams = extend({ model: 'en-US_BroadbandModel' }, pick(options, QUERY_PARAMS_ALLOWED));
const queryString = Object.keys(queryParams)
.map(function(key) {
return key + '=' + (key === 'watson-token' ? queryParams[key] : encodeURIComponent(queryParams[key])); // our server chokes if the token is correctly url-encoded
})
.join('&');
const url = (options.url || 'wss://stream.watsonplatform.net/speech-to-text/api').replace(/^http/, 'ws') + '/v1/recognize?' + queryString;
const openingMessage = extend(
{
action: 'start',
'content-type': 'audio/wav',
continuous: true,
interim_results: true,
word_confidence: true,
timestamps: true,
max_alternatives: 3,
inactivity_timeout: 600
},
pick(options, OPENING_MESSAGE_PARAMS_ALLOWED)
);
This code is from IBM Developers and for my project I'm using and works perfectly.
You can see in the code line #53, set the listening to true, otherwise it will eventually timeout and close automatically with inactivity_timeout applies when you're sending audio with no speech in it, not when you aren't sending any data at all.
Have another example, see this example from IBM Watson - Watson Developer Cloud using Javascript for Speech to Text.
Elementary, my dear Watson! There are three or four things to pay attention to with IBM Watson tokens.
First, you won't get a token if you use your IBMid and password. You have to use the username and password that were provided for a project. That username is a string of letters and numbers with hyphens.
Second, the documentation for tokens gives you code for getting a token:
curl -X GET --user {username}:{password}
--output token
"https://stream.watsonplatform.net/authorization/api/v1/token?url=https://stream.watsonplatform.net/text-to-speech/api"
Part of that code is hidden on the webpage, specifically the part that says /text-to-speech/. You need to change that to the Watson product or service you want to use, e.g., /speech-to-text/. Tokens are for specific projects and specific services.
Third, tokens expire in one hour.
Lastly, I had to put in backslashes to get the code to run in my terminal:
curl -X GET --user s0921i-s002d-dh9328d9-hd923:wy928ye98e \
--output token \
"https://stream.watsonplatform.net/authorization/api/v1/token?url=https://stream.watsonplatform.net/speech-to-text/api"
I want to develop a chat application like facebook. I did this and now it works fine. I used ajax for continuing server request to save and retrieve data. One function which is called each 10 second:
// Load message
(function loadClient() {
$.ajax({
type: 'POST',
data: 'c_id=' + $.cookie("c_id") + '&offset=' + $('#c_name_msgHead').data('offset'), //'foo='+ bar+'&calibri='+ nolibri,
dataType: 'json',
url: $("#webroot").text() + 'chats/loadMsg',
success: function (data) {
var id =0;
if ($.cookie("status") == "active"){
$.each(data, function (i, item) {
if(item.Chat.status == 'active'){
$('.temp_msg').remove();
}
if (!$('#' + item.Chat.id)[0]) {
if (item.Chat.admin_message) {
$('<div class="msg_b" id="' + item.Chat.id + '">' + item.Chat.admin_message + '</div>').insertBefore('.client_area .msg_push');
}
if (item.Chat.client_message) {
$('<div class="msg_a" id="' + item.Chat.id + '">' + item.Chat.client_message + '</div>').insertBefore('.client_area .msg_push');
}
$('.msg_body').scrollTop($('.msg_body')[0].scrollHeight);
}
id = item.Chat.id;
});
$('#c_name_msgHead').data('offset', id);
}
},
complete: function () {
// Schedule the next request when the current one's complete
setTimeout(loadClient, 3000);
}
});
})();
// END load message
It load update data after 10 second. Now if there are 10000 users at a time 10000 request will be send to my server which is a concerned of performance and shutdown of server may occur. Even if 10000 users did not start chatting 10000 request will be performed. So what should I do to develop such application which need to tiger server continuously or which technology is used for facebook chatting. Any idea will be appreciated. Thanks
Facebook is using the technique called Long Polling.
However,for chatroom with high respond rate, it is strongly suggested and much better to use socket.io with node.js as your server side which makes use of sockets to achieve most realtime bi-directional communication channel between a client and a server.
You can read the following tutorial as your starting point
http://socket.io/get-started/chat/
Is there is any way to call ajax function in web worker.Actually i am directly using ajax function to get the response but data is too much heavy,due to that my window is going to be freeze until the response will come.To overcome this problem now i am using web worker.The data(JSON) is dynamic.So can you please tell me how to call ajax function so that i can use it in my application.Here i am attaching web-worker code.
//Worker.js File
var myCallback = function(data){
self.postMessage(JSON.stringify(data));
};
self.addEventListener('message', function(e) {
importScripts('json.js?callback=myCallback');
}, false);
//JOSN.js File
function getResult(){
var randomNum = (Math.floor(Math.random() * 5) + 1),
cacheBuster = (Math.floor(Math.random() * 10000) + 1);
$.ajax({url:'http://examples.kevinchisholm.com/utils/json/jsonp.php?callback=myCallback&cacheBuster=' + cacheBuster + '&sleep=' + randomNum,
type:'POST',cache:false,data:datas,dataType:"json",async:false,
success:function(xmlResponse){
return xmlResponse;
}});
}
getResult();
Yes you can definitely use ajax in web worker by simply using XML Http Request or fetch API and can post the message using postmessage by using my code hope it helps:->
#Declaring Worker
var worker= new Worker("ajax123.js");
worker.onmessage=function(data){
document.body.innerHTML=data.data;
}
#Web Worker Code
fetch(filename)
.then(response => { return response.text(); })
.then(data => { self.postMessage(data) });
I am a total node.js noobie and trying to figure out the best way to structure my application with proper separation of concerns.
I am using mongodb via mongoose and have successfully gotten my controllers separated out using node.js modules and am trying to then separate out my models. What I've gone appears to work, but when I check the database nothing has been saved. Also, I tried a console.log() in the save function and nothing gets logged.
from my server.js I have:
app.post(api.urlslug + '/messages', messagesapi.insert);
I then have a /controllers/api/messages.js:
var m = require('../../models/message');
exports.index = function(req, res, next){
res.send('all the messages...');
}
exports.insert = function(req, res, next){
var message;
message = new m.Message({
messagebody: req.body.messagebody
});
message.save(function(err) {
console.log('here we are in the save');
if(!err) {
return console.log('message created');
} else {
return console.log(err);
}
});
return res.send(message);
}
and my /models/message.js looks like this:
// required modules
var mongoose = require('mongoose')
, db = require('../models/db');
// setup database connection
mongoose.connect(db.connectionstring());
var Message = exports.Message = mongoose.model('Message', new mongoose.Schema({
messagebody: String
}));
When I post to the API I get a the proper JSON back and it even has the _id field with what appears to me as a mongodb provided unique id. With that, I am having trouble understanding why it is not actually going into mongodb if it appears to be creating the object and communicating with mongodb correctly.
sounds like a connection is not being made. try listening to the open/error events of the default mongoose connection to find out why.
function log (msg) { console.log('connection: ', msg) }
mongoose.connection.on('open', log);
mongoose.connection.on('error', log);