How to properly format a math expression before passing it to the math_expressions package in flutter?
Context
I'm using math_expressions package but there are two cases I found when it throws an error:
A. Missing an asterisk before a parenthesis.
B. Missing parenthesis within the expression.
E.g.
// Throws error
final expression = "8(3+1)"; // A
final expression = "8(3+1"; // B
// Executes correctly
final expression = "8*(3+1)";
final Parser parser = Parser();
Expression exp = parser.parse(expression);
ContextModel cm = ContextModel();
final double result = exp.evaluate(EvaluationType.REAL, cm);
I'm aware of the syntactic requirement of the package so I'd like to properly format the expression before passing it to the parser since I cannot guarantee user input will comply to the requirement mentioned before.
What I've got so far
A. Missing an asterisk before a parenthesis:
I read about the replaceAllMapped method but I don't really know how to start from here in order to add the missing asterisks when needed.
B. Missing parenthesis within the expression. (solved)
Hypothesis
A. Missing an asterisk before a parenthesis:
I think the way is to create an array of digits, search for coincidences of a digit + parenthesis and then replace it with the addition of an asterisk like this: digit + "*" + parenthesis
Any ideas on how to solve this appropriately?
I'm trying to loop through a string and count its characters in Swift. This code successfully outputs the character count, but I receive this warning:
warning: immutable value 'character' was never used; consider
replacing with '_' or removing it for character in quote {
^~~~~~~~~
_
This is my code:
var quote = "hello there"
var count = 0
for character in quote {
count = count + 1
}
print("\(count)")
Does anyone know why I have this warning? Also, is this the best way to approach this task? Thanks.
Please read the error message carefully, it tells you precisely what's wrong and what you can do.
immutable value 'character' was never used
That's indeed true, the variable character is unused. The compiler provides two fixes:
consider replacing with '_' or removing it
The latter is not an option in a loop, so use the first, replace character with an underscore
for _ in quote {
Code:
DEBUG_MODE = True # Manually change when debugging
try:
CFN_CLIENT = boto3.client('cloudformation')
except Exception as error:
print('Error creating boto3.client, error text follows:\n%s' % error)
raise Exception(error)
Question:
Template validation error: Template format error: YAML not
well-formed. (line 37, column 1)
In my case (above code) the word "try" is placed at line 37 column 1. I wonder what is not correct? Thanks.
I want to implement a Scala-style string interpolation in Scala. Here is an example,
val str = "hello ${var1} world ${var2}"
At runtime I want to replace "${var1}" and "${var2}" with some runtime strings. However, when trying to use Regex.replaceAllIn(target: CharSequence, replacer: (Match) ⇒ String), I ran into the following problem:
import scala.util.matching.Regex
val placeholder = new Regex("""(\$\{\w+\})""")
placeholder.replaceAllIn(str, m => s"A${m.matched}B")
java.lang.IllegalArgumentException: No group with name {var1}
at java.util.regex.Matcher.appendReplacement(Matcher.java:800)
at scala.util.matching.Regex$Replacement$class.replace(Regex.scala:722)
at scala.util.matching.Regex$MatchIterator$$anon$1.replace(Regex.scala:700)
at scala.util.matching.Regex$$anonfun$replaceAllIn$1.apply(Regex.scala:410)
at scala.util.matching.Regex$$anonfun$replaceAllIn$1.apply(Regex.scala:410)
at scala.collection.Iterator$class.foreach(Iterator.scala:743)
at scala.collection.AbstractIterator.foreach(Iterator.scala:1174)
at scala.util.matching.Regex.replaceAllIn(Regex.scala:410)
... 32 elided
However, when I removed '$' from the regular expression, it worked:
val placeholder = new Regex("""(\{\w+\})""")
placeholder.replaceAllIn(str, m => s"A${m.matched}B")
res2: String = hello $A{var1}B world $A{var2}B
So my question is that whether this is a bug in Scala Regex. And if so, are there other elegant ways to achieve the same goal (other than brutal force replaceAllLiterally on all placeholders)?
$ is a treated specially in the replacement string. This is described in the documentation of replaceAllIn:
In the replacement String, a dollar sign ($) followed by a number will be interpreted as a reference to a group in the matched pattern, with numbers 1 through 9 corresponding to the first nine groups, and 0 standing for the whole match. Any other character is an error. The backslash (\) character will be interpreted as an escape character and can be used to escape the dollar sign. Use Regex.quoteReplacement to escape these characters.
(Actually, that doesn't mention named group references, so I guess it's only sort of documented.)
Anyway, the takeaway here is that you need to escape the $ characters in the replacement string if you don't want them to be treated as references.
new scala.util.matching.Regex("""(\$\{\w+\})""")
.replaceAllIn("hello ${var1} world ${var2}", m => s"A\\${m.matched}B")
// "hello A${var1}B world A${var2}B"
It's hard to tell what you're expecting the behavior to do. The issue is that s"${m.matched}" is turning into "${var1}" (and "${var2}"). The '$' is special character to say "place the group with name {var1} here instead".
For example:
scala> placeholder.replaceAllIn(str, m => "$1")
res0: String = hello ${var1} world ${var2}
It replaces the match with the first capturing group (which is m itself).
It's hard to tell exactly what you're doing, but you could escape any $ like so:
scala> placeholder.replaceAllIn(str, m => s"${m.matched.replace("$","\\$")}")
res1: String = hello ${var1} world ${var2}
If what you really want to do is evaluate var1/var2 for some variables in the local scope of the method; that's not possible. In fact, the s"Hello, $name" pattern is actually converted into new StringContext("Hello, ", "").s(name) at compile time.
I want to split the following Scala code line like this:
ConditionParser.parseSingleCondition("field=*value1*").description
must equalTo("field should contain value1")
But which is the line continuation character?
Wrap it in parentheses:
(ConditionParser.parseSingleCondition("field=*value1*").description
must equalTo("field should contain value1"))
Scala does not have a "line continuation character" - it infers a semicolon always when:
An expression can end
The following (not whitespace) line begins not with a token that can start a statement
There are no unclosed ( or [ found before
Thus, to "delay" semicolon inference one can place a method call or the dot at the end of the line or place the dot at the beginning of the following line:
ConditionParser.
parseSingleCondition("field=*value1*").
description must equalTo("field should contain value1")
a +
b +
c
List(1,2,3)
.map(_+1)