lundi 1 mars 2021

Java score is not increasing with if statements

For my java trivia game, I set the questions in the beginning, e.g.

if(command.equals("question 1"))
    {
        txtAnswer.setText("");
        q1 = true;
        btnQ1.setEnabled(false);
        lblQuestion.setText("What is 2 + 2?");
        lblOutcome.setText("");
    }

        

and then after all the "if"s for the questions, I have code that verifies if it is correct or not, and if it's correct I increase the score. This is the code I use:

if(command.equals("Check")&& (txtAnswer.getText().equalsIgnoreCase("4") && (q1)))
        {
            q1= false;
            lblOutcome.setText("Correct");
            score = score +1;
            lblScore.setText("Current Score: " + score);
            
        }
        else if(command.equals("Check")&& (!txtAnswer.getText().equalsIgnoreCase("4") && (q1)))
        {
            q1= false;
            lblOutcome.setText("Incorrect");
            lblScore.setText("Current Score: " + score);
        
        }
        
        
        
        if(command.equals("Check")&& (txtAnswer.getText().equalsIgnoreCase("8") && (q2)))
        {
            q2= false;
            lblOutcome.setText("Correct");
            score = score +1;
            lblScore.setText("Current Score: " + score);
            
        }
        else if(command.equals("Check")&& (!txtAnswer.getText().equalsIgnoreCase("8") && (q2))
        {
            q2= false;
            lblOutcome.setText("Incorrect");
            lblScore.setText("Current Score: " + score);
            
        }
        

But the problem I'm having right now is that the score is not increasing, it just completely resets to 0 after each question so if I get all the questions right, the score remains at 1. I was wondering what I have to do to fix this?

Edit: this is where wrote the code

private static class ButtonHandler implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
        String command = e.getActionCommand();
        int score = 0;

VBA replace last 3 symbols in a CELL to COMBOBOX value

I have a code that finds cells that start with "UZL." and is 16 symbols long:

Dim vDB As Variant
Dim rngDB As Range
Dim s As String, sReplace As String
Dim i As Long
Dim Ws As Worksheet

Set Ws = Sheets("BOM")
With Ws
    Set rngDB = .Range("E2", .Range("E" & Rows.Count).End(xlUp))
End With
vDB = rngDB
For i = 1 To UBound(vDB, 1)
    s = vDB(i, 1)
    If s Like "UZL.*" And Len(s) = 16 Then
        sReplace = Me.LanguageBox.Value
        s = Replace(s, "ENG", sReplace)
        vDB(i, 1) = s
    End If
Next i
rngDB = vDB

In which there's a line:

s = Replace(s, "ENG", sReplace)

That change's only the cells that has ".ENG" in them (always at the end), but I need to define it to not be dependant on that. Instead of .ENG it probably should say "change last three symbols to what the combobox says". There's a combobox with 249 difefrent options for what there last three symbols may be changed and I need to be able to change them over and over again, say from ENG to AUS to RUS and so on.

Would someone please help me modify this code to make changes over and over again?

Workbook: https://easyupload.io/37tztt

Flutter: for loop or if-statement is not working perfectly

I want a create a live exam app. Here is some question in a list and some answer under those question. Users can select only one answer from per question. That why I write a for loop , for check box select. Answer is select perfectly, but else option of if()else condition is not working perfectly. Where is my problem ? Please someone help me.

Here is my Code-

import 'package:flutter/material.dart';

class AnswerSheet extends StatefulWidget {
  @override
  _AnswerSheetState createState() => _AnswerSheetState();
}

class _AnswerSheetState extends State<AnswerSheet> {
  List answerSheet = [
    {
      "qNo": 1,
      "question": "Who are you ?",
      "answer": [
        {"ans": "Teacher", "isSelect": false},
        {"ans": "Student", "isSelect": false},
        {"ans": "Farmer", "isSelect": false},
        {"ans": "Developer", "isSelect": false},
      ]
    },
    {
      "qNo": 2,
      "question": "Where are you from ?",
      "answer": [
        {"ans": "India", "isSelect": false},
        {"ans": "Bangladesh", "isSelect": false},
        {"ans": "India", "isSelect": false},
        {"ans": "China", "isSelect": false},
      ]
    },
    {
      "qNo": 3,
      "question": "Where you born ?",
      "answer": [
        {"ans": "Dhaka", "isSelect": false},
        {"ans": "Barguna", "isSelect": false},
        {"ans": "Patuakhali", "isSelect": false},
        {"ans": "Gazipur", "isSelect": false},
      ]
    },
  ];

  @override
  Widget build(BuildContext context) {
    double _width = MediaQuery.of(context).size.width;
    double _height = MediaQuery.of(context).size.height;
    return Scaffold(
      body: Container(
        height: _height,
        width: _width,
        child: SingleChildScrollView(
          child: Column(
            children: answerSheet.map((questionList) {
              return Padding(
                padding: const EdgeInsets.all(20.0),
                child: Column(
                  children: [
                    Row(
                      children: [
                        Text(questionList["qNo"].toString()),
                        SizedBox(
                          width: 5,
                        ),
                        Text(
                          questionList["question"],
                          style: TextStyle(fontSize: 28),
                        ),
                      ],
                    ),
                    ListView.builder(
                        shrinkWrap: true,
                        physics: NeverScrollableScrollPhysics(),
                        itemCount: questionList["answer"].length,
                        itemBuilder: (buildContext, index) {
                          var answerIndex = questionList["answer"][index];
                          return Row(
                            children: [
                              Checkbox(
                                  value: answerIndex["isSelect"],
                                  onChanged: (value) {
                                    print(
                                        "Length is ${questionList["answer"].length}");
                                    for (var i = 0;
                                        i < questionList["answer"].length;
                                        i++) {
                                      print(
                                          "$i = ${questionList["answer"].indexOf(answerIndex)}");
                                      if (i ==
                                          questionList["answer"].indexOf(
                                              questionList["answer"][index])) {
                                        setState(() {
                                          answerIndex["isSelect"] = value;
                                        });
                                      } else {
                                        setState(() {
                                          questionList["answer"][i]
                                              ["is_selected"] = false;
                                        });
                                      }
                                    }

                                    print(answerIndex["isSelect"]);
                                  }),
                              Container(
                                color: answerIndex["isSelect"] == true
                                    ? Colors.green
                                    : null,
                                child: Text(
                                  answerIndex["ans"] ?? "",
                                  style: TextStyle(fontSize: 24),
                                ),
                              )
                            ],
                          );
                        })
                  ],
                ),
              );
            }).toList(),
          ),
        ),
      ),
    );
  }
}

IF function to change data in R

So, I have a large pedigree consisting of individuals, parents, year of births and average year of birth for the individuals offspring. To be clarify with an example: for Individual 5 the year of birth is 1900. This is not possible because its parents are born in 1975 and 1977. Individual 5 also has offspring with year of birth. A common method to "fix" missing or faulty year of birth data is to subtract the generation interval from average year of birth from the offspring. So, for individual 5, average year of birth of the offspring is 1983, so 1983 - 5 = 1978. I tried to code it using the IF function, but it did not work as I got two errors (pasted below). Would case_when and mutate work better?

Indiv <- c(1:10)
Mother <- c(NA, NA, NA, 2, 3, 3, 6, 3, 8, 8)
Father <- c(NA, NA, NA, 1, 1, 1, 5, 4, 4, 9)
YOB <- c(1975, 1975, 1977, 1980, 1900, 1982, 1983, NA, 1988, 1993)
AvgYOBOff <- c(1954, 1981, 1943, 1988, 1983, 1983, NA, 1990.5, 1993, NA)
df <- data.frame(Indiv, Mother, Father, YOB, AvgYOBOff)
L = 5 #generation interval of 5 years

if(df$YOB < df$YOB[match(df$Mother, df$Indiv)] & df$YOB[match(df$Father, df$Indiv)]){
   mutate(df, YOB = AvgYOBOff - L)
}
Error in if (df$YOB < df$YOB[match(df$Mother, df$Indiv)] & df$YOB[match(df$Father,  : 
  missing value where TRUE/FALSE needed
In addition: Warning message:
In if (df$YOB < df$YOB[match(df$Mother, df$Indiv)] & df$YOB[match(df$Father,  :
  the condition has length > 1 and only the first element will be used

Is there a better and shorter way of my for loop?

i'm newbie here and this my first question. I learn basic c++ on Visual Studio 2019. I study on functions and loops.

I have a homework that wants print:

I solved it with my code of 30 lines. But I just wonder is there shorter and better way of this?

using namespace std;
int main() 
{   
        for (int j = 0; j < 5; j++)
        {
            if (j == 1)
                break;
            cout << "*";
            cout << endl;
            if (j == 2)
                break;
            cout << "**";
            cout << endl;
            if (j == 3)
                break;
            cout << "***";
            cout << endl;
            if (j == 4)
                break;
            cout << "****";
            cout << endl;
            if (j == 5)
                break;
            cout << "*****";
            cout << endl;
        }
    return 0;
}

Return simulated pricing result

I am quite new to R and try to do a pricing simulation. The goal is to have a vector with length n, that gives a percentage for the coupon that will be received. When I use print, I get exactly the result I want. However, for my subsequent calculations I cannot proceed with results in print format. I tried replacing it with return but this just gives me one result.

Any input is appreciated. Thank you very much for your help!

(package used for rgpd is POT)

bond_coupon <- function(n, l) {
     events <- rpois(n, l) #simulates the rate of arrival according to a Poisson process
     for (i in 1:length(events)){
         cat <- rgpd(events[i], loc=1000, scale=100, shape=1) #simulates the severance of each event
         if(events[i]>1){
             coupon <- prod(1-((cat-1000)/cat))
         } else if(events[i]==1){
             coupon<- 1-((cat-1000)/cat)
         } else{
             coupon<- 1.00
         }
         print(coupon)
     }
 }

TaskscheduleR not working when there is if condition in the R script

data <- read_html("https://www.amazon.in/Sony-Mirrorless-Real-time-Tracking-Vlogging/dp/B081JRT3X1/ref=sr_1_13?dchild=1&keywords=mirrorless+camera&qid=1614577648&sr=8-13")

price <- html_node(data, "#priceblock_ourprice")%>%
    html_text()

price <- gsub('[^a-zA-Z0-9.]', '', price)%>%
    as.numeric()
    
email_msg <- gm_mime()%>%
    gm_to('****@gmail.com')%>%
    gm_from("****@gmail.com")%>%
    gm_subject("DSLR price update ")%>%
    gm_text_body(paste("The price of Sony Alpha ILCE at ",
                       Sys.time(),
                       "is ", 
                       paste0("Rupees ",price),
                       "on Amazon",
                       sep = "\n"))
if (price <= 59809){
    gm_send_message(email_msg)}

I am trying to schedule it to run at every minute starting from 62 seconds from now. The task name is created successfully but no email is sent. However, when the script above is run separately it is sending an email. Where am i wrong? My taskscheduleR code is :

script <- "C:/Users/***/Documents/R/amazon_price_alerts.R"



library(taskscheduleR)


taskscheduler_create(taskname = "alert_email", 
                     rscript = script,
                     schedule = "MINUTE",
                     starttime = format(Sys.time()+62, "%H:%M"))