问:
How to scroll a sync'd up MotionLayout+AppBarLayout programmatically?
Consider the following Coordinator+AppBar+MotionLayout and its MotionScene from Google's demo. This creates a MotionLayout that sync's its Transition progress when the user is scrolling.

Video Preview: https://i.imgur.com/1MnPB8R.mp4

However, I would like to do this in programmatically in Kotlin. Here are my failed attempts.

```<code>val motion = findViewById<MotionLayout>(R.id.constraintToolbar)
motion.transitionToState(R.id.end)
</code>```

The above would cause the MotionLayout to animate, but would immediately blink back to the start state once finished. The AppBarLayout also does not change height.

```<code>val appbar = findViewById<AppBarLayout>(R.id.app_bar)
val scrollable = findViewById<NestedScrollView>(R.id.scrollable)
val s = if(motion.progress==0F) appbar.totalScrollRange else 0
scrollable.smoothScrollTo(0, s)
</code>```

The above scrolls the NestedScrollView, but the AppBarLayout and MotionLayout does not receive the scroll events.

```<code>val s = if(motion.progress==0F)-appbar.totalScrollRange else 0
val appbar = findViewById<AppBarLayout>(R.id.app_bar)
appbar.scrollTo(0,s)
appbar.offsetTopAndBottom(s)
</code>```

The above shifts the AppBarLayout, breaking the layout completely.

How do you trigger this scroll programmatically?

答:
If there's only 2 states, you should try setExpanded()

```<code>val e = motion.progress != 0F
appbar.setExpanded(e, true)
</code>```

Body:
Consider the following Coordinator+AppBar+MotionLayout and its MotionScene from Google's demo. This creates a MotionLayout that sync's its Transition progress when the user is scrolling.

Video Preview: https://i.imgur.com/1MnPB8R.mp4

However, I would like to do this in programmatically in Kotlin. Here are my failed attempts.

val motion = findViewById<MotionLayout>(R.id.constraintToolbar)
motion.transitionToState(R.id.end)

The above would cause the MotionLayout to animate, but would immediately blink back to the start state once finished. The AppBarLayout also does not change height.

val appbar = findViewById<AppBarLayout>(R.id.app_bar)
val scrollable = findViewById<NestedScrollView>(R.id.scrollable)
val s = if(motion.progress==0F) appbar.totalScrollRange else 0
scrollable.smoothScrollTo(0, s)

The above scrolls the NestedScrollView, but the AppBarLayout and MotionLayout does not receive the scroll events.

val s = if(motion.progress==0F)-appbar.totalScrollRange else 0
val appbar = findViewById<AppBarLayout>(R.id.app_bar)
appbar.scrollTo(0,s)
appbar.offsetTopAndBottom(s)

The above shifts the AppBarLayout, breaking the layout completely.

How do you trigger this scroll programmatically?

Body:
If there's only 2 states, you should try setExpanded()

val e = motion.progress != 0F
appbar.setExpanded(e, true)


来源: stackexchange

问:
JPA select from select distinct
I'm trying to execute the following SQL query writing native query in JPA:

```<code>            SELECT id FROM (
                SELECT DISTINCT id, DENSE_RANK() OVER (ORDER BY id) AS row FROM table
            ) WHERE row BETWEEN 1 AND 10;
</code>```

In the Query annotation I wrote:

```<code>@Query(value = "SELECT t.id FROM (SELECT DISTINCT(e.id), DENSE_RANK() OVER (ORDER BY e.id) AS row FROM Table e) t WHERE row BETWEEN ? AND ?")
</code>```

but I have syntax errors here FROM (SELECT.
Please, can you help me?

答:
You have probably forgot nativeQuery=true
Try this:

```<code>@Query(value = "SELECT t.id FROM (SELECT DISTINCT(e.id), DENSE_RANK() OVER (ORDER BY e.id) AS row FROM Table e) t WHERE row BETWEEN ? AND ?", nativeQuery = true)
</code>```

ContentLicense: CC BY-SA 4.0

Title: JPA select from select distinct

Body:
I'm trying to execute the following SQL query writing native query in JPA:

            SELECT id FROM (
                SELECT DISTINCT id, DENSE_RANK() OVER (ORDER BY id) AS row FROM table
            ) WHERE row BETWEEN 1 AND 10;

In the Query annotation I wrote:

@Query(value = "SELECT t.id FROM (SELECT DISTINCT(e.id), DENSE_RANK() OVER (ORDER BY e.id) AS row FROM Table e) t WHERE row BETWEEN ? AND ?")

but I have syntax errors here FROM (SELECT.
Please, can you help me?

Body:
You have probably forgot nativeQuery=true
Try this:

@Query(value = "SELECT t.id FROM (SELECT DISTINCT(e.id), DENSE_RANK() OVER (ORDER BY e.id) AS row FROM Table e) t WHERE row BETWEEN ? AND ?", nativeQuery = true)


问:
Pandas groupby with "Wide" data
My dataframes are in a "wide" format, such that columns contain data for different entities, and rows are dates, e.g. product costs through time:

```<code>import pandas as pd

cost = pd.DataFrame([[10,20,30,40],[11,22,33,44],[111,222,333,444]], columns=['Knife','Fork','Spoon','Spatula'], index=pd.date_range('2022-01-01','2022-01-03'))
</code>```
```<code>            Knife  Fork  Spoon  Spatula
2022-01-01     10    20     30       40
2022-01-02     11    22     33       44
2022-01-03    111   222    333      444
</code>```

I have a similar dataframe that places each data point in one of two groups (1 or 2):

```<code>grp = pd.DataFrame([[1,2,1,2],[1,1,2,2],[2,1,1,2]], columns=['Knife','Fork','Spoon','Spatula'], index=pd.date_range('2022-01-01','2022-01-03'))
</code>```
```<code>            Knife  Fork  Spoon  Spatula
2022-01-01      1     2      1        2
2022-01-02      1     1      2        2
2022-01-03      2     1      1        2
</code>```

I want to do an aggregate groupby-style mean on each of the groups for each date. As such, this is my desired output, showing the averages for groups 1 and 2:

```<code>avg =  pd.DataFrame([[(10+30)/2,(20+40)/2],[(11+22)/2,(33+44)/2],[(111+444)/2,(222+333)/2]], columns=[1,2], index=pd.date_range('2022-01-01','2022-01-03'))
</code>```
```<code>                1      2
2022-01-01   20.0   30.0
2022-01-02   16.5   38.5
2022-01-03  277.5  277.5
</code>```

I've tried to melt each dataframe, reindex, merge, groupby, aggregate and pivot but it's a real mess (esp the reindexing).

It seems to me there must be a better way to aggregate this kind of "wide" data? My actual data is way bigger (and with more groups), hence a desire for efficiency.

How can I most efficiently gain my desired output?

答:
Stuart really has a point. I edited the algorithm so it can accept a range of groups in a more automated way. I believe it became a more elegant solution.

```<code>import numpy as np

avg = pd.concat([((grp == i) * cost).replace(0, np.NaN).mean(axis=1) for i in np.unique(grp)], axis=1)
avg.columns = np.unique(grp)
</code>```

Output:

```<code>                1       2
2022-01-01   20.0    30.0
2022-01-02   16.5    38.5
2022-01-03  277.5   277.5
</code>```

Title: Pandas groupby with "Wide" data

Body:
My dataframes are in a "wide" format, such that columns contain data for different entities, and rows are dates, e.g. product costs through time:

import pandas as pd

cost = pd.DataFrame([[10,20,30,40],[11,22,33,44],[111,222,333,444]], columns=['Knife','Fork','Spoon','Spatula'], index=pd.date_range('2022-01-01','2022-01-03'))

            Knife  Fork  Spoon  Spatula
2022-01-01     10    20     30       40
2022-01-02     11    22     33       44
2022-01-03    111   222    333      444

I have a similar dataframe that places each data point in one of two groups (1 or 2):

grp = pd.DataFrame([[1,2,1,2],[1,1,2,2],[2,1,1,2]], columns=['Knife','Fork','Spoon','Spatula'], index=pd.date_range('2022-01-01','2022-01-03'))

            Knife  Fork  Spoon  Spatula
2022-01-01      1     2      1        2
2022-01-02      1     1      2        2
2022-01-03      2     1      1        2

I want to do an aggregate groupby-style mean on each of the groups for each date. As such, this is my desired output, showing the averages for groups 1 and 2:

avg =  pd.DataFrame([[(10+30)/2,(20+40)/2],[(11+22)/2,(33+44)/2],[(111+444)/2,(222+333)/2]], columns=[1,2], index=pd.date_range('2022-01-01','2022-01-03'))

                1      2
2022-01-01   20.0   30.0
2022-01-02   16.5   38.5
2022-01-03  277.5  277.5

I've tried to melt each dataframe, reindex, merge, groupby, aggregate and pivot but it's a real mess (esp the reindexing).

It seems to me there must be a better way to aggregate this kind of "wide" data? My actual data is way bigger (and with more groups), hence a desire for efficiency.

How can I most efficiently gain my desired output?

Body:
Stuart really has a point. I edited the algorithm so it can accept a range of groups in a more automated way. I believe it became a more elegant solution.

import numpy as np

avg = pd.concat([((grp == i) * cost).replace(0, np.NaN).mean(axis=1) for i in np.unique(grp)], axis=1)
avg.columns = np.unique(grp)

Output:

                1       2
2022-01-01   20.0    30.0
2022-01-02   16.5    38.5
2022-01-03  277.5   277.5


问:
Data.Vector.Mutable field can not be written/set properly? : Haskell
I have struggled for days to compose a data structure that has a field of mutable value of Data.Vector.Mutable

I confirmed Data.Vector.Mutable itself behaves as I expected; however once it's included into a structure, somehow stops working against my expectation.

Below is a demo-code that simply has newVal, getVal and setVal targeting the mutable field value of the structure.

newIO is the constructor of the data structure typed as newIO :: a -> A a.

```<code>module Main where
import Control.Monad.Primitive (PrimMonad (PrimState))
import qualified Data.Vector.Mutable as M
------------------------------------
data A a = A
  { ioVal :: IO (M.MVector (PrimState IO) a)
  }

newIO :: a -> A a
newIO = \a -> A (newVal a)
------------------------------
newVal :: a -> IO (M.MVector (PrimState IO) a)
newVal = \a -> do
  val <- M.new 1
  M.write val 0 a
  return val

getVal :: A a -> IO a
getVal = \aA -> do
  val <- ioVal aA
  M.read val 0

setVal :: a -> A a -> IO ()
setVal = \a -> \aA -> do
  val <- ioVal aA
  M.write val 0 a
------------------------------
main :: IO ()
main = do
  let ioA = newIO (5 :: Int)
  (getVal ioA) >>= print -- 5
  setVal 10 ioA
  (getVal ioA) >>= print -- 5 ?? expected 10
</code>```

So, here, to confirm the basic behavior of set/get of the structure, I try to create, read, (re)write, and (re)read the mutable value of the field; however, it does not work as expected as the set should perform.

What's wrong with the code? Please advise.

答:
A main property of Haskell is referential transparency: we can always replace defined entities with their definitions. Now consider the posted code:

```<code>main :: IO ()
main = do
  let ioA = newIO (5 :: Int)
  (getVal ioA) >>= print -- 5
  setVal 10 ioA
  (getVal ioA) >>= print -- 5 ?? expected 10
</code>```

This defines ioA, so we can replace it with its own definition. We get:

```<code>main :: IO ()
main = do
  (getVal (newIO (5 :: Int))) >>= print -- 5
  setVal 10 (newIO (5 :: Int))
  (getVal (newIO (5 :: Int))) >>= print -- 5 ?? expected 10
</code>```

Now we can see the problem: we create three independent vectors. The issue is that let ioA = ... defines an IO action (roughly, an imperative procedure) that we can call multiple times later on.
But we don't want that: we want newIO (5 :: Int) to be executed only once.

For that, we must avoid let and use monadic bind (<-, in do blocks).

```<code>main :: IO ()
main = do
  ioA <- newIO (5 :: Int)   -- run the action, just once
  (getVal ioA) >>= print
  setVal 10 ioA
  (getVal ioA) >>= print
</code>```

This will trigger a bunch of type errors, since e.g. getVal is no longer passed an IO action, but is passed the result of the IO action. This is what we want, though, so we need to fix the types accordingly.

Start by removing IO here:

```<code>data A a = A
  { ioVal :: M.MVector (PrimState IO) a
  }
</code>```

Indeed, we don't want to store a procedure that makes a vector, we want to store the vector.

Consequently, we need to remove <- in favor of let in a few other points.

```<code>getVal :: A a -> IO a
getVal = \aA -> do
  let val = ioVal aA  -- no IO action to run here
  M.read val 0
</code>```

Also, newIO must return an IO value.

```<code>newIO :: a -> IO (A a)
newIO = \a -> fmap A (newVal a)
</code>```

I think you can figure out the rest now.

Body:
I have struggled for days to compose a data structure that has a field of mutable value of Data.Vector.Mutable

I confirmed Data.Vector.Mutable itself behaves as I expected; however once it's included into a structure, somehow stops working against my expectation.

Below is a demo-code that simply has newVal, getVal and setVal targeting the mutable field value of the structure.

newIO is the constructor of the data structure typed as newIO :: a -> A a.

module Main where
import Control.Monad.Primitive (PrimMonad (PrimState))
import qualified Data.Vector.Mutable as M
------------------------------------
data A a = A
  { ioVal :: IO (M.MVector (PrimState IO) a)
  }

newIO :: a -> A a
newIO = \a -> A (newVal a)
------------------------------
newVal :: a -> IO (M.MVector (PrimState IO) a)
newVal = \a -> do
  val <- M.new 1
  M.write val 0 a
  return val

getVal :: A a -> IO a
getVal = \aA -> do
  val <- ioVal aA
  M.read val 0

setVal :: a -> A a -> IO ()
setVal = \a -> \aA -> do
  val <- ioVal aA
  M.write val 0 a
------------------------------
main :: IO ()
main = do
  let ioA = newIO (5 :: Int)
  (getVal ioA) >>= print -- 5
  setVal 10 ioA
  (getVal ioA) >>= print -- 5 ?? expected 10

So, here, to confirm the basic behavior of set/get of the structure, I try to create, read, (re)write, and (re)read the mutable value of the field; however, it does not work as expected as the set should perform.

What's wrong with the code? Please advise.

Body:
A main property of Haskell is referential transparency: we can always replace defined entities with their definitions. Now consider the posted code:

main :: IO ()
main = do
  let ioA = newIO (5 :: Int)
  (getVal ioA) >>= print -- 5
  setVal 10 ioA
  (getVal ioA) >>= print -- 5 ?? expected 10

This defines ioA, so we can replace it with its own definition. We get:

main :: IO ()
main = do
  (getVal (newIO (5 :: Int))) >>= print -- 5
  setVal 10 (newIO (5 :: Int))
  (getVal (newIO (5 :: Int))) >>= print -- 5 ?? expected 10

Now we can see the problem: we create three independent vectors. The issue is that let ioA = ... defines an IO action (roughly, an imperative procedure) that we can call multiple times later on.
But we don't want that: we want newIO (5 :: Int) to be executed only once.

For that, we must avoid let and use monadic bind (<-, in do blocks).

main :: IO ()
main = do
  ioA <- newIO (5 :: Int)   -- run the action, just once
  (getVal ioA) >>= print
  setVal 10 ioA
  (getVal ioA) >>= print

This will trigger a bunch of type errors, since e.g. getVal is no longer passed an IO action, but is passed the result of the IO action. This is what we want, though, so we need to fix the types accordingly.

Start by removing IO here:

data A a = A
  { ioVal :: M.MVector (PrimState IO) a
  }

Indeed, we don't want to store a procedure that makes a vector, we want to store the vector.

Consequently, we need to remove <- in favor of let in a few other points.

getVal :: A a -> IO a
getVal = \aA -> do
  let val = ioVal aA  -- no IO action to run here
  M.read val 0

Also, newIO must return an IO value.

newIO :: a -> IO (A a)
newIO = \a -> fmap A (newVal a)

I think you can figure out the rest now.


问:
It's possible to use an array of property on "item-text" in Vuetify?
```<code> <v-autocomplete
   v-model="friends"
   :disabled="isUpdating"
   :items="people"
   label="Select"
   item-text="name" <!-- use here Array ['name', 'id', 'value'] -->
   item-value="name"
  >
</code>```

It's possible to use an array of property on "text-item" in Vuetify?

答:
As the documentation mention, yes, you can use an array too.

https://vuetifyjs.com/en/api/v-autocomplete/#props

Body:
 <v-autocomplete
   v-model="friends"
   :disabled="isUpdating"
   :items="people"
   label="Select"
   item-text="name"
   item-value="name"
  >

It's possible to use an array of property on "text-item" in Vuetify?


问:
Sharing data across processes on linux
In my application, I have a process which forks off a child, say child1, and this child process writes a huge binary file on the disk and exits. The parent process then forks off another child process, child2, which reads in this huge file to do further processing.

The file dumping and re-loading is making my application slow and I'm thinking of possible
ways of avoiding disk I/O completely. Possible ways I have identified are ram-disk or tmpfs.
Can I somehow implement ram-disk or tmpfs from within my application? Or is there any other
way by which I can avoid disk I/O completely and send data across processes reliably.

答: Spawn the two processes and have them transfer the data via sockets.  TCP will be easiest to get started, but if you want a bit more efficiency, use Unix Domain Sockets.  This assumes you don't care about the data being written to disk per se.</p>

ContentLicense: CC BY-SA 3.0

Title: Sharing data across processes on linux


问:
Multiple Selection From Dropdown Using if-else Rshiny
I am trying to create two dropdowns based on user input. If a user selects "val1", then show values in the second dropdown from "x". If "val2", then "y". If both "val1" and "val2", then z.

So far, I succeeded except for the multiple selection part. I also tried:

else if (input$lab == "val1" & input$lab == "val2")

which gives me the same error:

the condition has length > 1 and only the first element will be used

```<code>x <- c("x1", "x2", "x3")
y <- c("y1", "y2", "y3")
z <- c("x1", "x2", "x3", "y1", "y2", "y3")
</code>```
```<code>library(shiny)
library(shinydashboard)
library(shinyWidgets)

ui <- dashboardPage(
  dashboardHeader(title = "title"),

  dashboardSidebar(
    sidebarMenu(
      menuItem("xxx", tabName = "tab1")
    )
  ),

  dashboardBody(
    tabItems(
      tabItem(
        tabName = "tab1",
        pickerInput("dropdown1", "Values:", choices = c("x", "y"), multiple = T),
        uiOutput("dropdown2")
      )
    )
  )
)

server <- function(input, output, session) {
  values <- reactive({
    req(input$dropdown1)

    if (input$dropdown1 == "x") {
      x
    }

    else if (input$dropdown1 == "y") {
      y
    }

    else if (input$dropdown1 == "x" && input$dropdown1 == "y") {
      z
    }
  })

  output$dropdown2 <- renderUI({
    pickerInput("dropdown2", "Values:", choices = values())
  })
}

shinyApp(ui, server)

</code>```

答:
Slight change in approach in your server. Rather than ifelse to test for for x, y, or x&y, you can instead test for length == 1 and then within that case, whether it's x or y.

```<code>server <- function(input, output, session) {
  values <- reactive({
    req(input$dropdown1)

    if (length(input$dropdown1) == 1) {
      if (input$dropdown1 == "x") {
        c("x1", "x2", "x3")
      }
      else {
        c("y1", "y2", "y3")
      }
    }
    else {
      c("x1", "x2", "x3", "y1", "y2", "y3")
    }
  })

  output$dropdown2 <- renderUI({
    pickerInput("dropdown2", "Values:", choices = values())
  })

}
</code>```

Depending on what really will go in "x" and "y", using ifelse() might save you space in this approach.

Body:
I am trying to create two dropdowns based on user input. If a user selects "val1", then show values in the second dropdown from "x". If "val2", then "y". If both "val1" and "val2", then z.

So far, I succeeded except for the multiple selection part. I also tried:

else if (input$lab == "val1" & input$lab == "val2")

which gives me the same error:

the condition has length > 1 and only the first element will be used

x <- c("x1", "x2", "x3")
y <- c("y1", "y2", "y3")
z <- c("x1", "x2", "x3", "y1", "y2", "y3")

library(shiny)
library(shinydashboard)
library(shinyWidgets)

ui <- dashboardPage(
  dashboardHeader(title = "title"),

  dashboardSidebar(
    sidebarMenu(
      menuItem("xxx", tabName = "tab1")
    )
  ),

  dashboardBody(
    tabItems(
      tabItem(
        tabName = "tab1",
        pickerInput("dropdown1", "Values:", choices = c("x", "y"), multiple = T),
        uiOutput("dropdown2")
      )
    )
  )
)

server <- function(input, output, session) {
  values <- reactive({
    req(input$dropdown1)

    if (input$dropdown1 == "x") {
      x
    }

    else if (input$dropdown1 == "y") {
      y
    }

    else if (input$dropdown1 == "x" && input$dropdown1 == "y") {
      z
    }
  })

  output$dropdown2 <- renderUI({
    pickerInput("dropdown2", "Values:", choices = values())
  })
}

shinyApp(ui, server)

Body:
Slight change in approach in your server. Rather than ifelse to test for for x, y, or x&y, you can instead test for length == 1 and then within that case, whether it's x or y.

server <- function(input, output, session) {
  values <- reactive({
    req(input$dropdown1)

    if (length(input$dropdown1) == 1) {
      if (input$dropdown1 == "x") {
        c("x1", "x2", "x3")
      }
      else {
        c("y1", "y2", "y3")
      }
    }
    else {
      c("x1", "x2", "x3", "y1", "y2", "y3")
    }
  })

  output$dropdown2 <- renderUI({
    pickerInput("dropdown2", "Values:", choices = values())
  })

}

Depending on what really will go in "x" and "y", using ifelse() might save you space in this approach.


问:
bazel connect find_package from cmake
I'm trying to use bazel's cmake from rules_foreign_cc to build a library called fcl. That package has, in it's CMakeLists.txt, a find_package(ccd QUIET) statement. It wants to find the ccd (or libccd) package. I build that package as well, but just using cc_library. How can I get the find_package statement to find the package that I build?

So

```<code>cc_library(
    name = "libccd",
    visibility = ["//visibility:public"],
    include_prefix = "libccd/src",
    hdrs = [stuff],
    srcs = [stuff],
}

cmake(
    name = "fcl",
    cache_entries = {
        ?maybe this?
    },
    env_vars = {
        ?maybe this?
    },
    lib_source = "@fcl//:all",
    deps = [
        ":libccd",
    ],
)
</code>```

答: I highly recommend you to bazelize fcl. Not sure, but maybe this has been done already here. I bazelized a few CMake projects in the past and it always worked well (e.g. openexr, oneTBB, fmt)</p>

Title: bazel connect find_package from cmake

Body:
I'm trying to use bazel's cmake from rules_foreign_cc to build a library called fcl. That package has, in it's CMakeLists.txt, a find_package(ccd QUIET) statement. It wants to find the ccd (or libccd) package. I build that package as well, but just using cc_library. How can I get the find_package statement to find the package that I build?

So

cc_library(
    name = "libccd",
    visibility = ["//visibility:public"],
    include_prefix = "libccd/src",
    hdrs = [stuff],
    srcs = [stuff],
}

cmake(
    name = "fcl",
    cache_entries = {
        ?maybe this?
    },
    env_vars = {
        ?maybe this?
    },
    lib_source = "@fcl//:all",
    deps = [
        ":libccd",
    ],
)


问:
How to check for array in java
I am getting values params[point.id] . i want to check whether params[point.id] is array or not ,how to do this </p>

答:
Try isArray(),

```<code>foo.getClass().isArray();
</code>```

where foo is the Object in question.

Title: How to check for array in java

Body:
Try isArray(),

foo.getClass().isArray();

where foo is the Object in question.


问:
Numpy take consecutive values from array1, put them into array2 at consecutive indexes stored in array3
I have an array of bgr values called img_matrix, an empty array called new_img, and another array that tells what index every pixel value in img_matrix should go to in new_img, called img_index. So basically:

```<code>for i, point in enumerate(img_index):
    x = point[0]
    y = point[1]
    new_img[y][x] = img_matrix[i]
</code>```

How can i get rid of the for loop and speed things up? Im sure there's a numpy function that does this.

--some clarification--
my end goal is projecting a 640x480 image from a camera on a drone with a known rotation and displacement, onto the z=0 plane. After projection, the image turns into a grid of points on the z=0 plane resembling a trapezoid. I am trying to "interpolate" these points onto a regular grid. All other methods were too slow (scipy.interpolate, nearest neighbor using k-d tree) so i devised another method. I "round" the coordinates into the closest point on the grid i want to sample, and assign the rgb values of those points to the image matrix new_img where they line up. If nothing lines up, i would like the rgb values to all be zero. If multiple points line up on top of each other, any will do.

an example would maybe be

```<code>img_index =
[[0, 0]
 [0, 1]
 [0, 1]
 [1, 1]]

img_matrix =
[[1, 2, 3]
 [4, 5, 6]
 [7, 8, 9]
 [10, 11, 12]]

new_img=
[[[1,2,3],[7,8,9]]
 [[0,0,0],[10,11,12]]]
</code>```

Thanks in advance!

答:
It seems that you want to create an empty array and fill its values at the specific places. You could do it in a vectorised way like so:</p>
```<code>img_index = np.array([[0, 0], [0, 1], [0, 1], [1, 1]])
img_matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
new_img = np.zeros(shape=(2, 2, 3), dtype=int)
new_img[img_index[:,0], img_index[:,1]] = img_matrix
new_img
>>>
array([[[ 1,  2,  3],
        [ 7,  8,  9]],

       [[ 0,  0,  0],
        [10, 11, 12]]])
</code>```

Body:
I have an array of bgr values called img_matrix, an empty array called new_img, and another array that tells what index every pixel value in img_matrix should go to in new_img, called img_index. So basically:

for i, point in enumerate(img_index):
    x = point[0]
    y = point[1]
    new_img[y][x] = img_matrix[i]

How can i get rid of the for loop and speed things up? Im sure there's a numpy function that does this.

--some clarification--
my end goal is projecting a 640x480 image from a camera on a drone with a known rotation and displacement, onto the z=0 plane. After projection, the image turns into a grid of points on the z=0 plane resembling a trapezoid. I am trying to "interpolate" these points onto a regular grid. All other methods were too slow (scipy.interpolate, nearest neighbor using k-d tree) so i devised another method. I "round" the coordinates into the closest point on the grid i want to sample, and assign the rgb values of those points to the image matrix new_img where they line up. If nothing lines up, i would like the rgb values to all be zero. If multiple points line up on top of each other, any will do.

an example would maybe be

img_index =
[[0, 0]
 [0, 1]
 [0, 1]
 [1, 1]]

img_matrix =
[[1, 2, 3]
 [4, 5, 6]
 [7, 8, 9]
 [10, 11, 12]]

new_img=
[[[1,2,3],[7,8,9]]
 [[0,0,0],[10,11,12]]]

Thanks in advance!

Body:
It seems that you want to create an empty array and fill its values at the specific places. You could do it in a vectorised way like so:

img_index = np.array([[0, 0], [0, 1], [0, 1], [1, 1]])
img_matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
new_img = np.zeros(shape=(2, 2, 3), dtype=int)
new_img[img_index[:,0], img_index[:,1]] = img_matrix
new_img
>>>
array([[[ 1,  2,  3],
        [ 7,  8,  9]],

       [[ 0,  0,  0],
        [10, 11, 12]]])


问:
Rasterizing polygons with complicated weighting
Imagine a regular 0.5° grid across the Earth's surface. A 3x3 subset of this grid is shown below. As a stylized example of what I'm working with, let's say I have three polygons—yellow, orange, and blue—that for the sake of simplicity all are 1 unit in area. These polygons have attributes Population and Value, which you can see in the legend:

I want to turn these polygons into a 0.5° raster (with global extent) whose values are based on the weighted-mean Value of the polygons. The tricky part is that I want to weight the polygons' values based on not their Population, but rather on their included population.

I know—theoretically—what I want to do, and below have done it for the center gridcell.

Multiply Population by Included (the area of the polygon that is included in the gridcell) to get Pop. included. (Assumes population is distributed evenly throughout polygon, which is acceptable.)

Divide each polygon's Included_pop by the sum of all polygons' Included_pop (32) to get Weight.

Multiply each polygon's Value by Weight to get Result.

Sum all polygons' Result to get the value for the center gridcell (0.31).

Population
Value
Frac. included
Pop. included
Weight
Result

Yellow
24
0.8
0.25
6
0.1875
0.15

Orange
16
0.4
0.5
8
0.25
0.10

Blue
18
0.1
1
18
0.5625
0.06

32

0.31

I have an idea of how to accomplish this in R, as described below. Where possible, I've filled in code that I think will do what I want. My questions: How do I do steps 2 and 3? Or is there a simpler way to do this? If you want to play around with this, I have uploaded old_polygons as a .rds file here.

```<code>library("sf")
library("raster")
</code>```

Calculate the area of each polygon: old_polygons$area <- as.numeric(st_area(old_polygons))

Generate the global 0.5° grid as some kind of Spatial object.

Split the polygons by the grid, generating new_polygons.

Calculate area of the new polygons: new_polygons$new_area <- as.numeric(st_area(new_polygons))

Calculate fraction included for each new polygon: new_polygons$frac_included <- new_polygons$new_area / new_polygons$old_area

Calculate "included population" in the new polygons: new_polygons$pop_included <- new_polygons$pop * new_polygons$frac_included

Calculate a new attribute for each polygon that is just their Value times their included population. new_polygons$tmp <- new_polygons$Value * new_polygons$frac_included

Set up an empty raster for the next steps: empty_raster <- raster(nrows=360, ncols=720, xmn=-180, xmx=180, ymn=-90, ymx=90)

Rasterize the polygons by summing this new attribute together within each gridcell. tmp_raster <- rasterize(new_polygons, empty_raster, "tmp", fun = "sum")

Create another raster that is just the total population in each gridcell: pop_raster <- rasterize(new_polygons, empty_raster, "pop_included", fun = "sum")

Divide the first raster by the second to get what I want:

```<code>output_raster <- empty_raster
values(output_raster) <- getValues(tmp_raster) / getValues(pop_raster)
</code>```

Any help would be much appreciated!

答:
This is fast and scalable:</p>
```<code>library(data.table)
library(terra)

# make the 3 polygons with radius = 5km
center_points <- data.frame(lon = c(0.5, 0.65, 1),
                            lat = c(0.75, 0.65, 1),
                            Population = c(16, 18, 24),
                            Value = c(0.4, 0.1, 0.8))
polygon <- vect(center_points, crs = "EPSG:4326")
polygon <- buffer(polygon, 5000)

# make the raster
my_raster <- rast(nrow = 3, ncol = 3, xmin = 0, xmax = 1.5, ymin = 0, ymax = 1.5, crs = "EPSG:4326")
my_raster[] <- 0 # set the value to 0 for now

# find the fractions of cells in each polygon
# "cells" gives you the cell ID and "weights" (or "exact") gives you the cell fraction in the polygon
# using "exact" instead of "weights" is more accurate
my_Table <- extract(my_raster, polygon, cells = TRUE, weights = TRUE)
setDT(my_Table) # convert to datatable

# merge the polygon attributes to "my_Table"
poly_Table <- setDT(as.data.frame(polygon))
poly_Table[, ID := 1:nrow(poly_Table)] # add the IDs which are the row numbers
merged_Table <- merge(my_Table, poly_Table, by = "ID")

# find Frac_included
merged_Table[, Frac_included := weight / sum(weight), by = ID]

# find Pop_included
merged_Table[, Pop_included := Frac_included * Population]

# find Weight, to avoid confusion with "weight" produced above, I call this "my_Weight"
merged_Table[, my_Weight := Pop_included / sum(Pop_included), by = cell]

# final results
Result <- merged_Table[, .(Result = sum(Value * my_Weight)), by = cell]

# add the values to the raster
my_raster[Result$cell] <- Result$Result
plot(my_raster)
</code>```

Body:
Imagine a regular 0.5° grid across the Earth's surface. A 3x3 subset of this grid is shown below. As a stylized example of what I'm working with, let's say I have three polygons—yellow, orange, and blue—that for the sake of simplicity all are 1 unit in area. These polygons have attributes Population and Value, which you can see in the legend:

I want to turn these polygons into a 0.5° raster (with global extent) whose values are based on the weighted-mean Value of the polygons. The tricky part is that I want to weight the polygons' values based on not their Population, but rather on their included population.

I know—theoretically—what I want to do, and below have done it for the center gridcell.

Multiply Population by Included (the area of the polygon that is included in the gridcell) to get Pop. included. (Assumes population is distributed evenly throughout polygon, which is acceptable.)

Divide each polygon's Included_pop by the sum of all polygons' Included_pop (32) to get Weight.

Multiply each polygon's Value by Weight to get Result.

Sum all polygons' Result to get the value for the center gridcell (0.31).

Population
Value
Frac. included
Pop. included
Weight
Result

Yellow
24
0.8
0.25
6
0.1875
0.15

Orange
16
0.4
0.5
8
0.25
0.10

Blue
18
0.1
1
18
0.5625
0.06

32

0.31

I have an idea of how to accomplish this in R, as described below. Where possible, I've filled in code that I think will do what I want. My questions: How do I do steps 2 and 3? Or is there a simpler way to do this? If you want to play around with this, I have uploaded old_polygons as a .rds file here.

library("sf")
library("raster")

Calculate the area of each polygon: old_polygons$area <- as.numeric(st_area(old_polygons))

Generate the global 0.5° grid as some kind of Spatial object.

Split the polygons by the grid, generating new_polygons.

Calculate area of the new polygons: new_polygons$new_area <- as.numeric(st_area(new_polygons))

Calculate fraction included for each new polygon: new_polygons$frac_included <- new_polygons$new_area / new_polygons$old_area

Calculate "included population" in the new polygons: new_polygons$pop_included <- new_polygons$pop * new_polygons$frac_included

Calculate a new attribute for each polygon that is just their Value times their included population. new_polygons$tmp <- new_polygons$Value * new_polygons$frac_included

Set up an empty raster for the next steps: empty_raster <- raster(nrows=360, ncols=720, xmn=-180, xmx=180, ymn=-90, ymx=90)

Rasterize the polygons by summing this new attribute together within each gridcell. tmp_raster <- rasterize(new_polygons, empty_raster, "tmp", fun = "sum")

Create another raster that is just the total population in each gridcell: pop_raster <- rasterize(new_polygons, empty_raster, "pop_included", fun = "sum")

Divide the first raster by the second to get what I want:

output_raster <- empty_raster
values(output_raster) <- getValues(tmp_raster) / getValues(pop_raster)

Any help would be much appreciated!

Body:
This is fast and scalable:

library(data.table)
library(terra)

# make the 3 polygons with radius = 5km
center_points <- data.frame(lon = c(0.5, 0.65, 1),
                            lat = c(0.75, 0.65, 1),
                            Population = c(16, 18, 24),
                            Value = c(0.4, 0.1, 0.8))
polygon <- vect(center_points, crs = "EPSG:4326")
polygon <- buffer(polygon, 5000)

# make the raster
my_raster <- rast(nrow = 3, ncol = 3, xmin = 0, xmax = 1.5, ymin = 0, ymax = 1.5, crs = "EPSG:4326")
my_raster[] <- 0 # set the value to 0 for now

# find the fractions of cells in each polygon
# "cells" gives you the cell ID and "weights" (or "exact") gives you the cell fraction in the polygon
# using "exact" instead of "weights" is more accurate
my_Table <- extract(my_raster, polygon, cells = TRUE, weights = TRUE)
setDT(my_Table) # convert to datatable

# merge the polygon attributes to "my_Table"
poly_Table <- setDT(as.data.frame(polygon))
poly_Table[, ID := 1:nrow(poly_Table)] # add the IDs which are the row numbers
merged_Table <- merge(my_Table, poly_Table, by = "ID")

# find Frac_included
merged_Table[, Frac_included := weight / sum(weight), by = ID]

# find Pop_included
merged_Table[, Pop_included := Frac_included * Population]

# find Weight, to avoid confusion with "weight" produced above, I call this "my_Weight"
merged_Table[, my_Weight := Pop_included / sum(Pop_included), by = cell]

# final results
Result <- merged_Table[, .(Result = sum(Value * my_Weight)), by = cell]

# add the values to the raster
my_raster[Result$cell] <- Result$Result
plot(my_raster)


问:
php and html contact form
So I've been working on creating a contact form. No matter what I try, I can't get it to work. I've read different blogs, how to's, etc. I would love some help. Note: when it says email@email.com, I've input my own email.

HTML:

```<code><div class="col-lg-6 offset-lg-1">
   <form action="form-data/formdata.php" class="form-widget form-control-op-02">
        <div class="field-wrp">
                <input type="hidden" name="to"value="email@email.com">

</code>```

I won't bore you with all the details of the form fields i.e. name, phone number, email, etc.

PHP:

```<code>if (isset($_POST) && sizeof($_POST) > 0) {

    $to = $_POST['to']['val']; // <=== Set static email here.

    if (isset($_POST['formtype'])) {
        unset($_POST['formtype']);
    }
    if (isset($_POST['to'])) {
        unset($_POST['to']);
    }

    $email_address = $_POST['email']['val'];
    $email_subject = "Form submitted by: ".$_POST['name']['val'];
    $email_body    = "You have received a new message. <br/>".
                     "Here are the details: <br/><br/>";
                     foreach ($_POST as $key => $value) {
                        $email_body .= "<strong>" . $value['label'] . ": </strong> " . $value['val'] . "<br/><br/>";
                     }

    $headers = "From:<$email_address>\n";
    $headers.= "Content-Type:text/html; charset=UTF-8";
    if($email_address != "") {
        mail($to,$email_subject,$email_body,$headers);
        return true;
    }
}
?>
</code>```

答:
Change

```<code><form action="form-data/formdata.php" class="form-widget form-control-op-02">
</code>```

into this

```<code><form action="form-data/formdata.php" method="post" class="form-widget form-control-op-02">
</code>```

by default HTML form method is get also if i understand correctly you are storing your own Email into input type="hidden you can just store that into a PHP variable for instance $myEmail = "free2rhyme@gmail.com"; so you don't have dangling input type="hidden in your form

Title: php and html contact form

Body:
So I've been working on creating a contact form. No matter what I try, I can't get it to work. I've read different blogs, how to's, etc. I would love some help. Note: when it says email@email.com, I've input my own email.

HTML:

   <form action="form-data/formdata.php" class="form-widget form-control-op-02">

                <input type="hidden" name="to"value="email@email.com">

I won't bore you with all the details of the form fields i.e. name, phone number, email, etc.

PHP:

if (isset($_POST) && sizeof($_POST) > 0) {

    $to = $_POST['to']['val']; // <=== Set static email here.

    if (isset($_POST['formtype'])) {
        unset($_POST['formtype']);
    }
    if (isset($_POST['to'])) {
        unset($_POST['to']);
    }

    $email_address = $_POST['email']['val'];
    $email_subject = "Form submitted by: ".$_POST['name']['val'];
    $email_body    = "You have received a new message.
".
                     "Here are the details:

";
                     foreach ($_POST as $key => $value) {
                        $email_body .= "" . $value['label'] . ":  " . $value['val'] . "

";
                     }

    $headers = "From:<$email_address>\n";
    $headers.= "Content-Type:text/html; charset=UTF-8";
    if($email_address != "") {
        mail($to,$email_subject,$email_body,$headers);
        return true;
    }
}
?>

Body:
Change

<form action="form-data/formdata.php" class="form-widget form-control-op-02">

into this

<form action="form-data/formdata.php" method="post" class="form-widget form-control-op-02">

by default HTML form method is get also if i understand correctly you are storing your own Email into input type="hidden you can just store that into a PHP variable for instance $myEmail = "free2rhyme@gmail.com"; so you don't have dangling input type="hidden in your form


问:
Ifelse with conditional on grouped data
This has got to be simple, but I'm stuck. I want to mutate some grouped data using a where statement within an ifelse statement. Here's an example that works:

```<code>example <- tibble::tribble(
  ~Group, ~Code, ~Value,
  "1", "A", 1,
  "1", "B", 1,
  "1", "C", 5,
  "2", "A", 1,
  "2", "B", 5,
  "2", "C", 2
)

example %>% group_by(Group) %>%
  mutate(GroupStatus=ifelse(Value[Code=="C"]==5, 1, 0))
</code>```

This gives the desired result:

```<code>  Group Code  Value GroupStatus
  <chr> <chr> <dbl>       <dbl>
1 1     A         1           1
2 1     B         1           1
3 1     C         5           1
4 2     A         1           0
5 2     B         5           0
6 2     C         2           0
</code>```

The problem is when one of the groups is missing Code C, as below:

```<code>example2 <- tibble::tribble(
  ~Group, ~Code, ~Value,
  "1", "A", 1,
  "1", "B", 1,
  "1", "C", 5,
  "2", "A", 1,
  "2", "B", 5
)

example2 %>% group_by(Group) %>%
  mutate(GroupStatus=ifelse(Value[Code=="C"]==5, 1, 0))
</code>```

This gives me an error: Error: Problem with mutate() column GroupStatus.
i GroupStatus = ifelse(Value[Code == "C"] == 5, 1, 0).
i GroupStatus must be size 2 or 1, not 0.
i The error occurred in group 2: Group = "2".

What I'd like is for "GroupStatus" in any group that is missing Code C to just be set to zero. Is that possible?

答:
You really only have a single condition to check per group, so we can simplify to an any() instead of ifelse():

```<code>example2 %>%
  group_by(Group) %>%
  mutate(GroupStatus = as.integer(any(Value == 5 & Code == "C")))
# # A tibble: 5 × 4
# # Groups:   Group [2]
#   Group Code  Value GroupStatus
#   <chr> <chr> <dbl>       <dbl>
# 1 1     A         1           1
# 2 1     B         1           1
# 3 1     C         5           1
# 4 2     A         1           0
# 5 2     B         5           0
</code>```

Title: Ifelse with conditional on grouped data

Body:
This has got to be simple, but I'm stuck. I want to mutate some grouped data using a where statement within an ifelse statement. Here's an example that works:

example <- tibble::tribble(
  ~Group, ~Code, ~Value,
  "1", "A", 1,
  "1", "B", 1,
  "1", "C", 5,
  "2", "A", 1,
  "2", "B", 5,
  "2", "C", 2
)

example %>% group_by(Group) %>%
  mutate(GroupStatus=ifelse(Value[Code=="C"]==5, 1, 0))

This gives the desired result:

  Group Code  Value GroupStatus
  <chr> <chr> <dbl>       <dbl>
1 1     A         1           1
2 1     B         1           1
3 1     C         5           1
4 2     A         1           0
5 2     B         5           0
6 2     C         2           0

The problem is when one of the groups is missing Code C, as below:

example2 <- tibble::tribble(
  ~Group, ~Code, ~Value,
  "1", "A", 1,
  "1", "B", 1,
  "1", "C", 5,
  "2", "A", 1,
  "2", "B", 5
)

example2 %>% group_by(Group) %>%
  mutate(GroupStatus=ifelse(Value[Code=="C"]==5, 1, 0))

This gives me an error: Error: Problem with mutate() column GroupStatus.
i GroupStatus = ifelse(Value[Code == "C"] == 5, 1, 0).
i GroupStatus must be size 2 or 1, not 0.
i The error occurred in group 2: Group = "2".

What I'd like is for "GroupStatus" in any group that is missing Code C to just be set to zero. Is that possible?

Body:
You really only have a single condition to check per group, so we can simplify to an any() instead of ifelse():

example2 %>%
  group_by(Group) %>%
  mutate(GroupStatus = as.integer(any(Value == 5 & Code == "C")))
# # A tibble: 5 × 4
# # Groups:   Group [2]
#   Group Code  Value GroupStatus
#   <chr> <chr> <dbl>       <dbl>
# 1 1     A         1           1
# 2 1     B         1           1
# 3 1     C         5           1
# 4 2     A         1           0
# 5 2     B         5           0


问:
Music Bot Discord (Python)
python show me this error:
raceback (most recent call last):
File , line 10, in
import pynacl
ModuleNotFoundError: No module named 'pynacl'

i use python 3.10.2

i installed pynacl.

Can you help me please?

答:
pip install PyNaCl

If you install PyNaCl, and this problem repeated

Try pip freeze and find PyNaCl==1.4.0 (or other version)

You can solve this problem only this way

Title: Music Bot Discord (Python)


问:
Get a reference to the workflow from inside the workflow
I want my workflow to Abort after failing some tests.

How can I get a reference to the workflow I am in so that I have something to call abort on.

I'm, going to try passing in a reference to the workflow in the IDictionary as I start the workflow but I would have thought that the Context had a reference to the workflow inside it somewhere.

Any thoughts?
Richard

答:
Do you want to Abort or Terminate your workflow?

Normally aborting is only done when an unhanded error occurs and you want to restart from the last state in the persistence store. You do that by throwing an exception using the Throw acticity, not catching it in your workflow and specifying an UnhandledExceptionAction of Abort.

When an invalid state is detected in a workflow termination is more common. You can do that using a TerminateWorkflow activity.


问:
Programming Languages where a keyword is needed to specify that the method is extended from its parent class
Forgive me for my ignorance, but does anyone know any languages that strictly enforce the condition I've given on the title? For example, using Python syntax, we can extend a class with a new method like this

class A:
    pass

class B(A):
    def foo(self):
        pass
```
<p>But is there a language that needs an additional keyword, let's say <code>new</code>, to specify that this method is unique to the child class and is not an override of the methods of its parent class/es? For example:</p>
```class A:
    pass

class B(A):
    def new foo(self):
        pass
```

I am asking this because, when I am working on a project that requires multiple inheritance such as class B(A, C, D), and I saw a method defined in B, I need to check if the given method is from one of its parent class or its own method, and I find it extremely tedious.

答:
The closest I can think of is the @Override annotation in Java, which can be applied to a method declaration in order for the compiler to check that it overrides an inherited method (or implements an interface method).

When used in conjunction with a linter which checks that all method overrides are annotated with @Override, then your IDE will give you a linter warning when you omit the annotation. IntellIJ IDEA and SonarSource both have linter rules for this, for example.

So long as you are strict about obeying the linter warning, then it's "strict" in that sense, but of course linter warnings don't actually prevent your code from being compiled or executed. Nonetheless, I don't know of a closer example from a real programming language. Unfortunately Java doesn't have multiple inheritance so it's not directly applicable to your problem.

Body:
Forgive me for my ignorance, but does anyone know any languages that strictly enforce the condition I've given on the title? For example, using Python syntax, we can extend a class with a new method like this

class A:
    pass

class B(A):
    def foo(self):
        pass

But is there a language that needs an additional keyword, let's say new, to specify that this method is unique to the child class and is not an override of the methods of its parent class/es? For example:

class A:
    pass

class B(A):
    def new foo(self):
        pass

I am asking this because, when I am working on a project that requires multiple inheritance such as class B(A, C, D), and I saw a method defined in B, I need to check if the given method is from one of its parent class or its own method, and I find it extremely tedious.


问:
Sendgrid multiple attachments using URL
I am having difficulty implementing multiple attachments to sendgrid. The issue I am facing is that fetchAttach function request, is not returning textBuffered before sendEmail object is created even though it is a async/await function. Below is my code for better understanding and also the result of the logs

```<code>let fileNames = [
  "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf",
  "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf",
];
let attachments = [];

async function fetchAttach(file) {
  let textBuffered;
  request(file, { encoding: null }, (err, res, body) => {
    if (err) {
      console.log("Error-->", err);
    }
    if (res) {
      console.log(res.statusCode);
    }
    if (body) {
      textBuffered = Buffer.from(body);
      console.log("textBuffered");
    }
  });
  return textBuffered;
}
</code>```

```<code>app.post("/api/custom-email", async (req, res) => {
  const {
    firstName,
    lastName,
    email,
    message
  } = req.body;

  for (let file of fileNames) {
    await fetchAttach(file)
      .then((res) => {
        console.log("1st. then");
        const attachObj = {
          content: res.toString("base64"),
          filename: `${firstName}${lastName}.pdf`,
          type: "application/pdf",
          disposition: "attachment",
          content_id: "mytext",
        };
        attachments.push(attachObj);
      })

      .then(() => {
        console.log("attachments-->", attachments);
        console.log("2nd .then triggered");
        const sendEmail = {
          method: "POST",
          url: "https://api.sendgrid.com/v3/mail/send",
          headers: {
            "content-type": "application/json",
            Authorization: `Bearer SG.xxxxxxxxxxxxxxxxxxxxxxxxxxx`,
          },
          body: {
            personalizations: [
              {
                to: [
                  {
                    email,
                    name: `${firstName} ${lastName}`,
                  },
                ],
                dynamic_template_data: {
                   message,

                },
              },
            ],
            from: {
              email: "info@xxxxx.com",
              name: `(Do not reply) - ${businessName}`,
            },
            reply_to: {
              email: "info@xxxxx.com",
              name: "xxxxxxx",
            },
            template_id: "d-xxxxxxxxxxxxxxxxxx",
            attachments: attachments,
          },
          json: true,
        };

        console.log("sendEmail triggered");
      });
  }

  return res.send("OK");
});
</code>```

Below are the logs in console:

```<code>1st. then
attachments--> [
  {
    content: undefined,
    filename: 'testEmaila.pdf',
    type: 'application/pdf',
    disposition: 'attachment',
    content_id: 'mytext'
  }
]
2nd .then triggered
sendEmail triggered
1st. then
attachments--> [
  {
    content: undefined,
    filename: 'testEmaila.pdf',
    type: 'application/pdf',
    disposition: 'attachment',
    content_id: 'mytext'
  },
  {
    content: undefined,
    filename: 'testEmaila.pdf',
    type: 'application/pdf',
    disposition: 'attachment',
    content_id: 'mytext'
  }
]
2nd .then triggered
sendEmail triggered
200
textBuffered
200
textBuffered
</code>```

答:
I found a solution to my question above using this post.

request npm package does not support async/await instead I ended up using request-promise package and now my fetchAttach functions looks like below

```<code>async function fetchAttach(file) {
  let textBuffered;
  await request(file, { encoding: null }, (err, res, body) => {
    if (err) {
      console.log("Error-->", err);
    }
    if (res) {
      console.log(res.statusCode);
    }
    if (body) {
      textBuffered = Buffer.from(body);
      console.log("textBuffered");
    }
  });
  return textBuffered;
}
</code>```

added await before the request(file, ...) which is supported by request-promise package.

Title: Sendgrid multiple attachments using URL

Body:
I am having difficulty implementing multiple attachments to sendgrid. The issue I am facing is that fetchAttach function request, is not returning textBuffered before sendEmail object is created even though it is a async/await function. Below is my code for better understanding and also the result of the logs

let fileNames = [
  "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf",
  "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf",
];
let attachments = [];

async function fetchAttach(file) {
  let textBuffered;
  request(file, { encoding: null }, (err, res, body) => {
    if (err) {
      console.log("Error-->", err);
    }
    if (res) {
      console.log(res.statusCode);
    }
    if (body) {
      textBuffered = Buffer.from(body);
      console.log("textBuffered");
    }
  });
  return textBuffered;
}

app.post("/api/custom-email", async (req, res) => {
  const {
    firstName,
    lastName,
    email,
    message
  } = req.body;

  for (let file of fileNames) {
    await fetchAttach(file)
      .then((res) => {
        console.log("1st. then");
        const attachObj = {
          content: res.toString("base64"),
          filename: `${firstName}${lastName}.pdf`,
          type: "application/pdf",
          disposition: "attachment",
          content_id: "mytext",
        };
        attachments.push(attachObj);
      })

      .then(() => {
        console.log("attachments-->", attachments);
        console.log("2nd .then triggered");
        const sendEmail = {
          method: "POST",
          url: "https://api.sendgrid.com/v3/mail/send",
          headers: {
            "content-type": "application/json",
            Authorization: `Bearer SG.xxxxxxxxxxxxxxxxxxxxxxxxxxx`,
          },
          body: {
            personalizations: [
              {
                to: [
                  {
                    email,
                    name: `${firstName} ${lastName}`,
                  },
                ],
                dynamic_template_data: {
                   message,

                },
              },
            ],
            from: {
              email: "info@xxxxx.com",
              name: `(Do not reply) - ${businessName}`,
            },
            reply_to: {
              email: "info@xxxxx.com",
              name: "xxxxxxx",
            },
            template_id: "d-xxxxxxxxxxxxxxxxxx",
            attachments: attachments,
          },
          json: true,
        };

        console.log("sendEmail triggered");
      });
  }

  return res.send("OK");
});

Below are the logs in console:

1st. then
attachments--> [
  {
    content: undefined,
    filename: 'testEmaila.pdf',
    type: 'application/pdf',
    disposition: 'attachment',
    content_id: 'mytext'
  }
]
2nd .then triggered
sendEmail triggered
1st. then
attachments--> [
  {
    content: undefined,
    filename: 'testEmaila.pdf',
    type: 'application/pdf',
    disposition: 'attachment',
    content_id: 'mytext'
  },
  {
    content: undefined,
    filename: 'testEmaila.pdf',
    type: 'application/pdf',
    disposition: 'attachment',
    content_id: 'mytext'
  }
]
2nd .then triggered
sendEmail triggered
200
textBuffered
200
textBuffered

Body:
I found a solution to my question above using this post.

request npm package does not support async/await instead I ended up using request-promise package and now my fetchAttach functions looks like below

async function fetchAttach(file) {
  let textBuffered;
  await request(file, { encoding: null }, (err, res, body) => {
    if (err) {
      console.log("Error-->", err);
    }
    if (res) {
      console.log(res.statusCode);
    }
    if (body) {
      textBuffered = Buffer.from(body);
      console.log("textBuffered");
    }
  });
  return textBuffered;
}

added await before the request(file, ...) which is supported by request-promise package.


问:
kubernetes kubectl exec forbidden
I did a basic kubernetes installation, and added hello-world pod. When I try to kubectl exec, I get below error.

```<code>kubectl logs hello-world-pod1

Error from server (Forbidden): pods "hello-world-pod1" is forbidden: User "system:node:kubnode1" cannot get resource "pods/log" in API group "" in the namespace "default"

kubectl exec -it hello-world-pod1 -- /bin/sh

Error from server (Forbidden): pods "hello-world-pod1" is forbidden: User "system:node:kw1" cannot create resource "pods/exec" in API group "" in the namespace "default"

</code>```

There is not any special installation, just basic instructions, and could not access shell of a basic pod, i researched internet but could not find any solution or source of error.

答:
Due to following error that appears in your case:

```<code>Error from server: error dialing backend: dial tcp 10.0.2.46:10250: connect: no route to host
</code>```

I would suggest disabling the firewall on all nodes.
To fix the problem for not disabled worker nodes firewall run:

systemctl disable firewalld && systemctl stop firewalld
-Removed symlink /etc/systemd/system/dbus-org.fedoraproject.FirewallD1...
-Removed symlink /etc/systemd/system/basic.target.wants/firewalld.service.```
</code>```

See also references:

This similar problem

Documentation connected to non-public IP used for containers

Title: kubernetes kubectl exec forbidden

Body:
I did a basic kubernetes installation, and added hello-world pod. When I try to kubectl exec, I get below error.

kubectl logs hello-world-pod1

Error from server (Forbidden): pods "hello-world-pod1" is forbidden: User "system:node:kubnode1" cannot get resource "pods/log" in API group "" in the namespace "default"

kubectl exec -it hello-world-pod1 -- /bin/sh

Error from server (Forbidden): pods "hello-world-pod1" is forbidden: User "system:node:kw1" cannot create resource "pods/exec" in API group "" in the namespace "default"

There is not any special installation, just basic instructions, and could not access shell of a basic pod, i researched internet but could not find any solution or source of error.

Body:
Due to following error that appears in your case:

Error from server: error dialing backend: dial tcp 10.0.2.46:10250: connect: no route to host

I would suggest disabling the firewall on all nodes.
To fix the problem for not disabled worker nodes firewall run:

systemctl disable firewalld && systemctl stop firewalld
-Removed symlink /etc/systemd/system/dbus-org.fedoraproject.FirewallD1...
-Removed symlink /etc/systemd/system/basic.target.wants/firewalld.service.```

See also references:

This similar problem

Documentation connected to non-public IP used for containers


问:
How to join adjacent elements in a list with a string in between?
I am starting on my Python journey and am doing some exercises to get the hang of it all. One question is really giving me troubles as I do not understand how to complete it.

Given a list with an even number of integers, join adjacent elements using '-' and print each pair.
So it will be that this is given:

```<code>a = [1, 2, 3, 4, 5, 6, 7, 8]
</code>```

and the output needs to be:

```<code>1-2
3-4
5-6
7-8
</code>```

Now I have gotten as far as this, but have no idea what to do next:

```<code>a = [1, 2, 3, 4, 5, 6, 7, 8]
a1 = a[::2]
a2 = a[1::2]

duos = zip(a1, a2)
print(list(duos))
</code>```

And this only gives me this as result:

```<code>[(1, 2), (3, 4), (5, 6), (7, 8)]
</code>```

I feel like I am close and just missing one tiny step.

答:
You're indeed very close. Now just print each pair in duos on a separate line with a dash as separator:

```<code>for a,b in duos: print(a,b,sep="-")
</code>```

Or you could do it all in one line using a combination of map, zip and join:

```<code>print(*map("-".join,zip(*[map(str,a)]*2)),sep="\n")
</code>```

Body:
I am starting on my Python journey and am doing some exercises to get the hang of it all. One question is really giving me troubles as I do not understand how to complete it.

Given a list with an even number of integers, join adjacent elements using '-' and print each pair.
So it will be that this is given:

a = [1, 2, 3, 4, 5, 6, 7, 8]

and the output needs to be:

1-2
3-4
5-6
7-8

Now I have gotten as far as this, but have no idea what to do next:

a = [1, 2, 3, 4, 5, 6, 7, 8]
a1 = a[::2]
a2 = a[1::2]

duos = zip(a1, a2)
print(list(duos))

And this only gives me this as result:

[(1, 2), (3, 4), (5, 6), (7, 8)]

I feel like I am close and just missing one tiny step.

Body:
You're indeed very close. Now just print each pair in duos on a separate line with a dash as separator:

for a,b in duos: print(a,b,sep="-")

Or you could do it all in one line using a combination of map, zip and join:

print(*map("-".join,zip(*[map(str,a)]*2)),sep="\n")


问:
Combine enumerate + itertools.izip in Python
I would like to iterate + enumerate over two lists in Python. The following code looks ugly. Is there any better solution?

```<code>for id, elements in enumerate(itertools.izip(as, bs)):
  a = elements[0]
  b = elements[1]
  # do something with id, a and b
</code>```

Thank you.

答:
You can assign a and b during the for loop:</p>

```<code>for id, (a, b) in enumerate(itertools.izip(as, bs)):
  # do something with id, a and b
</code>```

Body:
I would like to iterate + enumerate over two lists in Python. The following code looks ugly. Is there any better solution?

for id, elements in enumerate(itertools.izip(as, bs)):
  a = elements[0]
  b = elements[1]
  # do something with id, a and b

Thank you.

Body:
You can assign a and b during the for loop:

for id, (a, b) in enumerate(itertools.izip(as, bs)):
  # do something with id, a and b


问:
Solving a Query on SQLDeveloper
need some help on solving this query.
I want to get projects that had no change in their team (i.e. because project0002 has two different project managers it must not appear on the result of the query)

Can you help me ?

```<code>CREATE TABLE sprintMembers (
  userID                 NUMBER(10)    NOT NULL,
  sprintNumber           NUMBER(10)    NOT NULL,
  sprintProjectCode      VARCHAR(255) NOT NULL,
  memberRole                   VARCHAR(255) NOT NULL,

  PRIMARY KEY (userID, sprintNumber, sprintProjectCode));

INSERT INTO sprintMembers VALUES (4,1,'PROJ0001', 'Project Manager');
INSERT INTO sprintMembers VALUES (5,1,'PROJ0001', 'Product Owner');
INSERT INTO sprintMembers VALUES (6,1,'PROJ0001', 'Scrum Master');
INSERT INTO sprintMembers VALUES (4,1,'PROJ0002', 'Project Manager');
INSERT INTO sprintMembers VALUES (3,2,'PROJ0002', 'Project Manager');
INSERT INTO sprintMembers VALUES (4,3,'PROJ0002', 'Project Manager');
INSERT INTO sprintMembers VALUES (5,1,'PROJ0002', 'Product Owner');
INSERT INTO sprintMembers VALUES (5,2,'PROJ0002', 'Product Owner');
INSERT INTO sprintMembers VALUES (7,1,'PROJ0002', 'Team Member');
INSERT INTO sprintMembers VALUES (7,2,'PROJ0002', 'Team Member');
INSERT INTO sprintMembers VALUES (4,1,'PROJ0003', 'Project Manager');
INSERT INTO sprintMembers VALUES (4,2,'PROJ0003', 'Project Manager');
INSERT INTO sprintMembers VALUES (5,1,'PROJ0003', 'Product Owner');
INSERT INTO sprintMembers VALUES (5,2,'PROJ0003', 'Product Owner');
INSERT INTO sprintMembers VALUES (7,1,'PROJ0003', 'Scrum Master');
INSERT INTO sprintMembers VALUES (7,2,'PROJ0003', 'Scrum Master');
INSERT INTO sprintMembers VALUES (6,1,'PROJ0003', 'Team Member');
INSERT INTO sprintMembers VALUES (6,2,'PROJ0003', 'Team Member');
INSERT INTO sprintMembers VALUES (8,1,'PROJ0004', 'Project Manager');
INSERT INTO sprintMembers VALUES (8,2,'PROJ0004', 'Project Manager');
INSERT INTO sprintMembers VALUES (8,3,'PROJ0004', 'Project Manager');
INSERT INTO sprintMembers VALUES (9,1,'PROJ0004', 'Product Owner');
INSERT INTO sprintMembers VALUES (9,2,'PROJ0004', 'Product Owner');
INSERT INTO sprintMembers VALUES (9,3,'PROJ0004', 'Product Owner');
INSERT INTO sprintMembers VALUES (10,1,'PROJ0004', 'Scrum Master');
INSERT INTO sprintMembers VALUES (10,2,'PROJ0004', 'Scrum Master');
INSERT INTO sprintMembers VALUES (10,3,'PROJ0004', 'Scrum Master');
INSERT INTO sprintMembers VALUES (6,1,'PROJ0004', 'Team Member');
INSERT INTO sprintMembers VALUES (6,2,'PROJ0004', 'Team Member');
INSERT INTO sprintMembers VALUES (6,3,'PROJ0004', 'Team Member');
</code>```

答:
If I understand correctly you can aggregate and count distinct userId

```<code>select sprintProjectCode
from sprintMembers
group by sprintProjectCode
having Count(distinct case when memberRole='project manager' then userid end)=1
</code>```

Result:

```<code>PROJ0001
PROJ0003
PROJ0004
</code>```

Edit

Another approach applying to all member role values

```<code>with groups as (
    select sprintProjectCode, Count(*) cnt
    from sprintMembers
    group by sprintProjectCode, userid, memberrole
)
select sprintProjectCode
from groups
group by sprintProjectCode
having Min(cnt) = Max(cnt)
</code>```

Title: Solving a Query on SQLDeveloper

Body:
need some help on solving this query.
I want to get projects that had no change in their team (i.e. because project0002 has two different project managers it must not appear on the result of the query)

Can you help me ?

CREATE TABLE sprintMembers (
  userID                 NUMBER(10)    NOT NULL,
  sprintNumber           NUMBER(10)    NOT NULL,
  sprintProjectCode      VARCHAR(255) NOT NULL,
  memberRole                   VARCHAR(255) NOT NULL,

  PRIMARY KEY (userID, sprintNumber, sprintProjectCode));

INSERT INTO sprintMembers VALUES (4,1,'PROJ0001', 'Project Manager');
INSERT INTO sprintMembers VALUES (5,1,'PROJ0001', 'Product Owner');
INSERT INTO sprintMembers VALUES (6,1,'PROJ0001', 'Scrum Master');
INSERT INTO sprintMembers VALUES (4,1,'PROJ0002', 'Project Manager');
INSERT INTO sprintMembers VALUES (3,2,'PROJ0002', 'Project Manager');
INSERT INTO sprintMembers VALUES (4,3,'PROJ0002', 'Project Manager');
INSERT INTO sprintMembers VALUES (5,1,'PROJ0002', 'Product Owner');
INSERT INTO sprintMembers VALUES (5,2,'PROJ0002', 'Product Owner');
INSERT INTO sprintMembers VALUES (7,1,'PROJ0002', 'Team Member');
INSERT INTO sprintMembers VALUES (7,2,'PROJ0002', 'Team Member');
INSERT INTO sprintMembers VALUES (4,1,'PROJ0003', 'Project Manager');
INSERT INTO sprintMembers VALUES (4,2,'PROJ0003', 'Project Manager');
INSERT INTO sprintMembers VALUES (5,1,'PROJ0003', 'Product Owner');
INSERT INTO sprintMembers VALUES (5,2,'PROJ0003', 'Product Owner');
INSERT INTO sprintMembers VALUES (7,1,'PROJ0003', 'Scrum Master');
INSERT INTO sprintMembers VALUES (7,2,'PROJ0003', 'Scrum Master');
INSERT INTO sprintMembers VALUES (6,1,'PROJ0003', 'Team Member');
INSERT INTO sprintMembers VALUES (6,2,'PROJ0003', 'Team Member');
INSERT INTO sprintMembers VALUES (8,1,'PROJ0004', 'Project Manager');
INSERT INTO sprintMembers VALUES (8,2,'PROJ0004', 'Project Manager');
INSERT INTO sprintMembers VALUES (8,3,'PROJ0004', 'Project Manager');
INSERT INTO sprintMembers VALUES (9,1,'PROJ0004', 'Product Owner');
INSERT INTO sprintMembers VALUES (9,2,'PROJ0004', 'Product Owner');
INSERT INTO sprintMembers VALUES (9,3,'PROJ0004', 'Product Owner');
INSERT INTO sprintMembers VALUES (10,1,'PROJ0004', 'Scrum Master');
INSERT INTO sprintMembers VALUES (10,2,'PROJ0004', 'Scrum Master');
INSERT INTO sprintMembers VALUES (10,3,'PROJ0004', 'Scrum Master');
INSERT INTO sprintMembers VALUES (6,1,'PROJ0004', 'Team Member');
INSERT INTO sprintMembers VALUES (6,2,'PROJ0004', 'Team Member');
INSERT INTO sprintMembers VALUES (6,3,'PROJ0004', 'Team Member');

Body:
If I understand correctly you can aggregate and count distinct userId

select sprintProjectCode
from sprintMembers
group by sprintProjectCode
having Count(distinct case when memberRole='project manager' then userid end)=1

Result:

PROJ0001
PROJ0003
PROJ0004

Edit

Another approach applying to all member role values

with groups as (
    select sprintProjectCode, Count(*) cnt
    from sprintMembers
    group by sprintProjectCode, userid, memberrole
)
select sprintProjectCode
from groups
group by sprintProjectCode
having Min(cnt) = Max(cnt)


问:
Swift 3: Animate color fill of arc added to UIBezierPath
I wish to animate the color fill of a section of a pie chart. I create the pie chart by creating a UIBezierPath() for each piece of the pie and then use the addArc method to specify the size/constraints of the arc. To animate the pie chart segment, I want the color fill of the arc to animate from the center of the circle to the radius end. However, I am having trouble. I heard the strokeEnd keyPath animated from 0 to 1 should work, but there is no animation happening on the arcs (the arcs are just appearing at app launch).

```<code>let rad = 2 * Double.pi
let pieCenter: CGPoint = CGPoint(x: frame.width / 2, y: frame.height / 2)
var start: Double = 0
for i in 0...data.count - 1 {
    let size: Double = Double(data[i])! / 100 // the percentege of the circle that the given arc will take
    let end: Double = start + (size * rad)

    let path = UIBezierPath()
    path.move(to: pieCenter)
    path.addArc(withCenter: pieCenter, radius: frame.width / 3, startAngle: CGFloat(start), endAngle: CGFloat(end), clockwise: true)

    start += size * rad

    let lineLayer = CAShapeLayer()
    lineLayer.bounds = self.bounds
    lineLayer.position = self.layer.position
    lineLayer.path = path.cgPath
    lineLayer.strokeColor = UIColor.white.cgColor
    lineLayer.fillColor = colors[i]
    lineLayer.lineWidth = 0

    self.layer.addSublayer(lineLayer)

    let animation = CABasicAnimation(keyPath: "strokeEnd")
    animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
    animation.fillMode = kCAFillModeForwards
    animation.fromValue = pieCenter
    animation.toValue = frame.width / 3 // radius
    animation.duration = 2.5

    lineLayer.add(animation, forKey: nil)
}
</code>```

I've seen a solution to a similar problem here, but it does not work for the individual arcs.

答:
I may be very late to the party. But if anyone are looking for smooth circle Pie chart animation try this:-

In your ViewController class use below

```<code>class YourViewController: UIViewController {
@IBOutlet weak var myView: UIView!
let chartView = PieChartView()
    override func viewDidLoad() {
        super.viewDidLoad()

        myView.addSubview(chartView)
        chartView.translatesAutoresizingMaskIntoConstraints = false
        chartView.leftAnchor.constraint(equalTo: myView.leftAnchor).isActive = true
        chartView.rightAnchor.constraint(equalTo: myView.rightAnchor).isActive = true
        chartView.topAnchor.constraint(equalTo: myView.topAnchor).isActive = true
        chartView.bottomAnchor.constraint(equalTo: myView.bottomAnchor).isActive = true
        // Do any additional setup after loading the view.
    }

override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        let segments = [Segment(value: 70, color: .systemBlue), Segment(value: 40, color: .systemCyan), Segment(value: 5, color: .systemTeal), Segment(value: 4, color: .systemMint), Segment(value: 5, color: .systemPurple)]

        chartView.segments = segments
    }
}
</code>```

Create below PieChartView class which will animate pieChart as well

```<code>class PieChartView: UIView {

    /// An array of structs representing the segments of the pie chart
    var pieSliceLayer = CAShapeLayer()
    var count = 0
    var startAngle = -CGFloat.pi * 0.5
    var segments = [Segment]() {
        didSet {
            setNeedsDisplay() // re-draw view when the values get set
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        isOpaque = false // when overriding drawRect, you must specify this to maintain transparency.
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func draw(_ rect: CGRect) {
        addSlices()
      }

    func addSlices() {
        guard count < segments.count else {return}
        let radius = min(bounds.width, bounds.height) / 2.0 - 20
        let center: CGPoint = CGPoint(x: bounds.midX, y: bounds.midY)
        let valueCount = segments.reduce(0, {$0 + $1.value})
        for value in segments {
            let pieSliceLayer = CAShapeLayer()
            pieSliceLayer.strokeColor = value.color.cgColor
            pieSliceLayer.fillColor = UIColor.clear.cgColor
            pieSliceLayer.lineWidth = radius
            layer.addSublayer(pieSliceLayer)
            let endAngle = CGFloat(value.value) / valueCount * CGFloat.pi * 2.0 + startAngle
            pieSliceLayer.path = UIBezierPath(arcCenter: center, radius: radius/2, startAngle: startAngle, endAngle: endAngle, clockwise: true).cgPath
            startAngle = endAngle
        }
        pieSliceLayer.strokeColor = UIColor.white.cgColor
        pieSliceLayer.fillColor = UIColor.clear.cgColor
        pieSliceLayer.lineWidth = radius
        let startAngle: CGFloat = 3 * .pi / 2
        let endAngle: CGFloat =  -3 * .pi / 2
        pieSliceLayer.path = UIBezierPath(arcCenter: center, radius: radius/2, startAngle: startAngle, endAngle: endAngle, clockwise: false).cgPath
        pieSliceLayer.strokeEnd = 1
        layer.addSublayer(pieSliceLayer)
        startCircleAnimation()
    }

    private func startCircleAnimation() {
        pieSliceLayer.strokeEnd = 0
        let animation = CABasicAnimation(keyPath: "strokeEnd")
        animation.fromValue = 1
        animation.toValue = 0
        animation.duration = 1.0
        animation.timingFunction = CAMediaTimingFunction(controlPoints: 0.42, 0.00, 0.09, 1.00)
        pieSliceLayer.add(animation, forKey: nil)
    }
}
</code>```

Body:
I wish to animate the color fill of a section of a pie chart. I create the pie chart by creating a UIBezierPath() for each piece of the pie and then use the addArc method to specify the size/constraints of the arc. To animate the pie chart segment, I want the color fill of the arc to animate from the center of the circle to the radius end. However, I am having trouble. I heard the strokeEnd keyPath animated from 0 to 1 should work, but there is no animation happening on the arcs (the arcs are just appearing at app launch).

let rad = 2 * Double.pi
let pieCenter: CGPoint = CGPoint(x: frame.width / 2, y: frame.height / 2)
var start: Double = 0
for i in 0...data.count - 1 {
    let size: Double = Double(data[i])! / 100 // the percentege of the circle that the given arc will take
    let end: Double = start + (size * rad)

    let path = UIBezierPath()
    path.move(to: pieCenter)
    path.addArc(withCenter: pieCenter, radius: frame.width / 3, startAngle: CGFloat(start), endAngle: CGFloat(end), clockwise: true)

    start += size * rad

    let lineLayer = CAShapeLayer()
    lineLayer.bounds = self.bounds
    lineLayer.position = self.layer.position
    lineLayer.path = path.cgPath
    lineLayer.strokeColor = UIColor.white.cgColor
    lineLayer.fillColor = colors[i]
    lineLayer.lineWidth = 0

    self.layer.addSublayer(lineLayer)

    let animation = CABasicAnimation(keyPath: "strokeEnd")
    animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
    animation.fillMode = kCAFillModeForwards
    animation.fromValue = pieCenter
    animation.toValue = frame.width / 3 // radius
    animation.duration = 2.5

    lineLayer.add(animation, forKey: nil)
}

I've seen a solution to a similar problem here, but it does not work for the individual arcs.

Body:
I may be very late to the party. But if anyone are looking for smooth circle Pie chart animation try this:-

In your ViewController class use below

class YourViewController: UIViewController {
@IBOutlet weak var myView: UIView!
let chartView = PieChartView()
    override func viewDidLoad() {
        super.viewDidLoad()

        myView.addSubview(chartView)
        chartView.translatesAutoresizingMaskIntoConstraints = false
        chartView.leftAnchor.constraint(equalTo: myView.leftAnchor).isActive = true
        chartView.rightAnchor.constraint(equalTo: myView.rightAnchor).isActive = true
        chartView.topAnchor.constraint(equalTo: myView.topAnchor).isActive = true
        chartView.bottomAnchor.constraint(equalTo: myView.bottomAnchor).isActive = true
        // Do any additional setup after loading the view.
    }

override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        let segments = [Segment(value: 70, color: .systemBlue), Segment(value: 40, color: .systemCyan), Segment(value: 5, color: .systemTeal), Segment(value: 4, color: .systemMint), Segment(value: 5, color: .systemPurple)]

        chartView.segments = segments
    }
}

Create below PieChartView class which will animate pieChart as well

class PieChartView: UIView {

    /// An array of structs representing the segments of the pie chart
    var pieSliceLayer = CAShapeLayer()
    var count = 0
    var startAngle = -CGFloat.pi * 0.5
    var segments = [Segment]() {
        didSet {
            setNeedsDisplay() // re-draw view when the values get set
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        isOpaque = false // when overriding drawRect, you must specify this to maintain transparency.
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func draw(_ rect: CGRect) {
        addSlices()
      }

    func addSlices() {
        guard count < segments.count else {return}
        let radius = min(bounds.width, bounds.height) / 2.0 - 20
        let center: CGPoint = CGPoint(x: bounds.midX, y: bounds.midY)
        let valueCount = segments.reduce(0, {$0 + $1.value})
        for value in segments {
            let pieSliceLayer = CAShapeLayer()
            pieSliceLayer.strokeColor = value.color.cgColor
            pieSliceLayer.fillColor = UIColor.clear.cgColor
            pieSliceLayer.lineWidth = radius
            layer.addSublayer(pieSliceLayer)
            let endAngle = CGFloat(value.value) / valueCount * CGFloat.pi * 2.0 + startAngle
            pieSliceLayer.path = UIBezierPath(arcCenter: center, radius: radius/2, startAngle: startAngle, endAngle: endAngle, clockwise: true).cgPath
            startAngle = endAngle
        }
        pieSliceLayer.strokeColor = UIColor.white.cgColor
        pieSliceLayer.fillColor = UIColor.clear.cgColor
        pieSliceLayer.lineWidth = radius
        let startAngle: CGFloat = 3 * .pi / 2
        let endAngle: CGFloat =  -3 * .pi / 2
        pieSliceLayer.path = UIBezierPath(arcCenter: center, radius: radius/2, startAngle: startAngle, endAngle: endAngle, clockwise: false).cgPath
        pieSliceLayer.strokeEnd = 1
        layer.addSublayer(pieSliceLayer)
        startCircleAnimation()
    }

    private func startCircleAnimation() {
        pieSliceLayer.strokeEnd = 0
        let animation = CABasicAnimation(keyPath: "strokeEnd")
        animation.fromValue = 1
        animation.toValue = 0
        animation.duration = 1.0
        animation.timingFunction = CAMediaTimingFunction(controlPoints: 0.42, 0.00, 0.09, 1.00)
        pieSliceLayer.add(animation, forKey: nil)
    }
}


问:
How to display Current & Previous Month Name along with Total of Current Revenue per month & Total of Previous Revenue per month through SQL Query?
I have the following tables:

[Revenue Raw Data] consisting of Month_ID,Revenue

and it has the following sample data:

```<code>Month_ID
128
124
123
122
126
120

Revenue
1768077
1767617
1734230
1687976
1686309
</code>```

yt_Calendar_lookup consisting of Month_ID,Month_No,Month_Name

and it has the following sample data:

```<code>Month_No
1
2
3
4
5
6
7
8
9
10
11
12

Month_ID
120
121
122
123
124
125
126
127
128
129
130
131

Month_Name
January
February
March
April
May
June
July
August
September
October
November
December
</code>```

What I am trying to achieve is to display the results for the following 5 columns:

Display Current Month as the first column from the table yt_Calendar_lookup

Display Total Revenue for the Current Month as the second column from the table [Revenue Raw Data]

Display Previous Month as the third column from the table yt_Calendar_lookup

Display Total Revenue for the Previous Month as the fourth column from the table [Revenue Raw Data]

Display Revenue difference between Current Month and Previous Month as the fifth column from the table [Revenue Raw Data]

Initially, this is what I have tried:

```<code>SELECT
    A.[Total Revenue for Current Month]
    , B.[Total Revenue for Previous Month]
    , A.[Total Revenue for current Month] - B.[Total Revenue for previous Month] AS 'Revenue Difference between current Month and previous Month'
FROM (
    SELECT SUM(CAST(Revenue AS BIGINT)) AS 'Total Revenue for Current Month'
    FROM [Revenue Raw Data]
    WHERE Month_ID IN (SELECT MAX(Month_ID) FROM [Revenue Raw Data])
) A, (
    SELECT SUM(CAST(Revenue AS BIGINT)) AS 'Total Revenue for Previous Month'
    FROM [Revenue Raw Data]
    WHERE Month_ID IN (SELECT MAX(Month_ID) - 1 FROM [Revenue Raw Data])
) B
</code>```

With the query above, I could successfully display the following 3 columns:

Total Revenue for Current Month, Total Revenue for Previous Month, Revenue Difference between Current Month and Previous Month

And this is the result I have received:

```<code>Total Revenue for Current Month Total Revenue for Previous Month
21221564                        19973825

Revenue Difference between current Month and previous Month
1247739
</code>```

With the next query, I was trying to display the following 5 columns:

Current Month, Total Revenue for Current Month, Previous Month, Total Revenue for Previous Month, Revenue Difference between Current Month and Previous Month

This is what I have tried:

```<code>    SELECT A.[Current Month],
A.[Total Revenue for Current Month],
    B.[Previous Month],
B.[Total Revenue for Previous Month],
    A.[Total Revenue for current Month] - B.[Total Revenue for previous Month]
    AS 'Revenue Difference between current Month and previous Month'
    FROM
    (SELECT Month_Name
AS 'Current Month',
    SUM(CAST(Revenue AS BIGINT))
    AS 'Total Revenue for Current Month'
    FROM [Revenue Raw Data], yt_Calendar_lookup
    WHERE [Revenue Raw Data].Month_ID = yt_Calendar_lookup.Month_ID
    AND [Revenue Raw Data].Month_ID IN
    (SELECT MAX(Month_ID) FROM [Revenue Raw Data])
    ) A,
    (SELECT Month_Name
AS 'Previous Month',
    SUM(CAST(Revenue AS BIGINT))
    AS 'Total Revenue for Previous Month'
    FROM [Revenue Raw Data], yt_Calendar_lookup
    WHERE [Revenue Raw Data].Month_ID = yt_Calendar_lookup.Month_ID
    AND [Revenue Raw Data].Month_ID IN
(SELECT MAX(Month_ID) - 1 FROM [Revenue Raw Data])
    ) B
</code>```

I received the following error message:

Column 'yt_Calendar_lookup.Month_Name' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

I even tried by adding GROUP BY A.Month_Name,B.Month_Name, and even after that I am receiving the same error message.

I am still trying to figure out on where I am making the mistake for this particular query.

Solution for this particular issue will be highly appreciated.

答:
You just had to add GROUP BY Month_Name to the 2 sub-queries.

```<code>SELECT
  C.[Current Month],
  C.[Total Revenue for Current Month],
  P.[Previous Month],
  P.[Total Revenue for Previous Month],
  C.[Total Revenue for current Month] - P.[Total Revenue for previous Month]
    AS [Revenue Difference between current Month and previous Month]
 FROM
 (
   SELECT Month_Name AS [Current Month],
    SUM(CAST(Revenue AS BIGINT)) AS [Total Revenue for Current Month]
   FROM [Revenue Raw Data], yt_Calendar_lookup
   WHERE [Revenue Raw Data].Month_ID = yt_Calendar_lookup.Month_ID
     AND [Revenue Raw Data].Month_ID IN (
           SELECT MAX(Month_ID)
           FROM [Revenue Raw Data])
   GROUP BY Month_Name
) C
CROSS JOIN
(
  SELECT Month_Name AS [Previous Month],
   SUM(CAST(Revenue AS BIGINT)) AS [Total Revenue for Previous Month]
  FROM [Revenue Raw Data], yt_Calendar_lookup
  WHERE [Revenue Raw Data].Month_ID = yt_Calendar_lookup.Month_ID
    AND [Revenue Raw Data].Month_ID IN (
          SELECT MAX(Month_ID) - 1
          FROM [Revenue Raw Data])
  GROUP BY Month_Name
) P;
</code>```

But this can also be calculated via conditional aggregation.

```<code>WITH CTE_MONTHS AS (
  SELECT TOP 2
    Month_ID
  , ROW_NUMBER() OVER (ORDER BY Month_ID DESC) AS rn
  FROM [Revenue Raw Data]
  GROUP BY Month_ID
  ORDER BY Month_ID DESC
)
SELECT
  Month1 AS [Current Month]
, Revenue1 AS [Total Revenue for Current Month]
, Month2 AS [Previous Month]
, Revenue2 AS [Total Revenue for Previous Month]
, Revenue1 - Revenue2 AS [Revenue Difference between current Month and previous Month]
FROM
(
SELECT
  MAX(CASE WHEN m.rn = 1 THEN c.Month_Name END) AS Month1
, MAX(CASE WHEN m.rn = 2 THEN c.Month_Name END) AS Month2
, SUM(CASE WHEN m.rn = 1 THEN CAST(r.Revenue AS BIGINT) END) AS Revenue1
, SUM(CASE WHEN m.rn = 2 THEN CAST(r.Revenue AS BIGINT) END) AS Revenue2
FROM [Revenue Raw Data] r
JOIN CTE_MONTHS m ON m.Month_ID = r.Month_ID
LEFT JOIN yt_Calendar_lookup c ON c.Month_ID = r.Month_ID
) q;
</code>```

Body:
I have the following tables:

[Revenue Raw Data] consisting of Month_ID,Revenue

and it has the following sample data:

Month_ID
128
124
123
122
126
120

Revenue
1768077
1767617
1734230
1687976
1686309

yt_Calendar_lookup consisting of Month_ID,Month_No,Month_Name

and it has the following sample data:

Month_No
1
2
3
4
5
6
7
8
9
10
11
12

Month_ID
120
121
122
123
124
125
126
127
128
129
130
131

Month_Name
January
February
March
April
May
June
July
August
September
October
November
December

What I am trying to achieve is to display the results for the following 5 columns:

Display Current Month as the first column from the table yt_Calendar_lookup

Display Total Revenue for the Current Month as the second column from the table [Revenue Raw Data]

Display Previous Month as the third column from the table yt_Calendar_lookup

Display Total Revenue for the Previous Month as the fourth column from the table [Revenue Raw Data]

Display Revenue difference between Current Month and Previous Month as the fifth column from the table [Revenue Raw Data]

Initially, this is what I have tried:

SELECT
    A.[Total Revenue for Current Month]
    , B.[Total Revenue for Previous Month]
    , A.[Total Revenue for current Month] - B.[Total Revenue for previous Month] AS 'Revenue Difference between current Month and previous Month'
FROM (
    SELECT SUM(CAST(Revenue AS BIGINT)) AS 'Total Revenue for Current Month'
    FROM [Revenue Raw Data]
    WHERE Month_ID IN (SELECT MAX(Month_ID) FROM [Revenue Raw Data])
) A, (
    SELECT SUM(CAST(Revenue AS BIGINT)) AS 'Total Revenue for Previous Month'
    FROM [Revenue Raw Data]
    WHERE Month_ID IN (SELECT MAX(Month_ID) - 1 FROM [Revenue Raw Data])
) B

With the query above, I could successfully display the following 3 columns:

Total Revenue for Current Month, Total Revenue for Previous Month, Revenue Difference between Current Month and Previous Month

And this is the result I have received:

Total Revenue for Current Month Total Revenue for Previous Month
21221564                        19973825

Revenue Difference between current Month and previous Month
1247739

With the next query, I was trying to display the following 5 columns:

Current Month, Total Revenue for Current Month, Previous Month, Total Revenue for Previous Month, Revenue Difference between Current Month and Previous Month

This is what I have tried:

    SELECT A.[Current Month],
A.[Total Revenue for Current Month],
    B.[Previous Month],
B.[Total Revenue for Previous Month],
    A.[Total Revenue for current Month] - B.[Total Revenue for previous Month]
    AS 'Revenue Difference between current Month and previous Month'
    FROM
    (SELECT Month_Name
AS 'Current Month',
    SUM(CAST(Revenue AS BIGINT))
    AS 'Total Revenue for Current Month'
    FROM [Revenue Raw Data], yt_Calendar_lookup
    WHERE [Revenue Raw Data].Month_ID = yt_Calendar_lookup.Month_ID
    AND [Revenue Raw Data].Month_ID IN
    (SELECT MAX(Month_ID) FROM [Revenue Raw Data])
    ) A,
    (SELECT Month_Name
AS 'Previous Month',
    SUM(CAST(Revenue AS BIGINT))
    AS 'Total Revenue for Previous Month'
    FROM [Revenue Raw Data], yt_Calendar_lookup
    WHERE [Revenue Raw Data].Month_ID = yt_Calendar_lookup.Month_ID
    AND [Revenue Raw Data].Month_ID IN
(SELECT MAX(Month_ID) - 1 FROM [Revenue Raw Data])
    ) B

I received the following error message:

Column 'yt_Calendar_lookup.Month_Name' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

I even tried by adding GROUP BY A.Month_Name,B.Month_Name, and even after that I am receiving the same error message.

I am still trying to figure out on where I am making the mistake for this particular query.

Solution for this particular issue will be highly appreciated.

Body:
You just had to add GROUP BY Month_Name to the 2 sub-queries.

SELECT
  C.[Current Month],
  C.[Total Revenue for Current Month],
  P.[Previous Month],
  P.[Total Revenue for Previous Month],
  C.[Total Revenue for current Month] - P.[Total Revenue for previous Month]
    AS [Revenue Difference between current Month and previous Month]
 FROM
 (
   SELECT Month_Name AS [Current Month],
    SUM(CAST(Revenue AS BIGINT)) AS [Total Revenue for Current Month]
   FROM [Revenue Raw Data], yt_Calendar_lookup
   WHERE [Revenue Raw Data].Month_ID = yt_Calendar_lookup.Month_ID
     AND [Revenue Raw Data].Month_ID IN (
           SELECT MAX(Month_ID)
           FROM [Revenue Raw Data])
   GROUP BY Month_Name
) C
CROSS JOIN
(
  SELECT Month_Name AS [Previous Month],
   SUM(CAST(Revenue AS BIGINT)) AS [Total Revenue for Previous Month]
  FROM [Revenue Raw Data], yt_Calendar_lookup
  WHERE [Revenue Raw Data].Month_ID = yt_Calendar_lookup.Month_ID
    AND [Revenue Raw Data].Month_ID IN (
          SELECT MAX(Month_ID) - 1
          FROM [Revenue Raw Data])
  GROUP BY Month_Name
) P;

But this can also be calculated via conditional aggregation.

WITH CTE_MONTHS AS (
  SELECT TOP 2
    Month_ID
  , ROW_NUMBER() OVER (ORDER BY Month_ID DESC) AS rn
  FROM [Revenue Raw Data]
  GROUP BY Month_ID
  ORDER BY Month_ID DESC
)
SELECT
  Month1 AS [Current Month]
, Revenue1 AS [Total Revenue for Current Month]
, Month2 AS [Previous Month]
, Revenue2 AS [Total Revenue for Previous Month]
, Revenue1 - Revenue2 AS [Revenue Difference between current Month and previous Month]
FROM
(
SELECT
  MAX(CASE WHEN m.rn = 1 THEN c.Month_Name END) AS Month1
, MAX(CASE WHEN m.rn = 2 THEN c.Month_Name END) AS Month2
, SUM(CASE WHEN m.rn = 1 THEN CAST(r.Revenue AS BIGINT) END) AS Revenue1
, SUM(CASE WHEN m.rn = 2 THEN CAST(r.Revenue AS BIGINT) END) AS Revenue2
FROM [Revenue Raw Data] r
JOIN CTE_MONTHS m ON m.Month_ID = r.Month_ID
LEFT JOIN yt_Calendar_lookup c ON c.Month_ID = r.Month_ID
) q;


问:
Dropdown with custom input in material ui
Is it possible to have a dropdown field but being able to add a value other than the ones suggested by the dropdown?

Something like the autocomplete field with showAllItems set to true and without the auto-complete functionality

Edit:

What I want to achieve is just submit the form with the custom value or the user selection from the dropdown (according to the user's choice)

答:
You're on the right track with mui autocomplete. Try using the freeSolo option

https://mui.com/components/autocomplete/#free-solo