How to print boolean value in Go? - boolean

As we have %d for int. What is the format specifier for boolean values?

If you use fmt package, you need %t format syntax, which will print true or false for boolean variables.
See package's reference for details.

%t is the answer for you.
package main
import "fmt"
func main() {
s := true
fmt.Printf("%t", s)
}

Use %t to format a boolean as true or false.

Some other options:
package main
import "strconv"
func main() {
s := strconv.FormatBool(true)
println(s == "true")
}
package main
import "fmt"
func main() {
var s string
// example 1
s = fmt.Sprint(true)
println(s == "true")
// example 2
s = fmt.Sprintf("%v", true)
println(s == "true")
}
https://golang.org/pkg/fmt#Sprint
https://golang.org/pkg/fmt#Sprintf
https://golang.org/pkg/strconv#FormatBool

Related

Cadence Workflow ZonedDateTime Args Zone ID Conversion

I have a workflow with ZonedDatetime of UTC as an argument. During the unit test with test env, I see the UTC zone is dropped while running the workflow. What would be the cause of this behavior?
[UPDATE] It turns out the timezone is not dropped, but somehow converted to Zone id of "Z" instead of the original "UTC", although they're basically the same. Sample code,
data class WorkflowArgs(
val currentTime: ZonedDateTime
)
class WorkflowImpl {
override fun execute(workflowArgs: WorkflowArgs) {
activityStub.doSomeActivity(
workflowArgs.currentTime // Zone ID of "Z"
)
}
}
WorkflowClient.start(workflowStub::execute, WorkflowArgs(ZonedDateTime.now(ZoneId.of("UTC"))) // Zone ID of "UTC"
You need to customize the DataConverter.
DataConvert is for converting between your argument(Class) and byte array so that your client can send the argument to Cadence server, and then server send it to workflow worker.
For example, you can do something like below.
NOTE that this is just an example for you to implement DataConverter. To encode/decode ZonedDataTime you need to find out a way to do it correctly. You may need to refer to Spring Data JPA - ZonedDateTime format for json serialization
data class WorkflowArgs(
val currentTime: ZonedDateTime
)
fun main1() { // this doesn't work
val dataConverter = JsonDataConverter.getInstance()
val args = WorkflowArgs( ZonedDateTime.now())
println(args.currentTime.zone)
val encoded = dataConverter.toData(args)
val decoded: WorkflowArgs = dataConverter.fromData(encoded, args.javaClass, args.javaClass)
println(decoded.currentTime.zone)
/**
* Results:
America/Los_Angeles
Exception in thread "main" com.uber.cadence.converter.DataConverterException: when parsing:"{"currentTime":{"dateTime":{"date":{"year":2021,"month":9,"day":13},"time":{"hour":9,"minute":14,"second":46,"nano":517000000}},"offset":{"totalSeconds":-25200},"zone":{"id":"America/Los_Angeles"}}}" into following types: [class com.uber.cadence.converter.WorkflowArgs]
at com.uber.cadence.converter.JsonDataConverter.fromData(JsonDataConverter.java:111)
at com.uber.cadence.converter.TestZonedDatatimeKt.main(TestZonedDatatime.kt:14)
at com.uber.cadence.converter.TestZonedDatatimeKt.main(TestZonedDatatime.kt)
Caused by: java.lang.RuntimeException: Failed to invoke java.time.ZoneId() with no args
at com.google.gson.internal.ConstructorConstructor$3.construct(ConstructorConstructor.java:113)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:212)
...
at com.uber.cadence.converter.JsonDataConverter.fromData(JsonDataConverter.java:109)
... 2 more
*/
}
fun main() { // you need to implement another DataConverter like this
val dataConverter = MyDataConvert()
val args = WorkflowArgs( ZonedDateTime.now())
println(args.currentTime.zone)
val encoded = dataConverter.toData(args)
val decoded: WorkflowArgs = dataConverter.fromData(encoded, args.javaClass, args.javaClass)
println(decoded.currentTime.zone)
/**
Resutls:
America/Los_Angeles
America/Los_Angeles
**/
}
class MyDataConvert:DataConverter{
val originalDataConverter = JsonDataConverter.getInstance()
override fun toData(vararg value: Any?): ByteArray {
if( (value.size == 1) && (value[0] is WorkflowArgs)){
val v = value[0] as WorkflowArgs
val zoneId = v.currentTime.zone.id
val br = zoneId.toByteArray()
return br
}else{
return originalDataConverter.toData(value)
}
}
override fun <T : Any?> fromData(content: ByteArray?, valueClass: Class<T>?, valueType: Type?): T {
if(valueClass!!.canonicalName.contains("WorkflowArgs") ){
val zi = String(content!!)
val zoneId: ZoneId = ZoneId.of(zi)
val dt = ZonedDateTime.now(zoneId)
return WorkflowArgs(dt) as T
}else{
return originalDataConverter.fromData(content, valueClass, valueType)
}
}
override fun fromDataArray(content: ByteArray?, vararg valueType: Type?): Array<Any> {
if( (valueType.size == 1) && (valueType[0]!!.typeName.contains("WorkflowArgs"))){
val zi = String(content!!)
val zoneId: ZoneId = ZoneId.of(zi)
val dt = ZonedDateTime.now(zoneId)
val arr = arrayOf(WorkflowArgs(dt))
return arr as Array<Any>
}
return originalDataConverter.fromDataArray(content, *valueType)
}
}
This is another example of implmenting DataConverter: https://github.com/uber/cadence-java-samples/pull/37

json4s always escapes unicode character €

I try pretty-writing a JString containing a € character with json4s as follows:
import org.joda.time.format.ISODateTimeFormat
import org.joda.time.{DateTime, DateTimeZone}
import org.json4s.native.Serialization.writePretty
import org.json4s.{DateFormat, DefaultFormats, Formats, JString}
import java.util.{Date, TimeZone}
object Json4sEncodingTest {
val formats = new Formats {
val dateFormat: DateFormat = new DateFormat {
override def parse(s: String): Option[Date] =
try {
Option(
DateTime
.parse(s, ISODateTimeFormat.dateTimeParser().withZoneUTC())
.withZone(DateTimeZone.forID(timezone.getID))
.toDate
)
} catch {
case e: IllegalArgumentException => None
}
override def format(d: Date): String = DefaultFormats.lossless.dateFormat.format(d)
override def timezone: TimeZone = DefaultFormats.lossless.dateFormat.timezone
}
override def alwaysEscapeUnicode: Boolean = false
}
def main(args: Array[String]): Unit = {
println(writePretty(JString("2€"))(formats))
}
}
This results in:
"2\u20ac"
My expected result would be:
"2€"
I found that in org.json4s.ParserUtil.quote characters between \u2000 and \u2100 are always escaped.
Question: Why is this the case?
json4s version: 3.7.0-M7
scala version: 2.12.11
As elaborated in this github issue, it is impossible currently to do this using json4s native. The code that checks if to escape or not is:
(c >= '\u0000' && c <= '\u001f') || (c >= '\u0080' && c < '\u00a0') || (c >= '\u2000' && c < '\u2100')
while € doesn't satisfy this condition. One possible solution (well, sort of solution) is using jackson instead of native. Then this will work:
import org.json4s.jackson.JsonMethods._
import org.json4s.JsonAST.JString
println(pretty(render(JString("2€"))))
Code run at Scastie.

Converting Spark UDF written in SCALA to JAVA

Below is my spark UD, can anyone help me to convert this into java?
val customUDF = udf((array: Seq[String]) => {
val newts = array.filter(_.nonEmpty)
if (newts.size == 0) null
else newts.head
})
Something like:
UDF2 my_udf = new UDF2<WrappedArray<String>, String>() {
public String call(WrappedArray<String> arr) throws Exception {
String[] newts = arr.filter(_.nonEmpty)
if (newts.length == 0) {
return null
} else { newts[0] }
}
};
spark.udf().register("my_udf", my_udf, DataTypes.StringType);
You can do it in two ways
Inline using Lambda i.e. Scala style
Or you can define a method and register it.
import org.apache.spark.sql.SparkSession;
import org.apache.spark.sql.api.java.UDF0;
import org.apache.spark.sql.api.java.UDF1;
import org.apache.spark.sql.types.DataTypes;
import java.util.List;
public class SimpleUDF {
public static void main(String[] args) {
SparkSession spark = SparkSession.builder().master("local[*]").getOrCreate();
spark.sqlContext()
.udf()
.register("sampleUDFLambda", (List<String> array) -> array.stream().filter(element ->
!element.isEmpty()).findFirst().orElse(null), DataTypes.StringType);
}
//Or you can define a function
private UDF1< List<String>,String> sampleUdf()
{
return ( array ) -> array.stream().filter(element ->
!element.isEmpty()).findFirst().orElse(null);
}
}

Reverse the input in Chisel3

I want to reverse the input signal in Chisel3. For instance, if the input is 12345678, I want the output to be 87654321. Can anyone please help me with this?
Code:
import chisel3._
import chisel3.util._
import chisel3.iotesters.{ChiselFlatSpec, Driver, PeekPokeTester}
import chisel3.util.Reverse
class Length extends Module {
val in = Input(UInt(64.W))
val out = Output(UInt(8.W))
out := Reverse(in.x)
}
The solution which was discussed in comments:
import chisel3._
import chisel3.util.Reverse
class Length extends Module {
val io = IO(
new Bundle {
val in = Input(UInt(64.W))
val out = Output(UInt(8.W))
}
)
io.out := Reverse(io.in)
}

not found value ~ in Scala

I am defining some paths but then i run into this error for the tilde ~ right before " pathPrefix(start)" . I am a bit new in Scala and so something do not click right away. thanks
not found:value ~
Is it because i need to define a function? If so why?
import
akka.http.scaladsl.marshallers.xml.ScalaXmlSupport.defaultNodeSeqMarshaller
import akka.http.scaladsl.server.{ HttpApp, Route }
import akka.http.scaladsl.model.StatusCodes
import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import com.typesafe.config.ConfigFactory
import akka.event.Logging
import akka.http.scaladsl.model._
object ABC extends HttpApp with App {
implicit val actorSystem = ActorSystem()
implicit val matter = ActorMaterializer()
val start = "hello"
val Routing= {
path(start) {
redirect( Uri(start+ "/index.html"), StatusCodes.PermanentRedirect )
}
~
pathPrefix(start) {
content
}
}
val content =
{
get
{
path("html") {
getFromResource("src/html") }
}
}
}
Make sure you have the following import:
import akka.http.scaladsl.server.Directives._
Once you added the import as per #chunjef answer, also note that ~ is an infix operator, so it comes with all the "quirks" of it.
To sort out your routes, you can avoid placing the ~ in a new line
val Routing= {
path(start) {
redirect( Uri(start+ "/index.html"), StatusCodes.PermanentRedirect )
} ~
pathPrefix(start) {
content
}
}
or you can wrap the concatenated routes in brackets
val Routing= {
(path(start) {
redirect( Uri(start+ "/index.html"), StatusCodes.PermanentRedirect )
}
~
pathPrefix(start) {
content
})
}