they could help me I do not know how to put buttons in telegram, only in facebook messenger, where the error can be ?
$botman->hears('1', function ($bot) {
$bot->reply("• Android versión 4.4.2 (KitKat) o superior
• Espacio en memoria de almacenamiento
• Memoria RAM superior a 1 GB
• Duración de batería superior a 12 horas de uso continuo
• Conexión a red celular 3G o superior
• Conexión a Internet");
$bot->reply('¿ Algo más en lo que pueda ayudarte ?')
->addButton(Button::create('Tell a joke')
)
->addButton(Button::create('Give me a fancy quote')
)
});
This is solved using the classes of app / Conversations.php
<?php
namespace App\Conversations;
use Illuminate\Foundation\Inspiring;
use BotMan\BotMan\Messages\Incoming\Answer;
use BotMan\BotMan\Messages\Outgoing\Question;
use BotMan\BotMan\Messages\Outgoing\Actions\Button;
use BotMan\BotMan\Messages\Conversations\Conversation;
class ExampleConversation extends Conversation
{
/**
* First question
*/
public function askReason()
{
$question = Question::create("Huh - you woke me up. What do you need?")
->fallback('Unable to ask question')
->callbackId('ask_reason')
->addButtons([
Button::create('Tell a joke')->value('joke'),
Button::create('Give me a fancy quote')->value('quote'),
]);
return $this->ask($question, function (Answer $answer) {
if ($answer->isInteractiveMessageReply()) {
if ($answer->getValue() === 'joke') {
$joke = json_decode(file_get_contents('http://api.icndb.com/jokes/random'));
$this->say($joke->value->joke);
} else {
$this->say(Inspiring::quote());
}
}
});
}
//clases dinamicas, cambiar estructura de base de datos :v
/**
* Start the conversation
*/
public function run()
{
$this->askReason();
}
}
and in your botman.php :
$botman->hears('/start', function (BotMan $bot) {
$bot->startConversation(new ExampleConversation());
});
Related
I'm working a python django and django rest framework + swagger (drf-yasg) project.
I need a dynamic decorator.
how do you pass a parameter(named in this case "essource") of post method to decorator?
def xxx(esSource):
source = {}
if esSource == 1:
source = {
'field_1': openapi.Schema(type=openapi.TYPE_INTEGER)
}
else:
source = {
'field_44': openapi.Schema(type=openapi.TYPE_INTEGER)
}
properties = {
'type_operator': openapi.Schema(type=openapi.TYPE_INTEGER,description="L'operatore di insieme AND(0) OR(1)"),
'column_to_hide': openapi.Schema(type=openapi.TYPE_STRING,description="L'elenco di colonne da nascondere separato da virgola")
}
return properties.update(source)
class ShowResultsView(views.APIView):
#swagger_auto_schema(
operation_description="La prima pagina di risultati della ricerca",
request_body=openapi.Schema(
type=openapi.TYPE_OBJECT,
required=['type_operator','column_to_hide'],
properties=xxx(essource)
),
)
def post(self,request,essource,page):
resp = {}
resp["status"] = 0
resp["data"] = {}
resp["message"] = "I risultati della ricerca"
return Response(resp,status=status.HTTP_200_OK)
I get an error in this line code:
properties=xxx(essource)
i'm new at dart. I don't know what kind of mistake i have made, but this code didn't work.
Is a simple code, just read the age in terminal and say it's underage or over 18.
import 'dart:io';
main(){
print("Entre com a sua idade: ");
var input = stdin.readLineSync();
var idade = int.parse(input);
if(idade >= 18){
print("É maior de idade");
}else{
print("É menor de idade");
}
}
And i get this error:
algoritmo01.dart:15:25: Error: The argument type 'String?' can't be assigned to the parameter type 'String' because 'String?' is nullable and 'String' isn't.
var idade = int.parse(input);
Welcome to Dart. What you are experience is the new null-safety feature (introduced with Dart 2.12.0) where variables by default cannot contain the value null. This is statically checked so you will get an error even before your program are executed.
In your example the problem is the following line:
var input = stdin.readLineSync();
If we check the manual we can see this method have the following signature:
String? readLineSync (
{Encoding encoding = systemEncoding,
bool retainNewlines = false}
)
https://api.dart.dev/stable/2.12.2/dart-io/Stdin/readLineSync.html
String? means it is a nullable type and is therefore allowed to contain any String or null. If the type instead was String it would mean the result can only be a String and never null.
This means that your variable input now has the type String?. This (introduced with 2.12.0) is a problem if you take a look at the second line of your example:
var idade = int.parse(input);
Since the signature of int.parse is:
int parse (
String source,
{int? radix,
#deprecated int onError(
String source
)}
)
https://api.dart.dev/stable/2.12.2/dart-core/int/parse.html
Which takes a String (which can therefore never be null). You are therefore not allowed to give your String? as parameter to a method which only handles String. The opposite would have been allowed (if method takes String? and you give it a String).
So what can we do about this situation? Well, you need to handle the case of null or tell Dart that it should just crash your program if input are null.
So you could handle it like:
import 'dart:io';
void main() {
print("Entre com a sua idade: ");
var input = stdin.readLineSync();
if (input != null) {
var idade = int.parse(input);
if (idade >= 18) {
print("É maior de idade");
} else {
print("É menor de idade");
}
} else {
print('Input was null!');
}
}
As you can see, this is allowed even if input are technically still of the type String?. But Dart can see that your if statement will prevent input to have the value null so it will be "promoted" to String as long as you are inside this if-statement.
Another solution is to tell Dart that it should stop complain about statically errors about input and just assume input is String when compiling the code:
import 'dart:io';
void main() {
print("Entre com a sua idade: ");
var input = stdin.readLineSync()!;
var idade = int.parse(input);
if (idade >= 18) {
print("É maior de idade");
} else {
print("É menor de idade");
}
}
(The change is the ! added after readLineSync())
Dart will in this case instead add its own null-check and crash the program if stdin.readLineSync does give a null value. This is to ensure that we are still never going to give int.parse a null value which could make your code crash somewhere else. By adding the null-check where we get the questionable value, we can ensure we fails fast and at the place where things was not as we expected it to be.
You can read a lot more about null-safety in Dart here (also linked to by Stephen): https://dart.dev/null-safety/understanding-null-safety
The accepted answer is right. But there is another alternative solution. You can use "if null" operator like this :
var idade = int.parse(input ?? "-1");
So full code will looks like this :
import 'dart:io';
main(){
print("Entre com a sua idade: ");
var input = stdin.readLineSync();
var idade = int.parse(input ?? "-1");
if(idade >= 18){
print("É maior de idade");
}else if(idade < 18 && idade > 0){
print("É menor de idade");
} else {
print("entrada errada");
}
}
I**t isn't because of null safety?
As I've reading to transform a string taken from a stdout to int you have to do the next:
import 'dart:io';
main(){
print("E**ntre com a sua idade: ");
//You use ?? to indicate "otherwise" and '0' to use 0 if it is null.
var input = stdin.readLineSync()??'0';
//Here you also add otherwise '0' if it is null
var idade = int.parse(input ?? '0');
if(idade >= 18){
print("É maior de idade");
}else{
print("É menor de idade");
}
}
I am having problems implementing WaterfallDialogs in ComponentDialogs trigered by LUIS in the BotFramework V4.2. After the first step, the dialog does not continue the Waterfall.
I don't really understand what should be the correct approach to persist the ComponentDialog: save the ConversationState? set the step.context? I've tried both but none worked for me so far 😣
This is my code for bot.js, where I have a LUIS instance to act as an orchestrator between dialogs:
async onTurn(turnContext) {
...
switch (dialogResult.status) {
case DialogTurnStatus.empty:
// Call to LUIS recognizer to get intent + entities
const results = await this.luisRecognizer.recognize(dc.context);
const topIntent = results.luisResult.topScoringIntent;
switch (topIntent.intent) {
case FMM_INTENT:
return await dc.beginDialog(FeedbackDialog.Name);
...
}
case DialogTurnStatus.waiting:
// The active dialog is waiting for a response from the user, so do nothing
break;
...
}
And this is my code por FeedbackDialog.js where I have the logic of the WaterfallDialog with Prompts:
module.exports = {
FeedbackDialog: class extends ComponentDialog {
static get Name() { return DIALOG_NAME; }
constructor(conversationState, botConfig, feedbackStateAccessor, dialogId) {
(dialogId === undefined) ? super(DIALOG_NAME) : super(dialogId);
this.conversationState = conversationState;
this.feedbackStateAccessor = feedbackStateAccessor;
this.addDialog(new WaterfallDialog(FBK_EVAL, [
this.feedbackPrompt.bind(this),
this.feedbackEvaluation.bind(this)
]));
this.addDialog(new ChoicePrompt(FBK_PROMPT));
}
async feedbackPrompt(step) {
let fmmState = await this.feedbackStateAccessor.get(step.context);
if (fmmState === undefined) {
await this.feedbackStateAccessor.set(step.context);
//opciones válidas, las mayúsculas las detecta también
const options = ['👍','👎'];
return await step.prompt(FBK_PROMPT, {
prompt: `¿Te ha resultado útil la respuesta?`,
retryPrompt: `¿Qué te ha parecido la respuesta?`,
choices: options
});
}
}
async feedbackEvaluation(step) {
let fmmState = await this.feedbackStateAccessor.get(step.context);
if (fmmState === undefined && step.result){
if (step.result == '👍'){
await step.context.sendActivity("¡Gracias por el feedback!");
return await step.endDialog();
}else {
await step.context.sendActivity("¡Revisaremos tu pregunta para seguir mejorando!");
return await this.conversationState.saveChanges(step.context);
}
} else {
return await step.next();
//next steps omitted since the code doesn't reach this step
}
}
I'm unsure what you're trying to achieve but if you're using a ChoicePrompt I believe the step result comes back into a value key, i.e. instead of
if (step.result == '👍')
try
if (step.result.value === '👍')
Then you can send a message back to the user and end the dialog and it should be fine:
await step.context.sendActivity("¡Gracias por el feedback!");
return step.endDialog();
or
await step.context.sendActivity("¡Revisaremos tu pregunta para seguir mejorando!");
return step.endDialog();
Also, remember to initialise the dialog correctly, i.e. in your bot file:
const { FeedbackDialog } = require('path/to/feedbackDialog')
const FEEDBACK_DIALOG = 'FeedbackDialog'
const FEEDBACK_PROPERTY = 'feedbackProperty'
and in the bot constructor (I use userState for state accessors, not conversation state):
this.dialogs = new DialogSet(this.dialogState)
this.feedbackAccessor = userState.createProperty(FEEDBACK_PROPERTY)
this.dialogs.add(new FeedbackDialog(
FEEDBACK_DIALOG,
this.feedbackAccessor
))
then call it as:
await dc.beginDialog(FEEDBACK_DIALOG);
I am new learning repaint g programing methos, i am trying to make a simple Rock paper sccissors with grahpics an animations. i am using netbeans
Context: 2 java clases: PPT.java wich extend jpanel and a netbeans JFrame Form.
i added the PPT as a bean on the JFRame and it render nice the start animation (slide down and resize the images of rockpaper...)
After the animation i try diferents events like click on the bean and recall the PPT.motor method who is the one who Reposition the things and call reprint and sleep for make the animation.
After clicking and triggering the event, the execution runs smooth just before call method motor (almost last lane).
But when the programs have to go to motor by 2nd time it stay there for a while with no errors, not printing nothing in the windows, if you click more times it print images small then enormous with no animation.
I am almost sure that my problems come from not handling nice the Threads but who knows.
this is PPT.java
package ppt;
import com.sun.org.apache.bcel.internal.classfile.Constant;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import static java.lang.Thread.sleep;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class PPT extends JPanel{
//Variables de Imagen buffered para prevenir FLIKR
private BufferedImage piedra;
private BufferedImage tijera;
private BufferedImage papel;
//Game Variables
private int cpu;//CPU choice
private int j1;//J1 choice
private int totalCPU;//score
private int totalJ1;//score
private int ganaRonda;//0 ties, 1 j1 win -1 cpu win
//
private static GUI ventana;//Declaramos asi la variable ventana para poder acceder a sus Variables fuera del main.
//piedra= rock papel=paper XY=cordinate var TXTY= SizeVar
private int piedraX=240, piedraXCPU;//Cordenada X para renderizar la imagen
private int piedraY=280, piedraYCPU;//Coordenada Y para renderizar la imagen
private int piedraTX=242;//Tamaño de salida de la imagen en X 900
private int piedraTY=242;//Tanaño de salida de la imagen en Y 645
private int papelX=444, papelXCPU=-100;//Cordenada X para renderizar la imagen
private int papelY=248, papelYCPU=-100;//Coordenada Y para renderizar la imagen
private int papelTX=300;//Tamaño de salida de la imagen en X 600
private int papelTY=300;//Tanaño de salida de la imagen en Y 376
private int tijeraX=280, tijeraXCPU=-100;//Cordenada X para renderizar la imagen
private int tijeraY=240, tijeraYCPU=-100;//Coordenada Y para renderizar la imagen
private int tijeraTX=400;//Tamaño de salida de la imagen en X 210
private int tijeraTY=400;//Tanaño de salida de la imagen en Y 400
private Color color1=Color.RED;//Color de la caja izq 1
private Color color2=Color.BLUE;//Color de la caja izq 2
public static void main(String[] args) {
// TODO code application logic here
//INSTANCE OF JFRAMEFORM
ventana =new GUI("Piedra Papel Tijera");
ventana.setLocationRelativeTo(null);//Centra la ventana en el media
ventana.setVisible(true);//Hace visible la ventana
ventana.pPT1.motor(4);//pPT1 IS THIS CLASS INSTANCED FROM JFRAME AS BEAN
}
public PPT (){
//CONSTRUCTOR getting images
try {
this.piedra = ImageIO.read(getClass().getResource("piedra.png"));
this.papel = ImageIO.read(getClass().getResource("papel.png"));
this.tijera = ImageIO.read(getClass().getResource("tijeras.png"));
} catch (IOException ex) {
Logger.getLogger(PPT.class.getName()).log(Level.SEVERE, null, ex);
}
this.setSize(800, 700);//Establece el tamaño del jpanel a 800x700
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
//THIS draw the Scores at the left of the screen
g.setFont(new Font("Arial",Font.BOLD,42));//establece la fuente
g.setColor(color1);//ColorRojo
g.fillRect(1, 350, 42, 84);//Dibuja el rectangulo Del Jugador
g.setColor(color2);//ColorAzul
g.fillRect(1, 264, 42, 84);//dibuja el rectangulo azul
g.drawString(Integer.toString(totalJ1) , 4, 420);//dibuja la puntuacion del J1 en azul
g.setColor(color1);//ColorRojo
g.drawString(Integer.toString(totalCPU) , 4, 313);//dibuja la puntuacion de la CPU en rojo
/THIS draw the images
g.drawImage(piedra, piedraX, piedraY,piedraTX,piedraTY,null);//pintamos la Image de la variable en la Posicion XY y con el tamaño TX TY
g.drawImage(papel, papelX, papelY,papelTX,papelTY,null);
g.drawImage(tijera, tijeraX, tijeraY,tijeraTX,tijeraTY,null);
}
public void cpuTira (){
//THIS generate RANDOM choose to cpu
cpu=(int) (Math.random() * (4 - 1)) + 1;
}
//This is the GameLoopHandler
public void motor (int num){
if (num==4){
//THIS RESET THE ORIGINAL VALUES OF vars FOR START AGAIN THE ANIMATION OF THE FIRST STAGE
piedraX=240;//Cordenada X para renderizar la imagen
piedraY=280;//Coordenada Y para renderizar la imagen
piedraTX=242;//Tamaño de salida de la imagen en X 900
piedraTY=242;//Tanaño de salida de la imagen en Y 645
papelX=444;//Cordenada X para renderizar la imagen
papelY=248;//Coordenada Y para renderizar la imagen
papelTX=300;//Tamaño de salida de la imagen en X 600
papelTY=300;//Tanaño de salida de la imagen en Y 376
tijeraX=280;//Cordenada X para renderizar la imagen
tijeraY=240;//Coordenada Y para renderizar la imagen
tijeraTX=400;//Tamaño de salida de la imagen en X 210
tijeraTY=400;//Tanaño de salida de la imagen en Y 400
//THIS MOVE THE IMAGES down until near the bottom and resize them
while (piedraY<500){
if (piedraY>400){
piedraTX--;
piedraTY--;
papelTX--;
papelTY--;
tijeraTX-=2;
tijeraTY-=2;
}
if(tijeraY>359)
tijeraX++;
if(papelY>385)
papelX++;
piedraY++;
tijeraY++;
papelY++;
repaint();
try {//CUANTO MAS TIEMPO DE SLEEP MAS LENTA VA LA ANIMACION (FPS)
Thread.sleep(18);
} catch (InterruptedException ex) {
Logger.getLogger(PPT.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
//THIS METHOD IS called by the event in JFRAME FORM
public void controlJuego(int jugador1){
j1=jugador1;//set the choice of j1
cpuTira();//set the choice of CPU
//Calculate win 1 rock, 2paper,3 scissors
switch(j1){
case 1:
if(cpu==1)
ganaRonda=0;
if(cpu==2)
ganaRonda=-1;
if(cpu==3)
ganaRonda=1;
break;
case 2:
if(cpu==1)
ganaRonda=1;
if(cpu==2)
ganaRonda=0;
if(cpu==3)
ganaRonda=-1;
break;
case 3:
if(cpu==1)
ganaRonda=-1;
if(cpu==2)
ganaRonda=1;
if(cpu==3)
ganaRonda=0;
}
//Animation of "Fight" Currently i just want to repeat the start animation
System.out.println("hellow");//it printed hellow quicly
motor(4);//4 = intro animation
System.out.println(Integer.toString(ganaRonda));//it printed the variable after half minut and dindt redender nothing.
}
}
The JFrame Form have the default netbeans code, and the bean deployed.
So the thread mess can come cause i call the eventClick in JFrame and then explode.
Thanks for helping, sorry about the wallcode i just want to understand the thing.
Solution:
i Started a new NOT netbeans GUI base project folowing this code https://www.youtube.com/watch?v=_ix-jCzG53A
and modifyng the Ant class to my own game class.
Also for the animations runing smoothly update i have to create a new Thread code wich have to run on the EDT with a timer repting it each 10ms or delay you want.
(Like this but setting setRepetas to true and ) 10ms instead of 300
Timer timer = new Timer(10, new ActionListener(){
https://stackoverflow.com/a/22968559/4748324
Final code like this
int delay=10;
//Creamos un timer que se repetira para actualizar la posicion de los elementos adecuadamente en el EDT
Timer piedraJtimer = new Timer(delay, new ActionListener(){
/*So the Timer object will create a new thread, delay for 300 milliseconds, and then call the 'actionPerformed' method.
This will happen on the Timer's thread. It's not recommended to change UI elements from any thread except for the EDT,
so we use the invokeLater method which causes swing to run the runnable on the EDT itself - so back on the original thread.*/
#Override
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
// runs code on the EDT to edit UI elements (recommended way)
if (piedraY!=280){//if StoneY is not in 280 make animation
if (piedraY<444){
piedraX++;
}
piedraY--;
}else//if Stone Y is in 280 y and the Cpu Stone or Cpu paper or Cpu sicssors are in place redy to roll out
if(piedraYCPU==404 || tijeraYCPU==400 || papelYCPU==400)
piedraX-=4;//Roll out sliding to left
if(piedraX<=0){//if Stone rolled out, set controls On and Stop the recursive timer
puedeAccionar = true;
piedraJtimer.stop();//Canceling the timer repeats.
}
}
});
}
});
The repaint(); method is caling in gameloop each delay miliseconds
I have this code:
public UILabel Error;
void OnRegister(GameObject g)
{
if (Error.text.Equals("That e-mail address is in use. Use password recovery if you forgot your password."))
{
Error.text= "Inserisci un indirizzo di posta elettronica (email) valido. Questa operazione e’ importante per recuperare la tua parola chiave (password), nel momento in cui l’hai dimenticata.";
return;
}
}
What i wanted to do is when the string is entered to the UILabel, when a button(having the function OnRegister) it would translate the string to italian. Thank you for the help :)