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 :)
Related
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");
}
}
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());
});
I need to send a temporary password via email to an user when i register a new Teacher.
i use Membership.GeneratePassword to generate random password.
here is my TeacherController
[HttpPost]
public async Task<ActionResult> Create(TeacherViewModel viewModel)
{
if (!ModelState.IsValid)
{
var model = new TeacherViewModel()
{
Courses = _context.Courses.ToList(),
SituationActuelles = _context.SituationActuelles.ToList()
};
return View("Create", model);
}
var teacher = new Teacher
{
PhoneNumber = viewModel.PhoneNumber,
Password = viewModel.Password
};
_context.Teachers.Add(teacher);
_context.SaveChanges();
var body = "<p>Merci de votre interet a NewEra Tutoring Corp.</p> <br/>" +
"Vos credentials pour acceder a votre platform est le suivant: <br/>" +
"Email: Votre email<br/>" +
"Votre mot de passe temporaire: " + viewModel.Password;
var message = new MailMessage();
message.To.Add(new MailAddress(viewModel.Email)); // replace with valid value
message.From = new MailAddress("recrutement#newera-tutoring.com"); // replace with valid value
message.Subject = "Your email subject";
message.Body = string.Format(body, "NewEra Tutoring", "recrutement#newera-tutoring.com", "Votre identifiant pour NewEra Tutoring");
message.IsBodyHtml = true;
using (var smtp = new SmtpClient())
{
var credential = new NetworkCredential
{
UserName = "recrutement#newera-tutoring.com", // replace with valid value
Password = "neweratutoring" // replace with valid value
};
smtp.Credentials = credential;
smtp.Host = "gator4123.hostgator.com";
smtp.Port = 587;
smtp.EnableSsl = true;
await smtp.SendMailAsync(message);
}
return RedirectToAction("Index", "Home");
}
But the password i receive in the email it's different from the one that it's saved in the database.
here is my model
TeacherViewModel{
public string Password => Membership.GeneratePassword(12, 1);
}
Where i am doing wrong?
You've used an expression bodied member in the view model for the password property which essentially creates a get wrapper around the call to membership password.
Each time you access the property it generates a new password as it runs the function again.
I don't see why you'd want to have it in the view model at all unless your intention is to offer a random password that they user could replace with their own. If that was the aim use a standard property get/set and create an initial password value in the view model constructor instead. Otherwise, take it out o of the view model & only create the password in the post action if every thing else is valid.
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 need some help with variable inheritance in VC form app! I have this code:
string ks;
ifstream sfile(ks);
if (sfile)
{
PatInfo ^ form = gcnew PatInfo;
form->ShowDialog();
}
else
{
MessageBox::Show( "Please try again.");
}
I want to pass the ks string to PatInfo form. How can it be done?