Kotlin // Solve the example in a line - kotlin

How to solve an example in a string?
Let's say we have val example : String = "3+5"
So how do I solve this example? Or if val example : String = "3*5/3"

Two ways to achieve it:
Keval - 3rd party dependency
You can either use Keval.eval("(3+4)(2/8 * 5) % PI") or as an extension function on String, "(3+4)(2/8 * 5) % PI".keval(). This will return the calculated value as Double. For your example, "3*5/3".keval().
To use it, add implementation("com.notkamui.libs:keval:0.8.0") in dependencies in app level build.gradle file and sync gradle. Then, use it in any file as mentioned in the above para, put the cursor on the line and press Alt + Enter (or hover for suggestions) to import the necessary imports.
Look into its Readme.md on the provided link for more usage and implementation details.
Custom String parsing using BODMAS rule
You can split the string using the BODMAS rule, parse the split array as int/double, if it throws exception, it means the substring is an expression too, again split it using BODMAS, parse and perform the calculation.

Related

Using Kotlin Symbol Processing API to compile String expression

I have a requirement where I need to make operation on Strings. This operation is expensive at runtime, and need to be made only on static expression. Therefore I want to do it at compile time.
Since the operation need to be made a lot of time, in many different modules, having to copy paste, doing manually the conversion, to past the result in the source code is long and slow.
I would like to add an annotation on the Strings which is required to convert, and have a file generated with all the results.
An example could be
val original = #Convert "Hello world"
functionRequiringTheConvertedStringValue(DATA.get(original))
original being equal to "Hello world" and the Data.get function giving the result.
With the DATA class being a static file containing all the string converted and able to fetch them.
Therefore I want to use an annotation processing, but when reading the examples, and the examples, I can't find a way to achieve the logic I want to implement.
I created a SymbolProcessor, but I am not able to get any expression, I can only get functions (KSFunctionDeclarationImpl) and classes (KSClassDeclarationImpl).
...
override fun process(resolver: Resolver): List<KSAnnotated> {
val symbols = resolver.getSymbolsWithAnnotation("com.example.annotation.Convert")
symbols.forEach {
logger.warn("class: ${it.javaClass.name}")
}
val ret = symbols.filter { !it.validate() }.toList()
return ret
}
When I use the annotation on an expression, I do not get it using the getSymbolsWithAnnotation.
My question being, how to get the expression and their value which are annotated by the annotation I created.
Edit:
Seems to be an open issued : https://github.com/google/ksp/issues/1194

Kotlin Native how to convert ByteArray to String?

I was playing with the kotlin-native samples.
I wonder how I could get String from pinned ByteArray. Just want to print it in the console.
If you need a solution for the JVM, since stringFromUtf8 is only available for the native platform, use toString with a Charset as argument:
val byteArray = "Hello World".toByteArray(Charsets.UTF_8)
val str = byteArray.toString(Charsets.UTF_8)
If you specifically only want to target native, use Sin's solution.
It seems that this API has changed
Now just use this: string.toUtf8(start, end)
https://github.com/JetBrains/kotlin-native/commit/cba7319e982ed9ba2dceb517a481cb54ed1b9352#diff-45a5f8d37067266e27b76d1b68f01173
Legacy version:
Use stringFromUtf8
/**
* Converts an UTF-8 array into a [String]. Replaces invalid input sequences with a default character.
*/
fun ByteArray.stringFromUtf8(start: Int = 0, size: Int = this.size) : String =
stringFromUtf8Impl(start, size)
See here.
And if the byteArray is like CPointer<ByteVar> by interoperating C APIs, pleace use .toKString() in Kotlin-Native
The OKIO library has a helper method for this commonToUtf8String
One can simply copy the method code don't need to add the entire lib just for this.
Another solution that could be used everyone but especially makes sense looking for a Kotlin Multiplatform solution and using ktor library already is using io.ktor.utils.io.core.String function directly without adding extra third pary library or extra actual class implementation. For example:
Your build.gradle.kts for all platforms:
implementation("io.ktor:ktor-client-core:${Versions.ktor}")
implementation("io.ktor:ktor-client-android:${Versions.ktor}")
implementation("io.ktor:ktor-client-apache:${Versions.ktor}")
implementation("io.ktor:ktor-client-ios:${Versions.ktor}")
Then use it
io.ktor.utils.io.core.String(byteArray, offset, length, Charsets.UTF_8)

How to pass a string to a var without escape symbol in Kotlin?

I hope to pass the string {"name":"My Settings 1"} to a var aa
I have to write it using the code var aa=" {\"name\":\"My Settings 1\"} "
Is there a simple way in Kotlin when I use Android Studio 3.0 ?
I know <![CDATA[...]]> is good for XML content
The simplest thing you can do in Kotlin is use raw strings with triple quote marks:
val a = """{"name":"My Settings 1"}"""
For a tooling solution instead of a language solution (so this works both in Kotlin and Java), you can use language injection in Android Studio or IntelliJ.
Create a string, and invoke intention actions on it with Alt + Enter. Select Inject language or reference, and then JSON.
Use Alt + Enter again, and choose Edit JSON Fragment.
Edit the raw JSON in the panel that appears on the bottom, and IntelliJ will automatically mirror its contents into the string, escaping any characters that have to be escaped.
Escaping special chars in regular Strings, like in your example, is what has to be done with Java and also Kotlin:
"{\"name\":\"My Settings 1\"}"
Kotlin offers raw Strings to evade this. In these raw Strings there's no need to escape special chars, which shows the following:
"""{"name":"My Settings 1"}"""
Raw Strings are delimited by a triple quote (""").
Read the docs here.

Workflow won't compile

I'm getting the following error when trying to execute my custom build definition (containing only 1 custom CodeActivity):
Exception Message: Expression Activity type 'CSharpReference`1' requires compilation in order to run. Please ensure that the workflow has been compiled. (type NotSupportedException)
I've tried multiple suggested answers to this error, but none of them are applicable to my activity. My CodeActivity only has a couple of methods that search through directories for specific files, and then returns a delimited string containing the file names.
I don't use any WorkflowInvoker or any DynamicActivities. For what reason would I keep getting this error?
Thanks
I had the same error on an assignment step.
System.NotSupportedException: Expression Activity type 'CSharpValue`1' requires compilation in order to run.
Please ensure that the workflow has been compiled.
The resolution was to remove the carriage returns from statement.
For example this works:
new Foo() { Bar = new Bar() { MyProp1 = "123" } }
This does not:
new Foo()
{
Bar = new Bar()
{
MyProp1 = "123"
}
}
I decided not to work in a clean xaml file, but instead to use the Default Template provided by TFS. The Default template ran my activities without errors.
I was able to fix this solution as well by using the Default Template provided by TFS, clearing all of their activities, and adding the custom activities and arguments in my original custom template.
However, more insight in to this issue, it seems to be caused by the fact that custom template use C# expressions to handle the arguments. Where as the default template is set up to use VB Expressions for it's arguments.
In my case, the language didn't matter because the values were simply strings.

VB.NET logical expression evaluator

I need to test a logical expression held in a string to see if it evaluate to TRUE or FALSE.(the strig is built dynamically)
For example the resulting string may contain "'dog'<'cat' OR (1>4 AND 4<6)". There are no variables in the string, it will logically evaluate. It will only contain simple operators = > < >< >= <= and AND , OR and Open and Close Brackets, string constants and numbers. (converted to correct syntax && || etc.)
I currently acheive this by creating a jscipt function and compiling it into a .dll. I then reference the .dll in my VB.NET project.
class ExpressionEvaluator
{
function Evaluate(Expression : String)
{
return eval(Expression);
}
}
Is there a simpler method using built in .NET functions or Lamdba expressions.
I tried the demo out for this project and you might like it over you current method of evaluating. Note, it doesn't use lamdba expressions or any build it .NET methods.
http://web1.codeproject.com/KB/vb/expression_evaluator.aspx?msg=1151870
try out: http://www.codeproject.com/KB/cs/ExpressionEval.aspx
More guidance :http://www.thefreakparade.com/2008/07/evaluating-expressions-at-runtime-in-net-c/
Good one: http://flee.codeplex.com/
Boolean Example which you are looking for : http://flee.codeplex.com/wikipage?title=BooleanExpression&referringTitle=Examples (ignore the variable adding part as you are not looking for variable)