问:
Input shape for 3d-CNN in python
I want to enter 8 images at the same time to the same CNN structure using conv3d. my CNN model is as following:

```<code>def build(sample, frame, height, width, channels,  classes):
    model = Sequential()
    inputShape = (sample, frame, height, width, channels)
    chanDim = -1

    if K.image_data_format() == "channels_first":
        inputShape = (sample, frame, channels, height, width)
        chanDim = 1

    model.add(Conv3D(32, (3, 3, 3), padding="same", input_shape=inputShape))
    model.add(Activation("relu"))
    model.add(BatchNormalization(axis=chanDim))
    model.add(MaxPooling3D(pool_size=(2, 2, 2), padding="same", data_format="channels_last"))
    model.add(Dropout(0.25))

    model.add(Conv3D(64, (3, 3, 3), padding="same"))
    model.add(Activation("relu"))
    model.add(BatchNormalization(axis=chanDim))
    model.add(MaxPooling3D(pool_size=(2, 2, 2), padding="same", data_format="channels_last"))
    model.add(Dropout(0.25))
    model.add(Flatten())
    model.add(Dense(128))    #(Dense(1024))
    model.add(Activation("relu"))
    model.add(BatchNormalization())
    model.add(Dropout(0.5))

    # softmax classifier
    model.add(Dense(classes))
    model.add(Activation("softmax")
</code>```

The training of model is as follow:

```<code>IMAGE_DIMS = (57, 8, 60, 60, 3) # since I have 460 images so 57 sample with 8 image each
data = np.array(data, dtype="float") / 255.0
labels = np.array(labels)
# binarize the labels
lb = LabelBinarizer()
labels = lb.fit_transform(labels)
# note: data is a list of all dataset images
(trainX, testX, trainY, testY) train_test_split(data, labels, test_size=0.2, random_state=42)
aug = ImageDataGenerator(rotation_range=25, width_shift_range=0.1, height_shift_range=0.1, shear_range=0.2, zoom_range=0.2, horizontal_flip=True, fill_mode="nearest")

# initialize the model
model = CNN_Network.build(sample= IMAGE_DIMS[0], frame=IMAGE_DIMS[1],
                      height = IMAGE_DIMS[2], width=IMAGE_DIMS[3],
                      channels=IMAGE_DIMS[4], classes=len(lb.classes_))

opt = Adam(lr=INIT_LR, decay=INIT_LR / EPOCHS)
model.compile(loss="categorical_crossentropy", optimizer= opt, metrics=["accuracy"])

# train the network
model.fit_generator(
aug.flow(trainX, trainY, batch_size=BS),
validation_data=(testX, testY),
steps_per_epoch=len(trainX) // BS,
epochs=EPOCHS, verbose=1)
</code>```

I have confused with the input_shape, I know Conv3D require 5D input, the input is 4D with batch added from keras, but I have the following error:

```<code>ValueError: Error when checking input: expected conv3d_1_input to have 5 dimensions, but got array with shape (92, 60, 60, 3)
</code>```

Can anyone please help me what can I do? what is the 92 resulted, I determine input_shape with (57, 8, 60, 60, 3). And what is my input_shape should become to get 8 colored images input to the same model at the same time.

答:
In Keras Python 3, the input shape can be as follows:

input_shape = (8, 64, 64, 1)
```

Where:

Value 1 (8) is the number of frames

Value 2 (64) is the width

Value 3 (64) is the height

Value 4 (1) is the number of channels

Title: Input shape for 3d-CNN in python

Body:
I want to enter 8 images at the same time to the same CNN structure using conv3d. my CNN model is as following:

def build(sample, frame, height, width, channels,  classes):
    model = Sequential()
    inputShape = (sample, frame, height, width, channels)
    chanDim = -1

    if K.image_data_format() == "channels_first":
        inputShape = (sample, frame, channels, height, width)
        chanDim = 1

    model.add(Conv3D(32, (3, 3, 3), padding="same", input_shape=inputShape))
    model.add(Activation("relu"))
    model.add(BatchNormalization(axis=chanDim))
    model.add(MaxPooling3D(pool_size=(2, 2, 2), padding="same", data_format="channels_last"))
    model.add(Dropout(0.25))

    model.add(Conv3D(64, (3, 3, 3), padding="same"))
    model.add(Activation("relu"))
    model.add(BatchNormalization(axis=chanDim))
    model.add(MaxPooling3D(pool_size=(2, 2, 2), padding="same", data_format="channels_last"))
    model.add(Dropout(0.25))
    model.add(Flatten())
    model.add(Dense(128))    #(Dense(1024))
    model.add(Activation("relu"))
    model.add(BatchNormalization())
    model.add(Dropout(0.5))

    # softmax classifier
    model.add(Dense(classes))
    model.add(Activation("softmax")

The training of model is as follow:

IMAGE_DIMS = (57, 8, 60, 60, 3) # since I have 460 images so 57 sample with 8 image each
data = np.array(data, dtype="float") / 255.0
labels = np.array(labels)
# binarize the labels
lb = LabelBinarizer()
labels = lb.fit_transform(labels)
# note: data is a list of all dataset images
(trainX, testX, trainY, testY) train_test_split(data, labels, test_size=0.2, random_state=42)
aug = ImageDataGenerator(rotation_range=25, width_shift_range=0.1, height_shift_range=0.1, shear_range=0.2, zoom_range=0.2, horizontal_flip=True, fill_mode="nearest")

# initialize the model
model = CNN_Network.build(sample= IMAGE_DIMS[0], frame=IMAGE_DIMS[1],
                      height = IMAGE_DIMS[2], width=IMAGE_DIMS[3],
                      channels=IMAGE_DIMS[4], classes=len(lb.classes_))

opt = Adam(lr=INIT_LR, decay=INIT_LR / EPOCHS)
model.compile(loss="categorical_crossentropy", optimizer= opt, metrics=["accuracy"])

# train the network
model.fit_generator(
aug.flow(trainX, trainY, batch_size=BS),
validation_data=(testX, testY),
steps_per_epoch=len(trainX) // BS,
epochs=EPOCHS, verbose=1)

I have confused with the input_shape, I know Conv3D require 5D input, the input is 4D with batch added from keras, but I have the following error:

ValueError: Error when checking input: expected conv3d_1_input to have 5 dimensions, but got array with shape (92, 60, 60, 3)

Can anyone please help me what can I do? what is the 92 resulted, I determine input_shape with (57, 8, 60, 60, 3). And what is my input_shape should become to get 8 colored images input to the same model at the same time.

Body:
In Keras Python 3, the input shape can be as follows:

input_shape = (8, 64, 64, 1)

Where:

Value 1 (8) is the number of frames

Value 2 (64) is the width

Value 3 (64) is the height

Value 4 (1) is the number of channels


来源: stackexchange

问:
How to disable a node in a treelist in Ext JS 7 classic
Hi can anyone please tell me how i can disable a node in a treelist. I am using Ext JS 7 classic.

I tried a config disabled: true on the treelistitem something like the below code. this config is there on the treelistitem in Ext JS 7 classic docs. But it does not work. Can anyone help please.

```<code>{
     text: eachRevision.name,
     iconCls: 'x-fa fa-folder',
     leaf: false,
     disabled: true
}
</code>```

答: Try using 'visible' instead of disabled. Set 'visible' to false on record in the node store. </p>

ContentLicense: CC BY-SA 4.0

Body:
Hi can anyone please tell me how i can disable a node in a treelist. I am using Ext JS 7 classic.

I tried a config disabled: true on the treelistitem something like the below code. this config is there on the treelistitem in Ext JS 7 classic docs. But it does not work. Can anyone help please.

{
     text: eachRevision.name,
     iconCls: 'x-fa fa-folder',
     leaf: false,
     disabled: true
}


问:
Shiny reactive input add and delete
I'm trying to write a shiny app where I produce a list and add and delete some elements.

I have a module to add somethind to my list.

```<code>find_inputUI <- function(id){
  ns <- NS(id)
  tagList(
  sliderInput(ns("first"), "Choose a number:", min=0, max=100, 30),
  radioButtons(ns("second"), "Choose a colour:", choices=c("red", "green", "black")),
  actionButton(ns("press"), "Add to queue"))

}

find_input <- function(input, output, session){
  queue <- list()
 observeEvent(input$press, {
  queue_append <- list(input$first, input$second)
queue <<- append(queue, queue_append )})
 queue_ret <- eventReactive(input$press,{return(list(queue=queue, add=input$press))})

}
</code>```

Then I call it twice and connect the 2 different inputs. Now I want to choose the elements to delete but this doesn't work.

```<code>source('/cloud/project/Queue/find_input.R')
library(shiny)

ui <- fluidPage(
  tagList(tabsetPanel(
    tabPanel("INPUT 1",
             find_inputUI("input1"),
             verbatimTextOutput("test")),
    tabPanel("INPUT 2",
             find_inputUI("input2")
    )
  ),
  actionButton("combine", "Show combined input"),
  verbatimTextOutput("combination"),
  uiOutput("del")
  )
)

# Define server logic required to draw a histogram
server <- function(input, output, session) {

  input_manual1 <- callModule(find_input,"input1")
  input_manual2 <- callModule(find_input, "input2")
  output$test <- renderPrint({input_manual1()$queue})

  appended <- eventReactive(input$combine, {
    return(append(input_manual1()$queue, input_manual2()$queue))
  })

  output$combination <- renderPrint({appended()})

  output$del <- renderUI({
    input$combine
    tagList(checkboxGroupInput("delete", "Choose do delete", seq(1:length(appended()))),
            actionButton("dodelete", "Delete selected"))
  })
  observeEvent(input$dodelete,{
    appended <<- appended()[-input$delete]
  })

}

# Run the application
shinyApp(ui = ui, server = server)
</code>```

Maybe anybody can tell me what's wrong so far?

Thanks in advance!

答:
Below is an app which seems to work but I'm not sure to understand what your app is intended to do.

In general, prefer reactive values (reactiveVal) instaed of using the non-local assignment <<-.

The code appended <<- appended()[-input$delete] is not correct. It does not replace the output of appended() by its originalvalue minus the input$delete index.

```<code>library(shiny)

find_inputUI <- function(id){
  ns <- NS(id)
  tagList(
    sliderInput(ns("first"), "Choose a number:", min=0, max=100, 30),
    radioButtons(ns("second"), "Choose a colour:", choices=c("red", "green", "black")),
    actionButton(ns("press"), "Add to queue"))

}

find_input <- function(input, output, session){

  queue <- reactiveVal(list())

  observeEvent(input$press, {
    queue_append <- list(input$first, input$second)
    queue(append(queue(), queue_append))
  })

  queue_ret <- eventReactive(input$press, {
    list(queue=queue(), add=input$press)
  })

}

ui <- fluidPage(
  tagList(tabsetPanel(
    tabPanel("INPUT 1",
             find_inputUI("input1"),
             verbatimTextOutput("test")),
    tabPanel("INPUT 2",
             find_inputUI("input2")
    )
  ),
  actionButton("combine", "Show combined input"),
  verbatimTextOutput("combination"),
  uiOutput("del")
  )
)

server <- function(input, output, session) {

  input_manual1 <- callModule(find_input,"input1")
  input_manual2 <- callModule(find_input, "input2")
  output$test <- renderPrint({input_manual1()$queue})

  appended <- reactiveVal(list())
  observeEvent(input$combine, {
    appended(append(input_manual1()$queue, input_manual2()$queue))
  })

  output$combination <- renderPrint({appended()})

  output$del <- renderUI({
    input$combine
    tagList(checkboxGroupInput("delete", "Choose do delete", seq_along(appended())),
            actionButton("dodelete", "Delete selected"))
  })

  observeEvent(input$dodelete,{
    appended(appended()[-as.integer(input$delete)])
  })

}

# Run the application
shinyApp(ui = ui, server = server)
</code>```

Title: Shiny reactive input add and delete

Body:
I'm trying to write a shiny app where I produce a list and add and delete some elements.

I have a module to add somethind to my list.

find_inputUI <- function(id){
  ns <- NS(id)
  tagList(
  sliderInput(ns("first"), "Choose a number:", min=0, max=100, 30),
  radioButtons(ns("second"), "Choose a colour:", choices=c("red", "green", "black")),
  actionButton(ns("press"), "Add to queue"))

}

find_input <- function(input, output, session){
  queue <- list()
 observeEvent(input$press, {
  queue_append <- list(input$first, input$second)
queue <<- append(queue, queue_append )})
 queue_ret <- eventReactive(input$press,{return(list(queue=queue, add=input$press))})

}

Then I call it twice and connect the 2 different inputs. Now I want to choose the elements to delete but this doesn't work.

source('/cloud/project/Queue/find_input.R')
library(shiny)

ui <- fluidPage(
  tagList(tabsetPanel(
    tabPanel("INPUT 1",
             find_inputUI("input1"),
             verbatimTextOutput("test")),
    tabPanel("INPUT 2",
             find_inputUI("input2")
    )
  ),
  actionButton("combine", "Show combined input"),
  verbatimTextOutput("combination"),
  uiOutput("del")
  )
)

# Define server logic required to draw a histogram
server <- function(input, output, session) {

  input_manual1 <- callModule(find_input,"input1")
  input_manual2 <- callModule(find_input, "input2")
  output$test <- renderPrint({input_manual1()$queue})

  appended <- eventReactive(input$combine, {
    return(append(input_manual1()$queue, input_manual2()$queue))
  })

  output$combination <- renderPrint({appended()})

  output$del <- renderUI({
    input$combine
    tagList(checkboxGroupInput("delete", "Choose do delete", seq(1:length(appended()))),
            actionButton("dodelete", "Delete selected"))
  })
  observeEvent(input$dodelete,{
    appended <<- appended()[-input$delete]
  })

}

# Run the application
shinyApp(ui = ui, server = server)

Maybe anybody can tell me what's wrong so far?

Thanks in advance!

Body:
Below is an app which seems to work but I'm not sure to understand what your app is intended to do.

In general, prefer reactive values (reactiveVal) instaed of using the non-local assignment <<-.

The code appended <<- appended()[-input$delete] is not correct. It does not replace the output of appended() by its originalvalue minus the input$delete index.

library(shiny)

find_inputUI <- function(id){
  ns <- NS(id)
  tagList(
    sliderInput(ns("first"), "Choose a number:", min=0, max=100, 30),
    radioButtons(ns("second"), "Choose a colour:", choices=c("red", "green", "black")),
    actionButton(ns("press"), "Add to queue"))

}

find_input <- function(input, output, session){

  queue <- reactiveVal(list())

  observeEvent(input$press, {
    queue_append <- list(input$first, input$second)
    queue(append(queue(), queue_append))
  })

  queue_ret <- eventReactive(input$press, {
    list(queue=queue(), add=input$press)
  })

}

ui <- fluidPage(
  tagList(tabsetPanel(
    tabPanel("INPUT 1",
             find_inputUI("input1"),
             verbatimTextOutput("test")),
    tabPanel("INPUT 2",
             find_inputUI("input2")
    )
  ),
  actionButton("combine", "Show combined input"),
  verbatimTextOutput("combination"),
  uiOutput("del")
  )
)

server <- function(input, output, session) {

  input_manual1 <- callModule(find_input,"input1")
  input_manual2 <- callModule(find_input, "input2")
  output$test <- renderPrint({input_manual1()$queue})

  appended <- reactiveVal(list())
  observeEvent(input$combine, {
    appended(append(input_manual1()$queue, input_manual2()$queue))
  })

  output$combination <- renderPrint({appended()})

  output$del <- renderUI({
    input$combine
    tagList(checkboxGroupInput("delete", "Choose do delete", seq_along(appended())),
            actionButton("dodelete", "Delete selected"))
  })

  observeEvent(input$dodelete,{
    appended(appended()[-as.integer(input$delete)])
  })

}

# Run the application
shinyApp(ui = ui, server = server)


问:
How to display a circle avatar image in flutter?
When using the folloing code I would expect a circle avatar image but getting an oval. I tried different parameters like width and height on the Container but that didn't help.</p>

```<code> appBar: AppBar(
        backgroundColor: Colors.white,
        leading: IconButton(
          icon: new Icon(Icons.star_border, color: Colors.black),
          onPressed: () => {},
        ),
        actions: <Widget>[
          Container(
            //height: 25.0,
            // width: 25.0,
            child: CircleAvatar(
              backgroundImage: NetworkImage('https://lh3.googleusercontent.com/a-/AAuE7mChgTiAe-N8ibcM3fB_qvGdl2vQ9jvjYv0iOOjB=s96-c'),
            )
            /*
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              image: DecorationImage(
                  fit: BoxFit.fill,
                  image: NetworkImage(
                      'https://lh3.googleusercontent.com/a-/AAuE7mChgTiAe-N8ibcM3fB_qvGdl2vQ9jvjYv0iOOjB=s96-c')),
            ),*/
          ),
        ],
</code>```

答:
I've had this issue in the past and have found that wrapping the AvatarCircle in a container with 58 width fixes the Circle radius ratio issue, making it a proper circle shape. One pixel more or less may fit your liking. Give this a try:</p>

```<code>appBar: AppBar(
    backgroundColor: Colors.white,
    leading: IconButton(
      icon: new Icon(Icons.star_border, color: Colors.black),
      onPressed: () => {},
    ),
    actions: <Widget>[
      Container(
        width: 58.0,
        child: CircleAvatar(
          backgroundImage: NetworkImage('https://lh3.googleusercontent.com/a-/AAuE7mChgTiAe-N8ibcM3fB_qvGdl2vQ9jvjYv0iOOjB=s96-c'),
        )
      ),
    ],
</code>```

Body:
When using the folloing code I would expect a circle avatar image but getting an oval. I tried different parameters like width and height on the Container but that didn't help.

 appBar: AppBar(
        backgroundColor: Colors.white,
        leading: IconButton(
          icon: new Icon(Icons.star_border, color: Colors.black),
          onPressed: () => {},
        ),
        actions: <Widget>[
          Container(
            //height: 25.0,
            // width: 25.0,
            child: CircleAvatar(
              backgroundImage: NetworkImage('https://lh3.googleusercontent.com/a-/AAuE7mChgTiAe-N8ibcM3fB_qvGdl2vQ9jvjYv0iOOjB=s96-c'),
            )
            /*
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              image: DecorationImage(
                  fit: BoxFit.fill,
                  image: NetworkImage(
                      'https://lh3.googleusercontent.com/a-/AAuE7mChgTiAe-N8ibcM3fB_qvGdl2vQ9jvjYv0iOOjB=s96-c')),
            ),*/
          ),
        ],

Body:
I've had this issue in the past and have found that wrapping the AvatarCircle in a container with 58 width fixes the Circle radius ratio issue, making it a proper circle shape. One pixel more or less may fit your liking. Give this a try:

appBar: AppBar(
    backgroundColor: Colors.white,
    leading: IconButton(
      icon: new Icon(Icons.star_border, color: Colors.black),
      onPressed: () => {},
    ),
    actions: <Widget>[
      Container(
        width: 58.0,
        child: CircleAvatar(
          backgroundImage: NetworkImage('https://lh3.googleusercontent.com/a-/AAuE7mChgTiAe-N8ibcM3fB_qvGdl2vQ9jvjYv0iOOjB=s96-c'),
        )
      ),
    ],


问:
How correctly filter column with data separated by a comma?
Let's say I have such DataFrame.

```<code>+-----------+
|amount     |
+-----------+
|100,200,300|
|73         |
|56,89      |
+-----------+
</code>```

Also, I have an array with numbers: var array = Array(200, 73).

I want to filter this DataFrame by the array and take such a result:

```<code>+-----------+
|amount     |
+-----------+
|100,200,300|
|73         |
+-----------+
</code>```

I used such code but it doesn't work the way I thought it would

```<code>df.filter(col("amount").isin(array: _*))
</code>```

My next code returns such a result:

```<code>+-----------+
|amount     |
+-----------+
|73         |
+-----------+
</code>```

What's wrong I did?

答:
If you can not use Spark 2.4, here is another way using array_contains and split functions.

First split the column amount to get array column:

```<code>val df2 = df.withColumn("amount_array", split($"amount", ","))
</code>```

Then filter using this filter expression:

```<code>val filterExpr = array.map(v => array_contains($"amount_array", v)).reduce(_ or _)

df2.filter(filterExpr).drop("amount_array").show()

//+-----------+
//|     amount|
//+-----------+
//|100,200,300|
//|         73|
//+-----------+
</code>```

Body:
Let's say I have such DataFrame.

+-----------+
|amount     |
+-----------+
|100,200,300|
|73         |
|56,89      |
+-----------+

Also, I have an array with numbers: var array = Array(200, 73).

I want to filter this DataFrame by the array and take such a result:

+-----------+
|amount     |
+-----------+
|100,200,300|
|73         |
+-----------+

I used such code but it doesn't work the way I thought it would

df.filter(col("amount").isin(array: _*))

My next code returns such a result:

+-----------+
|amount     |
+-----------+
|73         |
+-----------+

What's wrong I did?

Body:
If you can not use Spark 2.4, here is another way using array_contains and split functions.

First split the column amount to get array column:

val df2 = df.withColumn("amount_array", split($"amount", ","))

Then filter using this filter expression:

val filterExpr = array.map(v => array_contains($"amount_array", v)).reduce(_ or _)

df2.filter(filterExpr).drop("amount_array").show()

//+-----------+
//|     amount|
//+-----------+
//|100,200,300|
//|         73|
//+-----------+


问:
Show 'P' instead of NULL values in PIVOT table
I am working on a PIVOT data and I am stuck at one point. This is my procedure:

```<code>ALTER PROCEDURE [dbo].[usp_GetLeaveReportOrg]
@startDate date,
@endDate date

AS
BEGIN
DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)
DECLARE @leaveReport TABLE (
    BuddyId bigint,
    Name nvarchar(300),
    RoleName nvarchar(150),
    DivisionName nvarchar(200),
    LeaveTypeName nvarchar(max),
    DateFrom date,
    DateTo date
 )

 insert into @leaveReport
 select tbl_Lm.BuddyId, tbl_Bm.Name,tbl_Rm.RoleName, tbl_Dm.DivisionName,tbl_Lt.LeaveTypeName,tbl_Lm.DateFrom, tbl_Lm.DateTo from tbl_LeaveMaster as tbl_Lm
inner join tbl_BuddyMaster as tbl_Bm on tbl_Bm.id= tbl_Lm.BuddyId inner join tbl_DivisionMaster as tbl_Dm on tbl_Dm.Id = tbl_Bm.Divisionid
inner join tbl_LeaveType as tbl_Lt on  tbl_Lt.Id = tbl_Lm.LeaveTypeId inner join tbl_RoleMaster as tbl_Rm on tbl_Lt.Id = tbl_Rm.Id

select BuddyId,Name,  RoleName , DivisionName,DateFrom, isnull(LeaveTypeName,'P') temp into #PivotLeaveData from @leaveReport where
CAST (DateFrom as date) >= cast(@startDate as date) and
cast(DateTo as date) <= cast(@endDate as date)
order by DateFrom  ASC

SELECT @ColumnName =COALESCE (@ColumnName + ',[' + CONVERT(NVARCHAR, [DateFrom], 106) + ']',
           '[' + CONVERT(NVARCHAR, [DateFrom], 106) + ']')
           FROM    (SELECT DISTINCT [DateFrom] FROM #PivotLeaveData) PV
           ORDER BY [DateFrom]

 SET @DynamicPivotQuery =
N'SELECT BuddyId,Name,RoleName,DivisionName, ' + @ColumnName + '
FROM #PivotLeaveData
PIVOT(Max( [LeaveTypeName]   )
      FOR [DateFrom] IN (' + @ColumnName + ')) AS PVTTable'

EXEC(@DynamicPivotQuery)

END
</code>```

PROBLEM:

What I want is, I want to display 'P' for the LeaveTypeName if entry is null. That means, the employee is present at that day. When I am using isNull it showing NULL instead of P.

WHAT I TRIED:

Using COALESCE function to replace the LeaveTypeName with P, but that doesn't work either.

Using ISNULL, but no luck.

EDIT:
Here is my sample data:

```<code>BuddyId   Name  RoleName    DivisionName   01Jan2020     02Jan2020    ....
1          ABC  Developer    Dev              NULL      Casual Leave
2          DEF  Maintenance  Maintenance    Sick Leave   NULL
</code>```

WHAT I NEED:
Replace the Nulls with 'P'

Where I am going wrong?

答:
use another variable to handle null data</p>

```<code>ALTER PROCEDURE [dbo].[usp_GetLeaveReportOrg]
@startDate date,
@endDate date

AS
BEGIN
DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)
DECLARE @ShowColumnName AS NVARCHAR(MAX)
DECLARE @leaveReport TABLE (
    BuddyId bigint,
    Name nvarchar(300),
    RoleName nvarchar(150),
    DivisionName nvarchar(200),
    LeaveTypeName nvarchar(max),
    DateFrom date,
    DateTo date
 )

 insert into @leaveReport
 select tbl_Lm.BuddyId, tbl_Bm.Name,tbl_Rm.RoleName, tbl_Dm.DivisionName,tbl_Lt.LeaveTypeName,tbl_Lm.DateFrom, tbl_Lm.DateTo from tbl_LeaveMaster as tbl_Lm
inner join tbl_BuddyMaster as tbl_Bm on tbl_Bm.id= tbl_Lm.BuddyId inner join tbl_DivisionMaster as tbl_Dm on tbl_Dm.Id = tbl_Bm.Divisionid
inner join tbl_LeaveType as tbl_Lt on  tbl_Lt.Id = tbl_Lm.LeaveTypeId inner join tbl_RoleMaster as tbl_Rm on tbl_Lt.Id = tbl_Rm.Id

select BuddyId,Name,  RoleName , DivisionName,DateFrom, LeaveTypeName into #PivotLeaveData from @leaveReport where
CAST (DateFrom as date) >= cast(@startDate as date) and
cast(DateTo as date) <= cast(@endDate as date)
order by DateFrom  ASC

SELECT @ColumnName =COALESCE (@ColumnName + ',[' + CONVERT(NVARCHAR, [DateFrom], 106) + ']',
           '[' + CONVERT(NVARCHAR, [DateFrom], 106) + ']')
           FROM    (SELECT DISTINCT [DateFrom] FROM #PivotLeaveData) PV
           ORDER BY [DateFrom]

SELECT @ShowColumnName=COALESCE (@ColumnName + ',ISNULL([' + CONVERT(NVARCHAR, [DateFrom], 106) + '],''P'') as '+'[' + CONVERT(NVARCHAR, [DateFrom], 106) + ']',
           'ISNULL([' + CONVERT(NVARCHAR, [DateFrom], 106) + '],''P'') as '+'[' + CONVERT(NVARCHAR, [DateFrom], 106) + ']')
           FROM    (SELECT DISTINCT [DateFrom] FROM #PivotLeaveData) PV
           ORDER BY [DateFrom]

 SET @DynamicPivotQuery =
N'SELECT BuddyId,Name,RoleName,DivisionName, ' + @ShowColumnName+ '
FROM #PivotLeaveData
PIVOT(Max( [LeaveTypeName]   )
      FOR [DateFrom] IN (' + @ColumnName + ')) AS PVTTable'

EXEC(@DynamicPivotQuery)

END
</code>```

Body:
I am working on a PIVOT data and I am stuck at one point. This is my procedure:

ALTER PROCEDURE [dbo].[usp_GetLeaveReportOrg]
@startDate date,
@endDate date

AS
BEGIN
DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)
DECLARE @leaveReport TABLE (
    BuddyId bigint,
    Name nvarchar(300),
    RoleName nvarchar(150),
    DivisionName nvarchar(200),
    LeaveTypeName nvarchar(max),
    DateFrom date,
    DateTo date
 )

 insert into @leaveReport
 select tbl_Lm.BuddyId, tbl_Bm.Name,tbl_Rm.RoleName, tbl_Dm.DivisionName,tbl_Lt.LeaveTypeName,tbl_Lm.DateFrom, tbl_Lm.DateTo from tbl_LeaveMaster as tbl_Lm
inner join tbl_BuddyMaster as tbl_Bm on tbl_Bm.id= tbl_Lm.BuddyId inner join tbl_DivisionMaster as tbl_Dm on tbl_Dm.Id = tbl_Bm.Divisionid
inner join tbl_LeaveType as tbl_Lt on  tbl_Lt.Id = tbl_Lm.LeaveTypeId inner join tbl_RoleMaster as tbl_Rm on tbl_Lt.Id = tbl_Rm.Id

select BuddyId,Name,  RoleName , DivisionName,DateFrom, isnull(LeaveTypeName,'P') temp into #PivotLeaveData from @leaveReport where
CAST (DateFrom as date) >= cast(@startDate as date) and
cast(DateTo as date) <= cast(@endDate as date)
order by DateFrom  ASC

SELECT @ColumnName =COALESCE (@ColumnName + ',[' + CONVERT(NVARCHAR, [DateFrom], 106) + ']',
           '[' + CONVERT(NVARCHAR, [DateFrom], 106) + ']')
           FROM    (SELECT DISTINCT [DateFrom] FROM #PivotLeaveData) PV
           ORDER BY [DateFrom]

 SET @DynamicPivotQuery =
N'SELECT BuddyId,Name,RoleName,DivisionName, ' + @ColumnName + '
FROM #PivotLeaveData
PIVOT(Max( [LeaveTypeName]   )
      FOR [DateFrom] IN (' + @ColumnName + ')) AS PVTTable'

EXEC(@DynamicPivotQuery)

END

PROBLEM:

What I want is, I want to display 'P' for the LeaveTypeName if entry is null. That means, the employee is present at that day. When I am using isNull it showing NULL instead of P.

WHAT I TRIED:

Using COALESCE function to replace the LeaveTypeName with P, but that doesn't work either.

Using ISNULL, but no luck.

EDIT:
Here is my sample data:

BuddyId   Name  RoleName    DivisionName   01Jan2020     02Jan2020    ....
1          ABC  Developer    Dev              NULL      Casual Leave
2          DEF  Maintenance  Maintenance    Sick Leave   NULL

WHAT I NEED:
Replace the Nulls with 'P'

Where I am going wrong?

Body:
use another variable to handle null data

ALTER PROCEDURE [dbo].[usp_GetLeaveReportOrg]
@startDate date,
@endDate date

AS
BEGIN
DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)
DECLARE @ShowColumnName AS NVARCHAR(MAX)
DECLARE @leaveReport TABLE (
    BuddyId bigint,
    Name nvarchar(300),
    RoleName nvarchar(150),
    DivisionName nvarchar(200),
    LeaveTypeName nvarchar(max),
    DateFrom date,
    DateTo date
 )

 insert into @leaveReport
 select tbl_Lm.BuddyId, tbl_Bm.Name,tbl_Rm.RoleName, tbl_Dm.DivisionName,tbl_Lt.LeaveTypeName,tbl_Lm.DateFrom, tbl_Lm.DateTo from tbl_LeaveMaster as tbl_Lm
inner join tbl_BuddyMaster as tbl_Bm on tbl_Bm.id= tbl_Lm.BuddyId inner join tbl_DivisionMaster as tbl_Dm on tbl_Dm.Id = tbl_Bm.Divisionid
inner join tbl_LeaveType as tbl_Lt on  tbl_Lt.Id = tbl_Lm.LeaveTypeId inner join tbl_RoleMaster as tbl_Rm on tbl_Lt.Id = tbl_Rm.Id

select BuddyId,Name,  RoleName , DivisionName,DateFrom, LeaveTypeName into #PivotLeaveData from @leaveReport where
CAST (DateFrom as date) >= cast(@startDate as date) and
cast(DateTo as date) <= cast(@endDate as date)
order by DateFrom  ASC

SELECT @ColumnName =COALESCE (@ColumnName + ',[' + CONVERT(NVARCHAR, [DateFrom], 106) + ']',
           '[' + CONVERT(NVARCHAR, [DateFrom], 106) + ']')
           FROM    (SELECT DISTINCT [DateFrom] FROM #PivotLeaveData) PV
           ORDER BY [DateFrom]

SELECT @ShowColumnName=COALESCE (@ColumnName + ',ISNULL([' + CONVERT(NVARCHAR, [DateFrom], 106) + '],''P'') as '+'[' + CONVERT(NVARCHAR, [DateFrom], 106) + ']',
           'ISNULL([' + CONVERT(NVARCHAR, [DateFrom], 106) + '],''P'') as '+'[' + CONVERT(NVARCHAR, [DateFrom], 106) + ']')
           FROM    (SELECT DISTINCT [DateFrom] FROM #PivotLeaveData) PV
           ORDER BY [DateFrom]

 SET @DynamicPivotQuery =
N'SELECT BuddyId,Name,RoleName,DivisionName, ' + @ShowColumnName+ '
FROM #PivotLeaveData
PIVOT(Max( [LeaveTypeName]   )
      FOR [DateFrom] IN (' + @ColumnName + ')) AS PVTTable'

EXEC(@DynamicPivotQuery)

END


问:
Form onsubmit versus submit button onclick
UPDATE
From @BrendanEich

@mplungjan onclick of submit just falls out of that being a button; form onsubmit is clearly better.

Which would be the reasons to ever use the onclick of a submit button to determine whether or not the form should be submitted?

I believe strongly that

to execute something before submit and cancel the submit in case of error, the form's onsubmit event is the obvious place to put it

If you use the onclick of a submit button and later decide to use type="image" the event handler will fail in many browsers

if you change the submit to a button, you will have to add a submit to the onclick event handler too.

I am looking for strong reasons to prefer using a submit button's onclick event over the form's onsubmit.

UPDATE: Please note that I am personally well aware of many of the issues around form submission and validation.

For example that submitting by javascript will not trigger the onsubmit
http://jsfiddle.net/mplungjan/3A4Ha/

```<code><form onsubmit="alert('onSubmit called')">
    <input type="text" value="This will submit on enter but in IE the onclick is not triggered" style="width:100%"/><br/>
    <input type="submit" onclick="alert('Clicked')" />
</form><br />
<a href="#" onclick="alert('Submitting by script'); return false">Submit by script will not trigger onsubmit</a>
</code>```

Also that IE will not trigger the onclick if you hit enter in the form in my fiddle

History:

Got into a discussion here

html button not clickable without being disabled

I have an intense dislike of using the onclick of a submit button for ANYTHING due to many1 years of seeing this not work in a number of browsers, mostly older version of IE.
I have listed a few of the obvious reasons, but I am sure they will not convince the hardened user.

Can SO's community help me nail this one to the wall, like they nailed w3schools?
Also feel free to give comments as to how I can phrase this question in an acceptable manner.

1: since the days of NS2.x and IE3.02

答:
There are no direct reasons to use a from’s onsubmit handler over a button’s onclick handler. One should use named events according to their intent.

You may consider a scenario with two actions – a “send” action (as in “to send an e-mail”) and a “save” (as in “draft”). The former action assumes the form filled in a coherent manner, while the latter action should allow the user to persist whatever state the user likes. That makes the click handlers ideal places to decide on validation and cancellation. The relevance of the submit event in this case is undetermined.

To make the matter even more complicated you may add auto-save and optimistic concurrency to the scenario.

IMHO The years of tries and errors in the matter resulted in the HTML5 standard to have ruled the question in favor of the button element. See button’s [form*] attributes that allow to change the form action, method by each button individually.

Body:
UPDATE
From @BrendanEich

@mplungjan onclick of submit just falls out of that being a button; form onsubmit is clearly better.

Which would be the reasons to ever use the onclick of a submit button to determine whether or not the form should be submitted?

I believe strongly that

to execute something before submit and cancel the submit in case of error, the form's onsubmit event is the obvious place to put it

If you use the onclick of a submit button and later decide to use type="image" the event handler will fail in many browsers

if you change the submit to a button, you will have to add a submit to the onclick event handler too.

I am looking for strong reasons to prefer using a submit button's onclick event over the form's onsubmit.

UPDATE: Please note that I am personally well aware of many of the issues around form submission and validation.

For example that submitting by javascript will not trigger the onsubmit
http://jsfiddle.net/mplungjan/3A4Ha/

<form onsubmit="alert('onSubmit called')">
    <input type="text" value="This will submit on enter but in IE the onclick is not triggered" style="width:100%"/>

    <input type="submit" onclick="alert('Clicked')" />
</form>

Submit by script will not trigger onsubmit

Also that IE will not trigger the onclick if you hit enter in the form in my fiddle

History:

Got into a discussion here

html button not clickable without being disabled

I have an intense dislike of using the onclick of a submit button for ANYTHING due to many1 years of seeing this not work in a number of browsers, mostly older version of IE.
I have listed a few of the obvious reasons, but I am sure they will not convince the hardened user.

Can SO's community help me nail this one to the wall, like they nailed w3schools?
Also feel free to give comments as to how I can phrase this question in an acceptable manner.

1: since the days of NS2.x and IE3.02


问:
wkhtmltopdf - background color doesn't fill second page
I am trying to convert an HTML to a PDF document with wkhtmltopdf.

Command I am running is wkhtmltopdf ./test.html test.pdf

Software version:

```<code>wkhtmltopdf -V
wkhtmltopdf 0.12.5 (with patched qt)
</code>```

The content is dynamic therefore I don't really know where it will end.

Unfortunately when the content renders to the second page the background stops with the content.

HTML below, any help would be fully appreciated and make an old developer happy after struggling so much :)

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<head>
  <title>Testing PDF</title>

  <link href="https://fonts.googleapis.com/css?family=Lato:400,700" rel="stylesheet">

  <style>
    html {
      height: 100%;
      background: #f3f8fb;
    }

    body {
      font-family: "Lato", sans-serif;
      color: black;
      background: #f3f8fb;
    }
  </style>
</head>

<body>

  <p>This is a test with lots of dynamic content</p>
  <p>This is a test with lots of dynamic content</p>
  <p>This is a test with lots of dynamic content</p>
  <p>This is a test with lots of dynamic content</p>
  <p>This is a test with lots of dynamic content</p>
  <p>This is a test with lots of dynamic content</p>
  <p>This is a test with lots of dynamic content</p>
  <p>This is a test with lots of dynamic content</p>
  <p>This is a test with lots of dynamic content</p>
  <p>This is a test with lots of dynamic content</p>
  <p>This is a test with lots of dynamic content</p>
  <p>This is a test with lots of dynamic content</p>
  <p>This is a test with lots of dynamic content</p>
  <p>This is a test with lots of dynamic content</p>
  <p>This is a test with lots of dynamic content</p>
  <p>This is a test with lots of dynamic content</p>
  <p>This is a test with lots of dynamic content</p>
  <p>This is a test with lots of dynamic content</p>
  <p>This is a test with lots of dynamic content</p>
  <p>This is a test with lots of dynamic content</p>
  <p>This is a test with lots of dynamic content</p>
  <p>This is a test with lots of dynamic content</p>
  <p>This is a test with lots of dynamic content</p>
  <p>This is a test with lots of dynamic content</p>
  <p>This is a test with lots of dynamic content</p>
  <p>This is a test with lots of dynamic content</p>
  <p>This is a test with lots of dynamic content</p>
  <p>This is a test with lots of dynamic content</p>
  <p>This is a test with lots of dynamic content</p>
  <p>This is a test with lots of dynamic content</p>
  <p>This is a test with lots of dynamic content</p>
  <p>This is a test with lots of dynamic content</p>
  <p>This is a test with lots of dynamic content</p>
  <p>This is a test with lots of dynamic content</p>
  <p>This is a test with lots of dynamic content</p>
  <p>This is a test with lots of dynamic content</p>
  <p>This is a test with lots of dynamic content</p>
  <p>This is a test with lots of dynamic content</p>
  <p>This is a test with lots of dynamic content</p>
  <p>This is a test with lots of dynamic content</p>
  <p>This is a test with lots of dynamic content</p>

</body>

</html>
</code>```

答:
Use page-break-after: always; in the CSS so that it includes a page break and hence the background color is applied to the entire page. But the issue with that is, a new page gets added. Including a new block will fix that.

Reference: https://github.com/wkhtmltopdf/wkhtmltopdf/issues/3125

Body:
I am trying to convert an HTML to a PDF document with wkhtmltopdf.

Command I am running is wkhtmltopdf ./test.html test.pdf

Software version:

wkhtmltopdf -V
wkhtmltopdf 0.12.5 (with patched qt)

The content is dynamic therefore I don't really know where it will end.

Unfortunately when the content renders to the second page the background stops with the content.

HTML below, any help would be fully appreciated and make an old developer happy after struggling so much :)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

  <title>Testing PDF</title>

  <link href="https://fonts.googleapis.com/css?family=Lato:400,700" rel="stylesheet">

This is a test with lots of dynamic content

This is a test with lots of dynamic content

This is a test with lots of dynamic content

This is a test with lots of dynamic content

This is a test with lots of dynamic content

This is a test with lots of dynamic content

This is a test with lots of dynamic content

This is a test with lots of dynamic content

This is a test with lots of dynamic content

This is a test with lots of dynamic content

This is a test with lots of dynamic content

This is a test with lots of dynamic content

This is a test with lots of dynamic content

This is a test with lots of dynamic content

This is a test with lots of dynamic content

This is a test with lots of dynamic content

This is a test with lots of dynamic content

This is a test with lots of dynamic content

This is a test with lots of dynamic content

This is a test with lots of dynamic content

This is a test with lots of dynamic content

This is a test with lots of dynamic content

This is a test with lots of dynamic content

This is a test with lots of dynamic content

This is a test with lots of dynamic content

This is a test with lots of dynamic content

This is a test with lots of dynamic content

This is a test with lots of dynamic content

This is a test with lots of dynamic content

This is a test with lots of dynamic content

This is a test with lots of dynamic content

This is a test with lots of dynamic content

This is a test with lots of dynamic content

This is a test with lots of dynamic content

This is a test with lots of dynamic content

This is a test with lots of dynamic content

This is a test with lots of dynamic content

This is a test with lots of dynamic content

This is a test with lots of dynamic content

This is a test with lots of dynamic content

This is a test with lots of dynamic content


问:
Does iOS NFC Background Reading support NDEF Contact Card records?
I'm just getting into NFC Tags for iOS and I want to program a contact record into an NFC tag so that it can be read by an iPhone that supports Background Tag Reading. It seems like Background Tag Reading in iOS only supports universal links and certain URI/URL messages. This is the link I read for reference:

Background Tag Reading Support Info

I know that Android supports the NDEF VCard Record Type, where one can then program a tag with a contact's info, and then scan and add that contact. I noticed that when I used the same tag with Apple, nothing showed up, so that's why I am assuming Apple doesn't support this NDEF Record type.

First off, am I correct in this information so far? Apple does not support NDEF VCard Records?

If that's true, is there any way to program a contact in or is the closest I'm going to get to a contact through the use of the tel:+14085551212 url, as stated by the link above?

答:
Yes only URIs are identified by iOS. For v-Card you must use a third party app. The app I made for example can handle v-Cards. https://apps.apple.com/us/app/nfc-for-iphone/id1249686798

Apple might open this in the future but who knows...


问:
How to update multiple objects in django rest framework?
I am trying to update multiple objects using IDs which i am passing in every objects that need to be updated but can't find any way to do it successfully. Here is my code

models.py

```<code>class EventTicket(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid_generate_v1mc, editable=False)
    name = models.CharField(max_length=250)
    description = models.TextField(max_length=1000)
</code>```

views.py

```<code>  class EventTicketView(APIView, PaginationHandlerMixin):
        permission_classes = (AllowAny,)
        def get_object(self, ticket_id):
            try:
                return EventTicket.objects.get(id=ticket_id)
            except EventTicket.DoesNotExist():
                raise status.HTTP_400_BAD_REQUEST
        def patch(self, request, *args, **kwargs):
            for each_ticket in request.data:

                ticket_id = self.get_object(each_ticket['ticket_id'])

                serializer = EventTicketSerializer(instance=ticket_id,data=request.data,partial=True)
                if serializer.is_valid():
                    serializer.save()
                    result = {
                        'message': "updated sucessfully"
                    }
                    return Response(result, status=status.HTTP_201_CREATED)
                else:
                    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
</code>```

serializers.py

```<code>class EventTicketSerializer(serializers.ModelSerializer):
    class Meta:
        model = EventTicket
        fields = ['name', 'description']
```

I have to send data like list of multiple objects :::
[
    {
    "ticket_id": "054665ea-4fde-11ea-94b2-9f415c43ba4c",
    "name": "chris",
    "description":"The golden ticket for day only",

    },
    {
    "ticket_id": "054656ea-4fde-11ea-94b2-9f415c43ba4c",
    "name": "daut",
    "description":"The premium ticket for day only",

    }
]
```

答:
The following code will give you a proper understanding of updating multiple objects in single request.
For updating multiple objects in a single request it is best practice to use the PUT method instead of PATCH.
Here body data given is.

BODY DATA

```<code>{
    "ids":[
        "5e41770d2e8fa013d1f034ec",
        "5e41772c2e8fa013d1f034ee",
        "5e4177702e8fa013d1f034f2",
        "5e453f302e8fa075aa18b277",
        "5e4a314f2e8fa070c5251a0a"
    ]
}
</code>```

I'am updating the enabled attribute from False to True for given ids of DemoConfig model.
In the same way, you can update your data. As per your requirement, you can write validate methods to validate the body data.
Serializer has written to serialized the instance data for the response.

class DemoAPI(APIView):

    def get_object(self, obj_id):
        try:
            return DemoConfig.objects.get(id=obj_id)
        except (DemoConfig.DoesNotExist, ValidationError):
            raise status.HTTP_400_BAD_REQUEST

    def validate_ids(self, id_list):
        for id in id_list:
            try:
                DemoConfig.objects.get(id=id)
            except (DemoConfig.DoesNotExist, ValidationError):
                raise status.HTTP_400_BAD_REQUEST
        return True

    def put(self, request, *args, **kwargs):
        id_list = request.data['ids']
        self.validate_ids(id_list=id_list)
        instances = []
        for id in id_list:
            obj = self.get_object(obj_id=id)
            obj.enabled = True
            obj.save()
            instances.append(obj)
        serializer = DemoSerializer(instances, many=True)
        return Response(serializer.data)
```

<p>Serialiser for this view is:</p>

<pre class="lang-py prettyprint-override"><code>class DemoSerializer(DocumentSerializer):
    class Meta:
        model = DemoConfig
        fields = '__all__'

</code>```

Output:

```<code>{
  "data": [
    {
      "id": "5e41770d2e8fa013d1f034ec",
      "name": "CONFIG_1",
      "enabled": true,

    },
    {
      "id": "5e41772c2e8fa013d1f034ee",
      "name": "CONFIG_2",
      "enabled": true,

    },
    {
      "id": "5e4177702e8fa013d1f034f2",
      "name": "CONFIG_3",
      "enabled": true,

    },
    {
      "id": "5e453f302e8fa075aa18b277",
      "name": "CONFIG_4",
      "enabled": true,

    },
    {
      "id": "5e4a314f2e8fa070c5251a0a",
      "name": "CONFIG_5",
      "enabled": true,

    }
  ]
}
</code>```

As per your code requirement you need to use put method in follwoing way.

    def put(self, request, *args, **kwargs):
        data = request.data
        ticket_ids = [i['ticket_id'] for i in data]
        self.validate_ids(ticket_ids)
        instances = []
        for temp_dict in data:
            ticket_id = temp_dict['ticket_id']
            name = temp_dict['name']
            description = temp_dict['description']
            obj = self.get_object(ticket_id)
            obj.name = name
            obj.description = description
            obj.save()
            instances.append(obj)
        serializer = DemoSerializer(instances, many=True)
        return Response(serializer.data)
```

Body:
I am trying to update multiple objects using IDs which i am passing in every objects that need to be updated but can't find any way to do it successfully. Here is my code

models.py

class EventTicket(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid_generate_v1mc, editable=False)
    name = models.CharField(max_length=250)
    description = models.TextField(max_length=1000)

views.py

  class EventTicketView(APIView, PaginationHandlerMixin):
        permission_classes = (AllowAny,)
        def get_object(self, ticket_id):
            try:
                return EventTicket.objects.get(id=ticket_id)
            except EventTicket.DoesNotExist():
                raise status.HTTP_400_BAD_REQUEST
        def patch(self, request, *args, **kwargs):
            for each_ticket in request.data:

                ticket_id = self.get_object(each_ticket['ticket_id'])

                serializer = EventTicketSerializer(instance=ticket_id,data=request.data,partial=True)
                if serializer.is_valid():
                    serializer.save()
                    result = {
                        'message': "updated sucessfully"
                    }
                    return Response(result, status=status.HTTP_201_CREATED)
                else:
                    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

serializers.py

class EventTicketSerializer(serializers.ModelSerializer):
    class Meta:
        model = EventTicket
        fields = ['name', 'description']
```

I have to send data like list of multiple objects :::
[
    {
    "ticket_id": "054665ea-4fde-11ea-94b2-9f415c43ba4c",
    "name": "chris",
    "description":"The golden ticket for day only",

    },
    {
    "ticket_id": "054656ea-4fde-11ea-94b2-9f415c43ba4c",
    "name": "daut",
    "description":"The premium ticket for day only",

    }
]

Body:
The following code will give you a proper understanding of updating multiple objects in single request.
For updating multiple objects in a single request it is best practice to use the PUT method instead of PATCH.
Here body data given is.

BODY DATA

{
    "ids":[
        "5e41770d2e8fa013d1f034ec",
        "5e41772c2e8fa013d1f034ee",
        "5e4177702e8fa013d1f034f2",
        "5e453f302e8fa075aa18b277",
        "5e4a314f2e8fa070c5251a0a"
    ]
}

I'am updating the enabled attribute from False to True for given ids of DemoConfig model.
In the same way, you can update your data. As per your requirement, you can write validate methods to validate the body data.
Serializer has written to serialized the instance data for the response.

class DemoAPI(APIView):

    def get_object(self, obj_id):
        try:
            return DemoConfig.objects.get(id=obj_id)
        except (DemoConfig.DoesNotExist, ValidationError):
            raise status.HTTP_400_BAD_REQUEST

    def validate_ids(self, id_list):
        for id in id_list:
            try:
                DemoConfig.objects.get(id=id)
            except (DemoConfig.DoesNotExist, ValidationError):
                raise status.HTTP_400_BAD_REQUEST
        return True

    def put(self, request, *args, **kwargs):
        id_list = request.data['ids']
        self.validate_ids(id_list=id_list)
        instances = []
        for id in id_list:
            obj = self.get_object(obj_id=id)
            obj.enabled = True
            obj.save()
            instances.append(obj)
        serializer = DemoSerializer(instances, many=True)
        return Response(serializer.data)

Serialiser for this view is:

class DemoSerializer(DocumentSerializer):
    class Meta:
        model = DemoConfig
        fields = '__all__'

Output:

{
  "data": [
    {
      "id": "5e41770d2e8fa013d1f034ec",
      "name": "CONFIG_1",
      "enabled": true,

    },
    {
      "id": "5e41772c2e8fa013d1f034ee",
      "name": "CONFIG_2",
      "enabled": true,

    },
    {
      "id": "5e4177702e8fa013d1f034f2",
      "name": "CONFIG_3",
      "enabled": true,

    },
    {
      "id": "5e453f302e8fa075aa18b277",
      "name": "CONFIG_4",
      "enabled": true,

    },
    {
      "id": "5e4a314f2e8fa070c5251a0a",
      "name": "CONFIG_5",
      "enabled": true,

    }
  ]
}

As per your code requirement you need to use put method in follwoing way.

    def put(self, request, *args, **kwargs):
        data = request.data
        ticket_ids = [i['ticket_id'] for i in data]
        self.validate_ids(ticket_ids)
        instances = []
        for temp_dict in data:
            ticket_id = temp_dict['ticket_id']
            name = temp_dict['name']
            description = temp_dict['description']
            obj = self.get_object(ticket_id)
            obj.name = name
            obj.description = description
            obj.save()
            instances.append(obj)
        serializer = DemoSerializer(instances, many=True)
        return Response(serializer.data)


问:
Laravel How to call a function with a if else
Im trying to make a function where if the date from the database is past the current date to send an email to the user. My email function works. Now I also already build that if the date is past the current date it adds a  with 'paste current date'. Now I would like to know if its possible to also send out an email to the user?.

This is my code

```<code><td class="wrong">
 @php
     $date = new DateTime($i->EindDatum);
     $now = new DateTime();

     if($date < $now)  echo  'past current date'
 @endphp
 @if ($date < $now)
 {{ $users = User::find(1)  $user->notify(new TaksComplete)}}
 @endif
</td>
</code>```

Now the @if function returns this error syntax error, unexpected '$user' (T_VARIABLE), expecting ')'>

I know the application doesnt know User because its a function but I dont know how to fix that.

The function does work because when I for example use it in my routes/web.php it does work like this:

```<code>Route::get('/hosting', function(){

    $users = User::find(1);
    Notification::send($users, new TaksComplete);
    return view('hosting');

} );
</code>```

This does send an email to the user when it clicks /hosting but I did that just for testing

ps. I am new to laravel

答:
keep doing calculation in <code>@php</code> tag only don't split </p>

```<code>
@php
 $date = new DateTime($i->EindDatum);
 $now = new DateTime();

 if($date < $now)  echo  'past current date';

 if ($date < $now) {
    $user = /App/User::find(1)->first();
    $user->notify(new TaksComplete);
 }
 @endphp

</code>```

Body:
Im trying to make a function where if the date from the database is past the current date to send an email to the user. My email function works. Now I also already build that if the date is past the current date it adds a  with 'paste current date'. Now I would like to know if its possible to also send out an email to the user?.

This is my code

 @php
     $date = new DateTime($i->EindDatum);
     $now = new DateTime();

     if($date < $now)  echo  'past current date'
 @endphp
 @if ($date < $now)
 {{ $users = User::find(1)  $user->notify(new TaksComplete)}}
 @endif

Now the @if function returns this error syntax error, unexpected '$user' (T_VARIABLE), expecting ')'>

I know the application doesnt know User because its a function but I dont know how to fix that.

The function does work because when I for example use it in my routes/web.php it does work like this:

Route::get('/hosting', function(){

    $users = User::find(1);
    Notification::send($users, new TaksComplete);
    return view('hosting');

} );

This does send an email to the user when it clicks /hosting but I did that just for testing

ps. I am new to laravel

Body:
keep doing calculation in @php tag only don't split

@php
 $date = new DateTime($i->EindDatum);
 $now = new DateTime();

 if($date < $now)  echo  'past current date';

 if ($date < $now) {
    $user = /App/User::find(1)->first();
    $user->notify(new TaksComplete);
 }
 @endphp


问:
Find two closest numbers to zero in given array in Java Script
Is there any better solution than these(Solution 1 and Solution 2 )? Can you please suggest.

Solution 1:

var arr = [2, 5.5, -3, 10, -1, 1.5];

let min1 = arr[0],
  min2 = arr[1];

for (let i = 2; i < arr.length; i++) {
  if (Math.abs(arr[i]) < Math.abs(min1)) {
    min1 = arr[i];

  }
  if (Math.abs(min2) > Math.abs(min1)) {
    let temp = min2;
    min2 = min1;
    min1 = temp;
  }
}

console.log("Closest numbers to Zero = " + min1 + ", " + min2);```
</div>
</div>
</p>

<p><strong>Solution 2:</strong> </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var arr = [2, 5.5, -3, 10, -1, 1.5];
arr.sort((a, b) => Math.abs(a) - Math.abs(b));
console.log("Closest numbers to Zero = " + arr[0] + ", " + arr[1]);</code>```

答:
Closest to zero just means the lowest absolute value, so you just need to calculate that and then find the two smallest results.

let arr = [2, 5.5, -3, 10, -1, 1.5];
let abs = arr.map(x=>Math.abs(x));
for(let t=0;t<2;t++)
 {
 let lowestI = 0;
 for(let i=1;i<arr.length;i++)
 {
   if (abs[i] < abs[lowestI]) {lowestI = i;}
 }
 console.log((t+1)+".-closest number to zero:",arr[lowestI]);
 arr.splice(lowestI,1)
 abs.splice(lowestI,1)
}```

The complexity is n*t, so this would only be useful if t is very low (like the 2 in your case) and the length is very high, else the sorting approach with n*log(n) would be more than sufficient.

Body:
Is there any better solution than these(Solution 1 and Solution 2 )? Can you please suggest.

Solution 1:

var arr = [2, 5.5, -3, 10, -1, 1.5];

let min1 = arr[0],
  min2 = arr[1];

for (let i = 2; i < arr.length; i++) {
  if (Math.abs(arr[i]) < Math.abs(min1)) {
    min1 = arr[i];

  }
  if (Math.abs(min2) > Math.abs(min1)) {
    let temp = min2;
    min2 = min1;
    min1 = temp;
  }
}

console.log("Closest numbers to Zero = " + min1 + ", " + min2);

Solution 2:

var arr = [2, 5.5, -3, 10, -1, 1.5];
arr.sort((a, b) => Math.abs(a) - Math.abs(b));
console.log("Closest numbers to Zero = " + arr[0] + ", " + arr[1]);

Body:
Closest to zero just means the lowest absolute value, so you just need to calculate that and then find the two smallest results.

let arr = [2, 5.5, -3, 10, -1, 1.5];
let abs = arr.map(x=>Math.abs(x));
for(let t=0;t<2;t++)
 {
 let lowestI = 0;
 for(let i=1;i<arr.length;i++)
 {
   if (abs[i] < abs[lowestI]) {lowestI = i;}
 }
 console.log((t+1)+".-closest number to zero:",arr[lowestI]);
 arr.splice(lowestI,1)
 abs.splice(lowestI,1)
}

The complexity is n*t, so this would only be useful if t is very low (like the 2 in your case) and the length is very high, else the sorting approach with n*log(n) would be more than sufficient.


问:
Character offset in Brat's annotation file through python
I have two UTF-8 text files:

repr(file1.txt):

```<code>\nSTATEMENT OF WORK\n\n\nSTATEMENT OF WORK NO. 7\nEffective Date: February 15, 2015
</code>```

repr(file2.txt):

```<code>RENEWAL/AMENDMENT\n\nTHIS agreement is entered as of July 25, 2014. b
</code>```

Their respective Brat annotation files have the following annotation:

file1.ann:

```<code>T1  date 61 78  February 15, 2015
</code>```

file2.ann:

```<code>T1  date 53 67   July 25, 2014.
</code>```

But when I use python to retrieve the characters from .txt using above offsets, I get:

file1.read()[61:78]:

```<code>February 15, 2015
</code>```

file2.read()[53:67]:

```<code>ly 25, 2014. b
</code>```

Why does my offsetting work in the first case but not the second case?

答:
The problem comes from the fact the carriage returns (\r in the text file) and newline (\n) are not considered the same way in Windows and Unix/Mac. If you use a Windows system to generate or modify the .txt files there will be some '\r\n' but brat (that is not thought for Windows) will only counts the '\n' sign.

Using python, you may pass from Windows count to brat count using a dict after having opened the file with the argument newline='' that ensures '\r' will be present in the created W_Contents variable:

```<code>with open('file.txt', newline='', encoding='utf-8') as f:
    W_Content = f.read()

counter = -1
UfromW_dic = {}
for n, char in enumerate(W_Content):
    if char != '\r':
        counter += 1
        UfromW_dic[n] = counter
</code>```

After that, the intial span [x,y] will be found at [UfromW_dic[x],UfromW_dic[y]].

ContentLicense: CC BY-SA 3.0

Body:
I have two UTF-8 text files:

repr(file1.txt):

\nSTATEMENT OF WORK\n\n\nSTATEMENT OF WORK NO. 7\nEffective Date: February 15, 2015

repr(file2.txt):

RENEWAL/AMENDMENT\n\nTHIS agreement is entered as of July 25, 2014. b

Their respective Brat annotation files have the following annotation:

file1.ann:

T1  date 61 78  February 15, 2015

file2.ann:

T1  date 53 67   July 25, 2014.

But when I use python to retrieve the characters from .txt using above offsets, I get:

file1.read()[61:78]:

February 15, 2015

file2.read()[53:67]:

ly 25, 2014. b

Why does my offsetting work in the first case but not the second case?

Body:
The problem comes from the fact the carriage returns (\r in the text file) and newline (\n) are not considered the same way in Windows and Unix/Mac. If you use a Windows system to generate or modify the .txt files there will be some '\r\n' but brat (that is not thought for Windows) will only counts the '\n' sign.

Using python, you may pass from Windows count to brat count using a dict after having opened the file with the argument newline='' that ensures '\r' will be present in the created W_Contents variable:

with open('file.txt', newline='', encoding='utf-8') as f:
    W_Content = f.read()

counter = -1
UfromW_dic = {}
for n, char in enumerate(W_Content):
    if char != '\r':
        counter += 1
        UfromW_dic[n] = counter

After that, the intial span [x,y] will be found at [UfromW_dic[x],UfromW_dic[y]].


问:
How does a vector as a key works internally in C++?
This SO answers says that STL Map with a Vector for the Key the vector can be used as a key. So when we use a vector as a key. How does that actually work since the key needs to be unique so when we insert another vector with the same elements will the map check for duplicate element by element or the name of the vector does specify something? Like the name of the array represents the base address. So an array can be used as a key since the base address can be used as a key in this case but what is the key in case of a vector. How does it work internally.

Because when I print the name of the vector, I do get an error

```<code>vector<int> v;
cout<<v; //error
</code>```

答:
Name of an object and content of that object are always unrelated things.

operator == for std::vector will first compare length of vectors and then each of it's elements using operator == as well.

operator < compares elements in vector lexicographically, i.e. it returns x[i] < y[i] for the first non-equal element in vectors x and y.

These are the requirements std::map has for a type used as Key. Since std::vector satisfies both, it can be used by as Key. Note that type managed by vector must also has these operators overloaded for this to work (because std::vector relies on those operators to implement it's own operators).

Body:
This SO answers says that STL Map with a Vector for the Key the vector can be used as a key. So when we use a vector as a key. How does that actually work since the key needs to be unique so when we insert another vector with the same elements will the map check for duplicate element by element or the name of the vector does specify something? Like the name of the array represents the base address. So an array can be used as a key since the base address can be used as a key in this case but what is the key in case of a vector. How does it work internally.

Because when I print the name of the vector, I do get an error

vector<int> v;
cout<<v; //error


问:
CharSet for MS Access '97 DB using UCanAccess
Hey I am reading a database using ucanaccess-5.0.0.
The database is propably < Access 2000, since it's not UTF-8.
It seems like I have to setup a charset. I tried this using the charset parameter in the url:

jdbc:ucanaccess://${databaseFile.absolutePath};memory=false;charSet=Cp1250

It seems to be ignored, since I still don't get my german umlauts out of the DB.

What can I do about it?

答:
Working Solution:</p>

```<code>class DatabaseOpener : JackcessOpenerInterface {
  override fun open(fl: File, pwd: String?): Database {
    return DatabaseBuilder.open(fl).apply {
      this.charset = charset("Cp1252")
    }
  }
}

// URL
"jdbc:ucanaccess://<path-to-mdb-file>;memory=false;jackcessOpener=${DatabaseOpener::class.qualifiedName!!}"

</code>```

Body:
Working Solution:

class DatabaseOpener : JackcessOpenerInterface {
  override fun open(fl: File, pwd: String?): Database {
    return DatabaseBuilder.open(fl).apply {
      this.charset = charset("Cp1252")
    }
  }
}

// URL
"jdbc:ucanaccess://<path-to-mdb-file>;memory=false;jackcessOpener=${DatabaseOpener::class.qualifiedName!!}"


问:
How to open multiple instances of Android Studio or instances of Same Project but different branch simultaneously on Windows?
I have been struggling to manage two branches of a Project at the same time. By Manage, I mean, to be able to open the Project(same) twice or more than than.

Suppose, on Windows, I create a new Desktop and open Android Studio in this. I can open Google Chrome and other apps but opening the entire Android Studio simultaneously is not possible.

I don't find any such questions on SO. isn't there a need for that?

I just want to open and edit and code on two branches of the same Project on Windows and it need not to be on a different desktop.

答:
You cant work with same project, but with different branches simultaneously - just because branch - is a changes in sources and when you switching branch, you make changes nf files in project folder.
So solution - use different folders or better uses difftools build-in in android studio to compare sources of branches.


问:
php + mysql query returning only a single row (std class) from class function
Can you tell me why this returns only the last row of my query?
As you see I'm extracting as std class. Also I already tried different approaches like a foreach key=>value inside the while but it does not help. I can't populate $out correctly.</p>

```<code>class myclass {

    function Query($sql){

    $results = $this->db->query($sql);

    if (mysqli_num_rows($results)<1){
        throw new Exception('NoResults');
    }

    $out = new stdClass;
    while ($r = $results->fetch_object()){

        $out = $r;
    }

    return $out;
    $out = null;
    }

}

}

---------------

$client = new myclass;

    $sql = "SELECT * FROM books";
    $q = $client->Query($sql);

    print_r($q);
</code>```

答:
Your $r is object. You dont need stdClass.  You need to add your objects to $out array. </p>

```<code>function Query($sql)
{
    $results = $this->db->query($sql);

    if (mysqli_num_rows($results) < 1) {
       throw new Exception('NoResults');
    }

    $out = new stdClass;
    $i=0;
    while ($r = $results->fetch_object()){
        $out->{$i} = $r;
        $i++
    }

    return $out;
}
</code>```

Body:
Can you tell me why this returns only the last row of my query?
As you see I'm extracting as std class. Also I already tried different approaches like a foreach key=>value inside the while but it does not help. I can't populate $out correctly.

class myclass {

    function Query($sql){

    $results = $this->db->query($sql);

    if (mysqli_num_rows($results)<1){
        throw new Exception('NoResults');
    }

    $out = new stdClass;
    while ($r = $results->fetch_object()){

        $out = $r;
    }

    return $out;
    $out = null;
    }

}

}

---------------

$client = new myclass;

    $sql = "SELECT * FROM books";
    $q = $client->Query($sql);

    print_r($q);

Body:
Your $r is object. You dont need stdClass.  You need to add your objects to $out array.

function Query($sql)
{
    $results = $this->db->query($sql);

    if (mysqli_num_rows($results) < 1) {
       throw new Exception('NoResults');
    }

    $out = new stdClass;
    $i=0;
    while ($r = $results->fetch_object()){
        $out->{$i} = $r;
        $i++
    }

    return $out;
}


问:
Why am i getting a class cast exception when adding a button in android studio?
I'm on Android Studio 3.4, and using Material Design.
When I add a button to the layout i'm getting a java.lang.ClassCastException@11378fc8 and i can't use anymore the layout editor until I remove the button.

I have already tried to "invalidate/restart", to rebuild, to clean and build.

This is my tree structure :
Tree structure

Build.Gradle :

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "fr.aurelien.test_dessin_android"
        minSdkVersion 24
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.0.0-beta01'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0-beta01'
    implementation 'com.google.android.material:material:1.1.0-alpha06'
    implementation 'com.google.code.gson:gson:2.8.5'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.0-alpha4'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0-alpha4'
}
</code>```

Class cast exception :

```<code>java.lang.IllegalArgumentException: java.lang.ClassCastException@126d0c4
    at sun.reflect.GeneratedMethodAccessor1380.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at android.animation.PropertyValuesHolder_Delegate.callMethod(PropertyValuesHolder_Delegate.java:108)
    at android.animation.PropertyValuesHolder_Delegate.nCallFloatMethod(PropertyValuesHolder_Delegate.java:143)
    at android.animation.PropertyValuesHolder.nCallFloatMethod(PropertyValuesHolder.java)
    at android.animation.PropertyValuesHolder.access$400(PropertyValuesHolder.java:38)
    at android.animation.PropertyValuesHolder$FloatPropertyValuesHolder.setAnimatedValue(PropertyValuesHolder.java:1387)
    at android.animation.ObjectAnimator.animateValue(ObjectAnimator.java:990)
    at android.animation.ValueAnimator.setCurrentFraction(ValueAnimator.java:674)
    at android.animation.ValueAnimator.start(ValueAnimator.java:1071)
    at android.animation.ValueAnimator.start(ValueAnimator.java:1088)
    at android.animation.ObjectAnimator.start(ObjectAnimator.java:852)
    at android.animation.ValueAnimator.startWithoutPulsing(ValueAnimator.java:1081)
    at android.animation.AnimatorSet.handleAnimationEvents(AnimatorSet.java:1142)
    at android.animation.AnimatorSet.doAnimationFrame(AnimatorSet.java:1046)
    at android.animation.AnimationHandler.doAnimationFrame(AnimationHandler.java:146)
    at android.animation.AnimationHandler.access$100(AnimationHandler.java:37)
    at android.animation.AnimationHandler$1.doFrame(AnimationHandler.java:54)
    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:947)
    at android.view.Choreographer.doCallbacks(Choreographer.java:761)
    at android.view.Choreographer_Delegate.doFrame(Choreographer_Delegate.java:66)
    at com.android.layoutlib.bridge.impl.RenderSessionImpl.renderAndBuildResult(RenderSessionImpl.java:563)
    at com.android.layoutlib.bridge.impl.RenderSessionImpl.render(RenderSessionImpl.java:425)
    at com.android.layoutlib.bridge.BridgeRenderSession.render(BridgeRenderSession.java:120)
    at com.android.ide.common.rendering.api.RenderSession.render(RenderSession.java:151)
    at com.android.ide.common.rendering.api.RenderSession.render(RenderSession.java:133)
    at com.android.tools.idea.rendering.RenderTask.lambda$null$8(RenderTask.java:755)
    at java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1590)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
</code>```

MainActivity :

```<code>package fr.aurelien.test_dessin_android;

import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.add(R.id.frameLayout, new SimpleFragment());
        fragmentTransaction.commit();
    }
}
</code>```

Fragment class :

```<code>package fr.aurelien.test_dessin_android;

import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class SimpleFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View retView = inflater.inflate(R.layout.fragment_layout, container, false);
        return retView;
    }
}
</code>```

Manifest.xml :

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="fr.aurelien.test_dessin_android">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme.default">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

XML code :

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="70dp"
        android:layout_marginTop="16dp"
        android:text="TextView"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="55dp"
        android:layout_marginTop="31dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        app:srcCompat="@mipmap/ic_launcher" />

    <Button
        android:id="@+id/button5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="Button"
        app:layout_constraintTop_toTopOf="parent"
        tools:layout_editor_absoluteX="189dp" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

答:
If you want to use material components you need to change your default theme in styles.xml from Theme.AppCompat to Theme.MaterialComponents.
Don't forget to add this
 implementation 'com.google.android.material:material:1.1.0' in your app level build.gradle

Body:
I'm on Android Studio 3.4, and using Material Design.
When I add a button to the layout i'm getting a java.lang.ClassCastException@11378fc8 and i can't use anymore the layout editor until I remove the button.

I have already tried to "invalidate/restart", to rebuild, to clean and build.

This is my tree structure :
Tree structure

Build.Gradle :

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "fr.aurelien.test_dessin_android"
        minSdkVersion 24
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.0.0-beta01'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0-beta01'
    implementation 'com.google.android.material:material:1.1.0-alpha06'
    implementation 'com.google.code.gson:gson:2.8.5'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.0-alpha4'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0-alpha4'
}

Class cast exception :

java.lang.IllegalArgumentException: java.lang.ClassCastException@126d0c4
    at sun.reflect.GeneratedMethodAccessor1380.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at android.animation.PropertyValuesHolder_Delegate.callMethod(PropertyValuesHolder_Delegate.java:108)
    at android.animation.PropertyValuesHolder_Delegate.nCallFloatMethod(PropertyValuesHolder_Delegate.java:143)
    at android.animation.PropertyValuesHolder.nCallFloatMethod(PropertyValuesHolder.java)
    at android.animation.PropertyValuesHolder.access$400(PropertyValuesHolder.java:38)
    at android.animation.PropertyValuesHolder$FloatPropertyValuesHolder.setAnimatedValue(PropertyValuesHolder.java:1387)
    at android.animation.ObjectAnimator.animateValue(ObjectAnimator.java:990)
    at android.animation.ValueAnimator.setCurrentFraction(ValueAnimator.java:674)
    at android.animation.ValueAnimator.start(ValueAnimator.java:1071)
    at android.animation.ValueAnimator.start(ValueAnimator.java:1088)
    at android.animation.ObjectAnimator.start(ObjectAnimator.java:852)
    at android.animation.ValueAnimator.startWithoutPulsing(ValueAnimator.java:1081)
    at android.animation.AnimatorSet.handleAnimationEvents(AnimatorSet.java:1142)
    at android.animation.AnimatorSet.doAnimationFrame(AnimatorSet.java:1046)
    at android.animation.AnimationHandler.doAnimationFrame(AnimationHandler.java:146)
    at android.animation.AnimationHandler.access$100(AnimationHandler.java:37)
    at android.animation.AnimationHandler$1.doFrame(AnimationHandler.java:54)
    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:947)
    at android.view.Choreographer.doCallbacks(Choreographer.java:761)
    at android.view.Choreographer_Delegate.doFrame(Choreographer_Delegate.java:66)
    at com.android.layoutlib.bridge.impl.RenderSessionImpl.renderAndBuildResult(RenderSessionImpl.java:563)
    at com.android.layoutlib.bridge.impl.RenderSessionImpl.render(RenderSessionImpl.java:425)
    at com.android.layoutlib.bridge.BridgeRenderSession.render(BridgeRenderSession.java:120)
    at com.android.ide.common.rendering.api.RenderSession.render(RenderSession.java:151)
    at com.android.ide.common.rendering.api.RenderSession.render(RenderSession.java:133)
    at com.android.tools.idea.rendering.RenderTask.lambda$null$8(RenderTask.java:755)
    at java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1590)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

MainActivity :

package fr.aurelien.test_dessin_android;

import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.add(R.id.frameLayout, new SimpleFragment());
        fragmentTransaction.commit();
    }
}

Fragment class :

package fr.aurelien.test_dessin_android;

import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class SimpleFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View retView = inflater.inflate(R.layout.fragment_layout, container, false);
        return retView;
    }
}

Manifest.xml :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="fr.aurelien.test_dessin_android">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme.default">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

XML code :

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="70dp"
        android:layout_marginTop="16dp"
        android:text="TextView"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="55dp"
        android:layout_marginTop="31dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        app:srcCompat="@mipmap/ic_launcher" />

    <Button
        android:id="@+id/button5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="Button"
        app:layout_constraintTop_toTopOf="parent"
        tools:layout_editor_absoluteX="189dp" />

</androidx.constraintlayout.widget.ConstraintLayout>


问:
Laravel 5: Enable laravel-debugbar
I'm using Laravel 5 and would like to use the barryvdh/laravel-debugbar. After the installation and configuration the bar is not showing.

I did the following:

Installation:

```<code>composer require barryvdh/laravel-debugbar
</code>```

Add the following lines to the config/app.php

```<code>'Barryvdh\Debugbar\ServiceProvider',

'Debugbar' => 'Barryvdh\Debugbar\Facade',
</code>```

Further I execute:

```<code>php artisan vendor:publish
</code>```

which generates the debugbar.php file within the config folder.

Any ideas what could be missing?

Thank you

UPDATE:

I made a fresh Laravel 5 installation and installed the debugbar which works perfectly and showed my the debugbar. After executing the artisan commands:

```<code> php artisan cache:clear
</code>```

and

```<code> php artisan config:cache
</code>```

the debugbar is not visible anymore. I think this was also my problem of the previous question. Any ideas why this happens and how I can make the debugbar revisible?Thank you

答:
to add debugger in your code
step 1

composer require barryvdh/laravel-debugbar --dev

inside config/app.php

Barryvdh\Debugbar\ServiceProvider::class,

'Debugbar' => Barryvdh\Debugbar\Facade::class,

at last run this command

php artisan vendor:publish --provider="Barryvdh\Debugbar\ServiceProvider"

Title: Laravel 5: Enable laravel-debugbar

Body:
I'm using Laravel 5 and would like to use the barryvdh/laravel-debugbar. After the installation and configuration the bar is not showing.

I did the following:

Installation:

composer require barryvdh/laravel-debugbar

Add the following lines to the config/app.php

'Barryvdh\Debugbar\ServiceProvider',

'Debugbar' => 'Barryvdh\Debugbar\Facade',

Further I execute:

php artisan vendor:publish

which generates the debugbar.php file within the config folder.

Any ideas what could be missing?

Thank you

UPDATE:

I made a fresh Laravel 5 installation and installed the debugbar which works perfectly and showed my the debugbar. After executing the artisan commands:

 php artisan cache:clear

and

 php artisan config:cache

the debugbar is not visible anymore. I think this was also my problem of the previous question. Any ideas why this happens and how I can make the debugbar revisible?Thank you


问:
Make the layout below button
In one of my fragment class, it has two buttons (A and B) on top, used to switch to another fragment when clicked using viewPager.

When buttonA is clicked, it should switch to page A and so on.

When I click button A, how can I make the text in A show below the two buttons?

fragment_menu.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/buttonA"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="15dp"
        android:layout_marginTop="10dp"
        android:padding="15dp"
        android:text="ButtonA"
        android:textSize="12sp" />

    <Button
        android:id="@+id/buttonB"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_marginLeft="15dp"
        android:layout_marginTop="10dp"
        android:layout_marginRight="15dp"
        android:layout_toRightOf="@+id/buttonB"
        android:backgroundTint="@color/materialGrey600"
        android:padding="15dp"
        android:text="ButtonB"
        android:textSize="12sp" />

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>
</code>```

MenuFragment

```<code>public class MenuFragment extends BaseFragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_menu, container, false);
        final ViewPager viewPager = (ViewPager) v.findViewById(R.id.pager);
        viewPager.setAdapter(new ViewPagerAdapter(getActivity().getFragmentManager()));

        Button btnA = (Button) v.findViewById(R.id.buttonA);
        Button btnB = (Button) v.findViewById(R.id.buttonB);

        btnA.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                viewPager.setCurrentItem(0, true);
            }
        });

        btnB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                viewPager.setCurrentItem(1, true);
            }
        });
        return v;
    }
}
</code>```

ViewPagerAdapter

```<code>  public class ViewPagerAdapter extends FragmentPagerAdapter {

        public ViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position)
            {
                case 0:
                    return new A()
                case 1:
                    return new B()

            }
            return null;
        }

        @Override
        public int getCount() {
            return 2;
        }
    }
</code>```

Output

答:
Since you are using Relative Layout you can add layout_below </p>

```<code> <androidx.viewpager.widget.ViewPager
    android:layout_below="@id/buttonB"
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
</code>```

Title: Make the layout below button

Body:
In one of my fragment class, it has two buttons (A and B) on top, used to switch to another fragment when clicked using viewPager.

When buttonA is clicked, it should switch to page A and so on.

When I click button A, how can I make the text in A show below the two buttons?

fragment_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/buttonA"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="15dp"
        android:layout_marginTop="10dp"
        android:padding="15dp"
        android:text="ButtonA"
        android:textSize="12sp" />

    <Button
        android:id="@+id/buttonB"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_marginLeft="15dp"
        android:layout_marginTop="10dp"
        android:layout_marginRight="15dp"
        android:layout_toRightOf="@+id/buttonB"
        android:backgroundTint="@color/materialGrey600"
        android:padding="15dp"
        android:text="ButtonB"
        android:textSize="12sp" />

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

MenuFragment

public class MenuFragment extends BaseFragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_menu, container, false);
        final ViewPager viewPager = (ViewPager) v.findViewById(R.id.pager);
        viewPager.setAdapter(new ViewPagerAdapter(getActivity().getFragmentManager()));

        Button btnA = (Button) v.findViewById(R.id.buttonA);
        Button btnB = (Button) v.findViewById(R.id.buttonB);

        btnA.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                viewPager.setCurrentItem(0, true);
            }
        });

        btnB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                viewPager.setCurrentItem(1, true);
            }
        });
        return v;
    }
}

ViewPagerAdapter

  public class ViewPagerAdapter extends FragmentPagerAdapter {

        public ViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position)
            {
                case 0:
                    return new A()
                case 1:
                    return new B()

            }
            return null;
        }

        @Override
        public int getCount() {
            return 2;
        }
    }

Output

Body:
Since you are using Relative Layout you can add layout_below

 <androidx.viewpager.widget.ViewPager
    android:layout_below="@id/buttonB"
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />


问:
How to convert timestamp date to java.util date(yyyy-mm-dd) in java
I am getting date from Oracle is in Timestamp but I need to convert it in to this format 2020-02-17 (yyyy-mm-dd) format, but currently in postman I am receiving date as "2020-02-17T09:40:37.850+0000" in this format.

Any help on this would be really appreciated

答:
That question is answered here

And what you want exactly, to display the date with that format or save with that format.

If you want display the date with (yyyy-mm-dd)

```<code>String dateFormated = new SimpleDateFormat("yyyy-MM-dd").format(myTimestamp);
System.out.println(dateFormated);
</code>```

If you want save the date with that format you can try to do this:

```<code>try {
     SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd);
     String dateFormated = dateFormat.format(myTimestamp);
     Date parsedDate = dateFormat.parse(dateFormated);
     Timestamp timestamp = new java.sql.Timestamp(parsedDate.getTime());
} catch(Exception e) {

}
</code>```

Body:
That question is answered here

And what you want exactly, to display the date with that format or save with that format.

If you want display the date with (yyyy-mm-dd)

String dateFormated = new SimpleDateFormat("yyyy-MM-dd").format(myTimestamp);
System.out.println(dateFormated);

If you want save the date with that format you can try to do this:

try {
     SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd);
     String dateFormated = dateFormat.format(myTimestamp);
     Date parsedDate = dateFormat.parse(dateFormated);
     Timestamp timestamp = new java.sql.Timestamp(parsedDate.getTime());
} catch(Exception e) {

}


答:
you are doing it wrong, You cannot align a button to itself. That's why your buttons are not working properly. In your button B do this:

```<code> android:layout_toRightOf="@+id/buttonA"
</code>```

instead of this:

```<code> android:layout_toRightOf="@+id/buttonB"
</code>```

And to your viewPager add "android:layout_below:"

```<code> <androidx.viewpager.widget.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/buttonA" />
</code>```

Title: Make the layout below button

Body:
you are doing it wrong, You cannot align a button to itself. That's why your buttons are not working properly. In your button B do this:

 android:layout_toRightOf="@+id/buttonA"

instead of this:

 android:layout_toRightOf="@+id/buttonB"

And to your viewPager add "android:layout_below:"

 <androidx.viewpager.widget.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/buttonA" />


答:
You have syntax error in your view fil. In your {{ }} brackets you are writing assignment and then missing semicolon there.

You can write this logic without leaving first @php tags.

```<code>
@php
    $date = new DateTime($i->EindDatum);
    $now = new DateTime();

    if($date < $now)  echo  'past current date';

    if ($date < $now) {
        $user = App\User::find(1);
        $user->notify(new App\Notifications\TaksComplete);
    }
@endphp
</code>```

Title: Laravel How to call a function with a if else

Body:
You have syntax error in your view fil. In your {{ }} brackets you are writing assignment and then missing semicolon there.

You can write this logic without leaving first @php tags.

@php
    $date = new DateTime($i->EindDatum);
    $now = new DateTime();

    if($date < $now)  echo  'past current date';

    if ($date < $now) {
        $user = App\User::find(1);
        $user->notify(new App\Notifications\TaksComplete);
    }
@endphp


问:
how to add nested object with new object
Actually, I want to add hats object to clothing object, i don't want to change object to array of object.
Can anyone help me how to add hats in my scenario.</p>

```<code>const clothing = {
shirts:{
id: 1,
title: 'shirts' ,
item: [
  {
    id: 01,
    name:'plain shirt',
  },
  {
    id: 02,
    name: 'stripe shirt',
  },
 ],
},

tshirt: {
id: 2,
title: 't-shirt',
item: [
  {
    id: 03,
    name: 'plain t-shirt',
  },
  {
    id: 04,
    name: 'stripe t-shirt',
   }
  ],
 },
}

const newClothing = {...clothing};
newClothing[{hats:{id:3, title:'hats', item:[{id:05, name:'blue hats'}]}}];

console.log(newClothing.hats);
</code>```

答:
This is the simplest way you can do it:</p>

```<code>const newClothing = {...clothing, hats: { ...your hats object here } };
</code>```

Body:
Actually, I want to add hats object to clothing object, i don't want to change object to array of object.
Can anyone help me how to add hats in my scenario.

const clothing = {
shirts:{
id: 1,
title: 'shirts' ,
item: [
  {
    id: 01,
    name:'plain shirt',
  },
  {
    id: 02,
    name: 'stripe shirt',
  },
 ],
},

tshirt: {
id: 2,
title: 't-shirt',
item: [
  {
    id: 03,
    name: 'plain t-shirt',
  },
  {
    id: 04,
    name: 'stripe t-shirt',
   }
  ],
 },
}

const newClothing = {...clothing};
newClothing[{hats:{id:3, title:'hats', item:[{id:05, name:'blue hats'}]}}];

console.log(newClothing.hats);

Body:
This is the simplest way you can do it:

const newClothing = {...clothing, hats: { ...your hats object here } };