I was thinking as bots have some generic questions like how are you ? may be i have around 10 answers which i would like Q&A maker to choose randomly not every time same answer.
or also questions like tell me a story
some generic questions like how are you ? may be i have around 10 answers which i would like Q&A maker to choose randomly not every time same answer.
To achieve this requirement, you can try this approach:
1) Add a QnA pair and use a special character (such as |) to split answers for question how are you?
2) Override the RespondFromQnAMakerResultAsync method, and split response and retrieve answer randomly in this method
protected override async Task RespondFromQnAMakerResultAsync(IDialogContext context, IMessageActivity message, QnAMakerResults result)
{
// This will only be called if Answers isn't empty
var response = result.Answers.First().Answer;
var answersforhowareyou = response.Split('|');
if (answersforhowareyou.Count() > 1)
{
Random rnd = new Random();
int index = rnd.Next(answersforhowareyou.Count());
response = answersforhowareyou[index];
}
await context.PostAsync(response);
}
Test result:
Related
I've found this function in an assemblyscript project for a NEAR contract:
export function assert_single_promise_success(): void {
const x = ContractPromise.getResults()
assert(x.length == 1, "Expected exactly one promise result")
assert(x[0].succeeded, "Expected PromiseStatus to be successful")
}
What does ContractPromise.getResults() do exactly? How should implement the same thing in rust?
here is something similar in Rust from one of the examples in the SDK repo
require!(env::promise_results_count() == 2);
let data0: Vec<u8> = match env::promise_result(0) {
PromiseResult::Successful(x) => x,
_ => env::panic_str("Promise with index 0 failed"),
};
I'm going to give an answer, comments taken directly from the implementation of ContractPromise.getResults(), which can be found here. The implementation also has an example on how to use the function, which may be useful.
Method to receive async (one or multiple) results from the remote
contract in the callback.
#returns An array of results based on the number of promises the
callback was created on. If the callback using then was scheduled
only on one result, then one result will be returned.
I've been tasked to write a basic guessing game, which I have done, but part of the task is confusing me. We've been asked to create a warning when a user inputs the same guess too many times. I've tried several ways to take the previous user guess and compare them with the current one but none seem to work. Can anyone help me with this? My Google skills seem to have failed me.
Mostly I've tried this:
void guessWarning(int confirmedGuess){
int prevGuess = currentGuess;
int currentGuess = confirmedGuess;
if(prevGuess == currentGuess){
text("Same guess, try again",350,350)
}
}
There are multiple ways to tackle this.
One option would be keep track of the previous attempts in a dynamic array (see ArrayList). Here a bit of code to illustrate the concept:
//create a new list of integers
ArrayList<Integer> guesses = new ArrayList<Integer>();
//in your check function, test if the new value already exists
if(guesses.contains(NEW_GUESS_HERE)){
println("you've already tried this number");
}else{//otherwise add the current guess to keep track of for next time
guesses.add(NEW_GUESS_HERE);
}
Another option is using a HashMap. This is an associative array as opposed to an index based array. This method is more efficient and you can also keep track of how many attempts there were for each value. Be sure to read more on HashMaps: it will help you on the long run and potentially impress your tutors on the short run.
Here's a basic sketch to illustrate the idea:
//create a new hashmap of integers (key = guess, value = number of times tried)
HashMap<Integer,Integer> guesses = new HashMap<Integer,Integer>();
int answer = '=';
void setup(){}
void draw(){}
void keyPressed(){
guess(keyCode);
println(keyCode);
}
void guess(int newValue){
if(newValue == answer){
println("you guessed it!");
}else{
//check if the value was already recorded
try{
//if there was a value with this key, it's been tried before
int numberOfTries = guesses.get(newValue);
println("you've tried this value",numberOfTries,"times");
//increment the number of times this has beeen attempted
guesses.put(newValue,numberOfTries+1);
}catch(NullPointerException e){
println("it's the first time you try this number, but you haven't guessed it yet");
guesses.put(newValue,1);
}
}
}
A similar option, but a bit more hacky would be using a JSONObject.
The concept is similar: an associative array (albeit the key is a string, instead of an int), but you'd need to convert the guessed number to a string to index it first:
JSONObject guesses = new JSONObject();
int answer = '=';
void setup(){}
void draw(){}
void keyPressed(){
guess(keyCode);
println(keyCode);
}
void guess(int newValue){
if(newValue == answer){
println("you guessed it!");
}else{
//hacky int to string
String newValueStr = newValue+"";
//check if the value was already recorded
if(guesses.hasKey(newValueStr)){
//if there was a value with this key, it's been tried before
int numberOfTries = guesses.getInt(newValueStr);
println("you've tried this value",numberOfTries,"times");
//increment the number of times this has beeen attempted
guesses.setInt(newValueStr,numberOfTries+1);
}else{
println("it's the first time you try this number, but you haven't guessed it yet");
guesses.setInt(newValueStr,1);
}
}
}
One nice thing is that you could save the guesses to disk, then load it so the program could recall previous guesses even if the it was restarted.
I'll leave you the fun exercise of attempting to load the data when the sketch starts and saving the data when the sketch exists.
I'm finding it difficult to compose an subject or observable where I have validation. This is the nature of Functional programming, but it seems that Reactive Programming only takes care of each piece of data. Also, the examples are a bit too generalistic, no real world example that covers a lot of aspects, though this is a personal opinion.
I'd like to send another value to the observer based on the previous one, but I can't find out how to achieve this.
Rx.Observable.create( function(obs) {
obs.next(1)
// if value is one, compile 3, if not, respond with 2
obs.next(someVal)
obs.onCompleted()
});
You'd find it simpler to use subject and map:
let src = new Subject<number>();
let other = src.map(v => (v === 1 ? 3 : 2));
other.subscribe(v => console.log(v));
src.next(1);// prints 3
src.next(4);// prints 2
Modified to clarify what I want to achieve.
Can I write a code with RxJs where the Observable collects data from Observers? Like scenario below:
one Examiner, multiple Students
the Examiner is an Observable
each Student is an Observer
every time the Examiner makes a question, the Students who know the answer (i.e. .filter()) will respond with the answer
the Examiner will take the first answer as the correct one
With Rxjs, when the Observable fires a new value with .next(), every Observer with method .subscribe() will react to that, but I don't know a way this observer can return a value to the Observable.
So, here is what I need:
how can the Observer send back a value to the Observable?
is it possible that the first Observer who respond wins the race and the others are ignored after that?
is it possible to know that no Observer responded?
I hope now I'm clear on my needs :)
Ok, I understand the problem better.
I believe what you need is for both Examiner and Students to have Observable and Observer properties. This is the only way you will get 2-way communication using Observables, as they are only a 1-way communication mechanism.
The solution is to make the students' answers be observables.
Then you can use race to make them race.
Hmmm... You'd have to define what it means for a student not to answer: is there a timeout, or are they able to declare that they will not answer later?
const question$ = Rx.Observable.range(1, 4)
// in case you want everyone to wait
.publish();
function makeStudent(name, worstTimeToAnswer) {
return q =>
Rx.Observable.of(`${name} answers question ${q}`)
.delay(Math.random() * 1000 * worstTimeToAnswer);
}
// Alice answers questions in at most 5 seconds
const alice = makeStudent("Alice", 5);
// Bob answers questions in at most 7 seconds
const bob = makeStudent("Bob", 7);
// This stream contains one answer for each question, as long as someone
// answered fast enough.
const winningAnswer$ =
question$
.concatMap(q =>
// see who answers faster between Alice and Bob
Rx.Observable.race(alice(q), bob(q))
// or drop the question if nobody answers within 4 seconds
.takeUntil(Rx.Observable.timer(4000))
);
winningAnswer$.subscribe(a => console.log(a));
question$.connect(); // questions start flowing
// should print something like:
// Alice answers question 1
// Bob answers question 3
// Alice answers question 4
// where Q2 was dropped because nobody answered fast enough
// and Alice often answers faster than Bob
If you actually want a feedback loop where the answers to a question change the next question, then you will probably need to use a Subject to close the loop.
The Events-ex library supports that the observer send back a value to the observable.
eventable = require('events-ex/eventable')
class Examiner
# advanced usage see API topic.
eventable Examiner
makeQuestion: ->
aQuestion = '....'
theAnswer = this.emit 'ask', aQuestion
class Student
constructor: (aExaminer)->
aExaminer.on 'ask', this.answer if aExaminer
answer: (aQuestion)->
# this is the event object, not the student instance.
this.result = 'myAnswer'
this.stopped = true # stop other listeners. defaults to false.
return
I'm testing out CouchDB to see how it could handle logging some search results. What I'd like to do is produce a view where I can produce the top queries from the results. At the moment I have something like this:
Example document portion
{
"query": "+dangerous +dogs",
"hits": "123"
}
Map function
(Not exactly what I need/want but it's good enough for testing)
function(doc) {
if (doc.query) {
var split = doc.query.split(" ");
for (var i in split) {
emit(split[i], 1);
}
}
}
Reduce Function
function (key, values, rereduce) {
return sum(values);
}
Now this will get me results in a format where a query term is the key and the count for that term on the right, which is great. But I'd like it ordered by the value, not the key. From the sounds of it, this is not yet possible with CouchDB.
So does anyone have any ideas of how I can get a view where I have an ordered version of the query terms & their related counts? I'm very new to CouchDB and I just can't think of how I'd write the functions needed.
It is true that there is no dead-simple answer. There are several patterns however.
http://wiki.apache.org/couchdb/View_Snippets#Retrieve_the_top_N_tags. I do not personally like this because they acknowledge that it is a brittle solution, and the code is not relaxing-looking.
Avi's answer, which is to sort in-memory in your application.
couchdb-lucene which it seems everybody finds themselves needing eventually!
What I like is what Chris said in Avi's quote. Relax. In CouchDB, databases are lightweight and excel at giving you a unique perspective of your data. These days, the buzz is all about filtered replication which is all about slicing out subsets of your data to put in a separate DB.
Anyway, the basics are simple. You take your .rows from the view output and you insert it into a separate DB which simply emits keyed on the count. An additional trick is to write a very simple _list function. Lists "render" the raw couch output into different formats. Your _list function should output
{ "docs":
[ {..view row1...},
{..view row2...},
{..etc...}
]
}
What that will do is format the view output exactly the way the _bulk_docs API requires it. Now you can pipe curl directly into another curl:
curl host:5984/db/_design/myapp/_list/bulkdocs_formatter/query_popularity \
| curl -X POST host:5984/popularity_sorter/_design/myapp/_view/by_count
In fact, if your list function can handle all the docs, you may just have it sort them itself and return them to the client sorted.
This came up on the CouchDB-user mailing list, and Chris Anderson, one of the primary developers, wrote:
This is a common request, but not supported directly by CouchDB's
views -- to do this you'll need to copy the group-reduce query to
another database, and build a view to sort by value.
This is a tradeoff we make in favor of dynamic range queries and
incremental indexes.
I needed to do this recently as well, and I ended up doing it in my app tier. This is easy to do in JavaScript:
db.view('mydesigndoc', 'myview', {'group':true}, function(err, data) {
if (err) throw new Error(JSON.stringify(err));
data.rows.sort(function(a, b) {
return a.value - b.value;
});
data.rows.reverse(); // optional, depending on your needs
// do something with the data…
});
This example runs in Node.js and uses node-couchdb, but it could easily be adapted to run in a browser or another JavaScript environment. And of course the concept is portable to any programming language/environment.
HTH!
This is an old question but I feel it still deserves a decent answer (I spent at least 20 minutes on searching for the correct answer...)
I disapprove of the other suggestions in the answers here and feel that they are unsatisfactory. Especially I don't like the suggestion to sort the rows in the applicative layer, as it doesn't scale well and doesn't deal with a case where you need to limit the result set in the DB.
The better approach that I came across is suggested in this thread and it posits that if you need to sort the values in the query you should add them into the key set and then query the key using a range - specifying a desired key and loosening the value range. For example if your key is composed of country, state and city:
emit([doc.address.country,doc.address.state, doc.address.city], doc);
Then you query just the country and get free sorting on the rest of the key components:
startkey=["US"]&endkey=["US",{}]
In case you also need to reverse the order - note that simple defining descending: true will not suffice. You actually need to reverse the start and end key order, i.e.:
startkey=["US",{}]&endkey=["US"]
See more reference at this great source.
I'm unsure about the 1 you have as your returned result, but I'm positive this should do the trick:
emit([doc.hits, split[i]], 1);
The rules of sorting are defined in the docs.
Based on Avi's answer, I came up with this Couchdb list function that worked for my needs, which is simply a report of most-popular events (key=event name, value=attendees).
ddoc.lists.eventPopularity = function(req, res) {
start({ headers : { "Content-type" : "text/plain" } });
var data = []
while(row = getRow()) {
data.push(row);
}
data.sort(function(a, b){
return a.value - b.value;
}).reverse();
for(i in data) {
send(data[i].value + ': ' + data[i].key + "\n");
}
}
For reference, here's the corresponding view function:
ddoc.views.eventPopularity = {
map : function(doc) {
if(doc.type == 'user') {
for(i in doc.events) {
emit(doc.events[i].event_name, 1);
}
}
},
reduce : '_count'
}
And the output of the list function (snipped):
165: Design-Driven Innovation: How Designers Facilitate the Dialog
165: Are Your Customers a Crowd or a Community?
164: Social Media Mythbusters
163: Don't Be Afraid Of Creativity! Anything Can Happen
159: Do Agencies Need to Think Like Software Companies?
158: Customer Experience: Future Trends & Insights
156: The Accidental Writer: Great Web Copy for Everyone
155: Why Everything is Amazing But Nobody is Happy
Every solution above will break couchdb performance I think. I am very new to this database. As I know couchdb views prepare results before it's being queried. It seems we need to prepare results manually. For example each search term will reside in database with hit counts. And when somebody searches, its search terms will be looked up and increments hit count. When we want to see search term popularity, it will emit (hitcount, searchterm) pair.
The Link Retrieve_the_top_N_tags seems to be broken, but I found another solution here.
Quoting the dev who wrote that solution:
rather than returning the results keyed by the tag in the map step, I would emit every occurrence of every tag instead. Then in the reduce step, I would calculate the aggregation values grouped by tag using a hash, transform it into an array, sort it, and choose the top 3.
As stated in the comments, the only problem would be in case of a long tail:
Problem is that you have to be careful with the number of tags you obtain; if the result is bigger than 500 bytes, you'll have couchdb complaining about it, since "reduce has to effectively reduce". 3 or 6 or even 20 tags shouldn't be a problem, though.
It worked perfectly for me, check the link to see the code !