问:
Merging Flow with one shot data
I have a Flow that fetches items from database (this is easy using Room), and then I have another data source which is an API. I can call this API (they don't implement Flows because it is an old Java API) which will give me other set of items (same type as the database ones).

My Room database returns a Flow<List<MyItem>> already and I can show it, and it gets updated on adding/deleting items, but now I need to fetch the other set of items from the API and I don't know how to proceed. Furthermore, I only can fetch them if the user has logged in (i.e., if the user has a valid token).

So, in order to use combine, I have used the function callbackFlow to get the items as a Flow and then I combine the flow from database and the flow from the API. However, I don't know how to update this flow from the API when the user logs in (fetch items) or logs out (clear items).

In my ideal world, I would have a LiveData which has the session token, and if it is null I would clear the flow and otherwise I would make the petition to the API, but I don't know how to implement this, I am new to the Flow concept and components.

Edit: I tried the following, but I don't know if I'm on the right path.

```<code>override fun getItemsAsFlow(): Flow<List<Item>>{
        return flow {
            val isLoggedIn = _loggedIn.value ?: false
            var id = 1000000L
            if (isLoggedIn) {
                val list = ItemAPIManager.getItems().map {
                    Item(id = id++, name = it.name)
                }
                emit(list)
            }
        }
    }
</code>```

Can anyone help me? Thank you.

Update: Based on @Tenfour04 answer, I updated my code. My API provider does this:

```<code>override fun getItemsAsFlow(): Flow<List<Item>> {
        val items =
        _loggedIn.flatMapLatest { loggedIn ->
            if(loggedIn) {
                callbackFlow {
                    var id = 1000000L
                    val list = ItemAPIManager.getItems().map {
                        Item(id = id++, name = it.name)
                    }
                    trySend(list)
                    awaitClose()
                }
            }
            else emptyFlow()
        }
        return items
    }
</code>```

My ViewModel where all these merge to create a RecyclerView has this function:

```<code>private val _databaseItems: Flow<List<Item>> = databaseProvider.getItemsAsFlow()
private val _otherDatabaseItems: Flow<List<Item>> = databaseProvider.getSpecialItemsAsFlow()
private val _apiItems: Flow<List<Item>> = apiProvider.getItemsAsFlow()

private fun fetchItems(): LiveData<List<ItemViewModel>> {
        val itemViewModelFlow = _databaseItems.combine<List<Item>, List<Item>, List<ItemViewModel>>(_otherDatabaseItems) { dbItems1, dbItems2 ->
            val retList = arrayListOf<ItemViewModel>()
            if (settingsProvider.areTheOtherItemsEnabled) {
                retList.addAll(createViewData(dbItems2))
            }
            retList.addAll(createViewData(dbItems1))
            return@combine retList
        }.combine<List<ItemViewModel>, List<Item>, List<ItemViewModel>>(_apiItems) { itemViewModels, apiItems ->
            val retList = arrayListOf<ItemViewModel>()
            retList.addAll(itemViewModels)
            retList.addAll(createViewData(apiItems))
            return@combine retList
        }

        return itemViewModelFlow.asLiveData()
    }
</code>```

The fact that I have two database lists is not relevant here, we can treat them as one. Basically, if a setting is enabled, these will get shown to the user, otherwise they won't.

The createViewData function just transforms a list of items into a list of item view models that are used in the RecyclerView.

Now if I'm logged in when I start the app, I can see the two database item lists, and I can see the API items, but if I log out I still can see the API items. Furthermore, if I'm logged out I cannot even see the database items (which I should).

Thank you for your patience, as I'm still learning Flows.

答:
Your attempt in your edit will not change behavior when logged in state changes unless you cancel and recollect it.

I’m on my phone so I might make a syntax error, but this would do what you’ve described. I don’t really understand what you’re doing with the items in your database (like whether they are are a cache of previously fetched API items or if they are persistent supplementary items) so I left that out.

```<code>// In your API provider/manager class:

// update this when login state changes
private val isLoggedIn = MutableStateFlow(false)

// The callbackFlow that fetches API items
private val fetchedItems: Flow<List<MyItem>> = TODO()

// Flow that starts collecting and emitting from fetchedItems at
// login and emits an empty list when logout occurs.
val loggedInItems = isLoggedIn.flatMapLatest { loggedIn ->
    if (loggedIn) fetchedItems else flowOf(emptyList())
}
</code>```

If the callback flow depends on credentials provided by login, then the isLoggedIn flow might be expanded to use a class that wraps login state with those credentials, and the callback flow might be more naturally defined inside the flatMapLatest flow so it can use those credentials when they become available. Something like this:

```<code>sealed interface LoginState {
    object LoggedOut: LoginState
    data class LoggedIn(val token: String): LoginState
}

private val loginState = MutableStateFlow<LoginState>(LoggedOut)

val loggedInItems = loginState.flatMapLatest { loginState ->
    when (loginState) {
        LoggedOut -> flowOf(emptyList())
        is LoggedIn -> callbackFlow {
            val token = loginState.token
            //...
        }
    }
}
</code>```

Title: Merging Flow with one shot data

Body:
I have a Flow that fetches items from database (this is easy using Room), and then I have another data source which is an API. I can call this API (they don't implement Flows because it is an old Java API) which will give me other set of items (same type as the database ones).

My Room database returns a Flow<List<MyItem>> already and I can show it, and it gets updated on adding/deleting items, but now I need to fetch the other set of items from the API and I don't know how to proceed. Furthermore, I only can fetch them if the user has logged in (i.e., if the user has a valid token).

So, in order to use combine, I have used the function callbackFlow to get the items as a Flow and then I combine the flow from database and the flow from the API. However, I don't know how to update this flow from the API when the user logs in (fetch items) or logs out (clear items).

In my ideal world, I would have a LiveData which has the session token, and if it is null I would clear the flow and otherwise I would make the petition to the API, but I don't know how to implement this, I am new to the Flow concept and components.

Edit: I tried the following, but I don't know if I'm on the right path.

override fun getItemsAsFlow(): Flow<List<Item>>{
        return flow {
            val isLoggedIn = _loggedIn.value ?: false
            var id = 1000000L
            if (isLoggedIn) {
                val list = ItemAPIManager.getItems().map {
                    Item(id = id++, name = it.name)
                }
                emit(list)
            }
        }
    }

Can anyone help me? Thank you.

Update: Based on @Tenfour04 answer, I updated my code. My API provider does this:

override fun getItemsAsFlow(): Flow<List<Item>> {
        val items =
        _loggedIn.flatMapLatest { loggedIn ->
            if(loggedIn) {
                callbackFlow {
                    var id = 1000000L
                    val list = ItemAPIManager.getItems().map {
                        Item(id = id++, name = it.name)
                    }
                    trySend(list)
                    awaitClose()
                }
            }
            else emptyFlow()
        }
        return items
    }

My ViewModel where all these merge to create a RecyclerView has this function:

private val _databaseItems: Flow<List<Item>> = databaseProvider.getItemsAsFlow()
private val _otherDatabaseItems: Flow<List<Item>> = databaseProvider.getSpecialItemsAsFlow()
private val _apiItems: Flow<List<Item>> = apiProvider.getItemsAsFlow()

private fun fetchItems(): LiveData<List<ItemViewModel>> {
        val itemViewModelFlow = _databaseItems.combine<List<Item>, List<Item>, List<ItemViewModel>>(_otherDatabaseItems) { dbItems1, dbItems2 ->
            val retList = arrayListOf<ItemViewModel>()
            if (settingsProvider.areTheOtherItemsEnabled) {
                retList.addAll(createViewData(dbItems2))
            }
            retList.addAll(createViewData(dbItems1))
            return@combine retList
        }.combine<List<ItemViewModel>, List<Item>, List<ItemViewModel>>(_apiItems) { itemViewModels, apiItems ->
            val retList = arrayListOf<ItemViewModel>()
            retList.addAll(itemViewModels)
            retList.addAll(createViewData(apiItems))
            return@combine retList
        }

        return itemViewModelFlow.asLiveData()
    }

The fact that I have two database lists is not relevant here, we can treat them as one. Basically, if a setting is enabled, these will get shown to the user, otherwise they won't.

The createViewData function just transforms a list of items into a list of item view models that are used in the RecyclerView.

Now if I'm logged in when I start the app, I can see the two database item lists, and I can see the API items, but if I log out I still can see the API items. Furthermore, if I'm logged out I cannot even see the database items (which I should).

Thank you for your patience, as I'm still learning Flows.

Body:
Your attempt in your edit will not change behavior when logged in state changes unless you cancel and recollect it.

I’m on my phone so I might make a syntax error, but this would do what you’ve described. I don’t really understand what you’re doing with the items in your database (like whether they are are a cache of previously fetched API items or if they are persistent supplementary items) so I left that out.

// In your API provider/manager class:

// update this when login state changes
private val isLoggedIn = MutableStateFlow(false)

// The callbackFlow that fetches API items
private val fetchedItems: Flow<List<MyItem>> = TODO()

// Flow that starts collecting and emitting from fetchedItems at
// login and emits an empty list when logout occurs.
val loggedInItems = isLoggedIn.flatMapLatest { loggedIn ->
    if (loggedIn) fetchedItems else flowOf(emptyList())
}

If the callback flow depends on credentials provided by login, then the isLoggedIn flow might be expanded to use a class that wraps login state with those credentials, and the callback flow might be more naturally defined inside the flatMapLatest flow so it can use those credentials when they become available. Something like this:

sealed interface LoginState {
    object LoggedOut: LoginState
    data class LoggedIn(val token: String): LoginState
}

private val loginState = MutableStateFlow<LoginState>(LoggedOut)

val loggedInItems = loginState.flatMapLatest { loginState ->
    when (loginState) {
        LoggedOut -> flowOf(emptyList())
        is LoggedIn -> callbackFlow {
            val token = loginState.token
            //...
        }
    }
}


来源: stackexchange

问:
wait activity for result from another app android
I have 2 applications, APP1 will start a transaction and will send some data to APP2 then APP2 will return to APP1 with updated data then APP1 will continue the transaction.

what is the best way to this in android?

is there a way to wait activity for result from another app?

Thank you.

答:
I used to use startActivityForResult for same situation like you.
but I see it is deprecated now and I recommend you to check this.

OnActivityResult method is deprecated, what is the alternative?

ContentLicense: CC BY-SA 4.0


问:
Rotate meshgrid with numpy
I am wanting to produce a meshgrid whose coordinates have been rotated.  I have to do the rotation in a double loop and I'm sure there is a better way to vectorize it.  The code goes as so:

```<code># Define the range for x and y in the unrotated matrix
xspan = linspace(-2*pi, 2*pi, 101)
yspan = linspace(-2*pi, 2*pi, 101)

# Generate a meshgrid and rotate it by RotRad radians.
def DoRotation(xspan, yspan, RotRad=0):

    # Clockwise, 2D rotation matrix
    RotMatrix = np.array([  [np.cos(RotRad),  np.sin(RotRad)],
                            [-np.sin(RotRad), np.cos(RotRad)]])
    print RotMatrix

    # This makes two 2D arrays which are the x and y coordinates for each point.
    x, y = meshgrid(xspan,yspan)

    # After rotating, I'll have another two 2D arrays with the same shapes.
    xrot = zeros(x.shape)
    yrot = zeros(y.shape)

    # Dot the rotation matrix against each coordinate from the meshgrids.
    # I BELIEVE THERE IS A BETTER WAY THAN THIS DOUBLE LOOP!!!
    # I BELIEVE THERE IS A BETTER WAY THAN THIS DOUBLE LOOP!!!
    # I BELIEVE THERE IS A BETTER WAY THAN THIS DOUBLE LOOP!!!
    # I BELIEVE THERE IS A BETTER WAY THAN THIS DOUBLE LOOP!!!
    # I BELIEVE THERE IS A BETTER WAY THAN THIS DOUBLE LOOP!!!
    # I BELIEVE THERE IS A BETTER WAY THAN THIS DOUBLE LOOP!!!
    for i in range(len(xspan)):
        for j in range(len(yspan)):
            xrot[i,j], yrot[i,j] = dot(RotMatrix, array([x[i,j], y[i,j]]))

    # Now the matrix is rotated
    return xrot, yrot

# Pick some arbitrary function and plot it (no rotation)
x, y = DoRotation(xspan, yspan, 0)
z = sin(x)+cos(y)
imshow(z)
</code>```

```<code># And now with 0.3 radian rotation so you can see that it works.
x, y = DoRotation(xspan, yspan, 0.3)
z = sin(x)+cos(y)
figure()
imshow(z)
</code>```

It seems silly to have to write a double loop over the two meshgrids.  Do one of the wizards out there have an idea how to vectorize this?

答:
Just in case you want to go for 3D, scipy.spatial.transform.Rotation may be useful

```<code>import numpy as np
from scipy.spatial.transform import Rotation as R

# define lines for x- and y-subdivision
x = np.linspace(-5, 5)
y = np.linspace(-5, 5)

# create meshgrid for a plane surface (just as example)
X, Y  = np.meshgrid(x, y)
Z = np.zeros(X.shape) # alternatively Z may come from a 3D-meshgrid

# define rotation by rotation angle and axis, here 45DEG around z-axis
r = R.from_rotvec(np.pi/4 * np.array([0, 0, 1]))

# arrange point coordinates in shape (N, 3) for vectorized processing
XYZ = np.array([X.ravel(), Y.ravel(), Z.ravel()]).transpose()

# apply rotation
XYZrot = r.apply(XYZ)

# return to original shape of meshgrid
Xrot = XYZrot[:, 0].reshape(X.shape)
Yrot = XYZrot[:, 1].reshape(X.shape)
Zrot = XYZrot[:, 2].reshape(X.shape)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Rotate meshgrid with numpy

Body:
I am wanting to produce a meshgrid whose coordinates have been rotated.  I have to do the rotation in a double loop and I'm sure there is a better way to vectorize it.  The code goes as so:

# Define the range for x and y in the unrotated matrix
xspan = linspace(-2*pi, 2*pi, 101)
yspan = linspace(-2*pi, 2*pi, 101)

# Generate a meshgrid and rotate it by RotRad radians.
def DoRotation(xspan, yspan, RotRad=0):

    # Clockwise, 2D rotation matrix
    RotMatrix = np.array([  [np.cos(RotRad),  np.sin(RotRad)],
                            [-np.sin(RotRad), np.cos(RotRad)]])
    print RotMatrix

    # This makes two 2D arrays which are the x and y coordinates for each point.
    x, y = meshgrid(xspan,yspan)

    # After rotating, I'll have another two 2D arrays with the same shapes.
    xrot = zeros(x.shape)
    yrot = zeros(y.shape)

    # Dot the rotation matrix against each coordinate from the meshgrids.
    # I BELIEVE THERE IS A BETTER WAY THAN THIS DOUBLE LOOP!!!
    # I BELIEVE THERE IS A BETTER WAY THAN THIS DOUBLE LOOP!!!
    # I BELIEVE THERE IS A BETTER WAY THAN THIS DOUBLE LOOP!!!
    # I BELIEVE THERE IS A BETTER WAY THAN THIS DOUBLE LOOP!!!
    # I BELIEVE THERE IS A BETTER WAY THAN THIS DOUBLE LOOP!!!
    # I BELIEVE THERE IS A BETTER WAY THAN THIS DOUBLE LOOP!!!
    for i in range(len(xspan)):
        for j in range(len(yspan)):
            xrot[i,j], yrot[i,j] = dot(RotMatrix, array([x[i,j], y[i,j]]))

    # Now the matrix is rotated
    return xrot, yrot

# Pick some arbitrary function and plot it (no rotation)
x, y = DoRotation(xspan, yspan, 0)
z = sin(x)+cos(y)
imshow(z)

# And now with 0.3 radian rotation so you can see that it works.
x, y = DoRotation(xspan, yspan, 0.3)
z = sin(x)+cos(y)
figure()
imshow(z)

It seems silly to have to write a double loop over the two meshgrids.  Do one of the wizards out there have an idea how to vectorize this?

Body:
Just in case you want to go for 3D, scipy.spatial.transform.Rotation may be useful

import numpy as np
from scipy.spatial.transform import Rotation as R

# define lines for x- and y-subdivision
x = np.linspace(-5, 5)
y = np.linspace(-5, 5)

# create meshgrid for a plane surface (just as example)
X, Y  = np.meshgrid(x, y)
Z = np.zeros(X.shape) # alternatively Z may come from a 3D-meshgrid

# define rotation by rotation angle and axis, here 45DEG around z-axis
r = R.from_rotvec(np.pi/4 * np.array([0, 0, 1]))

# arrange point coordinates in shape (N, 3) for vectorized processing
XYZ = np.array([X.ravel(), Y.ravel(), Z.ravel()]).transpose()

# apply rotation
XYZrot = r.apply(XYZ)

# return to original shape of meshgrid
Xrot = XYZrot[:, 0].reshape(X.shape)
Yrot = XYZrot[:, 1].reshape(X.shape)
Zrot = XYZrot[:, 2].reshape(X.shape)


问:
How to tag and label Google GCP load balancers?
I am not seeing an option to tag google load balancers.  I can do it for compute instances. How can I tag LBs ?

Regards,

Muhammed Roshan

答:
It is now also possible to set labels on load balancer forwarding rules (as well as on static external IP addresses and VPN tunnels)

E.g.

```<code>gcloud compute forwarding-rules update my-ilb --update-labels=key=value
</code>```

Please check for more details in the gcloud reference documentation.

Body:
It is now also possible to set labels on load balancer forwarding rules (as well as on static external IP addresses and VPN tunnels)

E.g.

gcloud compute forwarding-rules update my-ilb --update-labels=key=value

Please check for more details in the gcloud reference documentation.


问:
Running timeout command in batch file without the timout message appearing
I am trying to make a Batch file, and part of it calls for a timeout command for 15 seconds to be called.  This is that part of the code...

```<code>@echo off
timeout 15
echo The script is waiting to run...
pause
</code>```

And the following is displayed...

```<code>Waiting for 15 seconds, press any key to continue...
The script is waiting to run...
pause
</code>```

But what I am trying to do is make the message below the timeout line display in place of the timeout message.  Is there any way that this can be done?

答:
If you want for the command to run without making message and without skip, type in the following code:

```<code>timeout /T 15 /NOBREAK > nul
</code>```

It should disable skipping or message display.

Nul is for disabling the message that is displayed when the script is running command timeout.

/T is for setting the time for the timeout command.

/NOBREAK prevents the timeout command from being skipped.

Note that if you replace nul with any other word, it will still keep the message disabled.

Body:
I am trying to make a Batch file, and part of it calls for a timeout command for 15 seconds to be called.  This is that part of the code...

@echo off
timeout 15
echo The script is waiting to run...
pause

And the following is displayed...

Waiting for 15 seconds, press any key to continue...
The script is waiting to run...
pause

But what I am trying to do is make the message below the timeout line display in place of the timeout message.  Is there any way that this can be done?

Body:
If you want for the command to run without making message and without skip, type in the following code:

timeout /T 15 /NOBREAK > nul

It should disable skipping or message display.

Nul is for disabling the message that is displayed when the script is running command timeout.

/T is for setting the time for the timeout command.

/NOBREAK prevents the timeout command from being skipped.

Note that if you replace nul with any other word, it will still keep the message disabled.


问:
An algorithm that determines the minimum leaf depth and the number of leaves in that depth
I need to make the algorithm that I indicated in the title, but I have a problem with the fact that I don’t know how to make it write out the number of leafs

My code:

```<code>class Node:
    def __init__(self , key):
        self.data = key
        self.left = None
        self.right = None

def minDepth(root):
    if root is None:
        return 0
    if root.left is None and root.right is None:
        return 1
    if root.left is None:
        return minDepth(root.right)+1
    if root.right is None:
        return minDepth(root.left) +1

    return min(minDepth(root.left), minDepth(root.right))+1
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print (minDepth(root))
</code>```

So I would like to ask if anyone knows how to find the number of leafs at certain depth

答:
After finding the minimum depth using your current DFS algorithm, you can perform another DFS search, except you pass along as parameters the 'desired depth' and 'current depth'.

def count_leaves_at_depth(root, desired_depth, current_depth):
    if root is None or current_depth > desired_depth:
        return 0

    if root.left is None and root.right is None:
        return 1 if current_depth == desired_depth else 0

    if root.left is None:
        return count_leaves_at_depth(root=root.right,
                                     desired_depth=desired_depth,
                                     current_depth=current_depth + 1)

    if root.right is None:
        return count_leaves_at_depth(root=root.left,
                                     desired_depth=desired_depth,
                                     current_depth=current_depth + 1)

    return (count_leaves_at_depth(root=root.right,
                                  desired_depth=desired_depth,
                                  current_depth=current_depth + 1)
            + count_leaves_at_depth(root=root.left,
                                    desired_depth=desired_depth,
                                    current_depth=current_depth + 1))

print(count_leaves_at_depth(root=root,
                            desired_depth=minDepth(root),
                            current_depth=1))
```

Body:
I need to make the algorithm that I indicated in the title, but I have a problem with the fact that I don’t know how to make it write out the number of leafs

My code:

class Node:
    def __init__(self , key):
        self.data = key
        self.left = None
        self.right = None

def minDepth(root):
    if root is None:
        return 0
    if root.left is None and root.right is None:
        return 1
    if root.left is None:
        return minDepth(root.right)+1
    if root.right is None:
        return minDepth(root.left) +1

    return min(minDepth(root.left), minDepth(root.right))+1
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print (minDepth(root))

So I would like to ask if anyone knows how to find the number of leafs at certain depth


问:
How to fill NA's when you have enough information to calculate what the NA should be in R
I've got a dataset where there are some NA's but I can manually work out what the values should be as the df is a column for name and the rest of the columns are just numbers followed by a final column with total. Only one NA appears per row at most so I can work out what the value should be by using the total column and the sum of all the other columns. Just wondering what would be the best way to fill these NA's without having to hardcode one by one as the df I'm using is pretty big

example df:

```<code>df = structure(list(city = c("sydney", "new york", "london", "beijing", "paris", "madrid"),
                    year = c(2005:2010),
                    A = c(1, 4, 5 , NA, 2, 1),
                    B = c(3, NA, 4 , 9, 0, 6),
                    C = c(3, 4 , 6, 1, 8, NA),
                    total = c(NA, 10, 15, 14, NA, 15)),
               class = "data.frame", row.names = c(NA, -6L))

df
</code>```

答:
data.table solution

```<code>library(data.table)
setDT(df)

cols <- c("A", "B", "C")

df[, (cols) := lapply(.SD, function(x) {
  ifelse(is.na(x), total - rowSums(.SD, na.rm = T), x)
}), .SDcols = cols][is.na(total), total := rowSums(.SD), .SDcols = cols]

df
#        city year A B C total
# 1:   sydney 2005 1 3 3     7
# 2: new york 2006 4 2 4    10
# 3:   london 2007 5 4 6    15
# 4:  beijing 2008 4 9 1    14
# 5:    paris 2009 2 0 8    10
# 6:   madrid 2010 1 6 8    15
</code>```

data

```<code>df = structure(list(
  city = c("sydney", "new york", "london", "beijing", "paris", "madrid"),
  year = c(2005:2010),
  A = c(1, 4, 5 , NA, 2, 1),
  B = c(3, NA, 4 , 9, 0, 6),
  C = c(3, 4 , 6, 1, 8, NA),
  total = c(NA, 10, 15, 14, NA, 15)),
  class = "data.frame", row.names = c(NA, -6L)
)
</code>```

Body:
I've got a dataset where there are some NA's but I can manually work out what the values should be as the df is a column for name and the rest of the columns are just numbers followed by a final column with total. Only one NA appears per row at most so I can work out what the value should be by using the total column and the sum of all the other columns. Just wondering what would be the best way to fill these NA's without having to hardcode one by one as the df I'm using is pretty big

example df:

df = structure(list(city = c("sydney", "new york", "london", "beijing", "paris", "madrid"),
                    year = c(2005:2010),
                    A = c(1, 4, 5 , NA, 2, 1),
                    B = c(3, NA, 4 , 9, 0, 6),
                    C = c(3, 4 , 6, 1, 8, NA),
                    total = c(NA, 10, 15, 14, NA, 15)),
               class = "data.frame", row.names = c(NA, -6L))

df

Body:
data.table solution

library(data.table)
setDT(df)

cols <- c("A", "B", "C")

df[, (cols) := lapply(.SD, function(x) {
  ifelse(is.na(x), total - rowSums(.SD, na.rm = T), x)
}), .SDcols = cols][is.na(total), total := rowSums(.SD), .SDcols = cols]

df
#        city year A B C total
# 1:   sydney 2005 1 3 3     7
# 2: new york 2006 4 2 4    10
# 3:   london 2007 5 4 6    15
# 4:  beijing 2008 4 9 1    14
# 5:    paris 2009 2 0 8    10
# 6:   madrid 2010 1 6 8    15

data

df = structure(list(
  city = c("sydney", "new york", "london", "beijing", "paris", "madrid"),
  year = c(2005:2010),
  A = c(1, 4, 5 , NA, 2, 1),
  B = c(3, NA, 4 , 9, 0, 6),
  C = c(3, 4 , 6, 1, 8, NA),
  total = c(NA, 10, 15, 14, NA, 15)),
  class = "data.frame", row.names = c(NA, -6L)
)


问:
Comparing two numpy arrays with different lengths line-wise
I am trying to compare all to all elements of two different lenght arrays. Lets say I have an array:

```<code>A = np.array([[15,25,22],[200,200,20]])
</code>```

And second array is an array I want to compare with:

```<code>B = np.array([[150., 350.],
 [250., 450.],
 [150., 350.],
 [400., 600.],
 [400., 600.],
 [650., 850.],
 [550., 750.],
 [650., 850.]])
</code>```

What I need is to compare all the elements on index 0 of all arrays in A (A[:, 0]) with all elements on index 0 in all arrays in array B (B[:, 0]).

If A is just a simple array such as A=[25,40,25], then it is simply done as:

```<code>smaller = np.array(A[0] > B[:, 0]).astype('int')
</code>```

I thought I can transform it to 2d comparison such that

```<code>smaller = np.array(A[:, 0] > B[:, 0]).astype('int')
</code>```

This is not working, error is clear, ValueError: operands could not be broadcast together with shapes (2,) (8,). I understand that this way I cannot compare it but I was not able to find the way how to do so.

My desired output would look like this:

```<code>[[False, False, False, False, False, False, False, False],
 [True, False, True, False, False, False, False, False]]
</code>```

答:
Thanks to @MichaelSzczesny I got the solution I was looking for. Simply adding [:, None] to the comparison worked:

```<code>smaller = np.array(A[:, 0][:, None] > B[:, 0]).astype('int')
</code>```

As explained in Use of None in Array indexing in Python, it adds an axis to the array. Thus from

```<code>[ 15 200]
</code>```

We get

```<code>[[ 15]
 [200]]
</code>```

Body:
I am trying to compare all to all elements of two different lenght arrays. Lets say I have an array:

A = np.array([[15,25,22],[200,200,20]])

And second array is an array I want to compare with:

B = np.array([[150., 350.],
 [250., 450.],
 [150., 350.],
 [400., 600.],
 [400., 600.],
 [650., 850.],
 [550., 750.],
 [650., 850.]])

What I need is to compare all the elements on index 0 of all arrays in A (A[:, 0]) with all elements on index 0 in all arrays in array B (B[:, 0]).

If A is just a simple array such as A=[25,40,25], then it is simply done as:

smaller = np.array(A[0] > B[:, 0]).astype('int')

I thought I can transform it to 2d comparison such that

smaller = np.array(A[:, 0] > B[:, 0]).astype('int')

This is not working, error is clear, ValueError: operands could not be broadcast together with shapes (2,) (8,). I understand that this way I cannot compare it but I was not able to find the way how to do so.

My desired output would look like this:

[[False, False, False, False, False, False, False, False],
 [True, False, True, False, False, False, False, False]]

Body:
Thanks to @MichaelSzczesny I got the solution I was looking for. Simply adding [:, None] to the comparison worked:

smaller = np.array(A[:, 0][:, None] > B[:, 0]).astype('int')

As explained in Use of None in Array indexing in Python, it adds an axis to the array. Thus from

[ 15 200]

We get

[[ 15]
 [200]]


问:
When trying to use turbo console log , variable gets replaced by character
I am new in visual studio code. I was seeking for useful plugins for vs code and I found that Turbo Console Log is a good one.

Now after installing, inside settings.json, I did some changes,

```<code>  "turboConsoleLog.wrapLogMessage":true,
  "turboConsoleLog.insertEnclosingFunction":true,
  "turboConsoleLog.includeFileNameAndLineNum":true,
</code>```

Also I noticed that Turbo Console Log is there and ctrl+alt+L is not have any conflicts with others.

Now when I am trying to use by selecting the word and then press ctrl+alt+L,

the variable replaced by  ̥

Did anyone face similar issue??

Edit:

Command Palette

答:
While I am aware that changing keyboard shortcut is the preferred solution,the root cause of this problem is with the keyboard language.When I switched to English (UK) keyboard, this problem didn't persist.Now there might be other keyboards that might not have this problem,English(UK) is the one I know so far to be free from this issue.

You can switch keyboards from the bottom right language option in the taskbar or press Windows + Space

Body:
I am new in visual studio code. I was seeking for useful plugins for vs code and I found that Turbo Console Log is a good one.

Now after installing, inside settings.json, I did some changes,

  "turboConsoleLog.wrapLogMessage":true,
  "turboConsoleLog.insertEnclosingFunction":true,
  "turboConsoleLog.includeFileNameAndLineNum":true,

Also I noticed that Turbo Console Log is there and ctrl+alt+L is not have any conflicts with others.

Now when I am trying to use by selecting the word and then press ctrl+alt+L,

the variable replaced by  ̥

Did anyone face similar issue??

Edit:

Command Palette


问:
Getting Maven resource exception
Could you please help me to overcome the issue:

Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.1.0:resources (default-resources) on project tight-core: Cannot create resource output directory:C:\TEJA

答: Check write permission on C:\ of Windows OS.

Title: Getting Maven resource exception


问:
show a list of the pages you manage toggle is off by default
My app has been approved for pages_show_list and permissions listed below. Everything was working fine till yesterday, but suddenly when user tries to login, show a list of the pages you manage toggle is off by default.

implementation 'com.facebook.android:facebook-login:[8,9)'
Permissions used : "email, public_profile, pages_show_list, business_management"

Login page image

答:
Adding a permission which is dependent on 'pages_show_list' will make the toggle on and make it disabled. For eg. pages_read_enagagement (but needs to be requested for approval).

Refer permission dependencies here.


问:
Get immediate subdirectories in ruby
I'm trying to write a simple ruby script that will copy a file to the immediate subdirectories of a directory. How would I get only the immediate subdirectories?</p>

答:
Based on @glenra's answer but without changing the directory permanently (which may cause issues with pry):

```<code>def folders
  Dir.chdir("/some/path/you/want/to/check/below") {
    Dir["*"].reject{|o| not File.directory?(o)}
  }
end

puts folders   # ["all", "the", "folders"]
binding.pry    # yay, works

</code>```

Title: Get immediate subdirectories in ruby

Body:
Based on @glenra's answer but without changing the directory permanently (which may cause issues with pry):

def folders
  Dir.chdir("/some/path/you/want/to/check/below") {
    Dir["*"].reject{|o| not File.directory?(o)}
  }
end

puts folders   # ["all", "the", "folders"]
binding.pry    # yay, works


问:
openpyxl - How to retrieve multiple columns of one row from an Excel file?
I'm looking for the correct way to print cell values from one desired row, but I only want the cell values that are in specific columns. e.g. columns 'A','C','F' etc.

Below is the code I currently have, I get no errors with this but am at a loss with how to progress with my desired outcome.

```<code>path_file = 'Readfrom.xlsx'
spreadsheet = load_workbook(path_file)

spreadsheet = spreadsheet.active

desire_columns = spreadsheet['A']

disire_row = spreadsheet['5']

for cell in disire_row:
    print(cell.value)
</code>```

答:
You can read data from excel using pandas

```<code>import pandas as pd
df = pd.read_excel('tmp.xlsx', index_col=0)

#Cell value can be accessed in this way
print (df['ColumnName'].iloc[rowIndex])

#This also can be done in a loop.
for index, row in df.iterrows():
    print(row['ColumnName'])
</code>```

Refer this link for further details
https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html

Body:
I'm looking for the correct way to print cell values from one desired row, but I only want the cell values that are in specific columns. e.g. columns 'A','C','F' etc.

Below is the code I currently have, I get no errors with this but am at a loss with how to progress with my desired outcome.

path_file = 'Readfrom.xlsx'
spreadsheet = load_workbook(path_file)

spreadsheet = spreadsheet.active

desire_columns = spreadsheet['A']

disire_row = spreadsheet['5']

for cell in disire_row:
    print(cell.value)

Body:
You can read data from excel using pandas

import pandas as pd
df = pd.read_excel('tmp.xlsx', index_col=0)

#Cell value can be accessed in this way
print (df['ColumnName'].iloc[rowIndex])

#This also can be done in a loop.
for index, row in df.iterrows():
    print(row['ColumnName'])

Refer this link for further details
https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html


问:
Changing an array column name
I have an array that contains NotePoperties that needs to be modified. When reading the array I need to do some code to figure out what the correct title for the array column should be.

This code is ready and works fine:

```<code>$Permissions | Get-Member | ? MemberType -EQ NoteProperty | % {
    $Column = $Permissions.($_.Name)
    $GroupResult = Switch ($Column[1]) {
        'GROUP' {$Settings[0].Group  + ' '}
        ''      {break}
        Default {$group + ' '}
    }
    $SiteResult = Switch ($Column[0]) {
        'Site'  {$Settings[0].Code + ' '}
        ''      {break}
        Default {$site + ' '}
    }
    $Result = ($GroupResult + $SiteResult + $_.Name).Trim()
}
</code>```

What I'm now trying to do is update/modify the existing title with the generated $Result string from above:

```<code>$_.Name = $Result
</code>```

When doing this, PowerShell throws the error 'Name' is a ReadOnly property..

What is the best way of changing the title of the array? I also need to remove line 2 and line 3, but I can do that afterwards.

Example of the $Permissions array where I'm trying to updated Plant manager to Belgium Awesome Plant manager:

```<code>Plant manager | Sales man | Warehouseman
-------------- ----------  -------------
Site          |           |
Group         | Group     |
Stuff         | Stuff     | Stuff
</code>```

Thank you for your help.

答:
```<code>($json | ConvertTo-csv).replace('"name"','"ServiceAccountName"') | ConvertFrom-csv | ConvertTo-Json
</code>```

$json is an existing json array with a column name "name". I convert it to a csv file wherein the first line defines the columns and replace the "name" with "ServiceAccountName" and convert it back from csv to json

Title: Changing an array column name

Body:
I have an array that contains NotePoperties that needs to be modified. When reading the array I need to do some code to figure out what the correct title for the array column should be.

This code is ready and works fine:

$Permissions | Get-Member | ? MemberType -EQ NoteProperty | % {
    $Column = $Permissions.($_.Name)
    $GroupResult = Switch ($Column[1]) {
        'GROUP' {$Settings[0].Group  + ' '}
        ''      {break}
        Default {$group + ' '}
    }
    $SiteResult = Switch ($Column[0]) {
        'Site'  {$Settings[0].Code + ' '}
        ''      {break}
        Default {$site + ' '}
    }
    $Result = ($GroupResult + $SiteResult + $_.Name).Trim()
}

What I'm now trying to do is update/modify the existing title with the generated $Result string from above:

$_.Name = $Result

When doing this, PowerShell throws the error 'Name' is a ReadOnly property..

What is the best way of changing the title of the array? I also need to remove line 2 and line 3, but I can do that afterwards.

Example of the $Permissions array where I'm trying to updated Plant manager to Belgium Awesome Plant manager:

Plant manager | Sales man | Warehouseman
-------------- ----------  -------------
Site          |           |
Group         | Group     |
Stuff         | Stuff     | Stuff

Thank you for your help.

Body:
($json | ConvertTo-csv).replace('"name"','"ServiceAccountName"') | ConvertFrom-csv | ConvertTo-Json

$json is an existing json array with a column name "name". I convert it to a csv file wherein the first line defines the columns and replace the "name" with "ServiceAccountName" and convert it back from csv to json


问:
How to extract the lines between patterns?
I have a file with format like :

```<code>[PATTERN]
line1
line2
line3
.
.
.
line
[PATTERN]
line1
line2
line3
.
.
.
line
[PATTERN]
line1
line2
line3
.
.
.
line
</code>```

I want to extract the following blocks from above file :

```<code>[PATTERN]
line1
line2
line3
.
.
.
line
</code>```

Note: Number of lines between 2 [PATTERN] may varies, so can't rely on number of lines.

Basically, I want to store each pattern and the lines following it to Database, so I wil have to iterate all such blocks in my file.

How do this with Shell Scripting ?

答:
This assumes you are using bash as your shell. For other shells, the actual solution can be different.

Assuming your data is in data:

```<code>i=0 ; cat data  | while read line ; do \
  if [ "$line" == "[PATTERN]" ] ; then \
    i=$(($i + 1)) ; touch file.$i ; continue ; \
  fi ; echo "$line" >> file.$i ; \
done
</code>```

Change [PATTERN] by your actual separation pattern.

This will create files file.1, file.2, etc.

Edit: responding to request about an awk solution:

```<code>awk '/^\[PATTERN\]$/{close("file"f);f++;next}{print $0 > "file"f}' data
</code>```

The idea is to open a new file each time the [PATTERN] is found (skipping that line - next command), and writing all successive lines to that file. If you need to include [PATTERN] in your generated files, delete the next command.

Notice the escaping of the [ and ], which have special meaning for regular expressions. If your pattern does not contain those, you do not need the escaping. The ^ and $ are advisable, since they tie your pattern to the beginning and end of line, which you will usually need.

Body:
I have a file with format like :

[PATTERN]
line1
line2
line3
.
.
.
line
[PATTERN]
line1
line2
line3
.
.
.
line
[PATTERN]
line1
line2
line3
.
.
.
line

I want to extract the following blocks from above file :

[PATTERN]
line1
line2
line3
.
.
.
line

Note: Number of lines between 2 [PATTERN] may varies, so can't rely on number of lines.

Basically, I want to store each pattern and the lines following it to Database, so I wil have to iterate all such blocks in my file.

How do this with Shell Scripting ?

Body:
This assumes you are using bash as your shell. For other shells, the actual solution can be different.

Assuming your data is in data:

i=0 ; cat data  | while read line ; do \
  if [ "$line" == "[PATTERN]" ] ; then \
    i=$(($i + 1)) ; touch file.$i ; continue ; \
  fi ; echo "$line" >> file.$i ; \
done

Change [PATTERN] by your actual separation pattern.

This will create files file.1, file.2, etc.

Edit: responding to request about an awk solution:

awk '/^\[PATTERN\]$/{close("file"f);f++;next}{print $0 > "file"f}' data

The idea is to open a new file each time the [PATTERN] is found (skipping that line - next command), and writing all successive lines to that file. If you need to include [PATTERN] in your generated files, delete the next command.

Notice the escaping of the [ and ], which have special meaning for regular expressions. If your pattern does not contain those, you do not need the escaping. The ^ and $ are advisable, since they tie your pattern to the beginning and end of line, which you will usually need.


问:
Qt Webassembly via conan package manager
I have a really simple Qt (QML) project :

CMakeLists.txt :

```<code>cmake_minimum_required(VERSION 3.12.2)

project(testtttt VERSION 0.1 LANGUAGES CXX)

set(CMAKE_INCLUDE_CURRENT_DIR ON)

set(CMAKE_AUTOUIC ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

find_package(QT NAMES Qt6 COMPONENTS Core Quick REQUIRED)
find_package(Qt${QT_VERSION_MAJOR} COMPONENTS Core Quick REQUIRED)

set(PROJECT_SOURCES
        main.cpp
        qml.qrc
)

qt_add_executable(testtttt
        MANUAL_FINALIZATION
        ${PROJECT_SOURCES}
)

target_link_libraries(testtttt PRIVATE Qt${QT_VERSION_MAJOR}::Core Qt${QT_VERSION_MAJOR}::Quick)

set_target_properties(testtttt PROPERTIES
    MACOSX_BUNDLE_GUI_IDENTIFIER my.example.com
    MACOSX_BUNDLE_BUNDLE_VERSION ${PROJECT_VERSION}
    MACOSX_BUNDLE_SHORT_VERSION_STRING ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}
)

qt_import_qml_plugins(testtttt)
qt_finalize_executable(testtttt)
</code>```

conanfile.txt :

```<code>[requires]
qtbase/6.2.2@qt/everywhere
qtdeclarative/6.2.2@qt/everywhere
</code>```

main.cpp :

```<code>#include <QGuiApplication>
#include <QQmlApplicationEngine>

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    const QUrl url(QStringLiteral("qrc:/main.qml"));
    QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                     &app, [url](QObject *obj, const QUrl &objUrl) {
        if (!obj && url == objUrl)
            QCoreApplication::exit(-1);
    }, Qt::QueuedConnection);
    engine.load(url);

    return app.exec();
}
</code>```

main.qml :

```<code>import QtQuick
import QtQuick.Window

Window {
    width: 640
    height: 480
    visible: true
    title: qsTr("Hello World")

    Rectangle {
        anchors.fill: parent
        color: "red"

        Text {
            anchors.centerIn: parent
            text: "Hello World!"
        }
    }
}
</code>```

qml.qrc :

```<code><RCC>
    <qresource prefix="/">
        <file>main.qml</file>
    </qresource>
</RCC>
</code>```

As you can see, it is downloading the official Qt conan packages, from the Qt conan server. (So it does NOT use the conan packages from the conan-center-index server.)

I can successfully build and run it under my macOS machine using this script :

build_and_run.sh :

```<code>set -e

conan install qtbuildprofiles/6.2.2@qt/everywhere -r qt

conan install -u conanfile.txt --profile=macos-universal-clang --build=never --update --generator=virtualenv -r qt
source activate.sh

mkdir -p build
cd build
echo "cmake ../ -G Ninja -DCMAKE_BUILD_TYPE=Release"
cmake ../ -G Ninja -DCMAKE_BUILD_TYPE=Release
VERBOSE=1 cmake --build . --config Release --clean-first
cd ..

#Run the built app :
./build/testtttt
</code>```

I am trying to build it for WebAssembly as well, using this script :

buildWasm.sh :

```<code>set -e

conan install qtbuildprofiles/6.2.2@qt/everywhere -r qt

mkdir -p wasmBuildMachine
cd wasmBuildMachine
conan install -u ../conanfile.txt --profile=../macos-universal-clang --build=never --update --generator=virtualenv -r qt
source activate.sh
QT_HOST_PATH=$(echo "$Qt6_DIR" | sed "s#/lib/cmake/Qt6##g")
echo "QT_HOST_PATH : $QT_HOST_PATH"
source deactivate.sh
cd ..

conan install -u conanfile.txt --profile=macos-webassembly-x86_64-clang --build=never --update --generator=virtualenv -r qt
source activate.sh

QT_CMAKE=$(echo "$Qt6_DIR" | sed "s#/lib/cmake/Qt6##g")
QT_CMAKE+="/bin/qt-cmake"
echo "QT_CMAKE : $QT_CMAKE"

mkdir -p buildWasm
cd buildWasm
echo "$QT_CMAKE ../ -G Ninja -DCMAKE_BUILD_TYPE=Release -DQT_HOST_PATH=$QT_HOST_PATH"
$QT_CMAKE ../ -G Ninja -DCMAKE_BUILD_TYPE=Release -DQT_HOST_PATH=$QT_HOST_PATH
VERBOSE=1 cmake --build . --config Release --clean-first
</code>```

The build fails with this error :

```<code>-- Could NOT find Qt6Quick (missing: Qt6Quick_DIR)
CMake Error at CMakeLists.txt:15 (find_package):
Found package configuration file:

/Users/myUser/.conan/data/qtbase/6.2.2/qt/everywhere/package/5f6084cf36d2dec9c03d119ccdb11027ce3fa5ba/lib/cmake/Qt6/Qt6Config.cmake

but it set Qt6_FOUND to FALSE so package "Qt6" is considered to be NOT
FOUND. Reason given by package:

Failed to find Qt component "Quick".

Expected Config file at
"/Users/myUser/.conan/data/qtbase/6.2.2/qt/everywhere/package/5f6084cf36d2dec9c03d119ccdb11027ce3fa5ba/lib/cmake/Qt6Quick/Qt6QuickConfig.cmake"
does NOT exist
</code>```

...and indeed : QtQuick is in the qtdeclarative conan folder (/Users/myUser/.conan/data/qtbase/6.2.2/qt/everywhere/package/...), and not in the qtbase folder.

How could I fix this issue?

I am following these documentation pages :

https://www.qt.io/blog/installing-qt-via-conan-package-manager

https://wiki.qt.io/Using_Conan_for_Qt6

https://www.qt.io/blog/qt-6-build-system

To simplify things : my project can be downloaded from here as well (every sources that I shared above) :

https://wetransfer.com/downloads/e8717b634b2eff069134b4407f77243c20220202190736/81e9433c52a22081915a7d5d144e2ef420220202190748/a8ec17

UPDATE :
I just tried this widget application : Qt/Examples/Qt-6.2.1/widgets/richtext/syntaxhighlighter/ .

It works well, using the exact same conanfile.txt and buildWasm.sh that I shared above.

Here is a screenshot as well about this Example application, that I compiled for WebAssembly, running in Chrome :

So it seems like that the issue is with the QtQuick module...
Possible solution ideas are very well welcomed!
I tried many things, but nothing worked so far...

答:
It turned out that this is a bug on Qt's side :
https://bugreports.qt.io/browse/QTBUG-94524 ( Introduce a QT_ADDITIONAL_HOST_PACKAGES_PREFIX_PATH variable ) .

The same script should work, once that fix will be deployed.

Body:
I have a really simple Qt (QML) project :

CMakeLists.txt :

cmake_minimum_required(VERSION 3.12.2)

project(testtttt VERSION 0.1 LANGUAGES CXX)

set(CMAKE_INCLUDE_CURRENT_DIR ON)

set(CMAKE_AUTOUIC ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

find_package(QT NAMES Qt6 COMPONENTS Core Quick REQUIRED)
find_package(Qt${QT_VERSION_MAJOR} COMPONENTS Core Quick REQUIRED)

set(PROJECT_SOURCES
        main.cpp
        qml.qrc
)

qt_add_executable(testtttt
        MANUAL_FINALIZATION
        ${PROJECT_SOURCES}
)

target_link_libraries(testtttt PRIVATE Qt${QT_VERSION_MAJOR}::Core Qt${QT_VERSION_MAJOR}::Quick)

set_target_properties(testtttt PROPERTIES
    MACOSX_BUNDLE_GUI_IDENTIFIER my.example.com
    MACOSX_BUNDLE_BUNDLE_VERSION ${PROJECT_VERSION}
    MACOSX_BUNDLE_SHORT_VERSION_STRING ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}
)

qt_import_qml_plugins(testtttt)
qt_finalize_executable(testtttt)

conanfile.txt :

[requires]
qtbase/6.2.2@qt/everywhere
qtdeclarative/6.2.2@qt/everywhere

main.cpp :

#include <QGuiApplication>
#include <QQmlApplicationEngine>

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    const QUrl url(QStringLiteral("qrc:/main.qml"));
    QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                     &app, [url](QObject *obj, const QUrl &objUrl) {
        if (!obj && url == objUrl)
            QCoreApplication::exit(-1);
    }, Qt::QueuedConnection);
    engine.load(url);

    return app.exec();
}

main.qml :

import QtQuick
import QtQuick.Window

Window {
    width: 640
    height: 480
    visible: true
    title: qsTr("Hello World")

    Rectangle {
        anchors.fill: parent
        color: "red"

        Text {
            anchors.centerIn: parent
            text: "Hello World!"
        }
    }
}

qml.qrc :

<RCC>
    <qresource prefix="/">
        <file>main.qml</file>
    </qresource>
</RCC>

As you can see, it is downloading the official Qt conan packages, from the Qt conan server. (So it does NOT use the conan packages from the conan-center-index server.)

I can successfully build and run it under my macOS machine using this script :

build_and_run.sh :

set -e

conan install qtbuildprofiles/6.2.2@qt/everywhere -r qt

conan install -u conanfile.txt --profile=macos-universal-clang --build=never --update --generator=virtualenv -r qt
source activate.sh

mkdir -p build
cd build
echo "cmake ../ -G Ninja -DCMAKE_BUILD_TYPE=Release"
cmake ../ -G Ninja -DCMAKE_BUILD_TYPE=Release
VERBOSE=1 cmake --build . --config Release --clean-first
cd ..

#Run the built app :
./build/testtttt

I am trying to build it for WebAssembly as well, using this script :

buildWasm.sh :

set -e

conan install qtbuildprofiles/6.2.2@qt/everywhere -r qt

mkdir -p wasmBuildMachine
cd wasmBuildMachine
conan install -u ../conanfile.txt --profile=../macos-universal-clang --build=never --update --generator=virtualenv -r qt
source activate.sh
QT_HOST_PATH=$(echo "$Qt6_DIR" | sed "s#/lib/cmake/Qt6##g")
echo "QT_HOST_PATH : $QT_HOST_PATH"
source deactivate.sh
cd ..

conan install -u conanfile.txt --profile=macos-webassembly-x86_64-clang --build=never --update --generator=virtualenv -r qt
source activate.sh

QT_CMAKE=$(echo "$Qt6_DIR" | sed "s#/lib/cmake/Qt6##g")
QT_CMAKE+="/bin/qt-cmake"
echo "QT_CMAKE : $QT_CMAKE"

mkdir -p buildWasm
cd buildWasm
echo "$QT_CMAKE ../ -G Ninja -DCMAKE_BUILD_TYPE=Release -DQT_HOST_PATH=$QT_HOST_PATH"
$QT_CMAKE ../ -G Ninja -DCMAKE_BUILD_TYPE=Release -DQT_HOST_PATH=$QT_HOST_PATH
VERBOSE=1 cmake --build . --config Release --clean-first

The build fails with this error :

-- Could NOT find Qt6Quick (missing: Qt6Quick_DIR)
CMake Error at CMakeLists.txt:15 (find_package):
Found package configuration file:

/Users/myUser/.conan/data/qtbase/6.2.2/qt/everywhere/package/5f6084cf36d2dec9c03d119ccdb11027ce3fa5ba/lib/cmake/Qt6/Qt6Config.cmake

but it set Qt6_FOUND to FALSE so package "Qt6" is considered to be NOT
FOUND. Reason given by package:

Failed to find Qt component "Quick".

Expected Config file at
"/Users/myUser/.conan/data/qtbase/6.2.2/qt/everywhere/package/5f6084cf36d2dec9c03d119ccdb11027ce3fa5ba/lib/cmake/Qt6Quick/Qt6QuickConfig.cmake"
does NOT exist

...and indeed : QtQuick is in the qtdeclarative conan folder (/Users/myUser/.conan/data/qtbase/6.2.2/qt/everywhere/package/...), and not in the qtbase folder.

How could I fix this issue?

I am following these documentation pages :

https://www.qt.io/blog/installing-qt-via-conan-package-manager

https://wiki.qt.io/Using_Conan_for_Qt6

https://www.qt.io/blog/qt-6-build-system

To simplify things : my project can be downloaded from here as well (every sources that I shared above) :

https://wetransfer.com/downloads/e8717b634b2eff069134b4407f77243c20220202190736/81e9433c52a22081915a7d5d144e2ef420220202190748/a8ec17

UPDATE :
I just tried this widget application : Qt/Examples/Qt-6.2.1/widgets/richtext/syntaxhighlighter/ .

It works well, using the exact same conanfile.txt and buildWasm.sh that I shared above.

Here is a screenshot as well about this Example application, that I compiled for WebAssembly, running in Chrome :

So it seems like that the issue is with the QtQuick module...
Possible solution ideas are very well welcomed!
I tried many things, but nothing worked so far...


问:
Windows Tesseract OCR getting scattered HOCR out put instead of clean standard format
A quick help is highly appreciated. I am extracting the text from the tiff image through tesseract-OCR.
The output I am looking for is.HOCR (HTML).
I am getting the perfect output in terms of content, but the format looks very unorganized.
But the same when I open with Notepad ++ it gives a clean format.

The windows command line is given below

```<code>Tesseract "Path\image.tiff" "Path\output" HOCR
</code>```

need your help in getting the organised hocr format in notepad as enclosed

How do I get organized  hocr  data when I open with notepad?

答: Problem is not in tesseract, but in notepad. Use some normal text editor like notepad++ or context.</p>

Body:
A quick help is highly appreciated. I am extracting the text from the tiff image through tesseract-OCR.
The output I am looking for is.HOCR (HTML).
I am getting the perfect output in terms of content, but the format looks very unorganized.
But the same when I open with Notepad ++ it gives a clean format.

The windows command line is given below

Tesseract "Path\image.tiff" "Path\output" HOCR

need your help in getting the organised hocr format in notepad as enclosed

How do I get organized  hocr  data when I open with notepad?


问:
How to write case in Switch else statement in javavscript?
//This is my Problem
Complete the getLetter(s) function in the editor. It has one parameter: a string, , consisting of lowercase English alphabetic letters (i.e., a through z). It must return A, B, C, or D depending on the following criteria:</p>
```<code>If the first character in string  is in the set {aeiou}, then return A.
If the first character in string  is in the set {bcdfg}, then return B.
If the first character in string  is in the set {hjklm},, then return C.
If the first character in string  is in the set {npqrstvwxyz}, then return D.

I am trying to implement the above scenarion and to dthis I have written the following code.

//Here is my code
    function getLetter(s) {
        let letter;
        // Write your code here

            switch (s) {
            case s.match(/[aeiou]/g).includes(s[0]):
            letter = 'A'
            break;

            case s.match(/[bcdfg]/g).includes(s[0]):
            letter = 'B'
            break;

            case s.match(/[hjklm]/g).includes(s[0]):
            letter = 'C';
            break;

            case s.match(/[npqrstvwxyz]/g).includes(s[0]):
            letter = 'D';
            break;
            default:
            console.log("hello")
        }
        return letter
    }

The code is showing error. Would any help me to figure it out? How can I implement the above task using switch statement.
</code>```

答:
Check out this: Switch statement for string matching in JavaScript. The issue is that match returns null, which breaks the switch statement.
Use

```<code>switch(s){
    case str.match(/^xyz/)?.input:
        //code
        break;
</code>```

This stops the match from returning null.

Body:
//This is my Problem
Complete the getLetter(s) function in the editor. It has one parameter: a string, , consisting of lowercase English alphabetic letters (i.e., a through z). It must return A, B, C, or D depending on the following criteria:

If the first character in string  is in the set {aeiou}, then return A.
If the first character in string  is in the set {bcdfg}, then return B.
If the first character in string  is in the set {hjklm},, then return C.
If the first character in string  is in the set {npqrstvwxyz}, then return D.

I am trying to implement the above scenarion and to dthis I have written the following code.

//Here is my code
    function getLetter(s) {
        let letter;
        // Write your code here

            switch (s) {
            case s.match(/[aeiou]/g).includes(s[0]):
            letter = 'A'
            break;

            case s.match(/[bcdfg]/g).includes(s[0]):
            letter = 'B'
            break;

            case s.match(/[hjklm]/g).includes(s[0]):
            letter = 'C';
            break;

            case s.match(/[npqrstvwxyz]/g).includes(s[0]):
            letter = 'D';
            break;
            default:
            console.log("hello")
        }
        return letter
    }

The code is showing error. Would any help me to figure it out? How can I implement the above task using switch statement.

Body:
Check out this: Switch statement for string matching in JavaScript. The issue is that match returns null, which breaks the switch statement.
Use

switch(s){
    case str.match(/^xyz/)?.input:
        //code
        break;

This stops the match from returning null.


问:
How to get recommendations based on previous orders in neo4j?
I am trying to work on neo4j for the first time. I have written the following:

```<code>LOAD CSV WITH HEADERS FROM "file:///restaurant_data.csv" AS data
MERGE(n1:Customer{Name:data.Name, Latitude:toFloat(data.Latitude),Longitude:toFloat(data.Longitude)})
MERGE(n2:Orders{OrderId:data.Order_ID,OrderTimestamp:data.Order_ts,FoodName:data.Food_Item})
MERGE(n3:Restaurant{RestaurantName:data.Restaurant, RestLat:toFloat(data.Rest_lat), RestLong:toFloat(data.Rest_long)})
MERGE (n1)-[r1:PLACES_ORDER]->(n2)
MERGE (n2)-[r2:BELONGS_TO]->(n3)
MERGE (n3)-[r3:SERVES]->(n2)
RETURN *;
</code>```

i can share the csv if needed.

I want to find recommendation of restaurant for customer based on his top 5 previous orders by order_timestamp and distance between restaurant and customer should be less than 5 kms.

```<code>MATCH(n1:Customer{Name:"Angy"})
MATCH(n1)-[:PLACES_ORDER]->(n2:Orders)<-[:SERVES]-(rec:Restaurant)
RETURN n2.FoodName, n2.OrderTimestamp, n3.RestaurantName
ORDER BY n2.OrderTimestamp
LIMIT 5
</code>```

This gives me only top 5 orders, how do I find restaurants serving those orders?

My file link: https://docs.google.com/spreadsheets/d/e/2PACX-1vTc35TBanV3Uk5gbCeEFeJkm2YAhbJPLnpS0KzmYErVRulvbXCWdSZ7xiKUfnCZQQUt-1ArabgmAGmL/pubhtml

答:
Your query did not work. This worked:</p>
```<code>MATCH(:Customer{Name:"Angy"})-[:PLACES_ORDER]->(o:Orders)
WITH o ORDER BY o.OrderTimestamp DESC LIMIT 5
WITH [o.FoodName] as foods
MATCH (r:Restaurant)-[:SERVES]->(n:Orders)
WHERE (n.FoodName in foods)
RETURN distinct r.RestaurantName,foods
</code>```

Body:
I am trying to work on neo4j for the first time. I have written the following:

LOAD CSV WITH HEADERS FROM "file:///restaurant_data.csv" AS data
MERGE(n1:Customer{Name:data.Name, Latitude:toFloat(data.Latitude),Longitude:toFloat(data.Longitude)})
MERGE(n2:Orders{OrderId:data.Order_ID,OrderTimestamp:data.Order_ts,FoodName:data.Food_Item})
MERGE(n3:Restaurant{RestaurantName:data.Restaurant, RestLat:toFloat(data.Rest_lat), RestLong:toFloat(data.Rest_long)})
MERGE (n1)-[r1:PLACES_ORDER]->(n2)
MERGE (n2)-[r2:BELONGS_TO]->(n3)
MERGE (n3)-[r3:SERVES]->(n2)
RETURN *;

i can share the csv if needed.

I want to find recommendation of restaurant for customer based on his top 5 previous orders by order_timestamp and distance between restaurant and customer should be less than 5 kms.

MATCH(n1:Customer{Name:"Angy"})
MATCH(n1)-[:PLACES_ORDER]->(n2:Orders)<-[:SERVES]-(rec:Restaurant)
RETURN n2.FoodName, n2.OrderTimestamp, n3.RestaurantName
ORDER BY n2.OrderTimestamp
LIMIT 5

This gives me only top 5 orders, how do I find restaurants serving those orders?

My file link: https://docs.google.com/spreadsheets/d/e/2PACX-1vTc35TBanV3Uk5gbCeEFeJkm2YAhbJPLnpS0KzmYErVRulvbXCWdSZ7xiKUfnCZQQUt-1ArabgmAGmL/pubhtml

Body:
Your query did not work. This worked:

MATCH(:Customer{Name:"Angy"})-[:PLACES_ORDER]->(o:Orders)
WITH o ORDER BY o.OrderTimestamp DESC LIMIT 5
WITH [o.FoodName] as foods
MATCH (r:Restaurant)-[:SERVES]->(n:Orders)
WHERE (n.FoodName in foods)
RETURN distinct r.RestaurantName,foods


问:
Change background point color at runtime for angular ng2-charts / chartjs
I am adding chartjs in my application & want to change particular point background color based on condition at runtime. I am able to plot the chart correctly but don't know how to change plot color.

From chartjs document I understand we can do it using pointBackgroundColor but all example online is with design time example.

I tried with  this._chart.chart.data.datasets[0].pointBackgroundColor = "red";  but its changed to all points and not to particular points

My version :

Angular ver 6

chartjs ver 2.7.3

ng2-charts  1.6.0

Component.ts code

```<code>@ViewChild(BaseChartDirective) public _chart: BaseChartDirective;

constructor(private router: Router, private _realtimeData  : RealtimeDataService) {
 this._realtimeData.getRealtimeData(1)).subscribe(data =>
{
for (let stat of data)
{
    this.labels.push(newDate(stat.DateTime).toLocaleDateString('de-IN', this.options));

    this.datasets_lines[0].data.push(stat.value);
    this.datasets_lines[1].data.push(stat.value1);
    this.datasets_lines[2].data.push(stat.vlue2);

    if ((stat.value > stat.value1) || (stat.value< stat.vlue2))
    {
    this._chart.chart.data.datasets[0].pointBorderColor = "red";
    }
    else
    {
    this._chart.chart.data.datasets[0].pointBorderColor = "black";
    }

    this._chart.chart.update();
}
}
}

public chartColors: Array<any> = [
  { // first color
    borderColor: "#36ff2f",
    pointBackgroundColor: 'rgba(225,10,24,0.2)',
    pointBorderColor: '#fff',
  },

  { // first color
    borderColor: '#1780cc',
    pointBackgroundColor: 'rgba(225,10,24,0.2)',
    pointBorderColor: '#fff',

  },

  { // second color
    borderColor: '#ed8b00',
    pointBackgroundColor: 'rgba(225,10,24,0.2)',
    pointBorderColor: '#fff',
  }];
</code>```

HTML Code

```<code><canvas
      #mylinechart
      baseChart
      [chartType]="'line'"
      [datasets]="datasets_lines"
      [labels]="labels"
      [options]="chartOptions"
      [legend]="true"
      [colors]="chartColors"
  </canvas>
</code>```

答:
Have you tried use ngZone?

```<code>mport { NgZone } from '@angular/core';

ngZone.run(() => {
      if (true)
      {
          this.chartColors[0].pointBorderColor = "red";
      }
 });
</code>```

Body:
I am adding chartjs in my application & want to change particular point background color based on condition at runtime. I am able to plot the chart correctly but don't know how to change plot color.

From chartjs document I understand we can do it using pointBackgroundColor but all example online is with design time example.

I tried with  this._chart.chart.data.datasets[0].pointBackgroundColor = "red";  but its changed to all points and not to particular points

My version :

Angular ver 6

chartjs ver 2.7.3

ng2-charts  1.6.0

Component.ts code

@ViewChild(BaseChartDirective) public _chart: BaseChartDirective;

constructor(private router: Router, private _realtimeData  : RealtimeDataService) {
 this._realtimeData.getRealtimeData(1)).subscribe(data =>
{
for (let stat of data)
{
    this.labels.push(newDate(stat.DateTime).toLocaleDateString('de-IN', this.options));

    this.datasets_lines[0].data.push(stat.value);
    this.datasets_lines[1].data.push(stat.value1);
    this.datasets_lines[2].data.push(stat.vlue2);

    if ((stat.value > stat.value1) || (stat.value< stat.vlue2))
    {
    this._chart.chart.data.datasets[0].pointBorderColor = "red";
    }
    else
    {
    this._chart.chart.data.datasets[0].pointBorderColor = "black";
    }

    this._chart.chart.update();
}
}
}

public chartColors: Array<any> = [
  { // first color
    borderColor: "#36ff2f",
    pointBackgroundColor: 'rgba(225,10,24,0.2)',
    pointBorderColor: '#fff',
  },

  { // first color
    borderColor: '#1780cc',
    pointBackgroundColor: 'rgba(225,10,24,0.2)',
    pointBorderColor: '#fff',

  },

  { // second color
    borderColor: '#ed8b00',
    pointBackgroundColor: 'rgba(225,10,24,0.2)',
    pointBorderColor: '#fff',
  }];

HTML Code

<canvas
      #mylinechart
      baseChart
      [chartType]="'line'"
      [datasets]="datasets_lines"
      [labels]="labels"
      [options]="chartOptions"
      [legend]="true"
      [colors]="chartColors"
  </canvas>

Body:
Have you tried use ngZone?

mport { NgZone } from '@angular/core';

ngZone.run(() => {
      if (true)
      {
          this.chartColors[0].pointBorderColor = "red";
      }
 });


问:
How can I define an Array of Strings in Ada?
What I want is to define an array of Strings in Ada.

I'm trying to execute this code:

```<code>type String is array (Positive range <>) of Character;
type lexicon is array(1..7) of String(1..20);
nomFumadors : lexicon := ("Macia","Xisco","Toni","Laura","Rocky","Paz");
nomNoFumadors : lexicon := ("Marina","Marta","Joan","Africa","America");
</code>```

And the compiler says:

```<code>warning:wrong length for array of subtype of "String" defined at line 42
</code>```

My line 42 is this:

```<code>type lexicon is array(1..7) of String(1..20);
</code>```

But compailer says the warning is in line 43 and 44: what are these:

```<code>nomFumadors : lexicon := ("Macia","Xisco","Toni","Laura","Rocky","Paz");
nomNoFumadors : lexicon := ("Marina","Marta","Joan","Africa","America");
</code>```

Can somebody help me with that?

答:
Similar to Jeff Carter's answer, but using a function to coerce any string into a fixed string ...

```<code>procedure Main is

   subtype Lexicon_Data is String (1 .. 20);
   type Lexicon is array (1 .. 7) of Lexicon_Data;

   function To_Lexicon_Data
     (Value : in String)
      return Lexicon_Data
   is
      Result : Lexicon_Data;
   begin

      if Value'Length < 1 then
         -- Empty string returns a bunch of spaces
         Result := (others => ' ');

      else
         declare
            Offset : constant Natural :=
              Value'First - Lexicon_Data'First;
         begin

            if Value'Length > Lexicon_Data'Length then
               -- Length exceeds range, so truncate
               Result (Lexicon_Data'Range) := Lexicon_Data
                 (Value (Offset + 1 .. Offset + Lexicon_Data'Length));

            else
               -- Copy into result, and pad right with spaces
               Result := (others => ' ');
               Result (Lexicon_Data'First .. Value'Length) :=
                 (Value (Offset + 1 .. Offset + Value'Length));

            end if;

         end;

      end if;

      return Result;

   end To_Lexicon_Data;

   nomFumadors : constant Lexicon :=
     (To_Lexicon_Data ("Macia"),
      To_Lexicon_Data ("Xisco"),
      To_Lexicon_Data ("Toni"),
      To_Lexicon_Data ("Laura"),
      To_Lexicon_Data ("Rocky"),
      To_Lexicon_Data ("Paz"),
      To_Lexicon_Data ("Mark"));

begin
   --  Insert code here.
   null;
end Main;
</code>```

If you wanted to prove AoRTE (ie SparkAda) then the declaration for Result in the function becomes

```<code>Result : Lexicon_Data
   with Relaxed_Initialization;
</code>```

.. and the function To_Lexicon_Data is proved as being runtime error free.

Note the extra item for Lexicon, Mark, since you need seven items for the Lexicon declaration to be valid.

Body:
What I want is to define an array of Strings in Ada.

I'm trying to execute this code:

type String is array (Positive range <>) of Character;
type lexicon is array(1..7) of String(1..20);
nomFumadors : lexicon := ("Macia","Xisco","Toni","Laura","Rocky","Paz");
nomNoFumadors : lexicon := ("Marina","Marta","Joan","Africa","America");

And the compiler says:

warning:wrong length for array of subtype of "String" defined at line 42

My line 42 is this:

type lexicon is array(1..7) of String(1..20);

But compailer says the warning is in line 43 and 44: what are these:

nomFumadors : lexicon := ("Macia","Xisco","Toni","Laura","Rocky","Paz");
nomNoFumadors : lexicon := ("Marina","Marta","Joan","Africa","America");

Can somebody help me with that?

Body:
Similar to Jeff Carter's answer, but using a function to coerce any string into a fixed string ...

procedure Main is

   subtype Lexicon_Data is String (1 .. 20);
   type Lexicon is array (1 .. 7) of Lexicon_Data;

   function To_Lexicon_Data
     (Value : in String)
      return Lexicon_Data
   is
      Result : Lexicon_Data;
   begin

      if Value'Length < 1 then
         -- Empty string returns a bunch of spaces
         Result := (others => ' ');

      else
         declare
            Offset : constant Natural :=
              Value'First - Lexicon_Data'First;
         begin

            if Value'Length > Lexicon_Data'Length then
               -- Length exceeds range, so truncate
               Result (Lexicon_Data'Range) := Lexicon_Data
                 (Value (Offset + 1 .. Offset + Lexicon_Data'Length));

            else
               -- Copy into result, and pad right with spaces
               Result := (others => ' ');
               Result (Lexicon_Data'First .. Value'Length) :=
                 (Value (Offset + 1 .. Offset + Value'Length));

            end if;

         end;

      end if;

      return Result;

   end To_Lexicon_Data;

   nomFumadors : constant Lexicon :=
     (To_Lexicon_Data ("Macia"),
      To_Lexicon_Data ("Xisco"),
      To_Lexicon_Data ("Toni"),
      To_Lexicon_Data ("Laura"),
      To_Lexicon_Data ("Rocky"),
      To_Lexicon_Data ("Paz"),
      To_Lexicon_Data ("Mark"));

begin
   --  Insert code here.
   null;
end Main;

If you wanted to prove AoRTE (ie SparkAda) then the declaration for Result in the function becomes

Result : Lexicon_Data
   with Relaxed_Initialization;

.. and the function To_Lexicon_Data is proved as being runtime error free.

Note the extra item for Lexicon, Mark, since you need seven items for the Lexicon declaration to be valid.


问:
Module not found: Error: Can't resolve 'lodash-es'
In my Angular 8 TypeScript code I was importing lodash directy (e.g. import * as _ from 'lodash';). In my package.json I had "lodash": "^4.17.15".

I decided to install the @types/lodash-es module and import the specific lodash functions that way (e.g. import { map } from 'lodash-es';). It is better because it saves runtime space and also uses the standard Angular/TypeScript import mechanism.

However, now when I run a build I am getting this error:

Module not found: Error: Can't resolve 'lodash-es'

How can I fix this error?

答: you can update your node__modules by npm update. It has removed the error for my case.</p>


问:
ACE (C++): Not calling cancel_timer == MLK?
If a one-shot timer was scheduled via

```<code>schedule_timer(timer,0,ACE_Time_Value(delay),ACE_Time_Value::zero)
</code>```

is cancel_timer required in order to avoid a memory leak?

答:
I think the answer is "it depends".  With anything but relative ancient versions of ACE, you can have the Reactor (or Timer_Queue) increase the reference count on your event handler, and decrement it when the event handler is removed from the Reactor (or Timer_Queue.)
Please notice that reference counting is optional, and has to be enabled.

In addition, I have not used this stuff, read the documentation and test!

OwnerDisplayName: Michael

ContentLicense: CC BY-SA 2.5

Body:
If a one-shot timer was scheduled via

schedule_timer(timer,0,ACE_Time_Value(delay),ACE_Time_Value::zero)

is cancel_timer required in order to avoid a memory leak?

OwnerDisplayName: coryan


问:
Duplicate Loader's content multiple times via addChild()?
I have small problem. I'm dynamically loading JPG file using Loader class. Everything works except if I want to tile the image few more times using addChild(loader.content) it just doesn't work. It always removes previous instance and leaves only the last one. I've tried everything but with no luck. Here's my code:

```<code>var loaderContext:LoaderContext = new LoaderContext(true);
var imageLoader:Loader = new Loader();
imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, imageLoaderDone);
var fileRequest:URLRequest = new URLRequest('http://127.0.0.1/blah/blah.jpg');
imageLoader.load(fileRequest, loaderContext);

var imageLoaderDone:Function = function(e){
    var k:int = landHolder.numChildren;
    while(k--) {
        landHolder.removeChildAt(k);
    }
    var howManyTimes:int = Math.ceil(1000 / e.content.width);

    var i:int = 0;
    while(i < howManyTimes) {
        var zombie:Sprite = new Sprite();
        zombie.addChild(e.content);
        zombie.x = i*zombie.width;
        landHolder.addChild(zombie); //here's the problem, it does not duplicate
        //landHolder is empty MovieClip placed on the stage
        i++;
    }

    landHolder.alpha = 1

}
</code>```

Thanks.

答:
The loaded content is a single instance of DisplayObject. What you are doing is to move this instance around the several sprites you create within your loop. Finally, your instance is added to the last sprite, and all the others are empty.

Diffent possibilities:

Try to set up a distinct loader for each sprite container - loading the same resource. The browser will cache the image, so it won't load it multiple times from the server.

Embed your image and create multiple instances of it.

Search for an algorithm to duplicate display objects using AS3.

Found this: http://www.kirupa.com/forum/showthread.php?223798-ActionScript-3-Tip-of-the-Day&p=1939827#post1939827 but did not verify. I am sure there are solutions posted here already.

Read also this answer: AS3: Copying a Loader from one object to another

Or this: http://blog.andredickson.net/?p=56

Or this: Duplicate image with Haxe

Body:
I have small problem. I'm dynamically loading JPG file using Loader class. Everything works except if I want to tile the image few more times using addChild(loader.content) it just doesn't work. It always removes previous instance and leaves only the last one. I've tried everything but with no luck. Here's my code:

var loaderContext:LoaderContext = new LoaderContext(true);
var imageLoader:Loader = new Loader();
imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, imageLoaderDone);
var fileRequest:URLRequest = new URLRequest('http://127.0.0.1/blah/blah.jpg');
imageLoader.load(fileRequest, loaderContext);

var imageLoaderDone:Function = function(e){
    var k:int = landHolder.numChildren;
    while(k--) {
        landHolder.removeChildAt(k);
    }
    var howManyTimes:int = Math.ceil(1000 / e.content.width);

    var i:int = 0;
    while(i < howManyTimes) {
        var zombie:Sprite = new Sprite();
        zombie.addChild(e.content);
        zombie.x = i*zombie.width;
        landHolder.addChild(zombie); //here's the problem, it does not duplicate
        //landHolder is empty MovieClip placed on the stage
        i++;
    }

    landHolder.alpha = 1

}

Thanks.


问:
Kafka offset is set to -1000
My Kafka Consumer says the following:

```<code>[TopicPartition{topic=my-topic,partition=0,offset=-1000,error=None}]
</code>```

Whenever I run poll(), it returns None.

I want the offset to be set to the last consumed message. If I manually set the offset=0, anytime I re-start the consumer, all messages will be re-read -- I only want to consume messages from the last offset.

Why is my offset set to -1000?

How can I have kafka manage the offset for me instead of it always being -1000?

What does a -1000 offset mean, it seems pretty invalid.

答:
I would think of 3 things:

Could you please confirm if the consumer received messages at any point of time?

Please try below cli command to see the lag of your consumer:

```<code>kafka-consumer-groups --bootstrap-server <> --group <consumer-group>  --command-config <kafka_client.properties-path> --describe
</code>```

How are you committing the offsets in your consumer code?(check enable.auto.commit property; if true kafka client should commit periodically)

Title: Kafka offset is set to -1000

Body:
My Kafka Consumer says the following:

[TopicPartition{topic=my-topic,partition=0,offset=-1000,error=None}]

Whenever I run poll(), it returns None.

I want the offset to be set to the last consumed message. If I manually set the offset=0, anytime I re-start the consumer, all messages will be re-read -- I only want to consume messages from the last offset.

Why is my offset set to -1000?

How can I have kafka manage the offset for me instead of it always being -1000?

What does a -1000 offset mean, it seems pretty invalid.

Body:
I would think of 3 things:

Could you please confirm if the consumer received messages at any point of time?

Please try below cli command to see the lag of your consumer:

kafka-consumer-groups --bootstrap-server <> --group <consumer-group>  --command-config <kafka_client.properties-path> --describe

How are you committing the offsets in your consumer code?(check enable.auto.commit property; if true kafka client should commit periodically)


问:
Defining a lazy stream in Scala (translating a Racket example)
I was learning Racket (University of Washington Programming Languages course on Coursera) and there is an interesting example to define a lazy stream of values in Racket:

```<code>(define ones
  (lambda () (cons 1 ones)))
</code>```

Basically this defines a function ones that returns a lambda that when called returns a tuple that the first element is 1 and the second element is the method itself.

I was trying to define this function in Scala but cannot get the typing right, there is some weird recursion going on:

```<code>def ones = () => (1, ones) // This complains that recursive function should have types
def ones: () => (Int, ???) = () => (1, ones) // What is the type here?
</code>```

What's the correct type for this function?

答:
Basically this defines a function ones that returns a lambda that when
called returns a tuple that the first element is 1 and the second
element is the method itself.

Here we go: (Do not recommend, scala 2.1 only)

```<code>import scala.language.existentials

type T = () => (Int, () => A) forSome { type A <: (Int, () => A) }

def ones: T = () => (1, ones)

val (i1, f1) = ones()
val (i2, f2) = f1()
val (i3, f3) = f2()

println(i1, i2, i3) // get (1, 1, 1)
</code>```

Body:
I was learning Racket (University of Washington Programming Languages course on Coursera) and there is an interesting example to define a lazy stream of values in Racket:

(define ones
  (lambda () (cons 1 ones)))

Basically this defines a function ones that returns a lambda that when called returns a tuple that the first element is 1 and the second element is the method itself.

I was trying to define this function in Scala but cannot get the typing right, there is some weird recursion going on:

def ones = () => (1, ones) // This complains that recursive function should have types
def ones: () => (Int, ???) = () => (1, ones) // What is the type here?

What's the correct type for this function?

Body:
Basically this defines a function ones that returns a lambda that when
called returns a tuple that the first element is 1 and the second
element is the method itself.

Here we go: (Do not recommend, scala 2.1 only)

import scala.language.existentials

type T = () => (Int, () => A) forSome { type A <: (Int, () => A) }

def ones: T = () => (1, ones)

val (i1, f1) = ones()
val (i2, f2) = f1()
val (i3, f3) = f2()

println(i1, i2, i3) // get (1, 1, 1)


问:
Converting "Stream<String>" to "String" in java8 to combine group of strings in a stream
I want to convert Stream<String> to String and print all the string.

```<code>Stream<String> result= Stream.of("do","re","ma","po","fa","si")
                             .filter(str -> str.length()>5)
                             .peek(System.out:: println);
                           //.allMatch(str -> str.length() >5);

System.out.println(result);
</code>```

Here down output i get

java.util.Spliterators$1Adapter@63961c42

The result is printing an object but not a String and while converting to toString() also printing the same but how to print as a String

答:
If you really only want to only print the elements rather than getting them in return, you can just

```<code>Stream.of("do","re","ma","po","fa","si")
    .filter(str -> str.length()>5)
    .forEach(System.out:: println);
</code>```

forEach is also a "terminating" operation on the stream, which means that it "actually executes" it.

Body:
I want to convert Stream<String> to String and print all the string.

Stream<String> result= Stream.of("do","re","ma","po","fa","si")
                             .filter(str -> str.length()>5)
                             .peek(System.out:: println);
                           //.allMatch(str -> str.length() >5);

System.out.println(result);

Here down output i get

java.util.Spliterators$1Adapter@63961c42

The result is printing an object but not a String and while converting to toString() also printing the same but how to print as a String

Body:
If you really only want to only print the elements rather than getting them in return, you can just

Stream.of("do","re","ma","po","fa","si")
    .filter(str -> str.length()>5)
    .forEach(System.out:: println);

forEach is also a "terminating" operation on the stream, which means that it "actually executes" it.


问:
Why does the "Remember me" functionality in Symfony 5.4 not work (with my setup)
I've a page with form login and "remember me" functionality enabled. Unfortunately the remember me" wont work.

The security panel doesn't show any authenticators. Interestingly after closing the browser and trying to get on the page again, the security panel shows the correct authenticated user, but redirects always to the login page.

Can anybody help?

Here part of my security.yml

```<code>security:
    enable_authenticator_manager: true
    role_hierarchy:
        ROLE_SUPPORT: ROLE_USER
        ROLE_ADMIN: [ROLE_SUPPORT, ROLE_ALLOWED_TO_SWITCH]

    password_hashers:
        Symfony\Component\Security\Core\User\User:
            algorithm: bcrypt
            cost: 12
        App\Entity\User:
            algorithm: auto

    providers:
        # used to reload user from session & other features (e.g. switch_user)
        app_user_provider:
            entity:
                class: App\Entity\User

    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false

        secured_area:
            form_login:
                login_path: login
                check_path: login
                enable_csrf: true
            logout:
                path:   /logout
                target: /
            remember_me:
                secret: '%kernel.secret%'
                lifetime: 604800 # 1 week in seconds

    access_control:
        - { path: ^/public, roles: PUBLIC_ACCESS }
        - { path: ^/others, roles: IS_AUTHENTICATED_FULLY  }
</code>```

Thx in advance

UPDATE

With lazy: true the security panel now shows authenticators

答: Unfortunately IS_AUTHENTICATED_REMEMBERED is missing in the access_control section.</p>

Body:
I've a page with form login and "remember me" functionality enabled. Unfortunately the remember me" wont work.

The security panel doesn't show any authenticators. Interestingly after closing the browser and trying to get on the page again, the security panel shows the correct authenticated user, but redirects always to the login page.

Can anybody help?

Here part of my security.yml

security:
    enable_authenticator_manager: true
    role_hierarchy:
        ROLE_SUPPORT: ROLE_USER
        ROLE_ADMIN: [ROLE_SUPPORT, ROLE_ALLOWED_TO_SWITCH]

    password_hashers:
        Symfony\Component\Security\Core\User\User:
            algorithm: bcrypt
            cost: 12
        App\Entity\User:
            algorithm: auto

    providers:
        # used to reload user from session & other features (e.g. switch_user)
        app_user_provider:
            entity:
                class: App\Entity\User

    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false

        secured_area:
            form_login:
                login_path: login
                check_path: login
                enable_csrf: true
            logout:
                path:   /logout
                target: /
            remember_me:
                secret: '%kernel.secret%'
                lifetime: 604800 # 1 week in seconds

    access_control:
        - { path: ^/public, roles: PUBLIC_ACCESS }
        - { path: ^/others, roles: IS_AUTHENTICATED_FULLY  }

Thx in advance

UPDATE

With lazy: true the security panel now shows authenticators


问:
Can I force the use of 'this' keyword in c# .NET?
Is there a way to force the use of the this keyword in Visual Studio when referencing current instance members?

Example with a bug in the constructor:

```<code>class MyClass
{
    public object Foo { get; set; }
    public MyClass(object foo)
    {
        Foo = Foo; // this should of course be lowercase but it's easy to miss
    }
}
</code>```

This code will probably generate the infamous 'object reference not set to an instance of an object' exception somewhere later on.

How to make it work but still It's easy to miss:

```<code>class MyClass
{
    public object Foo { get; set; }
    public MyClass(object foo)
    {
        Foo = foo; // Valid syntax but unclear.
    }
}
</code>```

This is valid syntax but it's easy to miss.

The syntax I'd like visual studio enforce:

```<code>class MyClass
{
    public object Foo { get; set; }
    public MyClass(object foo)
    {
        this.Foo = foo; // this is "safe".
    }
}
</code>```

If this convention is enforced i would have to type this.Foo = this.Foo to create the same type of bug as in the first example.

I always use the this keyword anyway since it makes my life easier while switching between c# and other languages so there wouldn't be any disadvantages at all.

答:
You can use StyleCop to generate a warning if you do not prefix with this. You can get StyleCop to run as part of the build process by following these these instructions

StyleCop comes with a bunch of default rules, many of them terrible, but you can edit your rules file to make the most sense for your developers. You can also share the StyleCop file so changes are immediately replicated to all your developers.

Its a fairly nice solution, free, provided by Microsoft and if you come up with a suitable rule set then your developers will create much "neater" code. You can also create custom rules along the lines of "Methods shouldn't be too long" where you define the length. Plenty of things to play with.

Also I guess you could set warnings as errors, but if you do make sure your StyleCop settings are exactly as you want them.

Body:
Is there a way to force the use of the this keyword in Visual Studio when referencing current instance members?

Example with a bug in the constructor:

class MyClass
{
    public object Foo { get; set; }
    public MyClass(object foo)
    {
        Foo = Foo; // this should of course be lowercase but it's easy to miss
    }
}

This code will probably generate the infamous 'object reference not set to an instance of an object' exception somewhere later on.

How to make it work but still It's easy to miss:

class MyClass
{
    public object Foo { get; set; }
    public MyClass(object foo)
    {
        Foo = foo; // Valid syntax but unclear.
    }
}

This is valid syntax but it's easy to miss.

The syntax I'd like visual studio enforce:

class MyClass
{
    public object Foo { get; set; }
    public MyClass(object foo)
    {
        this.Foo = foo; // this is "safe".
    }
}

If this convention is enforced i would have to type this.Foo = this.Foo to create the same type of bug as in the first example.

I always use the this keyword anyway since it makes my life easier while switching between c# and other languages so there wouldn't be any disadvantages at all.


问:
python skip importing a library
What I'd like to do is avoid an import that cause a problem. My code is like this:

main.py

```<code>import external_library
</code>```

external_library.py

```<code>import package_with_problem
</code>```

I know I could change external_library.py with something as

```<code>try:
    import package_with_problem
except:
    pass
</code>```

but I'm looking for a solution to implement in main.py. I would like a skip function that takes the package name as parameters and avoid the import.

答:
Just do in main.py the same as you would have in external_library.py. If you only want to skip a certain import, you can check the error:

try:
    import external_library
except ImportError as e:
    if "package_with_problem" not in e.msg:
        raise
```

This will "skip" the import of package_with_problem but will re-raise the error for any other package.

Title: python skip importing a library

Body:
What I'd like to do is avoid an import that cause a problem. My code is like this:

main.py

import external_library

external_library.py

import package_with_problem

I know I could change external_library.py with something as

try:
    import package_with_problem
except:
    pass

but I'm looking for a solution to implement in main.py. I would like a skip function that takes the package name as parameters and avoid the import.

Body:
Just do in main.py the same as you would have in external_library.py. If you only want to skip a certain import, you can check the error:

try:
    import external_library
except ImportError as e:
    if "package_with_problem" not in e.msg:
        raise

This will "skip" the import of package_with_problem but will re-raise the error for any other package.


问:
Multiple Datasources with single JPA Repository type
I have 2 databases with identical schemas, but for 2 different markets (let's say us-db and eu-db). Since the schemas are identical, I can use the same entity classes - the publisher table is the same in both databases, so I only need 1 Publisher class. It follows, that I only need a single Repo:

@Repository
public interface PublisherRepository extends CrudRepository<Publisher, Long> {
}
```

However, I would like to set it up so that my Spring Context contains 2 Beans of type PublisherRepository - one where the underlying datasource is us-db, and the other - eu-db.

Is it possible to achieve this? I'm also open to other implementation suggestions that eliminate the need for duplication of entity definitions.

答:
Spring (Boot) don't support multiple data-source out-of-the-box. You can use trick like this https://www.baeldung.com/spring-data-jpa-multiple-databases . I believe that, If Spring did not support multiple datasources out-of-the-box, your try is not good practice.

I think best practices is, using single datasource, but use 2 micro-services.

Or sometime switching environment application.properties file will be helpful to you.

Body:
I have 2 databases with identical schemas, but for 2 different markets (let's say us-db and eu-db). Since the schemas are identical, I can use the same entity classes - the publisher table is the same in both databases, so I only need 1 Publisher class. It follows, that I only need a single Repo:

@Repository
public interface PublisherRepository extends CrudRepository<Publisher, Long> {
}

However, I would like to set it up so that my Spring Context contains 2 Beans of type PublisherRepository - one where the underlying datasource is us-db, and the other - eu-db.

Is it possible to achieve this? I'm also open to other implementation suggestions that eliminate the need for duplication of entity definitions.


问:
Java - HashMap for booking system
I have been given an exercise to develop an appropriate data structure to implement a tennis court booking system.

A hashmap is what is required for this and I was given a diagram as a visual representation of the data structure.

From looking at the diagram, I am unclear on how the Key and Value should be defined in the HashMap. Should 'Court' be a class, which is the Key?

For the value, it shows a time, and a players name. How would the value be defined, since it has two values of time and player name?

diagram link

答:
Date1 (what a name) is a Map<String, Court> of courts by name, like "court1". Court has fields name and a reservation list.

So the key is (probably) a String, and the class itself is the value. One often sees, that the key/ID is also kept in the value class. So a Court object suffices to get its name.

Title: Java - HashMap for booking system


问:
Why is "a =(b>0)?1:0" better than "if-else" version in CUDA?
Could you tell me why

```<code>a =(b>0)?1:0
</code>```

is better than

```<code>if (b>0)a=1; else a =0;
</code>```

version in CUDA? Please give details. Many thanks.

Yik

答:
There was a time when the NVIDIA compiler used idiom testing to generate more efficient code for the ternary operator than if/then/else constructs. This is the results of a small test to see whether this is still the case:

```<code>__global__ void branchTest0(float *a, float *b, float *d)
{
        unsigned int tidx = threadIdx.x + blockDim.x*blockIdx.x;
        float aval = a[tidx], bval = b[tidx];
        float z0 = (aval > bval) ? aval : bval;

        d[tidx] = z0;
}

__global__ void branchTest1(float *a, float *b, float *d)
{
        unsigned int tidx = threadIdx.x + blockDim.x*blockIdx.x;
        float aval = a[tidx], bval = b[tidx];
        float z0;

        if (aval > bval) {
            z0 = aval;
        } else {
            z0 = bval;
        }
        d[tidx] = z0;
}
</code>```

Compiling these two kernels for compute capability 2.0 with the CUDA 4.0 release compiler, the comparison section produces this:

```<code>branchTest0:
max.f32         %f3, %f1, %f2;
</code>```

and

```<code>branchTest1:
setp.gt.f32     %p1, %f1, %f2;
selp.f32        %f3, %f1, %f2, %p1;
</code>```

The ternary operator gets compiled into a single floating point maximum instruction, whereas the if/then/else gets compiled into two instructions, a compare followed by a select. Both codes are conditionally executed - neither produces branching. The machine code emitted by the assembler for these is also different and closely replicates the PTX:

```<code>branchTest0:
    /*0070*/     /*0x00201c00081e0000*/     FMNMX R0, R2, R0, !pt;
</code>```

and

```<code>branchTest1:
    /*0070*/     /*0x0021dc00220e0000*/     FSETP.GT.AND P0, pt, R2, R0, pt;
    /*0078*/     /*0x00201c0420000000*/     SEL R0, R2, R0, P0;
</code>```

So it would seem that, at least for Fermi GPUs with CUDA 4.0 with this sort of construct, the ternary operator does produce fewer instructions that an equivalent if/then/else. Whether there is a performance difference between them comes down to microbenchmarking data which I don't have.

Body:
Could you tell me why

a =(b>0)?1:0

is better than

if (b>0)a=1; else a =0;

version in CUDA? Please give details. Many thanks.

Yik

Body:
There was a time when the NVIDIA compiler used idiom testing to generate more efficient code for the ternary operator than if/then/else constructs. This is the results of a small test to see whether this is still the case:

__global__ void branchTest0(float *a, float *b, float *d)
{
        unsigned int tidx = threadIdx.x + blockDim.x*blockIdx.x;
        float aval = a[tidx], bval = b[tidx];
        float z0 = (aval > bval) ? aval : bval;

        d[tidx] = z0;
}

__global__ void branchTest1(float *a, float *b, float *d)
{
        unsigned int tidx = threadIdx.x + blockDim.x*blockIdx.x;
        float aval = a[tidx], bval = b[tidx];
        float z0;

        if (aval > bval) {
            z0 = aval;
        } else {
            z0 = bval;
        }
        d[tidx] = z0;
}

Compiling these two kernels for compute capability 2.0 with the CUDA 4.0 release compiler, the comparison section produces this:

branchTest0:
max.f32         %f3, %f1, %f2;

and

branchTest1:
setp.gt.f32     %p1, %f1, %f2;
selp.f32        %f3, %f1, %f2, %p1;

The ternary operator gets compiled into a single floating point maximum instruction, whereas the if/then/else gets compiled into two instructions, a compare followed by a select. Both codes are conditionally executed - neither produces branching. The machine code emitted by the assembler for these is also different and closely replicates the PTX:

branchTest0:
    /*0070*/     /*0x00201c00081e0000*/     FMNMX R0, R2, R0, !pt;

and

branchTest1:
    /*0070*/     /*0x0021dc00220e0000*/     FSETP.GT.AND P0, pt, R2, R0, pt;
    /*0078*/     /*0x00201c0420000000*/     SEL R0, R2, R0, P0;

So it would seem that, at least for Fermi GPUs with CUDA 4.0 with this sort of construct, the ternary operator does produce fewer instructions that an equivalent if/then/else. Whether there is a performance difference between them comes down to microbenchmarking data which I don't have.