How to use Map in BroadcastProcessFunction in scala? - stream

I am trying to create a rulesource from http endpoint and broadcast that rule and match with each event with the rule and get rule as well as the event.My rule is of Map[String, String] so how to use that and get it broadcasted.
Below is the class I have defined :
import com.snowplowanalytics.snowplow.analytics.scalasdk.Event
import org.apache.flink.api.common.state.MapStateDescriptor
import org.apache.flink.streaming.api.functions.co.BroadcastProcessFunction
import org.apache.flink.util.Collector
class MapFunction extends BroadcastProcessFunction[Event, Map[String, String], (Event, String)] {
private lazy val ruleBroadcastState =
new MapStateDescriptor("rules", classOf[String], classOf[String])
override def processElement(
value: Event,
ctx: BroadcastProcessFunction[Event, Map[String, String], (Event, String)]#ReadOnlyContext,
out: Collector[(Event, String)]
): Unit = {
val state = ctx.getBroadcastState(ruleBroadcastState)
if (state.contains(value.app_id.getOrElse("unidentified"))) {
out.collect(value, state.get(value.app_id.getOrElse("unidentified")))
}
}
override def processBroadcastElement(
rule: Map[String, String],
ctx: BroadcastProcessFunction[Event, Map[String, String], (Event, String)]#Context,
out: Collector[(Event, String)]
): Unit = {
val state = ctx.getBroadcastState(ruleBroadcastState)
state.put("test-123", "test-stream")//this is for testing only actual is the Map iteration
}
}
Here in processBroadcastElement rule is of Map[String, String] so when I put the values in state do I have to iterate each element and put or what I have to do?
Rule is like below:
Map("test-123" -> "test-stream", "Original-app-2876" -> "prod-v0-model", "Original-app-2987" -> "prod-v1-model")

Try the putAll method.
https://github.com/apache/flink/blob/eb58aa1ab7bdbbcbf07de9726b4c8a81d8e5ab0e/flink-core/src/main/java/org/apache/flink/api/common/state/BroadcastState.java#L54
org.apache.flink.api.common.state.BroadcastState#putAll

Related

jetpack compose LazyLayout parameters is not Specified

I want to develop a LazyLayout in jetpack compose
#ExperimentalFoundationApi
#Composable
fun LazyLayout(
itemsProvider: LazyLayoutItemsProvider!,
modifier: Modifier! = Modifier,
prefetchState: LazyLayoutPrefetchState? = null,
measurePolicy: (#ExtensionFunctionType LazyLayoutMeasureScope.(Constraints) ->
MeasureResult)?
): Unit
there is two necessary parameters, itemsProvider and measurePolicy and this is all information about itemsProvider parameter in document:
#param itemsProvider provides all the needed info about the items which could be used to compose and measure items as part of [measurePolicy].
I don't know how to provide this parameter for LazyLayout.
any idea how it works?
You have to provide only "itemsProvider" parameter by creating object like this:
LazyLayout(
itemsProvider = object : LazyLayoutItemsProvider {
override fun getContent(index: Int): #Composable () -> Unit {
return {
//your content
}
}
override val itemsCount: Int
get() = //count content
override fun getKey(index: Int): Any = index
override val keyToIndexMap: Map<Any, Int> = emptyMap()
override fun getContentType(index: Int): Any? = null
},
//modifier = modifier
//.padding(paddingValues)
//.verticalScroll(state = state, flingBehavior = NoFlingBehavior)
) { constraints ->
//do whatever you want
}

How to pass a composable content parameter in data class

I need to pass a compose content parameter in data class. For example a button can render when added into this content.
data class ContentData {
val content: #Composable ()-> Unit
}
This is working but when I get the app background I am getting parcelable exception. How to solve this problem.
One possible explanation I think that will occur related with a parcelable error, happens if you try to pass such object between activities as extras through Intent. Consider not use Composable as parameters in objects. Instead, try to represent the parameters of your Composable with a model which contains the parameters.
// your compose function
#Composable
fun Item(content: String = "Default", padding: Dp){
// ...
}
// Ui Model which contains your data (instead of have a weird composable reference) as a parcelable.
data class ContentData(
val content: String = "Default",
val paddingRaw: Int = 0
) : Parcelable {
constructor(parcel: Parcel) : this(
parcel.readString().orEmpty(),
parcel.readInt()
) {
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(content)
parcel.writeInt(paddingRaw)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<ContentData> {
override fun createFromParcel(parcel: Parcel): ContentData {
return ContentData(parcel)
}
override fun newArray(size: Int): Array<ContentData?> {
return arrayOfNulls(size)
}
}
}
// Example if you need the model between activities through the intent as an extra.
val data = ContentData("your content", 11)
val intent = Intent().apply {
putExtra("keyContentData", data)
}
//The way of get and use your model.
val contentData = intent.extras?.get("keyContentData") as ContentData
#Composable
fun ParentComponent(){
// ...
Item(
contentData?.content.orEmpty(),
contentData?.paddingRaw?.dp ?: 0.dp
)
// ...
}

Swift Static Variables reach with dynamic parameters

I want to use static variables for APIrequests. This API runs with Get Method and I have to run with some parameters with dynamically. So How can I change this parameters ?
For Example :
static let productDetail = "http:.../ProductDetail?productID=101&subNo=148"
I want to reach with XClass.productDetail also change productID=101 and subNo=148 with needed parameters.
You could make it a function and then pass the productID and subNo you want as parameters:
static func productDetail(productID: Int, subNo: Int) -> String {
return "http:.../ProductDetail?productID=\(productID)&subNo=\(subNo)"
}
If you have more parameters, you could also pass them as dictionary:
func productDetail(parameters: [String: String]) -> String {
var str = "http:.../ProductDetail?"
parameters.forEach {
str.append("\($0.key)=\($0.value)&")
}
str = String(str.dropLast()) // drops last '&' char
return str
}
Usage:
productDetail(parameters: ["productID": "108", "subNo": "93"])
// returns "http:.../ProductDetail?productID=108&subNo=93"

Why is there an error: type mismatch in my code?

class Club(val name: String, val stadium: String) {
// Produces a textual description of the club (which consists of just the club's name).
override def toString = this.name
}
class Match(val home: String, val away: String) {
...
}
val match1 = new Match(club2, club1)
Why doesn't val match1 work?

In swift, can a function be a type?

While researching XCTAssert methods by pressing command+click, it looks like they underlying method is a function that has a type (a generic type referred to as T, that conforms to the Equatable protocol). Am I saying this correctly, and if so how do functions comform to protocols? Are functions types?
public func XCTAssertEqual<T : Equatable>(_ expression1: #autoclosure () throws -> ArraySlice<T>, _ expression2: #autoclosure () throws -> ArraySlice<T>, _ message: #autoclosure () -> String = default, file: StaticString = #file, line: UInt = #line)
This line is the most confusing which I'm trying to explain above:
func XCTAssertEqual<T : Equatable>`
Every function has a specific function type, made up of the parameter types and the return type of the function.
typealias FooType = (Int, String)->String
func foo(i: Int, s: String)->String {
return s + "_\(i)"
}
func bar(foo0: FooType)->String {
return foo0(100, "alpha")
}
print(bar(foo)) // alpha_100
let f:FooType = { i, s in
return s + "_\(i)"
}
print(f(200, "beta")) // beta_200
an appendix, especially for Brandon :-)
let farr:[()->Int] = [{return 1}, {return 2}, {return 3}]
for f in farr {
print(f())
/*
1
2
3
*/
}
appendix 2, for Brandon
func f1()->Int {
return 1
}
func f2()->Int {
return 2
}
let farr2:[()->Int] = [f1, f2]
for f in farr2 {
print(f())
/*
1
2
*/
}
app 3 :-)
let farr2 = [f1, f2]
for f in farr2 {
print(f())
/*
1
2
*/
}
from apple docs
Every function in Swift has a type, consisting of the function’s
parameter types and return type. You can use this type like any other
type in Swift, which makes it easy to pass functions as parameters to
other functions, and to return functions from functions. Functions can
also be written within other functions to encapsulate useful
functionality within a nested function scope.

Resources