How to store input from keyboard into variable? - autohotkey

I am currently using Random function in Autohotkey to generate random and save into variable rand but if user presses R.
my question is below this code
R::
Random, rand, 1, 3
Msgbox, %rand%
if (rand = "1")
{
;SAM()
}
else if (rand = "2")
{
;AAJ()
}
else if (rand = "3")
{
;HEAD()
}
else
{
;Msgbox, else
}
I also want to add code where if user presses 1 it will, may if I can add OR expression in if statement such as
if (rand = "1" || keyboardinput = "1" )
{
;SAM()
}

Why not use the same approach u used with your code for generating random numbers.
1::
if( rand == 1)
{
tooltip, hello
}
return
You are also missing a return at the end of the first part of your code, unless you want the script to start executing things it shouldn't.

Related

JS timeout causes eval exception

For some reason, one of my JS files is triggering an unsafe-eval Content Security Policy violation on my site. I thought this odd because there is no eval() anywhere in the file. The error happens on the following line:
setTimeout(callSpecific(), (lengthMF * (number.length + 2)));
The only thing I can see here is the arithmetic on the RHS that sets the timeout value. So, I tried:
setTimeout(callSpecific(), (parseInt(lengthMF) * (parseInt(number.length) + 2)));
Same thing. The variables themselves are not even strings - they are defined as:
var lengthMF = 150;
var number = ""; // yes, this is a string but number.length is not!
Why is this triggering a CSP violation? I have other setTimeout()s on the page and this seems to be the only problematic one. The weird thing is replacing the arithmetic expression temporarily with a constant (e.g. 50) does not cause the issue to go away.
If it's necessary, callSpecific() looks something like this:
function callSpecific() {
if (number == 0) {
operatorRing();
} else if (number.length == 2 && number.charAt(1) == 0) {
playReorder();
} else if (number.length == 3) {
//
} else if (number.length <7 || number.length > 11) {
//
} else if (number.length == 11 && (number.charAt(4) == 1 || number.charAt(4) == 0)) {
//
}
}

Combine if statement and for loop such that loop only gets executed once per every execution of if statement in swift

I'm trying to understand swift and therefore try to come up with simple command line games: in this game a player has to guess a secret word within 6 attempts by typing something in the command line, but every time he gets it wrong, a statement prints the number of his wrong attempts:
let response = readLine()
if response != "secret word" {
for n in 1...6 {
print(n)
}
}
else {
print("you are right!")
}
Now I know that my code will print all lines once the condition is not true, but I'm looking for a way to only print one item out of the four loop for every if statement consecutively.
I think a while loop works pretty well. Maybe something like this:
print("Welcome to the input game!\n\n\n\n")
var remainingTries = 5
let dictionary = ["apple", "grape", "pear", "banana"]
let secretWord = dictionary.randomElement()
print("Please guess a fruit")
while remainingTries > 0 {
remainingTries -= 1
let response = readLine()
if response == secretWord {
print("You got it!")
remainingTries = 0
} else if remainingTries <= 0 {
print("Too bad, you lose!")
remainingTries = 0
} else {
print("Incorrect. Tries remaining: \(remainingTries)")
}
}

Autohotkey iterate through loop, but only return value if key matches input

Suppose I have the following
^!r::
InputBox, input, Enter the string
if (input = "trip")
{
TripFunction()
}
else if (input = "leave")
{
LeaveFunction()
}
else
{
Msgbox, That word isnt defined.
}
Return
But, anticipating having to add a lot of different cases to test for, I figure the best idea is to put this into an array, and iterate through the array, looking for the matching key, returning the value (the function), and no longer iterating through the dictionary. So now, I have something like this:
^!r::
InputBox, input, Enter the string
dict = { "trip": TripFunction(), "leave": LeaveFunction() }
for k, v in dict
{
...
see if k = "trip", if so, return TripFunction(), if not, go to next
item in array
...
}
Return
The trouble I'm having is once it successfully matches akey in the dictionary, it will return all of the associated values. What should I put in the brackets to do what I intend?
You're using the wrong equal sign operator (use := for non-literal assignments instead of =)
Also, in the line dict = { "trip": TripFunction(), "leave": LeaveFunction() }, tripfunction aind leavefunction are executed, which you probably do not want.
Try:
^!r::
InputBox, input, Enter the string
dict := { "trip": "TripFunction", "leave": "LeaveFunction" }
for k, v in dict
{
if(k==input) {
%v%() ; documentation: https://autohotkey.com/docs/Functions.htm#DynCall
break
}
}
Return
TripFunction() {
msgbox trip
}
LeaveFunction() {
msgbox leave
}

While loop for renaming duplicate name

I am trying to implement some code that will automatically rename a users inputted name if the name they enter has already been submitted. I have it working to some extent, however the issue is that if the loop iterates over more than once, then you end up with the name being renamed to something like this 'Clothes (1) (2) (3)'
Here is the code that I have at the moment:
if nameLength == 0 {
fade()
entryWarningLabel.text = "Please enter a transaction name."
} else if arrayObject.paymentsArray().containsObject(transactionName) == true {
if autoAdjust == true {
var index = 1
while arrayObject.paymentsArray().containsObject(transactionName) == true {
transactionName = "\(transactionName) (\(index))"
index = index + 1
}
popToVC()
enterButtonCode()
} else {
fade()
entryWarningLabel.text = "You already have a transaction named '\(transactionName)'."
}
} else if nameLength > 0 {
popToVC()
enterButtonCode()
}
The first else if is the relevant part of the code.
How can I rename transactionName without ending up with multiple values in brackets?
This is because you are using transactionName that may have been modified by the prior iterations of the loop. You should use the original transactionName instead:
let originalName = transactionName;
while arrayObject.paymentsArray().containsObject(transactionName) {
transactionName = "\(originalName) (\(index))"
index = index + 1
}
}

How to write a standard calculator?

I am preparing a task for a C# course I teach where the students have to write a calculator in order to learn how to work with basic GUI. However in the process I found that I cannot reproduce the behavior of a standard calculator in full. My implementation always misses some corner cases and the output differs from what the Windows Calculator does in its Standard mode.
The Wikipedia article describes the working of the calculator but it does not list how it handles corner cases. It says that a calculator has two registers X and Y and X is always displayed on the screen but it does not describe how values are pushed from one register to the other in corner cases.
Examples of corner cases include the input sequences:
"3 * 2 = =" - should display 6 and then 12
"3 - =" which results in 0 on the Windows Calculator but in -3 on my implementation
"3 * 2 = + 3"
"3 * 2 = 3 =" which strangely results in 6 on the Windows Calculator
Of course I can handle the corner cases using enough flags but I am sure standard calculators were implemented the way they were implemented because this way was the simplest. I cannot think of a simple way to implement all the cases so I am probably doing it wrong. I have a single variable called previousValue I use in place of the Y register and I parse the textbox value when doing calculation to simulate the X register. I also have a variable which indicates if the next digit input should override the textbox (X register) value. There is also a variable for the current operation which is initialized to None. Basically I force calculation every time an operator button or = is pressed and I set the input flag to true.
Here is the code for digit input (AddInput), operation input (InputOperation), = button click (btnCalculate_Click) and the methods they call into.
private void AddInput(string input)
{
if (shouldOverrideDigits)
{
previousNumber = Decimal.Parse(txtDigits.Text);
txtDigits.Text = input;
shouldOverrideDigits = false;
}
else
{
txtDigits.Text += input;
}
}
private void InputOperation(CalculatorOperations operation)
{
if (!shouldOverrideDigits)
{
Calculate();
}
currentOperation = operation;
}
private void btnCalculate_Click(object sender, EventArgs e)
{
if (shouldOverrideDigits)
{
Calculate();
}
else
{
decimal currentNumber = Decimal.Parse(txtDigits.Text);
Calculate();
previousNumber = currentNumber;
}
}
private decimal Calculate()
{
decimal currentNumber = Decimal.Parse(txtDigits.Text);
decimal result;
switch (currentOperation)
{
case CalculatorOperations.None:
{
result = currentNumber;
} break;
case CalculatorOperations.Addition:
{
result = previousNumber + currentNumber;
} break;
case CalculatorOperations.Subtraction:
{
result = previousNumber - currentNumber;
} break;
case CalculatorOperations.Multiplication:
{
result = previousNumber * currentNumber;
} break;
case CalculatorOperations.Division:
{
result = previousNumber / currentNumber;
} break;
default:
{
throw new Exception("Unexpected operation type");
}
}
shouldOverrideDigits = true;
txtDigits.Text = result.ToString();
return result;
}
Can someone help with a simple solution? If the original calculators were able to handle everything with what is effectively three variables it is unlikely that the solution in a modern language needs much more.
Interestingly every article on implementing a calculator on the Internet I could find does it wrong.