问:
TypeConverter / mapper for the entire entity class in Room persistence?
I am trying to have a TypeConverter for the entire Entity class. All the examples I have seen so far only apply TypeConverter to individual fields of the entity, so I wonder if this is even possible?

In this contrieved example, I want to work with User class in the Dao, but room should save it as UserEntity

```<code>object TestTypeConverter{
    @TypeConverters
    fun entityToUser(entity: UserEntity) = User(entity.id, entity.username, entity.picUrl, SomeBitmapLoader(entity.pic), OtherInfoFromUsername(entity.username))

    @TypeConverters
    fun userToEntity(user: User) = UserEntity(user.id, user.username, user.picUrl)

}

@Entity(tableName = "users")
data class UserEntity(
        val id: Int,
        val username: String,
        val picUrl: String,
)

@Dao
@TypeConverters(TestTypeConverter::class)
interface UsersDao {
    @get:Query("SELECT * FROM users")
    val all: List<User>
}
</code>```

I get "Cannot figure out how to read this field from a cursor" when I build.

答:
so I wonder if this is even possible?

No (with TypeConverters assuming the object is to only store partial data e.g. to save image paths but not  the image) but Yes you can get a List<User> (with the missing/un-stored data).

NO with TypeConverters

Type Converters are all about individual fields and converting from a complex type to a single type that can be stored as a single column in the database.

by complex type, a type that is not :-

an integer (INTEGER type in SQLite) type (Int, Long, Byte etc), or

a decimal (REAL type in SQLite) type (Double, Float etc), or

a String (TEXT type in SQLite), or

a ByteArray (BLOB type in SQLite).

In your case the Entity (table in database terms) consists of Int, and String types, which are types that can be stored in columns without requiring conversion. So the Type converters are redundant.

Now if you had an entity such as (not that this is probably what you want) :-

```<code>@Entity(tableName = "users")
data class UserEntity(
        @PrimaryKey
        val id: Int=0,
        val username: String,
        val picUrl: String,
        val user: User //<<<<< TyepConverter required
)
</code>```

Then because the user field is a complex type then a TypeConverter would be expected for the user field as it's a complex type.

However, the TypeConverter userToEntity  would NOT be valid/suitable/usable because it converts from a user (complex type) to a userEntity (complex type).

YES if List<User> is the goal.

Extracting a List may be possible BUT it is not TypeConverters that would convert the picUrl to the pic (ByteArray/Bitmap). TypeConverters are purely for converting data that is stored between simple and complex types.

Assuming that the User class is :-

```<code>data class User(
    var id: Int,
    var username: String,
    var picUrl: String,
    var pic: ByteArray,
    var otherInfoFromUserName: String
)
</code>```

Then you could get a List if you let Room know that you want to build this from the data extracted.

What Room needs to have is matching fields and columns. So SELECT * From users will return 3 columns:-

id,

username, and

picUrl

whilst List<User> will, if as above,want 5 columns.

You could use a query such as SELECT *, zeroblob(0) AS pic, 'whatever'||username AS otherInfoFromUserName FROM users and this could then return a List BUT pic will be a ByteArray of 0 elements AND otherInforForUserName will be whatever followed by the username.

For just the 3 columns, you could have @Ignore annotation for the pic and otherInfoFromUserName e.g.

```<code>data class User(
    var id: Int,
    var username: String,
    var picUrl: String,
    @Ignore
    var pic: ByteArray,
    @Ignore
    var otherInfoFromUserName: String
)
</code>```

along with a Constructor that allowed construction of a User from those three values. e.g.

```<code>data class User(
    var id: Int,
    var username: String,
    var picUrl: String,
    @Ignore
    var pic: ByteArray,
    @Ignore
    var otherInfoFromUserName: String
)  {

    constructor(id: Int, username: String, picUrl: String): this(id = id, username = username, picUrl = picUrl, pic = byteArrayOf(), otherInfoFromUserName = "")
}
</code>```

and return a List<User> in which case pic would be an empty ByteArray and otherInfoFromUserName would be an empty String.

You could then have functions that resolve the values (pic and otherInfoFromUserName) and then apply them via the constructor e.g.

```<code>data class User(
    var id: Int,
    var username: String,
    var picUrl: String,
    @Ignore
    var pic: ByteArray,
    @Ignore
    var otherInfoFromUserName: String
)  {

    constructor(id: Int, username: String, picUrl: String): this(id = id, username = username, picUrl = picUrl, pic = byteArrayOf(), otherInfoFromUserName = "") {
        this.resolvePic()
        this.resolveOtherInfoFromUser()
    }

    fun resolvePic() {
        this.pic = byteArrayOf(0,1,2,3,4,5,6,7,8,9)
    }
    fun resolveOtherInfoFromUser() {
        this.otherInfoFromUserName = "whatever$username"
    }
}
</code>```

In which case the values would be resolved via the Constructor.

Having the resolve functions would also allow a Dao function with a body (in an abstract class as opposed to an interface) such as :-

```<code>@Dao
abstract class AllDao {

    @Insert(onConflict = IGNORE)
    abstract fun insert(userEntity: UserEntity): Long
    @Query("SELECT * FROM users")
    abstract fun getUsersAsListUser(): List<User>
    @Query("SELECT *, zeroblob(0) AS pic, 'whatever'||username AS otherInfoFromUserName FROM users ")
    abstract fun getUserEntityExpandedToUser(): List<User>

    @Query("")
    fun getResolvedUserList(): List<User> {
        val userList = getUsersAsListUser()
        for(u: User in userList) {
            u.resolvePic()
            u.resolveOtherInfoFromUser()
        }
        return userList
    }
}
</code>```

Example

Using the last User class and AllDao above then the following :-

```<code>    val db = TheDatabase.getInstance(this);
    val dao = db.getAllDao()

    dao.insert(UserEntity(1,"User1","image01"))
    dao.insert(UserEntity(2,"User2","image02"))
    dao.insert(UserEntity(3,"User3","image03"))

    for (u: User in dao.getUserEntityExpandedToUser()) {
        Log.d("DBINFO_01","Username = ${u.username} PIC URL =${u.picUrl} PIC = ${u.pic} (size = ${u.pic.size}) OTHER = ${u.otherInfoFromUserName} ")
    }
    for (u: User in dao.getUsersAsListUser()) {
        Log.d("DBINFO_01","Username = ${u.username} PIC URL =${u.picUrl} PIC = ${u.pic} (size = ${u.pic.size}) OTHER = ${u.otherInfoFromUserName} ")
    }
    for (u: User in dao.getResolvedUserList()) {
        Log.d("DBINFO_01","Username = ${u.username} PIC URL =${u.picUrl} PIC = ${u.pic} (size = ${u.pic.size}) OTHER = ${u.otherInfoFromUserName} ")
    }
</code>```

Will result in the Log, after running, including :-

```<code>2022-02-10 07:48:29.525 D/DBINFO_01: Username = User1 PIC URL =image01 PIC = [B@f1e7a3d (size = 10) OTHER = whateverUser1
2022-02-10 07:48:29.525 D/DBINFO_01: Username = User2 PIC URL =image02 PIC = [B@166d232 (size = 10) OTHER = whateverUser2
2022-02-10 07:48:29.525 D/DBINFO_01: Username = User3 PIC URL =image03 PIC = [B@17eeb83 (size = 10) OTHER = whateverUser3

2022-02-10 07:48:29.526 D/DBINFO_01: Username = User1 PIC URL =image01 PIC = [B@91e6100 (size = 10) OTHER = whateverUser1
2022-02-10 07:48:29.527 D/DBINFO_01: Username = User2 PIC URL =image02 PIC = [B@97d7d39 (size = 10) OTHER = whateverUser2
2022-02-10 07:48:29.527 D/DBINFO_01: Username = User3 PIC URL =image03 PIC = [B@9abdf7e (size = 10) OTHER = whateverUser3

2022-02-10 07:48:29.528 D/DBINFO_01: Username = User1 PIC URL =image01 PIC = [B@5babcdf (size = 10) OTHER = whateverUser1
2022-02-10 07:48:29.528 D/DBINFO_01: Username = User2 PIC URL =image02 PIC = [B@9888d2c (size = 10) OTHER = whateverUser2
2022-02-10 07:48:29.528 D/DBINFO_01: Username = User3 PIC URL =image03 PIC = [B@62fb3f5 (size = 10) OTHER = whateverUser3
</code>```

Other Permutations

Considering the above then you could question why two classes as clearly a single class could embody both aspects. So you could, for example, have/use :-

```<code>@Entity(tableName = "user_combined")
data class UserEntityCombined(
    @PrimaryKey
    val id: Long? = null,
    val username: String,
    val picUrl: String,
    @Ignore
    var pic: ByteArray = byteArrayOf(),
    @Ignore
    var otherInfoFromUserName: String = ""
) {
    constructor(id: Long?, username: String, picUrl: String): this(id = id, username = username, picUrl = picUrl, pic = byteArrayOf(), otherInfoFromUserName = "") {
        this.resolvePic()
        this.resolveOtherInfoForUserName()
    }
    fun resolvePic() {
        this.pic = byteArrayOf(0,1,2,3,4,5,6,7,8,9)
    }
    fun resolveOtherInfoForUserName() {
        this.otherInfoFromUserName = "whatever${username}"
    }
}
</code>```

If you really want two separate classes then you could EMBED the User class (which has the respective constructer and resolve methods), for example :-

```<code>@Entity(primaryKeys = ["id"], tableName = "user_embedded")
data class UserEntityWithEmbeddedUser(
    @Embedded
    val user: User
)
</code>```

The table names changed so that the above can all be compiled and therefore tested.

Example

With both of the above permutations added along with :-

```<code>data class User(
    var id: Int,
    var username: String,
    var picUrl: String,
    var pic: ByteArray,
    var otherInfoFromUserName: String
)
</code>```0

and :-

```<code>data class User(
    var id: Int,
    var username: String,
    var picUrl: String,
    var pic: ByteArray,
    var otherInfoFromUserName: String
)
</code>```1

and :-

```<code>data class User(
    var id: Int,
    var username: String,
    var picUrl: String,
    var pic: ByteArray,
    var otherInfoFromUserName: String
)
</code>```2

The in addition to the previous log, the log includes :-

```<code>2022-02-10 10:15:20.482 D/DBINFO_02: Username = User1 PIC URL =image01 PIC = [B@7949a71 (size = 10) OTHER = whateverUser1
2022-02-10 10:15:20.483 D/DBINFO_02: Username = User2 PIC URL =image02 PIC = [B@5ba6056 (size = 10) OTHER = whateverUser2
2022-02-10 10:15:20.483 D/DBINFO_02: Username = User3 PIC URL =image03 PIC = [B@23968d7 (size = 10) OTHER = whateverUser3
2022-02-10 10:15:20.486 D/DBINFO_03: Username = User1 PIC URL =image01 PIC = [B@dad55c4 (size = 10) OTHER = whateverUser1
2022-02-10 10:15:20.486 D/DBINFO_03: Username = User2 PIC URL =image02 PIC = [B@c876cad (size = 10) OTHER = whateverUser2
2022-02-10 10:15:20.486 D/DBINFO_03: Username = User3 PIC URL =image03 PIC = [B@3942be2 (size = 10) OTHER = whateverUser3
</code>```

Using App Inspection then the tables are basically identical:-

i.e. all of the above are just different ways to achieve the same end result of storing partial data of an object and with appropriate means of completing the other values of extracting the data as the overarching object.

Body:
I am trying to have a TypeConverter for the entire Entity class. All the examples I have seen so far only apply TypeConverter to individual fields of the entity, so I wonder if this is even possible?

In this contrieved example, I want to work with User class in the Dao, but room should save it as UserEntity

object TestTypeConverter{
    @TypeConverters
    fun entityToUser(entity: UserEntity) = User(entity.id, entity.username, entity.picUrl, SomeBitmapLoader(entity.pic), OtherInfoFromUsername(entity.username))

    @TypeConverters
    fun userToEntity(user: User) = UserEntity(user.id, user.username, user.picUrl)

}

@Entity(tableName = "users")
data class UserEntity(
        val id: Int,
        val username: String,
        val picUrl: String,
)

@Dao
@TypeConverters(TestTypeConverter::class)
interface UsersDao {
    @get:Query("SELECT * FROM users")
    val all: List<User>
}

I get "Cannot figure out how to read this field from a cursor" when I build.

Body:
so I wonder if this is even possible?

No (with TypeConverters assuming the object is to only store partial data e.g. to save image paths but not  the image) but Yes you can get a List<User> (with the missing/un-stored data).

NO with TypeConverters

Type Converters are all about individual fields and converting from a complex type to a single type that can be stored as a single column in the database.

by complex type, a type that is not :-

an integer (INTEGER type in SQLite) type (Int, Long, Byte etc), or

a decimal (REAL type in SQLite) type (Double, Float etc), or

a String (TEXT type in SQLite), or

a ByteArray (BLOB type in SQLite).

In your case the Entity (table in database terms) consists of Int, and String types, which are types that can be stored in columns without requiring conversion. So the Type converters are redundant.

Now if you had an entity such as (not that this is probably what you want) :-

@Entity(tableName = "users")
data class UserEntity(
        @PrimaryKey
        val id: Int=0,
        val username: String,
        val picUrl: String,
        val user: User //<<<<< TyepConverter required
)

Then because the user field is a complex type then a TypeConverter would be expected for the user field as it's a complex type.

However, the TypeConverter userToEntity  would NOT be valid/suitable/usable because it converts from a user (complex type) to a userEntity (complex type).

YES if List<User> is the goal.

Extracting a List may be possible BUT it is not TypeConverters that would convert the picUrl to the pic (ByteArray/Bitmap). TypeConverters are purely for converting data that is stored between simple and complex types.

Assuming that the User class is :-

data class User(
    var id: Int,
    var username: String,
    var picUrl: String,
    var pic: ByteArray,
    var otherInfoFromUserName: String
)

Then you could get a List if you let Room know that you want to build this from the data extracted.

What Room needs to have is matching fields and columns. So SELECT * From users will return 3 columns:-

id,

username, and

picUrl

whilst List<User> will, if as above,want 5 columns.

You could use a query such as SELECT *, zeroblob(0) AS pic, 'whatever'||username AS otherInfoFromUserName FROM users and this could then return a List BUT pic will be a ByteArray of 0 elements AND otherInforForUserName will be whatever followed by the username.

For just the 3 columns, you could have @Ignore annotation for the pic and otherInfoFromUserName e.g.

data class User(
    var id: Int,
    var username: String,
    var picUrl: String,
    @Ignore
    var pic: ByteArray,
    @Ignore
    var otherInfoFromUserName: String
)

along with a Constructor that allowed construction of a User from those three values. e.g.

data class User(
    var id: Int,
    var username: String,
    var picUrl: String,
    @Ignore
    var pic: ByteArray,
    @Ignore
    var otherInfoFromUserName: String
)  {

    constructor(id: Int, username: String, picUrl: String): this(id = id, username = username, picUrl = picUrl, pic = byteArrayOf(), otherInfoFromUserName = "")
}

and return a List<User> in which case pic would be an empty ByteArray and otherInfoFromUserName would be an empty String.

You could then have functions that resolve the values (pic and otherInfoFromUserName) and then apply them via the constructor e.g.

data class User(
    var id: Int,
    var username: String,
    var picUrl: String,
    @Ignore
    var pic: ByteArray,
    @Ignore
    var otherInfoFromUserName: String
)  {

    constructor(id: Int, username: String, picUrl: String): this(id = id, username = username, picUrl = picUrl, pic = byteArrayOf(), otherInfoFromUserName = "") {
        this.resolvePic()
        this.resolveOtherInfoFromUser()
    }

    fun resolvePic() {
        this.pic = byteArrayOf(0,1,2,3,4,5,6,7,8,9)
    }
    fun resolveOtherInfoFromUser() {
        this.otherInfoFromUserName = "whatever$username"
    }
}

In which case the values would be resolved via the Constructor.

Having the resolve functions would also allow a Dao function with a body (in an abstract class as opposed to an interface) such as :-

@Dao
abstract class AllDao {

    @Insert(onConflict = IGNORE)
    abstract fun insert(userEntity: UserEntity): Long
    @Query("SELECT * FROM users")
    abstract fun getUsersAsListUser(): List<User>
    @Query("SELECT *, zeroblob(0) AS pic, 'whatever'||username AS otherInfoFromUserName FROM users ")
    abstract fun getUserEntityExpandedToUser(): List<User>

    @Query("")
    fun getResolvedUserList(): List<User> {
        val userList = getUsersAsListUser()
        for(u: User in userList) {
            u.resolvePic()
            u.resolveOtherInfoFromUser()
        }
        return userList
    }
}

Example

Using the last User class and AllDao above then the following :-

    val db = TheDatabase.getInstance(this);
    val dao = db.getAllDao()

    dao.insert(UserEntity(1,"User1","image01"))
    dao.insert(UserEntity(2,"User2","image02"))
    dao.insert(UserEntity(3,"User3","image03"))

    for (u: User in dao.getUserEntityExpandedToUser()) {
        Log.d("DBINFO_01","Username = ${u.username} PIC URL =${u.picUrl} PIC = ${u.pic} (size = ${u.pic.size}) OTHER = ${u.otherInfoFromUserName} ")
    }
    for (u: User in dao.getUsersAsListUser()) {
        Log.d("DBINFO_01","Username = ${u.username} PIC URL =${u.picUrl} PIC = ${u.pic} (size = ${u.pic.size}) OTHER = ${u.otherInfoFromUserName} ")
    }
    for (u: User in dao.getResolvedUserList()) {
        Log.d("DBINFO_01","Username = ${u.username} PIC URL =${u.picUrl} PIC = ${u.pic} (size = ${u.pic.size}) OTHER = ${u.otherInfoFromUserName} ")
    }

Will result in the Log, after running, including :-

2022-02-10 07:48:29.525 D/DBINFO_01: Username = User1 PIC URL =image01 PIC = [B@f1e7a3d (size = 10) OTHER = whateverUser1
2022-02-10 07:48:29.525 D/DBINFO_01: Username = User2 PIC URL =image02 PIC = [B@166d232 (size = 10) OTHER = whateverUser2
2022-02-10 07:48:29.525 D/DBINFO_01: Username = User3 PIC URL =image03 PIC = [B@17eeb83 (size = 10) OTHER = whateverUser3

2022-02-10 07:48:29.526 D/DBINFO_01: Username = User1 PIC URL =image01 PIC = [B@91e6100 (size = 10) OTHER = whateverUser1
2022-02-10 07:48:29.527 D/DBINFO_01: Username = User2 PIC URL =image02 PIC = [B@97d7d39 (size = 10) OTHER = whateverUser2
2022-02-10 07:48:29.527 D/DBINFO_01: Username = User3 PIC URL =image03 PIC = [B@9abdf7e (size = 10) OTHER = whateverUser3

2022-02-10 07:48:29.528 D/DBINFO_01: Username = User1 PIC URL =image01 PIC = [B@5babcdf (size = 10) OTHER = whateverUser1
2022-02-10 07:48:29.528 D/DBINFO_01: Username = User2 PIC URL =image02 PIC = [B@9888d2c (size = 10) OTHER = whateverUser2
2022-02-10 07:48:29.528 D/DBINFO_01: Username = User3 PIC URL =image03 PIC = [B@62fb3f5 (size = 10) OTHER = whateverUser3

Other Permutations

Considering the above then you could question why two classes as clearly a single class could embody both aspects. So you could, for example, have/use :-

@Entity(tableName = "user_combined")
data class UserEntityCombined(
    @PrimaryKey
    val id: Long? = null,
    val username: String,
    val picUrl: String,
    @Ignore
    var pic: ByteArray = byteArrayOf(),
    @Ignore
    var otherInfoFromUserName: String = ""
) {
    constructor(id: Long?, username: String, picUrl: String): this(id = id, username = username, picUrl = picUrl, pic = byteArrayOf(), otherInfoFromUserName = "") {
        this.resolvePic()
        this.resolveOtherInfoForUserName()
    }
    fun resolvePic() {
        this.pic = byteArrayOf(0,1,2,3,4,5,6,7,8,9)
    }
    fun resolveOtherInfoForUserName() {
        this.otherInfoFromUserName = "whatever${username}"
    }
}

If you really want two separate classes then you could EMBED the User class (which has the respective constructer and resolve methods), for example :-

@Entity(primaryKeys = ["id"], tableName = "user_embedded")
data class UserEntityWithEmbeddedUser(
    @Embedded
    val user: User
)

The table names changed so that the above can all be compiled and therefore tested.

Example

With both of the above permutations added along with :-

@Insert(onConflict = IGNORE)
abstract fun insert(userEntityCombined: UserEntityCombined): Long
@Query("SELECT * FROM user_combined")
abstract fun getUserCombined(): List<UserEntityCombined>

@Insert(onConflict = IGNORE)
abstract fun insert(userEntityWithEmbeddedUser: UserEntityWithEmbeddedUser): Long
@Query("SELECT * FROM user_embedded")
abstract fun getUserEmbedded(): List<User>

and :-

    dao.insert(UserEntityCombined(1,"User1","image01"))
    dao.insert(UserEntityCombined(2,"User2","image02"))
    dao.insert(UserEntityCombined(3,"User3","image03"))

    dao.insert(UserEntityWithEmbeddedUser(User(1,"User1","image01")))
    dao.insert(UserEntityWithEmbeddedUser(User(2,"User2","image02")))
    dao.insert(UserEntityWithEmbeddedUser(User(3,"User3","image03")))

and :-

    /* UserEntityCombined */
    for (u: UserEntityCombined in dao.getUserCombined() ) {
        Log.d("DBINFO_02","Username = ${u.username} PIC URL =${u.picUrl} PIC = ${u.pic} (size = ${u.pic.size}) OTHER = ${u.otherInfoFromUserName} ")
    }

    /* UserEntityWithEmbeddedUser */
    for (u: User in dao.getUserEmbedded()) {
        Log.d("DBINFO_03","Username = ${u.username} PIC URL =${u.picUrl} PIC = ${u.pic} (size = ${u.pic.size}) OTHER = ${u.otherInfoFromUserName} ")
    }

The in addition to the previous log, the log includes :-

2022-02-10 10:15:20.482 D/DBINFO_02: Username = User1 PIC URL =image01 PIC = [B@7949a71 (size = 10) OTHER = whateverUser1
2022-02-10 10:15:20.483 D/DBINFO_02: Username = User2 PIC URL =image02 PIC = [B@5ba6056 (size = 10) OTHER = whateverUser2
2022-02-10 10:15:20.483 D/DBINFO_02: Username = User3 PIC URL =image03 PIC = [B@23968d7 (size = 10) OTHER = whateverUser3
2022-02-10 10:15:20.486 D/DBINFO_03: Username = User1 PIC URL =image01 PIC = [B@dad55c4 (size = 10) OTHER = whateverUser1
2022-02-10 10:15:20.486 D/DBINFO_03: Username = User2 PIC URL =image02 PIC = [B@c876cad (size = 10) OTHER = whateverUser2
2022-02-10 10:15:20.486 D/DBINFO_03: Username = User3 PIC URL =image03 PIC = [B@3942be2 (size = 10) OTHER = whateverUser3

Using App Inspection then the tables are basically identical:-

i.e. all of the above are just different ways to achieve the same end result of storing partial data of an object and with appropriate means of completing the other values of extracting the data as the overarching object.


来源: stackexchange

问:
creating dataframe from vectors
enter image description hereI have the following vectors:

```<code>bid = c(1,5,10,20,30,40,50)
n = c(31,29,27,25,23,21,19)
yes = c(0,3,6,7,9,13,17)
no = n - yes
</code>```

I have two questions, and I don't find any solutions for them, I would appreciate if someone can help me.

Q1: I want to write R code to create a two-column dataframe df. Column 1 has Bid,
where each Bid is repeated n times; Column 2 has c(rep(1,yes),rep(0,no) at
each bid.

Q2: Then when I have the data frame df, I want to write R codes to generate
(from df) vectors bid, n, yes, and no, again.

答:
I don't know what you mean for Q2, but for Q1 you could do this:

library(tidyverse)

pmap_dfr(list(bid, n, yes, no),
         \(V1, V2, V3, V4) tibble(col1 = rep(V1, V2),
                                  col2 = c(rep(1,V3),rep(0,V4))))
#> # A tibble: 175 x 2
#>     col1  col2
#>    <dbl> <dbl>
#>  1     1     0
#>  2     1     0
#>  3     1     0
#>  4     1     0
#>  5     1     0
#>  6     1     0
#>  7     1     0
#>  8     1     0
#>  9     1     0
#> 10     1     0
#> # ... with 165 more rows
```
<p>EDIT:
For Q2, you can follow this:</p>
<pre class="lang-r prettyprint-override"><code>library(tidyverse)

df <- pmap_dfr(list(bid, n, yes, no),
         \(V1, V2, V3, V4) tibble(col1 = rep(V1, V2),
                                  col2 = c(rep(1,V3),rep(0,V4))))

df2 <- df |>
  count(col1, col2) |>
  group_by(col1) |>
  summarise(yes = sum(n[col2==1]),
            n = sum(n))

bid2 <- df2$col1
n2 <- df2$n
yes2 <- df2$yes
no2 <- n2 - yes2

all.equal(c(bid, n, yes, no), c(bid2, n2, yes2, no2))
#> [1] TRUE
</code>```

ContentLicense: CC BY-SA 4.0

Title: creating dataframe from vectors

Body:
enter image description hereI have the following vectors:

bid = c(1,5,10,20,30,40,50)
n = c(31,29,27,25,23,21,19)
yes = c(0,3,6,7,9,13,17)
no = n - yes

I have two questions, and I don't find any solutions for them, I would appreciate if someone can help me.

Q1: I want to write R code to create a two-column dataframe df. Column 1 has Bid,
where each Bid is repeated n times; Column 2 has c(rep(1,yes),rep(0,no) at
each bid.

Q2: Then when I have the data frame df, I want to write R codes to generate
(from df) vectors bid, n, yes, and no, again.

Body:
I don't know what you mean for Q2, but for Q1 you could do this:

library(tidyverse)

pmap_dfr(list(bid, n, yes, no),
         \(V1, V2, V3, V4) tibble(col1 = rep(V1, V2),
                                  col2 = c(rep(1,V3),rep(0,V4))))
#> # A tibble: 175 x 2
#>     col1  col2
#>    <dbl> <dbl>
#>  1     1     0
#>  2     1     0
#>  3     1     0
#>  4     1     0
#>  5     1     0
#>  6     1     0
#>  7     1     0
#>  8     1     0
#>  9     1     0
#> 10     1     0
#> # ... with 165 more rows

EDIT:
For Q2, you can follow this:

library(tidyverse)

df <- pmap_dfr(list(bid, n, yes, no),
         \(V1, V2, V3, V4) tibble(col1 = rep(V1, V2),
                                  col2 = c(rep(1,V3),rep(0,V4))))

df2 <- df |>
  count(col1, col2) |>
  group_by(col1) |>
  summarise(yes = sum(n[col2==1]),
            n = sum(n))

bid2 <- df2$col1
n2 <- df2$n
yes2 <- df2$yes
no2 <- n2 - yes2

all.equal(c(bid, n, yes, no), c(bid2, n2, yes2, no2))
#> [1] TRUE


问:
ReactiveUI ViewModel memory leak
I am having really weird issues with memory leak and I cannot find source after long hours of testing, debugging and trial/error attempts.

The source of memory leak is reloading object base on push from subject. On which part I load current database values and add it to SourceCache.

This part is getting the push, to initiate reload

```<code>this.databaseSignalRClient
                .UpdatedObservable<JobLine>()
                .WhereNotNull()
                .Where(x => JobLinesCache.Lookup(x.Id).HasValue)
                .SelectMany(LoadJobLine)
                .ObserveOn(RxApp.MainThreadScheduler)
                .Subscribe(jl => JobLinesCache.AddOrUpdate(jl));
</code>```

Here I have the LoadJobLine func

```<code>        private async Task<JobLine> LoadJobLine(DbNotification dbNotification)
        {
            using var repo = Locator.Current.GetService<IWmsRepository>();
            return await repo.Job.JobLineRepository.FindAsync(dbNotification.Id);
        }
</code>```

And this is how I provide the ViewModels to UI:

```<code>        private readonly ReadOnlyObservableCollection<JobLineViewModel> jobLineViewModels;
        public ReadOnlyObservableCollection<JobLineViewModel> JobLineViewModels => jobLineViewModels;
</code>```
```<code>            JobLinesCache.Connect()
            .SortBy(jl => jl.CaseNo)
            .Transform(jl => new JobLineViewModel(jl))
            .ObserveOn(RxApp.MainThreadScheduler)
            .Bind(out jobLineViewModels)
            .Subscribe();
</code>```

This is the created ViewModel:

```<code>    public class JobLineViewModel : ReactiveObject
    {

        public JobLineViewModel(
            JobLine jobLine
            )
        {
            JobLine = jobLine;
        }

        [Reactive]
        public JobLine JobLine { get; private set; }

        [Reactive]
        public string ContainingItemsString { get; private set; }
    }
</code>```

At last binding collection to UI:

```<code>            this.WhenActivated(d =>
            {
                this.OneWayBind(ViewModel, vm => vm.JobLineViewModels, v => v.TestIC.ItemsSource)
                .DisposeWith(d);
            });
</code>```

I did test out virtualizing stack panel and without.

```<code>            <ItemsControl x:Name="TestIC">
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <VirtualizingStackPanel />
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
            </ItemsControl>
</code>```

And for the issue. The JobLineViewModel is for some reason not getting garbage collected. I simulate it by pinging the signalR update every 10ms.

I am seriously clueless what is making the JobLineView staying alive. I can post code of it as well, but I dont see any issue...:

```<code><rx:ReactiveUserControl x:Class="Mtc.UserControls.JobLineView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:Mtc.UserControls"
             mc:Ignorable="d"
                              x:TypeArguments="vm:JobLineViewModel"
             xmlns:rx="http://reactiveui.net"
                        xmlns:md="http://materialdesigninxaml.net/winfx/xaml/themes"
             xmlns:vm="clr-namespace:Wms.Mtc.ViewModels;assembly=Wms.Mtc"
             d:DesignHeight="450" d:DesignWidth="800">

        <md:Card Margin="20,10">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="auto" />
                <RowDefinition Height="auto" />
            </Grid.RowDefinitions>

            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*" />
                    <ColumnDefinition Width="auto" />
                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition Height="*" />
                </Grid.RowDefinitions>
                <Viewbox Margin="10">
                    <TextBlock x:Name="CaseNo_TextBlock" VerticalAlignment="Center" HorizontalAlignment="Center" />
                </Viewbox>
                <Grid Margin="10" Grid.Column="1">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*" />
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="auto" />
                        <RowDefinition Height="auto" />
                        <RowDefinition Height="auto" />
                    </Grid.RowDefinitions>
                    <TextBlock Text="D01 D01-020-0B-21" Grid.Row="0" HorizontalAlignment="Center" />
                    <!--<md:PackIcon Kind="ArrowBottom" Grid.Row="1" HorizontalAlignment="Center" Width="45" Height="45" />-->
                    <TextBlock Text="D09" Grid.Row="2" HorizontalAlignment="Center" />
                </Grid>
            </Grid>
            <TextBlock x:Name="Items_TextBlock" FontSize="28" HorizontalAlignment="Center" Margin="5" Grid.Row="1" />
        </Grid>
        </md:Card>
</rx:ReactiveUserControl>
</code>```

and code behind:

```<code>    public partial class JobLineView : ReactiveUserControl<JobLineViewModel>
    {
        public JobLineView()
        {
            InitializeComponent();
            this.WhenActivated(d =>
            {
                this.OneWayBind(ViewModel, vm => vm.JobLine, v => v.CaseNo_TextBlock.Text, jl=>jl.CaseNo)
                .DisposeWith(d);

         /*       this.OneWayBind(ViewModel, vm => vm.JobLine.Status, v => v.CaseNo_TextBlock.Foreground, status=> JobLineStatusToBrushConverter.Instance.Convert(status,null,null,null))
                .DisposeWith(d);

                this.OneWayBind(ViewModel, vm => vm.JobLine, v => v.Items_TextBlock.Text, jl=> JobLineToItemsStringConverter.Instance.Convert(jl, null,null,null))
                .DisposeWith(d);*/
            });
        }
    }
</code>```

I will be gratefull for any idea. This one is really tricky and I dont know how to solve it.

I am also adding screenshot of the managed memory:

Thanks

-----EDIT

I did strip whole View of everything, to dodge potential issue in MaterialDesign:

But the issue persist, gotta be something with ReactiveUI, but what...

Also this is JobLine class, which is getting passed to the VM:

```<code>    public class JobLine : ReactiveObject
    {
        [Reactive]
        public string CaseNo { get; set; }
        [Reactive]
        public decimal? CreatedBy { get; set; }
        [Reactive]
        public DateTime? CreatedDate { get; set; }
        [Reactive]
        public string FromInventory { get; set; }
        [Reactive]
        public string FromLocator { get; set; }
        [Reactive]
        public decimal Id { get; set; }
        [Reactive]
        public decimal? JobHeaderId { get; set; }
        [Reactive]
        public decimal? MachineId { get; set; }
        [Reactive]
        public decimal? PickingOrder { get; set; }
        [Reactive]
        public decimal? Printed { get; set; }
        [Reactive]
        public decimal? RoutingId { get; set; }
        [Reactive]
        public decimal? SourceLineId { get; set; }
        [Reactive]
        public decimal? Status { get; set; }
        [Reactive]
        public string ToInventory { get; set; }
        [Reactive]
        public string ToLocator { get; set; }
        [Reactive]
        public decimal? UpdatedBy { get; set; }
        [Reactive]
        public DateTime? UpdatedDate { get; set; }
        [Reactive]
        public decimal? Valid { get; set; }
        [Reactive]
        public string WindowsUser { get; set; }
    }
</code>```

After eliminating every factor possible (stripped the view and view model empty of any binding, or material design stuff (icon) etc) the issue still persist. Something is keeping the View alive in memory, altogether with the ViewModel. While not being in the visual tree anymore.

Any ideas are welcome.

答:
The bug was reported and fixed here in library repository:
https://github.com/reactiveui/ReactiveUI/issues/3091</p>

Title: ReactiveUI ViewModel memory leak

Body:
I am having really weird issues with memory leak and I cannot find source after long hours of testing, debugging and trial/error attempts.

The source of memory leak is reloading object base on push from subject. On which part I load current database values and add it to SourceCache.

This part is getting the push, to initiate reload

this.databaseSignalRClient
                .UpdatedObservable<JobLine>()
                .WhereNotNull()
                .Where(x => JobLinesCache.Lookup(x.Id).HasValue)
                .SelectMany(LoadJobLine)
                .ObserveOn(RxApp.MainThreadScheduler)
                .Subscribe(jl => JobLinesCache.AddOrUpdate(jl));

Here I have the LoadJobLine func

        private async Task<JobLine> LoadJobLine(DbNotification dbNotification)
        {
            using var repo = Locator.Current.GetService<IWmsRepository>();
            return await repo.Job.JobLineRepository.FindAsync(dbNotification.Id);
        }

And this is how I provide the ViewModels to UI:

        private readonly ReadOnlyObservableCollection<JobLineViewModel> jobLineViewModels;
        public ReadOnlyObservableCollection<JobLineViewModel> JobLineViewModels => jobLineViewModels;

            JobLinesCache.Connect()
            .SortBy(jl => jl.CaseNo)
            .Transform(jl => new JobLineViewModel(jl))
            .ObserveOn(RxApp.MainThreadScheduler)
            .Bind(out jobLineViewModels)
            .Subscribe();

This is the created ViewModel:

    public class JobLineViewModel : ReactiveObject
    {

        public JobLineViewModel(
            JobLine jobLine
            )
        {
            JobLine = jobLine;
        }

        [Reactive]
        public JobLine JobLine { get; private set; }

        [Reactive]
        public string ContainingItemsString { get; private set; }
    }

At last binding collection to UI:

            this.WhenActivated(d =>
            {
                this.OneWayBind(ViewModel, vm => vm.JobLineViewModels, v => v.TestIC.ItemsSource)
                .DisposeWith(d);
            });

I did test out virtualizing stack panel and without.

            <ItemsControl x:Name="TestIC">
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <VirtualizingStackPanel />
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
            </ItemsControl>

And for the issue. The JobLineViewModel is for some reason not getting garbage collected. I simulate it by pinging the signalR update every 10ms.

I am seriously clueless what is making the JobLineView staying alive. I can post code of it as well, but I dont see any issue...:

<rx:ReactiveUserControl x:Class="Mtc.UserControls.JobLineView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:Mtc.UserControls"
             mc:Ignorable="d"
                              x:TypeArguments="vm:JobLineViewModel"
             xmlns:rx="http://reactiveui.net"
                        xmlns:md="http://materialdesigninxaml.net/winfx/xaml/themes"
             xmlns:vm="clr-namespace:Wms.Mtc.ViewModels;assembly=Wms.Mtc"
             d:DesignHeight="450" d:DesignWidth="800">

        <md:Card Margin="20,10">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="auto" />
                <RowDefinition Height="auto" />
            </Grid.RowDefinitions>

            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*" />
                    <ColumnDefinition Width="auto" />
                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition Height="*" />
                </Grid.RowDefinitions>
                <Viewbox Margin="10">
                    <TextBlock x:Name="CaseNo_TextBlock" VerticalAlignment="Center" HorizontalAlignment="Center" />
                </Viewbox>
                <Grid Margin="10" Grid.Column="1">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*" />
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="auto" />
                        <RowDefinition Height="auto" />
                        <RowDefinition Height="auto" />
                    </Grid.RowDefinitions>
                    <TextBlock Text="D01 D01-020-0B-21" Grid.Row="0" HorizontalAlignment="Center" />

                    <TextBlock Text="D09" Grid.Row="2" HorizontalAlignment="Center" />
                </Grid>
            </Grid>
            <TextBlock x:Name="Items_TextBlock" FontSize="28" HorizontalAlignment="Center" Margin="5" Grid.Row="1" />
        </Grid>
        </md:Card>
</rx:ReactiveUserControl>

and code behind:

    public partial class JobLineView : ReactiveUserControl<JobLineViewModel>
    {
        public JobLineView()
        {
            InitializeComponent();
            this.WhenActivated(d =>
            {
                this.OneWayBind(ViewModel, vm => vm.JobLine, v => v.CaseNo_TextBlock.Text, jl=>jl.CaseNo)
                .DisposeWith(d);

         /*       this.OneWayBind(ViewModel, vm => vm.JobLine.Status, v => v.CaseNo_TextBlock.Foreground, status=> JobLineStatusToBrushConverter.Instance.Convert(status,null,null,null))
                .DisposeWith(d);

                this.OneWayBind(ViewModel, vm => vm.JobLine, v => v.Items_TextBlock.Text, jl=> JobLineToItemsStringConverter.Instance.Convert(jl, null,null,null))
                .DisposeWith(d);*/
            });
        }
    }

I will be gratefull for any idea. This one is really tricky and I dont know how to solve it.

I am also adding screenshot of the managed memory:

Thanks

-----EDIT

I did strip whole View of everything, to dodge potential issue in MaterialDesign:

But the issue persist, gotta be something with ReactiveUI, but what...

Also this is JobLine class, which is getting passed to the VM:

    public class JobLine : ReactiveObject
    {
        [Reactive]
        public string CaseNo { get; set; }
        [Reactive]
        public decimal? CreatedBy { get; set; }
        [Reactive]
        public DateTime? CreatedDate { get; set; }
        [Reactive]
        public string FromInventory { get; set; }
        [Reactive]
        public string FromLocator { get; set; }
        [Reactive]
        public decimal Id { get; set; }
        [Reactive]
        public decimal? JobHeaderId { get; set; }
        [Reactive]
        public decimal? MachineId { get; set; }
        [Reactive]
        public decimal? PickingOrder { get; set; }
        [Reactive]
        public decimal? Printed { get; set; }
        [Reactive]
        public decimal? RoutingId { get; set; }
        [Reactive]
        public decimal? SourceLineId { get; set; }
        [Reactive]
        public decimal? Status { get; set; }
        [Reactive]
        public string ToInventory { get; set; }
        [Reactive]
        public string ToLocator { get; set; }
        [Reactive]
        public decimal? UpdatedBy { get; set; }
        [Reactive]
        public DateTime? UpdatedDate { get; set; }
        [Reactive]
        public decimal? Valid { get; set; }
        [Reactive]
        public string WindowsUser { get; set; }
    }

After eliminating every factor possible (stripped the view and view model empty of any binding, or material design stuff (icon) etc) the issue still persist. Something is keeping the View alive in memory, altogether with the ViewModel. While not being in the visual tree anymore.

Any ideas are welcome.


问:
How to extract date from a string?
I have this weird string:

```<code>'": "1899-12-30 14:50:00.000"": " "'
</code>```

I need to just extract the date.
I have looked at all the different python string manipulation functions but I just can't seem to find one that works for this interesting format.

Thanks

答:
Based on your string if you just want 1899-12-30 you could do:

```<code>'": "1899-12-30 14:50:00.000"": " "'.split(' ')[1][1:]
</code>```

if you want the full 1899-12-30 14:50:00.000 you could do

```<code>'": "1899-12-30 14:50:00.000"": " "'.split('"')[2]
</code>```

Explanation:

taking the string we are splitting the string by its characters in the first example a space and in the second a double quote as those characters surround the date element. The split function creates a list in which we access the element that we would like in the first case the second element (0 index list) while the second list we grab the third element. For the first Example printing out the output before we do a slice of the sting would give an extra double quote before the date, therefore we take the first element off of the string to only get the date.

Title: How to extract date from a string?

Body:
I have this weird string:

'": "1899-12-30 14:50:00.000"": " "'

I need to just extract the date.
I have looked at all the different python string manipulation functions but I just can't seem to find one that works for this interesting format.

Thanks

Body:
Based on your string if you just want 1899-12-30 you could do:

'": "1899-12-30 14:50:00.000"": " "'.split(' ')[1][1:]

if you want the full 1899-12-30 14:50:00.000 you could do

'": "1899-12-30 14:50:00.000"": " "'.split('"')[2]

Explanation:

taking the string we are splitting the string by its characters in the first example a space and in the second a double quote as those characters surround the date element. The split function creates a list in which we access the element that we would like in the first case the second element (0 index list) while the second list we grab the third element. For the first Example printing out the output before we do a slice of the sting would give an extra double quote before the date, therefore we take the first element off of the string to only get the date.


问:
How to properly replace an owned collection of items?
I receive an exception when trying to replace the owned collection with the one I receive through API (EF Core 6).

System.InvalidOperationException: 'The instance of entity type 'Product' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached.

Here is my model configuration:

public class Order
{
    public int Id { get; set; }

    public ICollection<OrderItem> OrderItems { get; set; }
}

public class OrderItem
{
    public Product Product { get; set; }

    public int Quantity { get; set; }
}

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
}
```
<pre class="lang-csharp prettyprint-override"><code>modelBuilder.Entity<Product>(x =>
{
    x.HasKey(e => e.Id);
    x.Property(e => e.Name);
});
modelBuilder.Entity<Order>(x =>
{
    x.HasKey(e => e.Id);
    x.OwnsMany(e => e.OrderItems, p =>
    {
        p.ToTable("OrderItems")
            .WithOwner();
        p.HasOne(e => e.Product).WithMany();
        p.Property(e => e.Quantity);
    });
});
</code>```

Act:

//these are updated items received through API
var newItems = new List<OrderItem>
{
    new OrderItem{  Product = new Product { Id = 2}, Quantity = 2},
    new OrderItem{  Product = new Product { Id = 3}, Quantity = 3}
};

var existingOrder = _dbContext.Orders
    .Include(o => o.OrderItems).ThenInclude(i => i.Product)
    .Single(o => o.Id == 1);
// Existing OrderItems are already referencing Product with Id 2

existingOrder.OrderItems = newItems;

// Error occurs because Product with Id = 2 was already tracked
_dbContext.SaveChanges();
```

I know that the issue might be resolved by replacing Product with ProductId within my OrderItem class but I would rather prefer to keep my domain model as it is.

What is the best practice to perform such update?

答:
it's all about understanding of the modeling. You can create a model response to update also, but just have to update manually by calling it.

you have existingOrder from the query include, then include like this I guess

```<code>var existingOrder = ...
existingOrder.OrderItems.Update(yourentity_OrderItem);
await _dbContext.SaveChangesAsync();
</code>```

So this mean you have to retrieve each Product.id by a for, and update each new items, then savechanges.

Body:
I receive an exception when trying to replace the owned collection with the one I receive through API (EF Core 6).

System.InvalidOperationException: 'The instance of entity type 'Product' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached.

Here is my model configuration:

public class Order
{
    public int Id { get; set; }

    public ICollection<OrderItem> OrderItems { get; set; }
}

public class OrderItem
{
    public Product Product { get; set; }

    public int Quantity { get; set; }
}

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
}

modelBuilder.Entity<Product>(x =>
{
    x.HasKey(e => e.Id);
    x.Property(e => e.Name);
});
modelBuilder.Entity<Order>(x =>
{
    x.HasKey(e => e.Id);
    x.OwnsMany(e => e.OrderItems, p =>
    {
        p.ToTable("OrderItems")
            .WithOwner();
        p.HasOne(e => e.Product).WithMany();
        p.Property(e => e.Quantity);
    });
});

Act:

//these are updated items received through API
var newItems = new List<OrderItem>
{
    new OrderItem{  Product = new Product { Id = 2}, Quantity = 2},
    new OrderItem{  Product = new Product { Id = 3}, Quantity = 3}
};

var existingOrder = _dbContext.Orders
    .Include(o => o.OrderItems).ThenInclude(i => i.Product)
    .Single(o => o.Id == 1);
// Existing OrderItems are already referencing Product with Id 2

existingOrder.OrderItems = newItems;

// Error occurs because Product with Id = 2 was already tracked
_dbContext.SaveChanges();

I know that the issue might be resolved by replacing Product with ProductId within my OrderItem class but I would rather prefer to keep my domain model as it is.

What is the best practice to perform such update?

Body:
it's all about understanding of the modeling. You can create a model response to update also, but just have to update manually by calling it.

you have existingOrder from the query include, then include like this I guess

var existingOrder = ...
existingOrder.OrderItems.Update(yourentity_OrderItem);
await _dbContext.SaveChangesAsync();

So this mean you have to retrieve each Product.id by a for, and update each new items, then savechanges.


问:
How to get only repeated records in a table?
I couldn't figure out how better to ask this question, so my searches became desperate.

I have a table with three columns(Column1, Column2, Column3). There are lots of records consisted of different and same values in it. I want to get only the exactly same records as column1, column2 and column3 values. How can I get them in the fastest query in general SQL? And especially HSQLDB?

Besides, if my table has 4 columns (+ Column4) but still I need same records of column1,column2 and column3 values. Query must change or will be same?

Example;

```<code>-------------------------------
| Column1 | Column2 | Column3 |
|    1    |    2    |   3     |  <-- A
|    2    |    2    |   30    |  <-- B
|    3    |    3    |   10    |
|    4    |    12   |   3     |  <-- C
|    1    |    3    |   3     |
|    1    |    4    |   3     |
|    1    |    5    |   3     |
|    4    |    12   |   3     |  <-- C
|    2    |    2    |   30    |  <-- B
|    1    |    2    |   3     |  <-- A
|    4    |    12   |   3     |  <-- C
-------------------------------
</code>```

So I need to select all A,B and C records. The result should be;

```<code>-------------------------------
| Column1 | Column2 | Column3 |
|    1    |    2    |   3     |  <-- A
|    2    |    2    |   30    |  <-- B
|    4    |    12   |   3     |  <-- C
|    4    |    12   |   3     |  <-- C
|    2    |    2    |   30    |  <-- B
|    1    |    2    |   3     |  <-- A
|    4    |    12   |   3     |  <-- C
-------------------------------
</code>```

-Result omitted completely different records-

答:
```<code>SELECT Column1, Column2, Column3, count(*) from myTable
GROUP BY Column1, Column2, Column3
</code>```

You can omit the Count(*) if you don't care about the count.
Is this what you want?

It was a bit difficult to understand what you want. Could you please give an example of you desired output result?

ContentLicense: CC BY-SA 3.0

Body:
I couldn't figure out how better to ask this question, so my searches became desperate.

I have a table with three columns(Column1, Column2, Column3). There are lots of records consisted of different and same values in it. I want to get only the exactly same records as column1, column2 and column3 values. How can I get them in the fastest query in general SQL? And especially HSQLDB?

Besides, if my table has 4 columns (+ Column4) but still I need same records of column1,column2 and column3 values. Query must change or will be same?

Example;

-------------------------------
| Column1 | Column2 | Column3 |
|    1    |    2    |   3     |  <-- A
|    2    |    2    |   30    |  <-- B
|    3    |    3    |   10    |
|    4    |    12   |   3     |  <-- C
|    1    |    3    |   3     |
|    1    |    4    |   3     |
|    1    |    5    |   3     |
|    4    |    12   |   3     |  <-- C
|    2    |    2    |   30    |  <-- B
|    1    |    2    |   3     |  <-- A
|    4    |    12   |   3     |  <-- C
-------------------------------

So I need to select all A,B and C records. The result should be;

-------------------------------
| Column1 | Column2 | Column3 |
|    1    |    2    |   3     |  <-- A
|    2    |    2    |   30    |  <-- B
|    4    |    12   |   3     |  <-- C
|    4    |    12   |   3     |  <-- C
|    2    |    2    |   30    |  <-- B
|    1    |    2    |   3     |  <-- A
|    4    |    12   |   3     |  <-- C
-------------------------------

-Result omitted completely different records-

Body:
SELECT Column1, Column2, Column3, count(*) from myTable
GROUP BY Column1, Column2, Column3

You can omit the Count(*) if you don't care about the count.
Is this what you want?

It was a bit difficult to understand what you want. Could you please give an example of you desired output result?


问:
Where to place Javascript used in one page only in Rails 7 with importmap
When using Rails 7 with import maps, where do I put code that should be executed by one view only?

Specifically, I have a view that needs to run some Javascript code on load.  My Javascript looks something like this:

```<code>import {TheController} from "./TheController"

let controller = new TheController();

document.onreadystatechange = function () {
  if (document.readyState === 'complete') {
    controller.onLoad();
  }
};
</code>```

How do I setup the Javascript environment so that the document.onreadystatechange code is executed only by the desired view?  (Everything almost works when I put this code in a file imported by application.js, but then it gets executed by every view.)

I suspect the answer is to create separate importmaps and importmap_tags; but, I can find any demonstrations of how to do that in Rails 7.

答:
DHH explains it pretty well have a look plz
https://youtu.be/PtxZvFnL2i0?t=1287</p>

Body:
When using Rails 7 with import maps, where do I put code that should be executed by one view only?

Specifically, I have a view that needs to run some Javascript code on load.  My Javascript looks something like this:

import {TheController} from "./TheController"

let controller = new TheController();

document.onreadystatechange = function () {
  if (document.readyState === 'complete') {
    controller.onLoad();
  }
};

How do I setup the Javascript environment so that the document.onreadystatechange code is executed only by the desired view?  (Everything almost works when I put this code in a file imported by application.js, but then it gets executed by every view.)

I suspect the answer is to create separate importmaps and importmap_tags; but, I can find any demonstrations of how to do that in Rails 7.


问:
Does a replicaset with 3 replicas need an arbiter?
We are running a MongoDB database in HA mode on our k8s cluster. Our helm chart defines three replicas (with persitence: enabled: false) and one arbiter.

Since 3 replicas + 1 arbiter is an evil even number, I would love to know if the arbiter only comes into play when one replica goes down to ensure an odd number of electors to determine the new primary node, or is using an arbiter wrong when having defined an odd number of replicas?

答:
Option 1: ( Better option since having more ARBITER's is easy in k8s)

You may need to add 1x more ARBITER , 5x total voting members will allow you to keep the PRIMARY even 2x of the DATA members die simultaneously at the same time.

Option 2:

You remove the ARBITER since with 4x members and two down the PRIMARY will switch to SECONDARY since there will be no majority , but if you keep it election expected to be faster with 3x votes when only one member die.


问:
Adding double quotes while making a csv file in python
```<code>import csv
with open('innovators.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerow(["SN", "Name", "Contribution"])
    writer.writerow([1, "Linus Torvalds", "Linux Kernel"])
</code>```

The output I get:

```<code>SN, Name, Contribution
1, Linus Torvalds, Linux Kernel
</code>```

The output I want:

```<code>SN, Name, Contribution
1, Linus Torvalds, "Linux Kernel"
</code>```

So, I tried

```<code>writer.writerow([1, "Linus Torvalds", "\"Linux Kernel\""])
</code>```

But that just makes it into:

```<code>1, Linus Torvalds, ""Linux Kernel""
</code>```

I'm using Visual Studio Code with python 3, not sure how I can get it to output the word with double quotes

答:
```<code>import csv
with open('innovators.csv', 'w', newline='') as file:
    writer = csv.writer(file,quotechar = "'")
    writer.writerow(["SN", "Name", "Contribution"])
    writer.writerow([1, "Linus Torvalds",'"Linux Kernel"' ])
</code>```

Body:
import csv
with open('innovators.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerow(["SN", "Name", "Contribution"])
    writer.writerow([1, "Linus Torvalds", "Linux Kernel"])

The output I get:

SN, Name, Contribution
1, Linus Torvalds, Linux Kernel

The output I want:

SN, Name, Contribution
1, Linus Torvalds, "Linux Kernel"

So, I tried

writer.writerow([1, "Linus Torvalds", "\"Linux Kernel\""])

But that just makes it into:

1, Linus Torvalds, ""Linux Kernel""

I'm using Visual Studio Code with python 3, not sure how I can get it to output the word with double quotes


答:
You can control the level of quoting with quoting argument to csv.writer. If you just want to quote all values, use csv.QUOTE_ALL.

Quoting levels:

csv.QUOTE_ALL

Instructs writer objects to quote all fields.

csv.QUOTE_NONNUMERIC

Instructs writer objects to quote all non-numeric fields.

Instructs the reader to convert all non-quoted fields to type float.

csv.QUOTE_MINIMAL (Default)

Instructs writer objects to only quote those fields which contain special characters such as delimiter, quotechar or any of the characters in lineterminator.

csv.QUOTE_NONE

Instructs writer objects to never quote fields.

Example:

import csv

with open('innovators.csv', 'w', newline='') as file:
    writer = csv.writer(file, quoting=csv.QUOTE_NONNUMERIC)
    writer.writerow(["SN", "Name", "Contribution"])
    writer.writerow([1, "Linus Torvalds", "Linux Kernel"])
```
<p><strong>Output:</strong></p>
```"SN","Name","Contribution"
1,"Linus Torvalds","Linux Kernel"
```

Notice in the output that all the strings are quoted and the number is not.

Title: Adding double quotes while making a csv file in python

Body:
You can control the level of quoting with quoting argument to csv.writer. If you just want to quote all values, use csv.QUOTE_ALL.

Quoting levels:

csv.QUOTE_ALL

Instructs writer objects to quote all fields.

csv.QUOTE_NONNUMERIC

Instructs writer objects to quote all non-numeric fields.

Instructs the reader to convert all non-quoted fields to type float.

csv.QUOTE_MINIMAL (Default)

Instructs writer objects to only quote those fields which contain special characters such as delimiter, quotechar or any of the characters in lineterminator.

csv.QUOTE_NONE

Instructs writer objects to never quote fields.

Example:

import csv

with open('innovators.csv', 'w', newline='') as file:
    writer = csv.writer(file, quoting=csv.QUOTE_NONNUMERIC)
    writer.writerow(["SN", "Name", "Contribution"])
    writer.writerow([1, "Linus Torvalds", "Linux Kernel"])

Output:

"SN","Name","Contribution"
1,"Linus Torvalds","Linux Kernel"

Notice in the output that all the strings are quoted and the number is not.


Title: How to extract date from a string?

Body:
What about this solution:

mys = '": "1899-12-30 14:50:00.000"": " "'
print(mys.strip('": "'))


问:
System.out.printIn cannot find symbol
Whenever I try to compile this Java program in the command prompt I get an error about System.out.printIn saying that javac cannot find symbol. System.out.print works just fine but System.out.printIn refuses to cooperate. I've posted the program and the compiler message below. Thanks for the help.

```<code>    public class BeerSong {
public static void main (String[] args) {
int beerNum = 99;
String word = "bottles";

while (beerNum > 0) {

  if (beerNum == 1) {
    word = "bottle"; //singular, ONE bottle
}

System.out.printIn(beerNum + " " + word + "of beer on the wall");
System.out.printIn(beerNum + " " + word + "of beer.");
System.out.printIn("Take one down.");
System.out.printIn("Pass it around.");
beerNum = beerNum - 1;

if (beerNum > 0) {
    System.out.printIn(beerNum + " " + word + " of beer on the wall");
}   else {
    System.out.printIn("No more bottles of beer on the wall");
} //end else
} //end while loop
} //end main method
} //end class
</code>```

```<code>C:\Users\Jesse\Desktop>javac BeerSong.java
BeerSong.java:12: cannot find symbol
symbol  : method printIn(java.lang.String)
location: class java.io.PrintStream
    System.out.printIn(beerNum + " " + word + "of beer on the wall");
              ^
BeerSong.java:13: cannot find symbol
symbol  : method printIn(java.lang.String)
location: class java.io.PrintStream
    System.out.printIn(beerNum + " " + word + "of beer.");
              ^
BeerSong.java:14: cannot find symbol
symbol  : method printIn(java.lang.String)
location: class java.io.PrintStream
    System.out.printIn("Take one down.");
              ^
BeerSong.java:15: cannot find symbol
symbol  : method printIn(java.lang.String)
location: class java.io.PrintStream
    System.out.printIn("Pass it around.");
              ^
BeerSong.java:19: cannot find symbol
symbol  : method printIn(java.lang.String)
location: class java.io.PrintStream
        System.out.printIn(beerNum + " " + word + " of beer on the wall");
                  ^
BeerSong.java:21: cannot find symbol
symbol  : method printIn(java.lang.String)
location: class java.io.PrintStream
            System.out.printIn("No more bottles of beer on the wall");
                      ^
6 errors
</code>```

答: It is println with l (lower case L), not I (upper case i).

Title: System.out.printIn cannot find symbol

Body:
Whenever I try to compile this Java program in the command prompt I get an error about System.out.printIn saying that javac cannot find symbol. System.out.print works just fine but System.out.printIn refuses to cooperate. I've posted the program and the compiler message below. Thanks for the help.

    public class BeerSong {
public static void main (String[] args) {
int beerNum = 99;
String word = "bottles";

while (beerNum > 0) {

  if (beerNum == 1) {
    word = "bottle"; //singular, ONE bottle
}

System.out.printIn(beerNum + " " + word + "of beer on the wall");
System.out.printIn(beerNum + " " + word + "of beer.");
System.out.printIn("Take one down.");
System.out.printIn("Pass it around.");
beerNum = beerNum - 1;

if (beerNum > 0) {
    System.out.printIn(beerNum + " " + word + " of beer on the wall");
}   else {
    System.out.printIn("No more bottles of beer on the wall");
} //end else
} //end while loop
} //end main method
} //end class

C:\Users\Jesse\Desktop>javac BeerSong.java
BeerSong.java:12: cannot find symbol
symbol  : method printIn(java.lang.String)
location: class java.io.PrintStream
    System.out.printIn(beerNum + " " + word + "of beer on the wall");
              ^
BeerSong.java:13: cannot find symbol
symbol  : method printIn(java.lang.String)
location: class java.io.PrintStream
    System.out.printIn(beerNum + " " + word + "of beer.");
              ^
BeerSong.java:14: cannot find symbol
symbol  : method printIn(java.lang.String)
location: class java.io.PrintStream
    System.out.printIn("Take one down.");
              ^
BeerSong.java:15: cannot find symbol
symbol  : method printIn(java.lang.String)
location: class java.io.PrintStream
    System.out.printIn("Pass it around.");
              ^
BeerSong.java:19: cannot find symbol
symbol  : method printIn(java.lang.String)
location: class java.io.PrintStream
        System.out.printIn(beerNum + " " + word + " of beer on the wall");
                  ^
BeerSong.java:21: cannot find symbol
symbol  : method printIn(java.lang.String)
location: class java.io.PrintStream
            System.out.printIn("No more bottles of beer on the wall");
                      ^
6 errors


问:
Getting information from an Array with Strings and Integer Values as Strings by Size of Integer Values
Let's say you have an array that looks like this:

arr = ['Steve', '80000', 'Jen', '90000', 'Bob', '40000']```

Where arr[0] and arr[2] are the names of employees and arr[1] and arr[3] are their salaries.

How would you go about writing a function that would return the name of the person with the largest salary?

In the example above we'd look for the function to return 'Jen' because she has the highest salary.

My initial thought would be to turn all the values in the array to integers using parseInt(), finding the maximum value and then pointing to the value of the index before that maximum value but am having trouble writing a correct solution for this. Any help would be greatly appreciated!

答:
Chunk function

```<code>Object.defineProperty(Array.prototype, 'chunk', {value: function(n) {
    return Array.from(Array(Math.ceil(this.length/n)), (_,i)=>this.slice(i*n,i*n+n));
}});
</code>```

Then we can easily process [Name, Salary] pairs like,

```<code>["a", "11", "b", "12", "c", "3"]
  .chunk(2)
  .sort((p1, p2) => parseInt(p2) - parseInt(p1))[0]
</code>```

Body:
Let's say you have an array that looks like this:

arr = ['Steve', '80000', 'Jen', '90000', 'Bob', '40000']

Where arr[0] and arr[2] are the names of employees and arr[1] and arr[3] are their salaries.

How would you go about writing a function that would return the name of the person with the largest salary?

In the example above we'd look for the function to return 'Jen' because she has the highest salary.

My initial thought would be to turn all the values in the array to integers using parseInt(), finding the maximum value and then pointing to the value of the index before that maximum value but am having trouble writing a correct solution for this. Any help would be greatly appreciated!

Body:
Chunk function

Object.defineProperty(Array.prototype, 'chunk', {value: function(n) {
    return Array.from(Array(Math.ceil(this.length/n)), (_,i)=>this.slice(i*n,i*n+n));
}});

Then we can easily process [Name, Salary] pairs like,

["a", "11", "b", "12", "c", "3"]
  .chunk(2)
  .sort((p1, p2) => parseInt(p2) - parseInt(p1))[0]


问:
Having the same controller code for multiple HTTP methods, is it possible to hide only one of them from Swagger UI?
The same method and the same route are used for two different endpoints: one is a GET, the other one is a POST. Is there a way to hide only one of them (e.g. just the GET one) from the Swagger UI?

```<code>[Route("myroute")]
[HttpPost]
[HttpGet] // This is being keep for compatibility purposes (legacy services that are still using it)
</code>```

I tried using the IgnoreApi property (see below) with no luck: it hides both the GET and the POST. Seems like it hides the entire route, no matter the HTTP method.

```<code>[ApiExplorerSettings(IgnoreApi = false)]
</code>```

答:
Not on the same endpoint. The ApiExplorerSettings Attribute is for the entire method and cannot be applied to a specific Attribute accompanying the method.

What you can do is the following:

```<code>[HttpPost]
public void MyCurrentMethod() {
    //Do stuff...
}

[ApiExplorerSettings(IgnoreApi = true)]
[HttpGet]
public void MyDepricatedMethod() => MyCurrentMethod();
</code>```

Body:
The same method and the same route are used for two different endpoints: one is a GET, the other one is a POST. Is there a way to hide only one of them (e.g. just the GET one) from the Swagger UI?

[Route("myroute")]
[HttpPost]
[HttpGet] // This is being keep for compatibility purposes (legacy services that are still using it)

I tried using the IgnoreApi property (see below) with no luck: it hides both the GET and the POST. Seems like it hides the entire route, no matter the HTTP method.

[ApiExplorerSettings(IgnoreApi = false)]

Body:
Not on the same endpoint. The ApiExplorerSettings Attribute is for the entire method and cannot be applied to a specific Attribute accompanying the method.

What you can do is the following:

[HttpPost]
public void MyCurrentMethod() {
    //Do stuff...
}

[ApiExplorerSettings(IgnoreApi = true)]
[HttpGet]
public void MyDepricatedMethod() => MyCurrentMethod();


问:
too many clients already in postgres

I was working on a java project and it was working just fine. I was able to make connections. I closed all the connections properly in finally block. Now I am not able to make connections or even open psql in my terminal. How can I make it work as before. Much much appreciated

```<code>import java.sql.Connection;
import com.mchange.v2.c3p0.*;

public class MyConnection {
    public static Connection getConnection(){
        ComboPooledDataSource cpds1 = new ComboPooledDataSource();
        String dbDriver = "org.postgresql.Driver";
        String dbName = "jdbc:postgresql://localhost/postgres";
        cpds1.setJdbcUrl(dbName);
        String userName = "user_1";
        cpds1.setUser(userName);
        String password = "mypass";
        cpds1.setPassword(password);
        cpds1.setMaxStatements( 180 );
        try
        {
            cpds1.setDriverClass(dbDriver);
            return cpds1.getConnection();
        }
        catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
    }
}
</code>```

This is where I'm calling it

```<code>public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException
    {
        PrintWriter writer = response.getWriter();
        JSONObject jo = new JSONObject();
        JSONObject jObj;
        Statement stmt = null;
        Connection con = null;
        PreparedStatement ps;
        ResultSet rs = null;
        try
        {
            jObj = UtilityClass.getJSON(request);
            String uname = ((String) jObj.get("uname"));
            String pass = ((String) jObj.get("pass"));
            String sql = "SELECT * FROM users WHERE username = ?";
            try
            {
                con = MyConnection.getConnection();
                System.out.println("Got Connection");
                stmt = con.createStatement();
                ps = con.prepareStatement(sql);
                ps.setString(1, uname);
                rs = ps.executeQuery();
                if(rs.next())
                {
                    if(BCrypt.checkpw(pass,rs.getString("password")))
                    {
                        HttpSession session = request.getSession();
                        session.setAttribute("uname", uname);
                        if(session.isNew())
                        {
                            System.out.println("new");
                        }
                        if(uname.equals("admin"))
                        {
                            session.setAttribute("role", "admin");
                            jo.put("status", "admin");
                        }
                        else
                        {
                            session.setAttribute("role", "user");
                            jo.put("status", "authenticate");
                        }
                    }
                }
                writer.print(jo);
            }
            catch (Exception e)
            {
                e.printStackTrace();
                System.out.println("Not Connected");
            }
            finally
            {
                if(rs != null)
                {
                    rs.close();
                }
                if(stmt != null)
                {
                    stmt.close();
                }
                if(con != null)
                {
                    con.close();
                }
            }
        }
        catch(Exception e)
        {
            System.out.print("JSON Exception");
        }
    }
</code>```

答: Usually, DB Admins are using pooling technologies on Databases. For PostgreSQL one of the more popularly is a PGBOUNCER. We used PGBOUNCER in our large project, the result is excellent. I recommend it to you. To get more information about the pooling system you can read this link. For About Pooling

Title: too many clients already in postgres

Body:
I was working on a java project and it was working just fine. I was able to make connections. I closed all the connections properly in finally block. Now I am not able to make connections or even open psql in my terminal. How can I make it work as before. Much much appreciated

import java.sql.Connection;
import com.mchange.v2.c3p0.*;

public class MyConnection {
    public static Connection getConnection(){
        ComboPooledDataSource cpds1 = new ComboPooledDataSource();
        String dbDriver = "org.postgresql.Driver";
        String dbName = "jdbc:postgresql://localhost/postgres";
        cpds1.setJdbcUrl(dbName);
        String userName = "user_1";
        cpds1.setUser(userName);
        String password = "mypass";
        cpds1.setPassword(password);
        cpds1.setMaxStatements( 180 );
        try
        {
            cpds1.setDriverClass(dbDriver);
            return cpds1.getConnection();
        }
        catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
    }
}

This is where I'm calling it

public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException
    {
        PrintWriter writer = response.getWriter();
        JSONObject jo = new JSONObject();
        JSONObject jObj;
        Statement stmt = null;
        Connection con = null;
        PreparedStatement ps;
        ResultSet rs = null;
        try
        {
            jObj = UtilityClass.getJSON(request);
            String uname = ((String) jObj.get("uname"));
            String pass = ((String) jObj.get("pass"));
            String sql = "SELECT * FROM users WHERE username = ?";
            try
            {
                con = MyConnection.getConnection();
                System.out.println("Got Connection");
                stmt = con.createStatement();
                ps = con.prepareStatement(sql);
                ps.setString(1, uname);
                rs = ps.executeQuery();
                if(rs.next())
                {
                    if(BCrypt.checkpw(pass,rs.getString("password")))
                    {
                        HttpSession session = request.getSession();
                        session.setAttribute("uname", uname);
                        if(session.isNew())
                        {
                            System.out.println("new");
                        }
                        if(uname.equals("admin"))
                        {
                            session.setAttribute("role", "admin");
                            jo.put("status", "admin");
                        }
                        else
                        {
                            session.setAttribute("role", "user");
                            jo.put("status", "authenticate");
                        }
                    }
                }
                writer.print(jo);
            }
            catch (Exception e)
            {
                e.printStackTrace();
                System.out.println("Not Connected");
            }
            finally
            {
                if(rs != null)
                {
                    rs.close();
                }
                if(stmt != null)
                {
                    stmt.close();
                }
                if(con != null)
                {
                    con.close();
                }
            }
        }
        catch(Exception e)
        {
            System.out.print("JSON Exception");
        }
    }


问:
Military Time Form Validation msAccess Form View
I'm having a difficult time doing military time or short time in the form view. I caught an error where the user put in 15:83 which shouldn't be allowed because the minutes are over 59, as well hours being over 23. However, I'm not sure how to create a form validation for something like that and I can't seem to find any documentation for it online surrounding this type of formatting.</p>

答:
I can't seem to find any documentation for it online surrounding this
type of formatting.

That's because it is difficult and requires quite a lot of code, too much to post here. But, for example, to correct invalid input:

Private Sub Form_Error(DataErr As Integer, Response As Integer)

    Const TimeHourMaximum   As Integer = 24
    Const TimeHourDefault   As Integer = 20
    Const TimeMinuteTenMax  As Integer = 5

    Dim ctl                 As Control

    Dim Text                As String
    Dim SelStart            As Integer

    On Error Resume Next

    Set ctl = Screen.ActiveControl

    Select Case ctl.Name
        Case "Logon"
            Text = ctl.Text
            SelStart = ctl.SelStart
            If Not IsDate(Text) Then
                DoCmd.Beep
                If Val(Left(Text, 2)) > TimeHourMaximum Then
                    Mid(Text, 1) = CStr(TimeHourDefault)
                ElseIf Len(Text) > 3 Then
                    ' Length of Text is larger than two hour digits and the kolon.
                    Mid(Text, 1 + 3) = CStr(TimeMinuteTenMax)
                End If
            End If
            ctl.Text = Text
            ctl.SelStart = SelStart
            ctl.SelLength = 1
            Response = acDataErrContinue
    End Select

    Set ctl = Nothing

End Sub
```

Full code, documentation, and a demo application is posted with my project VBA.TimeEntry at GitHub:

Entering 24-hour time with input mask and full validation in Microsoft Access

Body:
I can't seem to find any documentation for it online surrounding this
type of formatting.

That's because it is difficult and requires quite a lot of code, too much to post here. But, for example, to correct invalid input:

Private Sub Form_Error(DataErr As Integer, Response As Integer)

    Const TimeHourMaximum   As Integer = 24
    Const TimeHourDefault   As Integer = 20
    Const TimeMinuteTenMax  As Integer = 5

    Dim ctl                 As Control

    Dim Text                As String
    Dim SelStart            As Integer

    On Error Resume Next

    Set ctl = Screen.ActiveControl

    Select Case ctl.Name
        Case "Logon"
            Text = ctl.Text
            SelStart = ctl.SelStart
            If Not IsDate(Text) Then
                DoCmd.Beep
                If Val(Left(Text, 2)) > TimeHourMaximum Then
                    Mid(Text, 1) = CStr(TimeHourDefault)
                ElseIf Len(Text) > 3 Then
                    ' Length of Text is larger than two hour digits and the kolon.
                    Mid(Text, 1 + 3) = CStr(TimeMinuteTenMax)
                End If
            End If
            ctl.Text = Text
            ctl.SelStart = SelStart
            ctl.SelLength = 1
            Response = acDataErrContinue
    End Select

    Set ctl = Nothing

End Sub

Full code, documentation, and a demo application is posted with my project VBA.TimeEntry at GitHub:

Entering 24-hour time with input mask and full validation in Microsoft Access


问:
Javascript event handler on body but not on input
I have the following  event handler

document.addEventListener('keydown', handleBodyKeyDown, false);

HOW DO i prevent it from occurring when inside a input box

答:
This worked for me:</p>
```<code>const fromInput = event => event.srcElement instanceof HTMLInputElement;

function handleBodyKeyDown(event) {
  if(fromInput(event))
    return;

  // do your magic here
}
</code>```

Body:
This worked for me:

const fromInput = event => event.srcElement instanceof HTMLInputElement;

function handleBodyKeyDown(event) {
  if(fromInput(event))
    return;

  // do your magic here
}


问:
Tailwind divide-y class place weird
I'm facing a problem when I use the divide-y class from Tailwind, I created an example from my original code and here is a link : https://play.tailwindcss.com/q28EwgI0Ho.

```<code><body>
  <div class="bg-blue-900 text-center py-12">Random Body</div>
  <div class="relative pt-12">
    <div class="bg-blue-900 absolute inset-0 h-24" />
    <div class="grid grid-cols-2 divide-x divide-y rounded-xl w-11/12 bg-white mx-auto pb-2">
      <div class="relative p-8">
        <div class="absolute bg-green-500 inset-x-0 w-1/5 md:w-1/12 text-center mx-auto -mt-12">Title</div>
        <div class="text-center text-xs">Random Text</div>
      </div>
      <div class="relative p-8">
        <div class="absolute bg-green-500 inset-x-0 w-1/5 md:w-1/12 text-center mx-auto -mt-12">Title</div>
        <div class="text-center text-xs">Random Text</div>
      </div>
      <div class="relative bg-white col-span-2">
        <div class="text-center text-xs">Random Text</div>
      </div>
    </div>
  </div>
</body>
</code>```

As you can see the divide-x property doesn't work well on the right side, it flows over and we can see it as the div have rounded corners. How can I avoid this please ?

Notice that I can't use overflow-hidden as this causes the title div to be hidden.

答: the problem is in using divide-y, instead, you can add border-t for the title which is below. Example: https://play.tailwindcss.com/7aPvDxo7z6

Title: Tailwind divide-y class place weird

Body:
I'm facing a problem when I use the divide-y class from Tailwind, I created an example from my original code and here is a link : https://play.tailwindcss.com/q28EwgI0Ho.

Random Body

Title

Random Text

Title

Random Text

Random Text

As you can see the divide-x property doesn't work well on the right side, it flows over and we can see it as the div have rounded corners. How can I avoid this please ?

Notice that I can't use overflow-hidden as this causes the title div to be hidden.


问:
Why is my code is not working? This method must return a result of type int
Im trying to code a tic tac toe game using the minimax algorithm. but the method failing, it always says "This method must return a result of type int"

the method is allways is going to return a result of type int

 static int minimax(String[][] board, int depth, boolean maxPlayer)
    {
      if (depth == 0 || gameOver(board) == true)
      {
        return gameEvaluation(board);
      }
      if (maxPlayer == true)
      {
        int maxEval = -100;
        for (int x = 0; x < 3; x++)
        {
          for (int y = 0; y < 3; y++)
          {
            if (board[x][y].equals(" "))
            {
              board[x][y] = "x";
              int eval = minimax(board, (depth - 1), false);
              maxEval = Math.max(maxEval, eval);
              board[x][y] = " ";
              return maxEval;
            }

          }
        }
      }
      else
      {
        int minEval = 100;
        for (int x = 0; x < 3; x++)
        {
          for (int y = 0; y < 3; y++)
          {
            if (board[x][y].equals(" "))
            {
              String[][] tempBoard = board;
              tempBoard[x][y] = "o";
              int eval = minimax(tempBoard, (depth - 1), true);
              minEval = Math.max(minEval, eval);
              return minEval;
            }

          }
        }
      }
    }
```

答:
You need to break up your logic in smaller methods.  For started, everything in your second if{} should go into one method and everything your else{} should go in another method. Then you can unit test each one independently for debugging.

if a method has a return value, ALWAYS have the last line in that method to either return a known value or throw an exception.  This is your problem. Whatever use case you have isn't hitting your other return statements so the method reaches the end with no return and throws the exception.


问:
why I get undefined value instead my input value
I'm new in JavaScript and I have a problem, it'll be great if someone could help me.
I'm trying to write something from one
 to h4.
my code is:

function ok() {
  document.getElementById("out").innerHTML = document.getElementById("name").value;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label id="label">your text is:</label>
<br>
<input type="text" />
<p id="name" style="font-family: 'Courier New', Courier, monospace;"></p>
<button type="submit" id="click" onclick="ok()">click</button>
<h4 id="out" style="font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;"></h4></code>```

but when I'm doing it I get undefined.
If someone could help me understand what I'm doing wrong it'll be great.

答:
It is giving undefined because
 element is empty and you are using .value you need to use .innerHTML so that is why it is returning undefined.

I changed your code a little bit you can see I am fetching values from the input tag and displaying them in p tag and h4 tag.

function ok()
{
document.getElementById("out").innerHTML=document.getElementById("name").innerHTML=document.getElementById("inputname").value;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label id="label">your text is:</label>
<br>
<input type="text" id="inputname"/>
<p id="name" style="font-family: 'Courier New', Courier, monospace;"></p>
<button type="submit" id="click" onclick="ok()">click</button>
<h4 id="out" style="font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;"></h4></code>```

Body:
I'm new in JavaScript and I have a problem, it'll be great if someone could help me.
I'm trying to write something from one
 to h4.
my code is:

function ok() {
  document.getElementById("out").innerHTML = document.getElementById("name").value;
}

your text is:

<input type="text" />

<button type="submit" id="click" onclick="ok()">click</button>

but when I'm doing it I get undefined.
If someone could help me understand what I'm doing wrong it'll be great.

Body:
It is giving undefined because <p> element is empty and you are using .value you need to use .innerHTML so that is why it is returning undefined.

I changed your code a little bit you can see I am fetching values from the input tag and displaying them in p tag and h4 tag.

function ok()
{
document.getElementById("out").innerHTML=document.getElementById("name").innerHTML=document.getElementById("inputname").value;
}

<label id="label">your text is:</label>
<br>
<input type="text" id="inputname"/>
<p id="name" style="font-family: 'Courier New', Courier, monospace;"></p>
<button type="submit" id="click" onclick="ok()">click</button>
<h4 id="out" style="font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;"></h4>


问:
PowerShell msiexec silent uninstall
I'm attempting to uninstall a program "Global VPN Client" from over 150 computers, these computers have multiple versions with different identifying numbers. I'm try to perform this silently and with no reboot. So far here's my code:

```<code>$GUID = Get-WmiObject -Class Win32_Product | where name -Like "Global VPN Client" | select IdentifyingNumber

$Arguments = "/x" + $GUID + "/qn REBOOT=ReallySuppress"

Start-Process msiexec.exe -Wait -ArgumentList $Arguments
</code>```

The process starts however it doesn't perform this silently, my assumption is because the last line starts the "/x" and $GUID, this starting the uninstall before passing the last bit of the arguments.

Any advice or insight to get this working and have the wanted behavior?

答:
First problem:

```<code> $GUID = Get-WmiObject -Class Win32_Product | where name -Like "Global VPN Client" | select IdentifyingNumber
</code>```

The Select-Object (alias select) command outputs an object, so the GUID value actually is in $GUID.IdentifyingNumber. You could use it as such, but it would be conceptually clearer to assign the value of property IdentifyingNumber to $GUID:

```<code>$GUID = Get-WmiObject -Class Win32_Product | where name -Like "Global VPN Client" | select -Expand IdentifyingNumber

# alternative:
$GUID = (Get-WmiObject -Class Win32_Product | where name -Like "Global VPN Client").IdentifyingNumber
</code>```

There is another problem:

```<code>$Arguments = "/x" + $GUID + "/qn REBOOT=ReallySuppress"
</code>```

A space character is missing between /x and the $GUID. Either explicitly insert a space or let PowerShell do it automatically by passing an array of arguments:

```<code>$Arguments = "/x", $GUID, "/qn", "REBOOT=ReallySuppress"
Start-Process msiexec.exe -Wait -ArgumentList $Arguments
</code>```

Title: PowerShell msiexec silent uninstall

Body:
I'm attempting to uninstall a program "Global VPN Client" from over 150 computers, these computers have multiple versions with different identifying numbers. I'm try to perform this silently and with no reboot. So far here's my code:

$GUID = Get-WmiObject -Class Win32_Product | where name -Like "Global VPN Client" | select IdentifyingNumber

$Arguments = "/x" + $GUID + "/qn REBOOT=ReallySuppress"

Start-Process msiexec.exe -Wait -ArgumentList $Arguments

The process starts however it doesn't perform this silently, my assumption is because the last line starts the "/x" and $GUID, this starting the uninstall before passing the last bit of the arguments.

Any advice or insight to get this working and have the wanted behavior?

Body:
First problem:

 $GUID = Get-WmiObject -Class Win32_Product | where name -Like "Global VPN Client" | select IdentifyingNumber

The Select-Object (alias select) command outputs an object, so the GUID value actually is in $GUID.IdentifyingNumber. You could use it as such, but it would be conceptually clearer to assign the value of property IdentifyingNumber to $GUID:

$GUID = Get-WmiObject -Class Win32_Product | where name -Like "Global VPN Client" | select -Expand IdentifyingNumber

# alternative:
$GUID = (Get-WmiObject -Class Win32_Product | where name -Like "Global VPN Client").IdentifyingNumber

There is another problem:

$Arguments = "/x" + $GUID + "/qn REBOOT=ReallySuppress"

A space character is missing between /x and the $GUID. Either explicitly insert a space or let PowerShell do it automatically by passing an array of arguments:

$Arguments = "/x", $GUID, "/qn", "REBOOT=ReallySuppress"
Start-Process msiexec.exe -Wait -ArgumentList $Arguments


问:
How to I solve formatting problem on vscode for react?
I've started watching a React Tutorial.

And I do have problem, vscode doesn't format styled consts.
Also if I want to write fs14 or fs It doesn't recommand me anything.

```<code>const Container = styled.div`
width: 100%;
height: 100vh;
display: flex;
position: relative;
background-color: coral;

`

const Arrow = styled.div`

    width: 50px;
    height: 50px;
    background-color: #fff7f7;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: absolute;
    top: 0;
    bottom: 0;
    left: ${(props) => props.direction === "left" && "10px"};
    right: ${(props) => props.direction === "right" && "10px"};
    margin: auto;
`

</code>```

After I format the file, the Container remains the same.
Also If I want to write fs/fs14 for example it doesn't recommand my font-size => font-size: 14;

Help please? :D

答: Try installing the styled components extension and see if that solves the problem https://marketplace.visualstudio.com/items?itemName=styled-components.vscode-styled-components</p>

Body:
I've started watching a React Tutorial.

And I do have problem, vscode doesn't format styled consts.
Also if I want to write fs14 or fs It doesn't recommand me anything.

const Container = styled.div`
width: 100%;
height: 100vh;
display: flex;
position: relative;
background-color: coral;

`

const Arrow = styled.div`

    width: 50px;
    height: 50px;
    background-color: #fff7f7;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: absolute;
    top: 0;
    bottom: 0;
    left: ${(props) => props.direction === "left" && "10px"};
    right: ${(props) => props.direction === "right" && "10px"};
    margin: auto;
`

After I format the file, the Container remains the same.
Also If I want to write fs/fs14 for example it doesn't recommand my font-size => font-size: 14;

Help please? :D


问:
How to locate nodes in the middle in plotly sankey diagram
With plotly sankey diagram I want to locate a node in the middle using code, but since this node does not have a flow for another node, plotly places it at the right end. I have the next code:

```<code>import plotly.graph_objects as go

fig1 = go.Figure(
    go.Sankey(
        node={"label": ["A", "B", "C", "D", "E", "F"]},
        link={
            "source": [0, 0, 0, 1, 2, 2],
            "target": [1, 2, 3, 4, 4, 5],
            "value": [20, 10, 20, 20, 5, 15]
        }
    )
)
fig1.show()
</code>```

The output:

For example, for the image I would like to locate node D below nodes B and C.

答:
This is not technically an answer as it uses another package (pyAlluv) that creates matplotlib figures.

The package needs to be installed directly from github, for example with:

```<code>pip install --upgrade --no-deps git+https://github.com/tools4digits/pyalluv.git
</code>```

The example is an adaptation from one of the existing examples:

```<code>import numpy as np
from pyalluv import Alluvial
import matplotlib.pyplot as plt

ext = [10, ]  # start at t1 with a single node containing 10 elements
flows = [[[5],  # flow form node 1 at t1 to node 1 at t2
          [2],  # flow from node 1 at t1 to node 2 at t2
          [3]],  # ...
         [[4, 0, 0],  # flows from nodes 1, 2, 3 at t2 to node 1 at t3
          [1, 0, 3]]]  # flows from nodes 1, 2, 3 at t2 to node 2 at t3
alluv = Alluvial(x=['t1', 't2', 't3'], flows=flows, ext=ext, width=0.2, yoff=0, layout=['top', 'optimized', 'top'])

plt.show()
</code>```

However, note that the package is indicated to be work in progress

It allows for quite some customization, that is not really documented though:

```<code>from pyalluv import Alluvial
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ext = [10, ]
flows = [[[5],
          [2],
          [3]],
         [[4, 0, 0],
          [1, 0, 3]]]
alluv = Alluvial(ax=ax, x=['t1', 't2', 't3'], flowprops={'fc':'gray', 'alpha':0.4}, ec='gray')
diag0 = alluv.add(flows=flows, ext=ext, width=0.2, yoff=0,
                 layout=['top', 'optimized', 'top'])
diag0.get_block((1,0)).set_facecolor('red')
diag0.get_block((1,1)).set_facecolor('purple')
diag0.get_block((1,2)).set_facecolor('green')
diag0.get_block((2,0)).set_facecolor('orange')
diag0.get_block((2,1)).set_facecolor('lightblue')
alluv.finish()

plt.show()

</code>```

Body:
With plotly sankey diagram I want to locate a node in the middle using code, but since this node does not have a flow for another node, plotly places it at the right end. I have the next code:

import plotly.graph_objects as go

fig1 = go.Figure(
    go.Sankey(
        node={"label": ["A", "B", "C", "D", "E", "F"]},
        link={
            "source": [0, 0, 0, 1, 2, 2],
            "target": [1, 2, 3, 4, 4, 5],
            "value": [20, 10, 20, 20, 5, 15]
        }
    )
)
fig1.show()

The output:

For example, for the image I would like to locate node D below nodes B and C.

Body:
This is not technically an answer as it uses another package (pyAlluv) that creates matplotlib figures.

The package needs to be installed directly from github, for example with:

pip install --upgrade --no-deps git+https://github.com/tools4digits/pyalluv.git

The example is an adaptation from one of the existing examples:

import numpy as np
from pyalluv import Alluvial
import matplotlib.pyplot as plt

ext = [10, ]  # start at t1 with a single node containing 10 elements
flows = [[[5],  # flow form node 1 at t1 to node 1 at t2
          [2],  # flow from node 1 at t1 to node 2 at t2
          [3]],  # ...
         [[4, 0, 0],  # flows from nodes 1, 2, 3 at t2 to node 1 at t3
          [1, 0, 3]]]  # flows from nodes 1, 2, 3 at t2 to node 2 at t3
alluv = Alluvial(x=['t1', 't2', 't3'], flows=flows, ext=ext, width=0.2, yoff=0, layout=['top', 'optimized', 'top'])

plt.show()

However, note that the package is indicated to be work in progress

It allows for quite some customization, that is not really documented though:

from pyalluv import Alluvial
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ext = [10, ]
flows = [[[5],
          [2],
          [3]],
         [[4, 0, 0],
          [1, 0, 3]]]
alluv = Alluvial(ax=ax, x=['t1', 't2', 't3'], flowprops={'fc':'gray', 'alpha':0.4}, ec='gray')
diag0 = alluv.add(flows=flows, ext=ext, width=0.2, yoff=0,
                 layout=['top', 'optimized', 'top'])
diag0.get_block((1,0)).set_facecolor('red')
diag0.get_block((1,1)).set_facecolor('purple')
diag0.get_block((1,2)).set_facecolor('green')
diag0.get_block((2,0)).set_facecolor('orange')
diag0.get_block((2,1)).set_facecolor('lightblue')
alluv.finish()

plt.show()


问:
SSIS OLE DB Destination Editor - Create New Table not an option?
I am trying to have upload a CSV file to my SQL Server via SSIS. Previously- like a few months ago- I was able to click 'New' on the destination editor to create a generic table based on the imported data. Is that option no longer available for some reason? I updated everything and made sure my credentials are correct and that I have read/write access but can't seem to get anything working. I'm using Visual Studio 2017 with SSDT.

My screen used to look like this :

But now it looks like this :

答:
I faced the same issue previously. The reason was that the TargetServerVersion was not set correctly. Make sure that this property is set to the same version of the SQL Server instance you are using.

How to change TargetServerVersion of my SSIS Project?


问:
how to set a context to NSString drawAtPoint?
I currently working on encapsulation many [NSString drawAtPoint:withFont:] function calls to a method so that I could draw lots of strings by a single call, but how can I tell the method where to draw these strings?

What if I pass a CGContextRef to it, how to set a CGContextRef as current context?

答:
Maybe you need this part of code:</p>

```<code>CGContextRef context = UIGraphicsGetCurrentContext();
</code>```

Body:
Maybe you need this part of code:

CGContextRef context = UIGraphicsGetCurrentContext();