问:
vscode snippets: How to link a position in the snippet to a tabstop?
I want to create a snippet that prints the value of a variable for debugging purposes. this is what I came up with:

{
  "Debug": {
    "prefix": ["db"],
    "body": ["console.log(\"$1 :\", $1)"]
  }
}
```
<p>When I use this snippet cursor goes between the quotes ( | is the cursor position):</p>
<pre class="lang-js prettyprint-override"><code>console.log("| :",)
</code>```

And after I typed the name of a variable it copies the name to the second parameter:

console.log("name :", name)
```
<p>But I can't use autocompletion in strings. sometimes the variable is an object and auto-completion helps me pick a specific key of the object. I want the cursor to stop in the second parameter so I can use autocompletion:</p>
<pre class="lang-js prettyprint-override"><code>console.log(" :", |)
</code>```

And whatever I type should be copied inside the double-quotes:

console.log("name :", name)
```

just like the previous example but backward.

How can I do that?

UPDATE:
I created an issue: https://github.com/microsoft/vscode/issues/142327

答:
I tried with the following version:

```<code>{
  "Debug": {
    "prefix": ["db"],
    "body": ["console.log(\"${2:$1} :\", $1);$0"]
  }
}
</code>```

It starts at $1, but immediately also shows the text for $2, with TAB I can change the text between double quotes but I do not get auto-completion for $1.

I think this should be asked in an issue on the repo. $2 should copy text of $1 after the TAB and $1 should have auto-completion like it does when using

```<code>{
  "Debug": {
    "prefix": ["db"],
    "body": ["console.log(\"$2 :\", $1);$0"]
  }
}
</code>```

Body:
I want to create a snippet that prints the value of a variable for debugging purposes. this is what I came up with:

{
  "Debug": {
    "prefix": ["db"],
    "body": ["console.log(\"$1 :\", $1)"]
  }
}

When I use this snippet cursor goes between the quotes ( | is the cursor position):

console.log("| :",)

And after I typed the name of a variable it copies the name to the second parameter:

console.log("name :", name)

But I can't use autocompletion in strings. sometimes the variable is an object and auto-completion helps me pick a specific key of the object. I want the cursor to stop in the second parameter so I can use autocompletion:

console.log(" :", |)

And whatever I type should be copied inside the double-quotes:

console.log("name :", name)

just like the previous example but backward.

How can I do that?

UPDATE:
I created an issue: https://github.com/microsoft/vscode/issues/142327

Body:
I tried with the following version:

{
  "Debug": {
    "prefix": ["db"],
    "body": ["console.log(\"${2:$1} :\", $1);$0"]
  }
}

It starts at $1, but immediately also shows the text for $2, with TAB I can change the text between double quotes but I do not get auto-completion for $1.

I think this should be asked in an issue on the repo. $2 should copy text of $1 after the TAB and $1 should have auto-completion like it does when using

{
  "Debug": {
    "prefix": ["db"],
    "body": ["console.log(\"$2 :\", $1);$0"]
  }
}


来源: stackexchange

问:
SwiftUI ScrollView stops working in ZStack under Rectangle with gradient
I'm having this issue where when I put a rectangle over a ScrollView with a gradient fill the scrollview stops reacting to touch.

The aim is to fade out items at the bottom of the scrollview so they don't clash with a custom bottom navigation view in the parent view.

I've tried to use a .frame modifier to make the fades height only the bottom quarter or so to hopefully stop blocking the scrollview but it didnt work.

Does anyone know a way around this?

```<code>import Foundation
import SwiftUI
import CoreData

struct TestView: View {

    var managedObjectContext:NSManagedObjectContext
    var spendings:FetchedResults<Spending>
    var expenses:FetchedResults<Expense>
    var settings:FetchedResults<Settings>
    @State private var showAddSpending:Bool = false

       @Binding var selection:Int

    var body: some View{
        VStack{
            HStack{
                Text("Spending").padding()

            }.padding(.horizontal)

            ZStack{

                //List items
                ScrollView{
                    ForEach(self.spendings) { spend in
                        //if(spend.currentMonth == true){
                        HStack{
                            // IS EXPANDED
                            if spend.isExpanded {

                                VStack{

                                    HStack{
                                        //NAME
                                        if(spend.currentMonth){
                                            Text("\(spend.name)")
                                                .lineLimit(1)
                                                .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
                                                .foregroundColor(Color .orange)
                                                .onLongPressGesture {
                                                    spend.currentMonth.toggle()
                                            }
                                        } else {

                                            Text("\(spend.name)")
                                                .lineLimit(1)
                                                .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
                                                .onLongPressGesture {
                                                    spend.currentMonth.toggle()
                                            }
                                        }

                                        //AMOUNT
                                        Text("\(spend.amount)")

                                            .frame(minWidth: 0, maxWidth: 70, alignment: .trailing)

                                        //DELETE
                                        DeleteStyle(text: "multiply", symbol: true)
                                            .onTapGesture {
                                                self.managedObjectContext.delete(spend)
                                                do {
                                                    try self.managedObjectContext.save()
                                                }catch{
                                                    print(error)
                                                }
                                        }
                                    }
                                    VStack{

                                        //CATEGORY
                                        Text("Category: \(spend.category)")

                                            .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)

                                    }
                                }

                                .onTapGesture {
                                    spend.isExpanded.toggle()
                                }

                            } else {

                                // ISNT EXPANDED
                                HStack{
                                    //NAME
                                    if(spend.currentMonth){
                                        Text("\(spend.name)")
                                            .lineLimit(1)
                                            .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
                                            .foregroundColor(Color .orange)
                                            .onLongPressGesture {
                                                spend.currentMonth.toggle()
                                        }
                                    } else {

                                        Text("\(spend.name)")
                                            .lineLimit(1)
                                            .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
                                            .onLongPressGesture {
                                                spend.currentMonth.toggle()
                                        }

                                    }

                                    Spacer()

                                    //AMOUNT
                                    Text("\(spend.amount)")

                                        .frame(minWidth: 0, maxWidth: 70, alignment: .trailing)

                                    //DELETE
                                    DeleteStyle(text: "multiply", symbol: true).onTapGesture {
                                        self.managedObjectContext.delete(spend)
                                        do {
                                            try self.managedObjectContext.save()
                                        }catch{
                                            print(error)
                                        }
                                    }
                                }

                                .onTapGesture {
                                    spend.isExpanded.toggle()
                                }

                            }
                        }
                    }
                    .foregroundColor(Color (UIColor .secondaryLabel))
                }.padding(.horizontal)

                //Button to add new item
                VStack{
                    Spacer()
                    HStack{
                        Spacer()
                        /*
                         Text("Total: £\(calculateTotalSpendingForCurrentMonth())")
                         .foregroundColor(.white)
                         .padding(15)
                         .background(Color .orange)
                         .cornerRadius(40)
                         */
                        if spendings.isEmpty {
                            HStack{
                                Text("Record a spend")
                                Image(systemName: "arrow.right")
                            }
                            .foregroundColor(Color (UIColor .secondaryLabel))
                            .padding(.bottom, 90)
                            .padding(.horizontal, 40)
                        }
                        VStack{
                            Button(action: {
                                self.showAddSpending = true
                            }) {
                                NavStyle(text: "plus", symbol: true)

                            }.sheet(isPresented: $showAddSpending) {
                                AddSpendingView(managedObjectContext: self.managedObjectContext, spendings: self.spendings, expenses: self.expenses)
                            }

                        }

                    }

                }

                //Black Fade at bottom
                VStack{
                    Spacer()
                    Rectangle()
                        .fill (
                            LinearGradient(gradient: Gradient(colors: [.clear, .black]),
                                           startPoint: .center, endPoint: .bottom)
                    )
                }
            }
        }.background(Color (UIColor.secondarySystemBackground))
    }
}
</code>```

答:
I'm doing something similar on a watch app, .overlaying a text field over a Slider. I couldn't get either .disable or .allowHitTesting to work when applied to the Text field.

To solve this, I found that placing the Text field in a Group{} (all by itself) and then applying the .allowHitTesting(false) worked perfectly. I guess Group is a replacement for the suggested OverlayWrapper.

ContentLicense: CC BY-SA 4.0

Body:
I'm having this issue where when I put a rectangle over a ScrollView with a gradient fill the scrollview stops reacting to touch.

The aim is to fade out items at the bottom of the scrollview so they don't clash with a custom bottom navigation view in the parent view.

I've tried to use a .frame modifier to make the fades height only the bottom quarter or so to hopefully stop blocking the scrollview but it didnt work.

Does anyone know a way around this?

import Foundation
import SwiftUI
import CoreData

struct TestView: View {

    var managedObjectContext:NSManagedObjectContext
    var spendings:FetchedResults<Spending>
    var expenses:FetchedResults<Expense>
    var settings:FetchedResults<Settings>
    @State private var showAddSpending:Bool = false

       @Binding var selection:Int

    var body: some View{
        VStack{
            HStack{
                Text("Spending").padding()

            }.padding(.horizontal)

            ZStack{

                //List items
                ScrollView{
                    ForEach(self.spendings) { spend in
                        //if(spend.currentMonth == true){
                        HStack{
                            // IS EXPANDED
                            if spend.isExpanded {

                                VStack{

                                    HStack{
                                        //NAME
                                        if(spend.currentMonth){
                                            Text("\(spend.name)")
                                                .lineLimit(1)
                                                .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
                                                .foregroundColor(Color .orange)
                                                .onLongPressGesture {
                                                    spend.currentMonth.toggle()
                                            }
                                        } else {

                                            Text("\(spend.name)")
                                                .lineLimit(1)
                                                .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
                                                .onLongPressGesture {
                                                    spend.currentMonth.toggle()
                                            }
                                        }

                                        //AMOUNT
                                        Text("\(spend.amount)")

                                            .frame(minWidth: 0, maxWidth: 70, alignment: .trailing)

                                        //DELETE
                                        DeleteStyle(text: "multiply", symbol: true)
                                            .onTapGesture {
                                                self.managedObjectContext.delete(spend)
                                                do {
                                                    try self.managedObjectContext.save()
                                                }catch{
                                                    print(error)
                                                }
                                        }
                                    }
                                    VStack{

                                        //CATEGORY
                                        Text("Category: \(spend.category)")

                                            .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)

                                    }
                                }

                                .onTapGesture {
                                    spend.isExpanded.toggle()
                                }

                            } else {

                                // ISNT EXPANDED
                                HStack{
                                    //NAME
                                    if(spend.currentMonth){
                                        Text("\(spend.name)")
                                            .lineLimit(1)
                                            .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
                                            .foregroundColor(Color .orange)
                                            .onLongPressGesture {
                                                spend.currentMonth.toggle()
                                        }
                                    } else {

                                        Text("\(spend.name)")
                                            .lineLimit(1)
                                            .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
                                            .onLongPressGesture {
                                                spend.currentMonth.toggle()
                                        }

                                    }

                                    Spacer()

                                    //AMOUNT
                                    Text("\(spend.amount)")

                                        .frame(minWidth: 0, maxWidth: 70, alignment: .trailing)

                                    //DELETE
                                    DeleteStyle(text: "multiply", symbol: true).onTapGesture {
                                        self.managedObjectContext.delete(spend)
                                        do {
                                            try self.managedObjectContext.save()
                                        }catch{
                                            print(error)
                                        }
                                    }
                                }

                                .onTapGesture {
                                    spend.isExpanded.toggle()
                                }

                            }
                        }
                    }
                    .foregroundColor(Color (UIColor .secondaryLabel))
                }.padding(.horizontal)

                //Button to add new item
                VStack{
                    Spacer()
                    HStack{
                        Spacer()
                        /*
                         Text("Total: £\(calculateTotalSpendingForCurrentMonth())")
                         .foregroundColor(.white)
                         .padding(15)
                         .background(Color .orange)
                         .cornerRadius(40)
                         */
                        if spendings.isEmpty {
                            HStack{
                                Text("Record a spend")
                                Image(systemName: "arrow.right")
                            }
                            .foregroundColor(Color (UIColor .secondaryLabel))
                            .padding(.bottom, 90)
                            .padding(.horizontal, 40)
                        }
                        VStack{
                            Button(action: {
                                self.showAddSpending = true
                            }) {
                                NavStyle(text: "plus", symbol: true)

                            }.sheet(isPresented: $showAddSpending) {
                                AddSpendingView(managedObjectContext: self.managedObjectContext, spendings: self.spendings, expenses: self.expenses)
                            }

                        }

                    }

                }

                //Black Fade at bottom
                VStack{
                    Spacer()
                    Rectangle()
                        .fill (
                            LinearGradient(gradient: Gradient(colors: [.clear, .black]),
                                           startPoint: .center, endPoint: .bottom)
                    )
                }
            }
        }.background(Color (UIColor.secondarySystemBackground))
    }
}


问:
Limited number of break lines in text in PHP
Assume a string is like

```<code>Section 1

Section 2 (after 1 line break)

Section 3 (after 2 line breaks)

Section 4 (after 4 line breaks)

Section 5 (after 1 line break)

</code>```

My intention is to only allow N number of breaks and replace the other ones with SPACE in PHP. For example, if N=3 then the text above would be outputed like:

```<code>Section 1

Section 2 (after 1 line break)

Section 3 (after 2 line breaks) Section 4 (after 4 line breaks) Section 5 (after 1 line break)
</code>```

My code is below but I am looking for a better way:

```<code>function limitedBreaks($str = '', $n = 5)
{
    $str = nl2br($str);
    $chars = str_split($str);
    $counter = 0;
    foreach ($chars as $key => $char) {
        if ($char == "<br/>")
            if ($counter > $n) {
                $chars[$key] = ' ';
            } else {
                $counter += 1;
            }
    }

    return implode($chars, ' ');

}
</code>```

答:
Your example with N=3 shows either 4 line breaks – if the empty lines count –, or 2 line breaks.

To make things clearer this is a function limitedLines, which reduces the text to a specific amount of lines:

```<code>$str = "
line 1
line 2
line 3
line 4
line 5
line 6
";

function limitedLines(string $str = '', int $maxLines = 5): string {
  $maxLines = $maxLines < 1 ? 1 : $maxLines;
  $arr = explode("\n", trim($str));
  while (count($arr) > $maxLines) {
    $last = array_pop($arr);
    $arr[array_key_last($arr)] .= ' ' . trim($last);
  }
  return implode("\n", $arr);
}

$result = limitedLines($str, 3);

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

This will print:

```<code>line 1
line 2
line 3 line 4 line 5 line 6
</code>```

Body:
Assume a string is like

Section 1

Section 2 (after 1 line break)

Section 3 (after 2 line breaks)

Section 4 (after 4 line breaks)

Section 5 (after 1 line break)

My intention is to only allow N number of breaks and replace the other ones with SPACE in PHP. For example, if N=3 then the text above would be outputed like:

Section 1

Section 2 (after 1 line break)

Section 3 (after 2 line breaks) Section 4 (after 4 line breaks) Section 5 (after 1 line break)

My code is below but I am looking for a better way:

function limitedBreaks($str = '', $n = 5)
{
    $str = nl2br($str);
    $chars = str_split($str);
    $counter = 0;
    foreach ($chars as $key => $char) {
        if ($char == "
")
            if ($counter > $n) {
                $chars[$key] = ' ';
            } else {
                $counter += 1;
            }
    }

    return implode($chars, ' ');

}

Body:
Your example with N=3 shows either 4 line breaks – if the empty lines count –, or 2 line breaks.

To make things clearer this is a function limitedLines, which reduces the text to a specific amount of lines:

$str = "
line 1
line 2
line 3
line 4
line 5
line 6
";

function limitedLines(string $str = '', int $maxLines = 5): string {
  $maxLines = $maxLines < 1 ? 1 : $maxLines;
  $arr = explode("\n", trim($str));
  while (count($arr) > $maxLines) {
    $last = array_pop($arr);
    $arr[array_key_last($arr)] .= ' ' . trim($last);
  }
  return implode("\n", $arr);
}

$result = limitedLines($str, 3);

print_r($result);

This will print:

line 1
line 2
line 3 line 4 line 5 line 6


问:
Delete json block with jq command
I have json file with multiple domains which is formated as is showed below. How can I delete whole blocks with domains? For example if I will want to delete whole block in json for domain domain.tld?

I tryed this, but output is error:

```<code>jq '."http-01"."domain"[]."main"="domain.tld"' acme.json
jq: error (at acme.json:11483): Cannot iterate over null (null)
</code>```

formating example file:

```<code>    {
  "http-01": {
    "Account": {
      "Email": "mail@placeholder.tld",
      "Registration": {
        "body": {
          "status": "valid",
          "contact": [
            "mailto:mail@placeholder.tld"
          ]
        },
        "uri": "https://acme-v02.api.letsencrypt.org/acme/acct/110801506"
      },
      "PrivateKey": "main_priv_key_string",
      "KeyType": "4096"
    },
    "Certificates": [
      {
        "domain": {
          "main": "www.some_domain.tld"
        },
        "certificate": "cert_string",
        "key": "key_string",
        "Store": "default"
      },
      {
        "domain": {
          "main": "some_domain.tld"
        },
        "certificate": "cert_string",
        "key": "key_string",
        "Store": "default"
      },
      {
        "domain": {
          "main": "www.some_domain2.tld"
        },
        "certificate": "cert_string",
        "key": "key_string",
        "Store": "default"
      },
      {
        "domain": {
          "main": "some_domain2.tld"
        },
        "certificate": "cert_string",
        "key": "key_string",
        "Store": "default"
      }
    ]
  }
}
</code>```

答:
Your question is quite broad. What is a "block"?

Let's assume you want to delete from within the object under http-01 each field that is of type array and has at index 0 an object satisfying .domain.main == "domain.tld". Then first navigate to where you want to delete from, and update it (|=) using del and select which performs the filtered deletion.

jq '
  ."http-01" |= del(
    .[] | select(arrays[0] | objects.domain.main == "domain.tld")
  )
' acme.json
```
<pre class="lang-json prettyprint-override"><code>{
  "http-01": {
    "Account": {
      "Email": "email@domain.tld",
      "Registration": {
        "body": {
          "status": "valid",
          "contact": [
            "mailto:email@domain.tld"
          ]
        },
        "uri": "https://acme-v02.api.letsencrypt.org/acme/acct/110801506"
      },
      "PrivateKey": "long_key_string",
      "KeyType": "4096"
    }
  }
}
</code>```

Demo

If your "block" is deeper, go deeper before updating. If it is higher, the whole document for instance, there's no need to update, just start with del.

Title: Delete json block with jq command

Body:
I have json file with multiple domains which is formated as is showed below. How can I delete whole blocks with domains? For example if I will want to delete whole block in json for domain domain.tld?

I tryed this, but output is error:

jq '."http-01"."domain"[]."main"="domain.tld"' acme.json
jq: error (at acme.json:11483): Cannot iterate over null (null)

formating example file:

    {
  "http-01": {
    "Account": {
      "Email": "mail@placeholder.tld",
      "Registration": {
        "body": {
          "status": "valid",
          "contact": [
            "mailto:mail@placeholder.tld"
          ]
        },
        "uri": "https://acme-v02.api.letsencrypt.org/acme/acct/110801506"
      },
      "PrivateKey": "main_priv_key_string",
      "KeyType": "4096"
    },
    "Certificates": [
      {
        "domain": {
          "main": "www.some_domain.tld"
        },
        "certificate": "cert_string",
        "key": "key_string",
        "Store": "default"
      },
      {
        "domain": {
          "main": "some_domain.tld"
        },
        "certificate": "cert_string",
        "key": "key_string",
        "Store": "default"
      },
      {
        "domain": {
          "main": "www.some_domain2.tld"
        },
        "certificate": "cert_string",
        "key": "key_string",
        "Store": "default"
      },
      {
        "domain": {
          "main": "some_domain2.tld"
        },
        "certificate": "cert_string",
        "key": "key_string",
        "Store": "default"
      }
    ]
  }
}

Body:
Your question is quite broad. What is a "block"?

Let's assume you want to delete from within the object under http-01 each field that is of type array and has at index 0 an object satisfying .domain.main == "domain.tld". Then first navigate to where you want to delete from, and update it (|=) using del and select which performs the filtered deletion.

jq '
  ."http-01" |= del(
    .[] | select(arrays[0] | objects.domain.main == "domain.tld")
  )
' acme.json

{
  "http-01": {
    "Account": {
      "Email": "email@domain.tld",
      "Registration": {
        "body": {
          "status": "valid",
          "contact": [
            "mailto:email@domain.tld"
          ]
        },
        "uri": "https://acme-v02.api.letsencrypt.org/acme/acct/110801506"
      },
      "PrivateKey": "long_key_string",
      "KeyType": "4096"
    }
  }
}

Demo

If your "block" is deeper, go deeper before updating. If it is higher, the whole document for instance, there's no need to update, just start with del.


问:
Problem with BasicTextField in Jetpack Compose on Wear OS
I'm new in Compose and I'm having a problem with input text field on Wear OS.
The problem is that I can't get soft keyboard to work as it usually does on Android. Also, when I tried to implement the same layout in XML - it worked.
So, when I tap on input text field the keyboard pops up and then hides. When I tap again - keyboard pops up and stays open, but if I try to enter any text - nothing appears in the input field (on the keyboard itself), although entered text is passing down to input text field on UI.

Here is what I get in logs on emulator when I tap on input text field to open the keyboard:

```<code>2021-11-24 09:44:36.569 W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
2021-11-24 09:44:36.571 W/IInputConnectionWrapper: getTextAfterCursor on inactive InputConnection
2021-11-24 09:44:36.649 W/RecordingIC: requestCursorUpdates is not supported
</code>```

Here is what I get on real device:

```<code>2021-11-24 09:35:39.783 W/IInputConnectionWrapper: getExtractedText on inactive InputConnection
2021-11-24 09:35:39.872 W/IInputConnectionWrapper: beginBatchEdit on inactive InputConnection
2021-11-24 09:35:39.873 W/IInputConnectionWrapper: endBatchEdit on inactive InputConnection
2021-11-24 09:35:39.873 W/IInputConnectionWrapper: setComposingRegion on inactive InputConnection
2021-11-24 09:35:39.873 W/IInputConnectionWrapper: beginBatchEdit on inactive InputConnection
2021-11-24 09:35:39.873 W/IInputConnectionWrapper: endBatchEdit on inactive InputConnection
2021-11-24 09:35:39.873 W/IInputConnectionWrapper: beginBatchEdit on inactive InputConnection
2021-11-24 09:35:39.873 W/IInputConnectionWrapper: endBatchEdit on inactive InputConnection
2021-11-24 09:35:39.873 W/IInputConnectionWrapper: getExtractedText on inactive InputConnection
2021-11-24 09:35:39.882 W/IInputConnectionWrapper: beginBatchEdit on inactive InputConnection
2021-11-24 09:35:39.883 W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
2021-11-24 09:35:39.884 W/IInputConnectionWrapper: getTextAfterCursor on inactive InputConnection
2021-11-24 09:35:39.888 W/IInputConnectionWrapper: getSelectedText on inactive InputConnection
2021-11-24 09:35:39.890 W/IInputConnectionWrapper: endBatchEdit on inactive InputConnection
2021-11-24 09:35:39.891 W/IInputConnectionWrapper: beginBatchEdit on inactive InputConnection
2021-11-24 09:35:39.891 W/IInputConnectionWrapper: endBatchEdit on inactive InputConnection
2021-11-24 09:35:39.891 W/IInputConnectionWrapper: beginBatchEdit on inactive InputConnection
2021-11-24 09:35:39.891 W/IInputConnectionWrapper: endBatchEdit on inactive InputConnection
</code>```

And here is my 'composable':

```<code>@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun ActivationScreen() {

    var key by remember { mutableStateOf("") }

    var isReady by remember {
        mutableStateOf(false)
    }

    Column(modifier = Modifier
        .padding(40.dp)
        .fillMaxSize()
    ) {
        val keyboardController = LocalSoftwareKeyboardController.current
        val focusRequester = FocusRequester()
        BasicTextField(
            value = key,
            onValueChange = {
                //isReady = it.length>11
                key = it
            },
            singleLine = true,
            keyboardOptions = KeyboardOptions.Default.copy(
                imeAction = ImeAction.Done
            ),
            keyboardActions = KeyboardActions(
                onDone = {
                    keyboardController?.hide()
                }
            ),
            modifier = Modifier
                .size(140.dp, 20.dp)
                .background(Color.White)
                .align(Alignment.CenterHorizontally)
                //.focusRequester(focusRequester)
                //.focusOrder(focusRequester)
        )

        Text(
            text = "ACTIVATION",
        )

        val status = if (isReady) "READY" else "NOT READY"
        Text(
            text = status,
        )
    }
}
</code>```

答:
Based on @Yuri Schimke's answer, here's a generic component implementation that accepts placeholder, value and onChange as attributes.

import android.app.RemoteInput
import android.content.Intent
import android.os.Bundle
import android.view.inputmethod.EditorInfo
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.wear.compose.material.Chip
import androidx.wear.compose.material.Text
import androidx.wear.input.RemoteInputIntentHelper
import androidx.wear.input.wearableExtender

@Composable
fun TextInput(
  placeholder: String,
  value: String?,
  onChange: (value: String) -> Unit,
) {
  val launcher =
    rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) {
      it.data?.let { data ->
        val results: Bundle = RemoteInput.getResultsFromIntent(data)
        val newValue: CharSequence? = results.getCharSequence(placeholder)
        onChange(newValue as String)
      }
    }
  Column() {
    Chip(
      label = { Text(if (value == null || value.isEmpty()) placeholder else value) },
      onClick = {
        val intent: Intent = RemoteInputIntentHelper.createActionRemoteInputIntent();
        val remoteInputs: List<RemoteInput> = listOf(
          RemoteInput.Builder(placeholder)
            .setLabel(placeholder)
            .wearableExtender {
              setEmojisAllowed(false)
              setInputActionType(EditorInfo.IME_ACTION_DONE)
            }.build()
        )

        RemoteInputIntentHelper.putRemoteInputsExtra(intent, remoteInputs)

        launcher.launch(intent)
      }
    )
  }
}
```

Attention: this requires androidx.wear:wear-input:1.2.0+

Body:
I'm new in Compose and I'm having a problem with input text field on Wear OS.
The problem is that I can't get soft keyboard to work as it usually does on Android. Also, when I tried to implement the same layout in XML - it worked.
So, when I tap on input text field the keyboard pops up and then hides. When I tap again - keyboard pops up and stays open, but if I try to enter any text - nothing appears in the input field (on the keyboard itself), although entered text is passing down to input text field on UI.

Here is what I get in logs on emulator when I tap on input text field to open the keyboard:

2021-11-24 09:44:36.569 W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
2021-11-24 09:44:36.571 W/IInputConnectionWrapper: getTextAfterCursor on inactive InputConnection
2021-11-24 09:44:36.649 W/RecordingIC: requestCursorUpdates is not supported

Here is what I get on real device:

2021-11-24 09:35:39.783 W/IInputConnectionWrapper: getExtractedText on inactive InputConnection
2021-11-24 09:35:39.872 W/IInputConnectionWrapper: beginBatchEdit on inactive InputConnection
2021-11-24 09:35:39.873 W/IInputConnectionWrapper: endBatchEdit on inactive InputConnection
2021-11-24 09:35:39.873 W/IInputConnectionWrapper: setComposingRegion on inactive InputConnection
2021-11-24 09:35:39.873 W/IInputConnectionWrapper: beginBatchEdit on inactive InputConnection
2021-11-24 09:35:39.873 W/IInputConnectionWrapper: endBatchEdit on inactive InputConnection
2021-11-24 09:35:39.873 W/IInputConnectionWrapper: beginBatchEdit on inactive InputConnection
2021-11-24 09:35:39.873 W/IInputConnectionWrapper: endBatchEdit on inactive InputConnection
2021-11-24 09:35:39.873 W/IInputConnectionWrapper: getExtractedText on inactive InputConnection
2021-11-24 09:35:39.882 W/IInputConnectionWrapper: beginBatchEdit on inactive InputConnection
2021-11-24 09:35:39.883 W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
2021-11-24 09:35:39.884 W/IInputConnectionWrapper: getTextAfterCursor on inactive InputConnection
2021-11-24 09:35:39.888 W/IInputConnectionWrapper: getSelectedText on inactive InputConnection
2021-11-24 09:35:39.890 W/IInputConnectionWrapper: endBatchEdit on inactive InputConnection
2021-11-24 09:35:39.891 W/IInputConnectionWrapper: beginBatchEdit on inactive InputConnection
2021-11-24 09:35:39.891 W/IInputConnectionWrapper: endBatchEdit on inactive InputConnection
2021-11-24 09:35:39.891 W/IInputConnectionWrapper: beginBatchEdit on inactive InputConnection
2021-11-24 09:35:39.891 W/IInputConnectionWrapper: endBatchEdit on inactive InputConnection

And here is my 'composable':

@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun ActivationScreen() {

    var key by remember { mutableStateOf("") }

    var isReady by remember {
        mutableStateOf(false)
    }

    Column(modifier = Modifier
        .padding(40.dp)
        .fillMaxSize()
    ) {
        val keyboardController = LocalSoftwareKeyboardController.current
        val focusRequester = FocusRequester()
        BasicTextField(
            value = key,
            onValueChange = {
                //isReady = it.length>11
                key = it
            },
            singleLine = true,
            keyboardOptions = KeyboardOptions.Default.copy(
                imeAction = ImeAction.Done
            ),
            keyboardActions = KeyboardActions(
                onDone = {
                    keyboardController?.hide()
                }
            ),
            modifier = Modifier
                .size(140.dp, 20.dp)
                .background(Color.White)
                .align(Alignment.CenterHorizontally)
                //.focusRequester(focusRequester)
                //.focusOrder(focusRequester)
        )

        Text(
            text = "ACTIVATION",
        )

        val status = if (isReady) "READY" else "NOT READY"
        Text(
            text = status,
        )
    }
}

Body:
Based on @Yuri Schimke's answer, here's a generic component implementation that accepts placeholder, value and onChange as attributes.

import android.app.RemoteInput
import android.content.Intent
import android.os.Bundle
import android.view.inputmethod.EditorInfo
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.wear.compose.material.Chip
import androidx.wear.compose.material.Text
import androidx.wear.input.RemoteInputIntentHelper
import androidx.wear.input.wearableExtender

@Composable
fun TextInput(
  placeholder: String,
  value: String?,
  onChange: (value: String) -> Unit,
) {
  val launcher =
    rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) {
      it.data?.let { data ->
        val results: Bundle = RemoteInput.getResultsFromIntent(data)
        val newValue: CharSequence? = results.getCharSequence(placeholder)
        onChange(newValue as String)
      }
    }
  Column() {
    Chip(
      label = { Text(if (value == null || value.isEmpty()) placeholder else value) },
      onClick = {
        val intent: Intent = RemoteInputIntentHelper.createActionRemoteInputIntent();
        val remoteInputs: List<RemoteInput> = listOf(
          RemoteInput.Builder(placeholder)
            .setLabel(placeholder)
            .wearableExtender {
              setEmojisAllowed(false)
              setInputActionType(EditorInfo.IME_ACTION_DONE)
            }.build()
        )

        RemoteInputIntentHelper.putRemoteInputsExtra(intent, remoteInputs)

        launcher.launch(intent)
      }
    )
  }
}

Attention: this requires androidx.wear:wear-input:1.2.0+


问:
MassTransit Mediator: Payload added by Send/Publish not found in ConsumeContext
I'm using MassTransit mediator to Send/Post messages to my consumers, however I'd like to get some metadata delivered to the consumers as a payload, i.e.

```<code>await mediator.Publish(message, ctx => ctx.GetOrAddPayload(() => metadata));
</code>```

I've looked into MassTransit's code and it seems the payloads from MessageSendContext<T> are not copied to MediatorReceiveContext<T>

So my question is if it is by design or it was somehow overlooked passing the payloads to MediatorReceiveContext<T> .ctor as it has a parameter params object[] payloads which might perfectly do the job.

答: This is by design, as coupling between the producer and consumer would introduce inconsistent expectations since payloads are not transferred between producers and consumers with buses. If you need to pass data to a consumer, it should be done using headers.</p>

Body:
I'm using MassTransit mediator to Send/Post messages to my consumers, however I'd like to get some metadata delivered to the consumers as a payload, i.e.

await mediator.Publish(message, ctx => ctx.GetOrAddPayload(() => metadata));

I've looked into MassTransit's code and it seems the payloads from MessageSendContext<T> are not copied to MediatorReceiveContext<T>

So my question is if it is by design or it was somehow overlooked passing the payloads to MediatorReceiveContext<T> .ctor as it has a parameter params object[] payloads which might perfectly do the job.


问:
Is it possible, 2 spread have 1 sheet to use farpoint spread
For example, 'A' spread and 'B' spread have same spread sheet(same design, and same formulars). So, if change the value in 'A' spread than change the same value in 'B' spread automatically. It is sure the same cell. Is it possible to simply?

Please, understand my english. Thank you.

答:
Use the CellChanged event.

```<code>fpSpread1.Sheets[SHEET_A].CellChanged += new FarPoint.Win.Spread.SheetViewEventHandler(sheetA_CellChanged);

void sheetA_CellChanged(object sender, FarPoint.Win.Spread.SheetViewEventArgs e)
{
   fpSpread1.Sheets[SHEET_B].Cells[e.Row, e.Column].Value = fpSpread1.Sheets[SHEET_A].Cells[e.Row, e.Column].Value;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Use the CellChanged event.

fpSpread1.Sheets[SHEET_A].CellChanged += new FarPoint.Win.Spread.SheetViewEventHandler(sheetA_CellChanged);

void sheetA_CellChanged(object sender, FarPoint.Win.Spread.SheetViewEventArgs e)
{
   fpSpread1.Sheets[SHEET_B].Cells[e.Row, e.Column].Value = fpSpread1.Sheets[SHEET_A].Cells[e.Row, e.Column].Value;
}


问:
SUM with left join returning incorrect result
I have 2 tables

Calls

Amount

I'm trying to left join both the tables to get the sum total of amount along side volume/date.

Below is the query I'm trying, however getting very huge amount as result.

```<code>SELECT
    PeriodDate, SUM(Volume), SUM(Amount)
FROM
    Calls
LEFT JOIN
    Amount ON Calls.PeriodDate = Amount.PeriodDate
GROUP BY
    PeriodDate
</code>```

答:
You can do:</p>
```<code>select a.*, b.amount
from (
  select perioddate, sum(volume) as volume from calls group by perioddate
) a
left join (
  select perioddate, sum(amount) as amount from amount group by perioddate
) b on b.perioddate = a.perioddate
</code>```

Body:
I have 2 tables

Calls

Amount

I'm trying to left join both the tables to get the sum total of amount along side volume/date.

Below is the query I'm trying, however getting very huge amount as result.

SELECT
    PeriodDate, SUM(Volume), SUM(Amount)
FROM
    Calls
LEFT JOIN
    Amount ON Calls.PeriodDate = Amount.PeriodDate
GROUP BY
    PeriodDate

Body:
You can do:

select a.*, b.amount
from (
  select perioddate, sum(volume) as volume from calls group by perioddate
) a
left join (
  select perioddate, sum(amount) as amount from amount group by perioddate
) b on b.perioddate = a.perioddate


问:
Hibernate-Spring boot : spring.jpa.hibernate.ddl-auto=update recreates tables and columns after update the entity
I started Spring Boot project connected to MySQL database. In my application.properties I put spring.jpa.hibernate.ddl-auto = update but still after I update the table name in the entity, a new Table is created, and after I update the column name of property a new column is created.

```<code>## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.url = jdbc:mysql://localhost:3306/d-gdd?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false
spring.datasource.username = root
spring.datasource.password =

## Hibernate Properties

# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect

# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = update
</code>```

答:
I have had the same wondering, however, just like the comment written above,
spring.jpa.hibernate.ddl-auto=update only detects the changes and updates those changes on db as if it's a new thing.

So if you are running locally I suggest do

spring.jpa.hibernate.ddl-auto=create-drop.

But this will delete all the records, so if you really want to "update", then update those column and table names manually.

Body:
I started Spring Boot project connected to MySQL database. In my application.properties I put spring.jpa.hibernate.ddl-auto = update but still after I update the table name in the entity, a new Table is created, and after I update the column name of property a new column is created.

## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.url = jdbc:mysql://localhost:3306/d-gdd?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false
spring.datasource.username = root
spring.datasource.password =

## Hibernate Properties

# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect

# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = update


问:
Execute action without redirecting(Add to wishlist)
So, I have some product cards that I'm displaying with a foreach loop. When I click a link, I want to add that product to my wishlist (Session["wishList"]). That calls a function and redirects me to /product/wishlist/01, where 01 is the product id.

My temporary fix is return Content(""); but no reloading would be better.

My code:

```<code><code>
 <a href="@Url.Action("AddToWishList", "Product", new {id = item.Id})"><i class="far fa-heart"></i></a>
</code>
</code>```

Controller:

```<code><code>
public ActionResult AddToWishList(int id)
        {
            if (Session["email"] != null && Session["role"] != null && (WebApplication1.Models.RoleType)Session["role"] == Models.RoleType.User)
            {
                var wishList = (List<int>)Session["wishList"];
                if (wishList.Contains(id))
                {
                    wishList.Remove(id);
                }
                else
                {
                    wishList.Add(id);
                }
                Session["wishList"] = wishList;
            }
            return Content("<script type='text/javascript'>window.history.back();</script>");
        }</code>
</code>```

答:
You can use Ajax in your case which is used to update a portion of the page without reloading the entire page. In your case, you can do something like:

Define a function which will take a the id of the selected element:

```<code><code>
 <a href="#" onClick='addToWishList('@item.Id')'><i class="far fa-heart"></i></a>
</code>
</code>```

Then you need to define a function which will take this id and send it to your Controller via Ajax:

```<code><script>

function addToWishList(id)
{
    var json = {
        id : id
    };

    $.ajax({
        type: 'POST',
        url: "@Url.Action("AddToWishList", "Product")",
        dataType : "json",
        data: {"json": JSON.stringify(json)},
        success: function(data) {
          if(data.status=="true")
          {
            alert(data.msg);
            var urlToRedirect= '@Url.Action("Index","Home")';
            window.location.href = urlToRedirect; //Redirect here
          }
        },
        error: function(data) {
            alert('Some error');
            window.location.reload();
        }
    });
}
</script>
</code>```

And then finally in your Controller, you can process this id and then return back a result:

```<code>using System.Web.Script.Serialization;

[HttpPost]
public ActionResult AddToWishList(string json)
{
    var serializer = new JavaScriptSerializer();
    dynamic jsondata = serializer.Deserialize(json, typeof(object));

    //Get your variables here from AJAX call
    var id = Convert.ToInt32(jsondata["id"]);
    if (Session["email"] != null && Session["role"] != null && (WebApplication1.Models.RoleType)Session["role"] == Models.RoleType.User)
    {
        var wishList = (List<int>)Session["wishList"];
        if (wishList.Contains(id))
        {
            wishList.Remove(id);
        }
        else
        {
            wishList.Add(id);
        }
        Session["wishList"] = wishList;
    }

    return Json(new {status="true", msg= "Successfully processed"});
}
</code>```

You can tailor the methods as per your requirement.

Body:
So, I have some product cards that I'm displaying with a foreach loop. When I click a link, I want to add that product to my wishlist (Session["wishList"]). That calls a function and redirects me to /product/wishlist/01, where 01 is the product id.

My temporary fix is return Content(""); but no reloading would be better.

My code:

Controller:

public ActionResult AddToWishList(int id)
        {
            if (Session["email"] != null && Session["role"] != null && (WebApplication1.Models.RoleType)Session["role"] == Models.RoleType.User)
            {
                var wishList = (List<int>)Session["wishList"];
                if (wishList.Contains(id))
                {
                    wishList.Remove(id);
                }
                else
                {
                    wishList.Add(id);
                }
                Session["wishList"] = wishList;
            }
            return Content("");
        }

Body:
You can use Ajax in your case which is used to update a portion of the page without reloading the entire page. In your case, you can do something like:

Define a function which will take a the id of the selected element:

<code>
 <a href="#" onClick='addToWishList('@item.Id')'><i class="far fa-heart"></i></a>
</code>

Then you need to define a function which will take this id and send it to your Controller via Ajax:

<script>

function addToWishList(id)
{
    var json = {
        id : id
    };

    $.ajax({
        type: 'POST',
        url: "@Url.Action("AddToWishList", "Product")",
        dataType : "json",
        data: {"json": JSON.stringify(json)},
        success: function(data) {
          if(data.status=="true")
          {
            alert(data.msg);
            var urlToRedirect= '@Url.Action("Index","Home")';
            window.location.href = urlToRedirect; //Redirect here
          }
        },
        error: function(data) {
            alert('Some error');
            window.location.reload();
        }
    });
}
</script>

And then finally in your Controller, you can process this id and then return back a result:

using System.Web.Script.Serialization;

[HttpPost]
public ActionResult AddToWishList(string json)
{
    var serializer = new JavaScriptSerializer();
    dynamic jsondata = serializer.Deserialize(json, typeof(object));

    //Get your variables here from AJAX call
    var id = Convert.ToInt32(jsondata["id"]);
    if (Session["email"] != null && Session["role"] != null && (WebApplication1.Models.RoleType)Session["role"] == Models.RoleType.User)
    {
        var wishList = (List<int>)Session["wishList"];
        if (wishList.Contains(id))
        {
            wishList.Remove(id);
        }
        else
        {
            wishList.Add(id);
        }
        Session["wishList"] = wishList;
    }

    return Json(new {status="true", msg= "Successfully processed"});
}

You can tailor the methods as per your requirement.


问:
How to send object in JavaScript With Trello API? (XMLHttpRequest)
I'm new to javaScript. I was able to send some PUT requests, the problem is none of them had me send an object.
now I want to send an object to add/change the cover of a card in Trello (change the color alone for example/ add a cover), but in the Trello API, the cover is of type object.
how can i do it with XMLHttpRequest?

my normal PUT request (Works, not for object though):

```<code>function updateCheckItem(cardId, checkItemId, state) { // state is boolean
   var url = "https://api.trello.com/1/cards/" + cardId + "/checkItem/" + checkItemId + "?key=...&token=...&state=" + state;

   var xhr = new XMLHttpRequest();
   xhr.open("PUT", URL);

   xhr.setRequestHeader("Accept", "application/json");
   xhr.setRequestHeader("Content-Type", "application/json");

   xhr.onreadystatechange = function () {
       if (this.readyState == 4) {
           //do something not relevant
       }
   };

   xhr.send();
}
</code>```

now, how should I send an object instead of something like the boolean state in the code above?

I've searched and found something about JSON.stringify but didn't work for me/ didn't know exactly how to use it.

my last unworking attempt:

```<code>function Cover(cardId) {
   var url = "https://api.trello.com/1/cards/" + cardId + "?key=...&token=...&cover";

   var xhr = new XMLHttpRequest();
   xhr.open("PUT", URL);

   xhr.setRequestHeader("Accept", "application/json");
   xhr.setRequestHeader("Content-Type", "application/json");

   xhr.onreadystatechange = function () {
       if (this.readyState == 4) {
            //do something not relevant
       }
   };

   xhr.send({ "cover": { "color": "pink" } });
}
</code>```

here are the options:
Options for Trello card cover update

here is what a JSON of a Trello card looks like:

```<code>{
   "id": "..."
   .
   .
   .
   "cover": {
      "idAttachment": null,
      "color": null,
      "idUploadedBackground": null,
      "size": "normal",
      "brightness": "dark",
      "idPlugin": null
   },
   .
   .
   .
}
</code>```

and Thank you.

答:
I solved it, if someone finds this and wants the answer, this is it:</p>
```<code>function uptadeCardCover(cardId,color,size) {
   var url = "https://api.trello.com/1/cards/" + cardId + "?key=xxxxxx&token=xxxxxxxxx";

   var xhr = new XMLHttpRequest();
   xhr.open("PUT", URL);

   xhr.setRequestHeader("Accept", "application/json");
   xhr.setRequestHeader("Content-Type", "application/json");

   xhr.onreadystatechange = function () {
       if (this.readyState == 4 && this.status == 429) {
           // not relevant
       }
   };

   xhr.send(JSON.stringify({
       "cover": {
           "color": color,
           "size": size
       }
   }));
}
</code>```

Body:
I'm new to javaScript. I was able to send some PUT requests, the problem is none of them had me send an object.
now I want to send an object to add/change the cover of a card in Trello (change the color alone for example/ add a cover), but in the Trello API, the cover is of type object.
how can i do it with XMLHttpRequest?

my normal PUT request (Works, not for object though):

function updateCheckItem(cardId, checkItemId, state) { // state is boolean
   var url = "https://api.trello.com/1/cards/" + cardId + "/checkItem/" + checkItemId + "?key=...&token=...&state=" + state;

   var xhr = new XMLHttpRequest();
   xhr.open("PUT", URL);

   xhr.setRequestHeader("Accept", "application/json");
   xhr.setRequestHeader("Content-Type", "application/json");

   xhr.onreadystatechange = function () {
       if (this.readyState == 4) {
           //do something not relevant
       }
   };

   xhr.send();
}

now, how should I send an object instead of something like the boolean state in the code above?

I've searched and found something about JSON.stringify but didn't work for me/ didn't know exactly how to use it.

my last unworking attempt:

function Cover(cardId) {
   var url = "https://api.trello.com/1/cards/" + cardId + "?key=...&token=...&cover";

   var xhr = new XMLHttpRequest();
   xhr.open("PUT", URL);

   xhr.setRequestHeader("Accept", "application/json");
   xhr.setRequestHeader("Content-Type", "application/json");

   xhr.onreadystatechange = function () {
       if (this.readyState == 4) {
            //do something not relevant
       }
   };

   xhr.send({ "cover": { "color": "pink" } });
}

here are the options:
Options for Trello card cover update

here is what a JSON of a Trello card looks like:

{
   "id": "..."
   .
   .
   .
   "cover": {
      "idAttachment": null,
      "color": null,
      "idUploadedBackground": null,
      "size": "normal",
      "brightness": "dark",
      "idPlugin": null
   },
   .
   .
   .
}

and Thank you.

Body:
I solved it, if someone finds this and wants the answer, this is it:

function uptadeCardCover(cardId,color,size) {
   var url = "https://api.trello.com/1/cards/" + cardId + "?key=xxxxxx&token=xxxxxxxxx";

   var xhr = new XMLHttpRequest();
   xhr.open("PUT", URL);

   xhr.setRequestHeader("Accept", "application/json");
   xhr.setRequestHeader("Content-Type", "application/json");

   xhr.onreadystatechange = function () {
       if (this.readyState == 4 && this.status == 429) {
           // not relevant
       }
   };

   xhr.send(JSON.stringify({
       "cover": {
           "color": color,
           "size": size
       }
   }));
}


问:
TemplateDoesNotExist in get_template in loader.py - Django

Hello, this is the error I'm getting on VS code. I'm using Windows 10. I'm following this course and did exactly as they said. It's still showing me this exception.
These are my folders and files.

This is from the settings.py file.

```<code>TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': ['templates'],
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            'django.contrib.auth.context_processors.auth',
            'django.contrib.messages.context_processors.messages',
        ],
    },
},
</code>```

]

This is my loader.py file from the template folder.

```<code>from . import engines
from .exceptions import TemplateDoesNotExist

def get_template(template_name, using=None):

    chain = []
    engines = _engine_list(using)
    for engine in engines:
        try:
            return engine.get_template(template_name)
        except TemplateDoesNotExist as e:
            chain.append(e)

    raise TemplateDoesNotExist(template_name, chain=chain)

def select_template(template_name_list, using=None):

    if isinstance(template_name_list, str):
        raise TypeError(
            'select_template() takes an iterable of template names but got a '
            'string: %r. Use get_template() if you want to load a single '
            'template by name.' % template_name_list
        )

    chain = []
    engines = _engine_list(using)
    for template_name in template_name_list:
        for engine in engines:
            try:
                return engine.get_template(template_name)
            except TemplateDoesNotExist as e:
                chain.append(e)

    if template_name_list:
        raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain)
    else:
        raise TemplateDoesNotExist("No template names provided")

def render_to_string(template_name, context=None, request=None, using=None):

    if isinstance(template_name, (list, tuple)):
        template = select_template(template_name, using=using)
    else:
        template = get_template(template_name, using=using)
    return template.render(context, request)

def _engine_list(using=None):
    return engines.all() if using is None else [engines[using]]
</code>```

My views.py file

```<code>from django.http import HttpResponse
from django.shortcuts import render
def home(request):
    return render(request, 'home.html')
</code>```

Thanks in advance for your help.

答: You need to add app name inside templates folder. For example templates>app_name>home.html</p>

Body:
Hello, this is the error I'm getting on VS code. I'm using Windows 10. I'm following this course and did exactly as they said. It's still showing me this exception.
These are my folders and files.

This is from the settings.py file.

TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': ['templates'],
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            'django.contrib.auth.context_processors.auth',
            'django.contrib.messages.context_processors.messages',
        ],
    },
},

]

This is my loader.py file from the template folder.

from . import engines
from .exceptions import TemplateDoesNotExist

def get_template(template_name, using=None):

    chain = []
    engines = _engine_list(using)
    for engine in engines:
        try:
            return engine.get_template(template_name)
        except TemplateDoesNotExist as e:
            chain.append(e)

    raise TemplateDoesNotExist(template_name, chain=chain)

def select_template(template_name_list, using=None):

    if isinstance(template_name_list, str):
        raise TypeError(
            'select_template() takes an iterable of template names but got a '
            'string: %r. Use get_template() if you want to load a single '
            'template by name.' % template_name_list
        )

    chain = []
    engines = _engine_list(using)
    for template_name in template_name_list:
        for engine in engines:
            try:
                return engine.get_template(template_name)
            except TemplateDoesNotExist as e:
                chain.append(e)

    if template_name_list:
        raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain)
    else:
        raise TemplateDoesNotExist("No template names provided")

def render_to_string(template_name, context=None, request=None, using=None):

    if isinstance(template_name, (list, tuple)):
        template = select_template(template_name, using=using)
    else:
        template = get_template(template_name, using=using)
    return template.render(context, request)

def _engine_list(using=None):
    return engines.all() if using is None else [engines[using]]

My views.py file

from django.http import HttpResponse
from django.shortcuts import render
def home(request):
    return render(request, 'home.html')

Thanks in advance for your help.


问:
SQL Question on CI Active Record Class Usage
I am using CodeIgniter Active Record Class to generat tables, my code snippet below.

I try to generated TWO tables from on DateBase table;
and the two HTML tables named Table_2010 and Table_2011.

```<code>/////////////////// YEAR 2010 ////////////////
// It works quite well to generate 2010 result table.

$this->db->select('year, distance, gender, rank, name, chiptime, racenumber');

                $this->db->order_by("year", "desc");

                $this->db->order_by("distance, gender, rank", "asc");

                $topNum = 5;
                $year = 2010;
                $array = array('rank <=' => $topNum, 'year' => $year);
                $this->db->where($array);

                $this->load->model('eventmain_model');

                $data['results_2010'] = $this->eventmain_model->get_result_top5($city);

                $tmpl =  $this->common_model->html_table_config();

                $this->load->library('table');

                $this->table->set_template($tmpl);

                $this->table->set_heading(array('Year', 'Dis', 'gender','Rank', 'Name', 'ChipTime', 'RaceNo'));

/////////////////// YEAR 2011 ////////////////
// I need query several different fields from the same data base table.
// such as I query 'lap', otherwise 'chiptime'
// It doesn't work well, since it always included 2010 and 2011 data to my 2nd 2011 new table.
// I want to remove 2010 rows from the 2011 table. How can I fix this?
// Is ther an method to new the db select object and generate my 2011 table?
//Thanks.
                // load database class

                $this->db->select('year, distance, gender, rank, name, lap, racenumber');

                $this->db->order_by("year", "desc");

                $this->db->order_by("distance, gender, rank", "asc");

                $topNum = 5;
                $year = 2011;
                $this->db->where('rank <=', $topNum);
                $this->db->where('year', $year);

                $this->load->model('eventmain_model');

                $data['results_2011'] = $this->eventmain_model->get_result_top5($city);

                $tmpl =  $this->common_model->html_table_config();

                $this->load->library('table');

                $this->table->set_template($tmpl);

                $this->table->set_heading(array('Year', 'Dis', 'gender','Rank', 'Name', 'Lap', 'RaceNo'));
</code>```

答:
Got the answer from CI official forum.

```<code>$this->table->clear();
</code>```

And I fixed the issue by add the code to my View Page. Thanks.

```<code>echo 'Table_2010<br>';

$this->table->set_heading(array('Year', 'Dis', 'gender','Rank', 'Name', 'ChipTime', 'RaceNo'));

echo $this->table->generate($results_2010);
$this->table->clear();

echo '<br>';
echo 'Table_2011<br>';
$this->table->set_heading(array('Year', 'Dis', 'gender','Rank', 'Name', 'Lap', 'RaceNo'));
echo $this->table->generate($results_2011);
</code>```

Body:
I am using CodeIgniter Active Record Class to generat tables, my code snippet below.

I try to generated TWO tables from on DateBase table;
and the two HTML tables named Table_2010 and Table_2011.

/////////////////// YEAR 2010 ////////////////
// It works quite well to generate 2010 result table.

$this->db->select('year, distance, gender, rank, name, chiptime, racenumber');

                $this->db->order_by("year", "desc");

                $this->db->order_by("distance, gender, rank", "asc");

                $topNum = 5;
                $year = 2010;
                $array = array('rank <=' => $topNum, 'year' => $year);
                $this->db->where($array);

                $this->load->model('eventmain_model');

                $data['results_2010'] = $this->eventmain_model->get_result_top5($city);

                $tmpl =  $this->common_model->html_table_config();

                $this->load->library('table');

                $this->table->set_template($tmpl);

                $this->table->set_heading(array('Year', 'Dis', 'gender','Rank', 'Name', 'ChipTime', 'RaceNo'));

/////////////////// YEAR 2011 ////////////////
// I need query several different fields from the same data base table.
// such as I query 'lap', otherwise 'chiptime'
// It doesn't work well, since it always included 2010 and 2011 data to my 2nd 2011 new table.
// I want to remove 2010 rows from the 2011 table. How can I fix this?
// Is ther an method to new the db select object and generate my 2011 table?
//Thanks.
                // load database class

                $this->db->select('year, distance, gender, rank, name, lap, racenumber');

                $this->db->order_by("year", "desc");

                $this->db->order_by("distance, gender, rank", "asc");

                $topNum = 5;
                $year = 2011;
                $this->db->where('rank <=', $topNum);
                $this->db->where('year', $year);

                $this->load->model('eventmain_model');

                $data['results_2011'] = $this->eventmain_model->get_result_top5($city);

                $tmpl =  $this->common_model->html_table_config();

                $this->load->library('table');

                $this->table->set_template($tmpl);

                $this->table->set_heading(array('Year', 'Dis', 'gender','Rank', 'Name', 'Lap', 'RaceNo'));

Body:
Got the answer from CI official forum.

$this->table->clear();

And I fixed the issue by add the code to my View Page. Thanks.

echo 'Table_2010<br>';

$this->table->set_heading(array('Year', 'Dis', 'gender','Rank', 'Name', 'ChipTime', 'RaceNo'));

echo $this->table->generate($results_2010);
$this->table->clear();

echo '<br>';
echo 'Table_2011<br>';
$this->table->set_heading(array('Year', 'Dis', 'gender','Rank', 'Name', 'Lap', 'RaceNo'));
echo $this->table->generate($results_2011);


问:
JAVA having trouble retrieving volley result variable value in another class
I have two classes in my android Java Project:
one is API which is inside a local android Module Library that has this code

```<code>package com.example.validationchecklib;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.widget.Toast;
import android.app.Application;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class API extends Application{

    public static int result;
    public static int resultInApi;

    public int checkSubscription(String packageName, String purchaseCode, RequestQueue q) {

        String apiUrl = "https://package.evisions.tech/check_validation.php?package_name=" + packageName;

        // creating a new variable for our request queue
        //RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
        // in this case the data we are getting is in the form
        // of array so we are making a json array request.
        // below is the line where we are making an json array
        // request and then extracting data from each json object.
        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, apiUrl, null, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {

                for (int i = 0; i < response.length(); i++) {
                    //creating  a new Json object and getting each
                    //object from our json array.
                    try {
                        // we are getting each json object.
                        JSONObject responseObj = response.getJSONObject(i);
                        // now we get our response from API in json object format.
                        // in below line we are extracting a string with
                        // its key value from our json object.
                        // similarly we are extracting all the strings from our json object.
                        String apiPackage = responseObj.getString("package_name");
                        String apiPurchaseCode = responseObj.getString("purchase_code");
                        int apiStatus = responseObj.getInt("status");

                        if (apiStatus == 1) {
                            if (apiPackage.equalsIgnoreCase(packageName) && apiPurchaseCode.equalsIgnoreCase(purchaseCode)) {
                                //subcription status is valid and user inputed data matches with api data
                                result = 1;
                                System.out.println("Result in Api = "+result);
                                break;
                            }
                        } else if (apiStatus == 0) {
                            result = 0;
                            System.out.println("Result in Api = "+result);
                            break;
                        } else {
                            result = 2;
                            System.out.println("Result in Api = "+result);
                            break;
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                result = 3;
                System.out.println("Result in Api = Failed to get the data...");
            }
        });

       q.add(jsonArrayRequest);
        return result;
    }

}
</code>```

The second class is MainActivity where I want to retrieve the value from the checkSubsccription() method that is on API class but I am getting 0 even when the request from volley has value 1.

You can test the request using this URL: https://package.evisions.tech/check_validation.php?package_name=aaaa

this is the code for MainActivity

```<code>package com.example.aaaa;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.example.validationchecklib.Subscription;
import com.example.validationchecklib.API;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    //Sample implementation of the Purchase validation android Library
    public String packageName, purchaseCode;
    public TextView txtPackageName, txtPurchaseCode;
    public Button btnResult;
    int serverResponse;
    public String r;
    private ArrayList<Subscription> subscriptionModalArrayList;

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

        subscriptionModalArrayList = new ArrayList<>();

        txtPackageName = findViewById(R.id.edtPackageName);
        txtPurchaseCode = findViewById(R.id.edtPurchaseCode);
        btnResult = findViewById(R.id.btnVerify);
        RequestQueue queue = Volley.newRequestQueue(this);

        API api = new API();

         btnResult.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View view) {

                 packageName = txtPackageName.getText().toString().trim();
                 purchaseCode = txtPurchaseCode.getText().toString().trim();
                 serverResponse = api.checkSubscription(packageName,purchaseCode, queue);

                 System.out.println("Result = "+serverResponse);

                 if(api.result == 1){
                     subscriptionModalArrayList.add(new Subscription(packageName,purchaseCode));
                     Intent intent = new Intent(MainActivity.this, ValidationResult.class);
                     startActivity(intent);
                 }
                 if(api.result == 0){
                    Toast.makeText(MainActivity.this, "Inactive Subscription", Toast.LENGTH_LONG).show();
                    System.exit(1);
                 }
                 if(serverResponse == 2 || serverResponse == 3){
                     Toast.makeText(MainActivity.this, "Failed to fetch data from API or other Error...", Toast.LENGTH_LONG).show();
                     System.exit(1);
                 }

                 txtPackageName.setText("");
                 txtPurchaseCode.setText("");
             }
         });

    }

}
</code>```

答:
The request you are making is asynchronous and you must wait to get the response from it.

The behavior you are seeing (always returning zero) because the result variable has not been initialized and defaults to zero.

```<code>public static int result;
</code>```

You can pass a callback to your checkSubscription method which will be called when you have a result from the request (either failure or success).

You can do this by defining an interface like so:

```<code>public interface Callback {
    public void onSuccess(int result);
    public void onFailure(String error);
}
</code>```

And making your activity implement this method:

```<code>public class MainActivity extends AppCompatActivity implements Callback {

 ...

 public void onSuccess(int result) {
    //Your logic here
 }

 public void onFailure(String error) {
    //Your logic here
 }
}
</code>```

And make sure to pass the activity to your API:

```<code>public int checkSubscription(String packageName, String purchaseCode, RequestQueue q, Callback callback) {
   .....
   callback.onSuccess(result)

  public void onErrorResponse(VolleyError error) {
            result = 3;
            System.out.println("Result in Api = Failed to get the data...");
           callback.onError("YOUR_ERROR_MESSAGE");
        }
}
</code>```

Disclaimer : the above code is just a rough outline and should be
tested

Body:
I have two classes in my android Java Project:
one is API which is inside a local android Module Library that has this code

package com.example.validationchecklib;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.widget.Toast;
import android.app.Application;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class API extends Application{

    public static int result;
    public static int resultInApi;

    public int checkSubscription(String packageName, String purchaseCode, RequestQueue q) {

        String apiUrl = "https://package.evisions.tech/check_validation.php?package_name=" + packageName;

        // creating a new variable for our request queue
        //RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
        // in this case the data we are getting is in the form
        // of array so we are making a json array request.
        // below is the line where we are making an json array
        // request and then extracting data from each json object.
        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, apiUrl, null, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {

                for (int i = 0; i < response.length(); i++) {
                    //creating  a new Json object and getting each
                    //object from our json array.
                    try {
                        // we are getting each json object.
                        JSONObject responseObj = response.getJSONObject(i);
                        // now we get our response from API in json object format.
                        // in below line we are extracting a string with
                        // its key value from our json object.
                        // similarly we are extracting all the strings from our json object.
                        String apiPackage = responseObj.getString("package_name");
                        String apiPurchaseCode = responseObj.getString("purchase_code");
                        int apiStatus = responseObj.getInt("status");

                        if (apiStatus == 1) {
                            if (apiPackage.equalsIgnoreCase(packageName) && apiPurchaseCode.equalsIgnoreCase(purchaseCode)) {
                                //subcription status is valid and user inputed data matches with api data
                                result = 1;
                                System.out.println("Result in Api = "+result);
                                break;
                            }
                        } else if (apiStatus == 0) {
                            result = 0;
                            System.out.println("Result in Api = "+result);
                            break;
                        } else {
                            result = 2;
                            System.out.println("Result in Api = "+result);
                            break;
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                result = 3;
                System.out.println("Result in Api = Failed to get the data...");
            }
        });

       q.add(jsonArrayRequest);
        return result;
    }

}

The second class is MainActivity where I want to retrieve the value from the checkSubsccription() method that is on API class but I am getting 0 even when the request from volley has value 1.

You can test the request using this URL: https://package.evisions.tech/check_validation.php?package_name=aaaa

this is the code for MainActivity

package com.example.aaaa;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.example.validationchecklib.Subscription;
import com.example.validationchecklib.API;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    //Sample implementation of the Purchase validation android Library
    public String packageName, purchaseCode;
    public TextView txtPackageName, txtPurchaseCode;
    public Button btnResult;
    int serverResponse;
    public String r;
    private ArrayList<Subscription> subscriptionModalArrayList;

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

        subscriptionModalArrayList = new ArrayList<>();

        txtPackageName = findViewById(R.id.edtPackageName);
        txtPurchaseCode = findViewById(R.id.edtPurchaseCode);
        btnResult = findViewById(R.id.btnVerify);
        RequestQueue queue = Volley.newRequestQueue(this);

        API api = new API();

         btnResult.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View view) {

                 packageName = txtPackageName.getText().toString().trim();
                 purchaseCode = txtPurchaseCode.getText().toString().trim();
                 serverResponse = api.checkSubscription(packageName,purchaseCode, queue);

                 System.out.println("Result = "+serverResponse);

                 if(api.result == 1){
                     subscriptionModalArrayList.add(new Subscription(packageName,purchaseCode));
                     Intent intent = new Intent(MainActivity.this, ValidationResult.class);
                     startActivity(intent);
                 }
                 if(api.result == 0){
                    Toast.makeText(MainActivity.this, "Inactive Subscription", Toast.LENGTH_LONG).show();
                    System.exit(1);
                 }
                 if(serverResponse == 2 || serverResponse == 3){
                     Toast.makeText(MainActivity.this, "Failed to fetch data from API or other Error...", Toast.LENGTH_LONG).show();
                     System.exit(1);
                 }

                 txtPackageName.setText("");
                 txtPurchaseCode.setText("");
             }
         });

    }

}

Body:
The request you are making is asynchronous and you must wait to get the response from it.

The behavior you are seeing (always returning zero) because the result variable has not been initialized and defaults to zero.

public static int result;

You can pass a callback to your checkSubscription method which will be called when you have a result from the request (either failure or success).

You can do this by defining an interface like so:

public interface Callback {
    public void onSuccess(int result);
    public void onFailure(String error);
}

And making your activity implement this method:

public class MainActivity extends AppCompatActivity implements Callback {

 ...

 public void onSuccess(int result) {
    //Your logic here
 }

 public void onFailure(String error) {
    //Your logic here
 }
}

And make sure to pass the activity to your API:

public int checkSubscription(String packageName, String purchaseCode, RequestQueue q, Callback callback) {
   .....
   callback.onSuccess(result)

  public void onErrorResponse(VolleyError error) {
            result = 3;
            System.out.println("Result in Api = Failed to get the data...");
           callback.onError("YOUR_ERROR_MESSAGE");
        }
}

Disclaimer : the above code is just a rough outline and should be
tested


问:
Regex for cryptocurrencies
I want to validate some fraction of cryptocurrencies, for example, I have the following VALID values

```<code>0,000001
0,000000001
1,00
1.000,00
</code>```

Right now I have this regex for validating currency (yes, with comma instead of dot)

```<code>/^[1-9]\d{0,2}(\.\d{3})*,\d{2}$/
</code>```

How can I do the same for the values above?

答:
You might either match the more exact pattern starting with a digit 1-9, or match a pattern starting with a zero and have 1 or more digits after the comma:

```<code>^(?:[1-9]\d{0,2}(?:\.\d{3})*,\d{2}|0\d*,\d+)$
</code>```

Regex demo

Title: Regex for cryptocurrencies

Body:
I want to validate some fraction of cryptocurrencies, for example, I have the following VALID values

0,000001
0,000000001
1,00
1.000,00

Right now I have this regex for validating currency (yes, with comma instead of dot)

/^[1-9]\d{0,2}(\.\d{3})*,\d{2}$/

How can I do the same for the values above?

Body:
You might either match the more exact pattern starting with a digit 1-9, or match a pattern starting with a zero and have 1 or more digits after the comma:

^(?:[1-9]\d{0,2}(?:\.\d{3})*,\d{2}|0\d*,\d+)$

Regex demo


问:
Insert new row duplicating old one and updating it with new data in one query
I have two tables:

car_consistent (it gets filled and never changes)

id
type
brand

1
dream
ferrari

car_expanded

version_id (pk\seq)
user_that_updated_version
parent_id (id from car_consistent)
current (boolean)
engine
color
length
wheelbase

1
prime
1
true
4.7
red
4,480
2,581

When new car version shows up - older is not replaced, you get something like this:

version_id(pk\seq)
user_that_updated_version
parent_id (id from car_consistent)
current (boolean)
engine
color
length
wheelbase

1
prime
1
false
4.7
red
4,480
2,581

2
mike
1
true
6.5
red
4,480
2,581

So when you join tables on id = parent_id where current = true you get full representation of the car in its current state.
It helps me to track versions and users that made them. Also i can rollback fast.

I am getting updates in following format: "Mike said engine is 6.5 now."

So what i need to do:

Insert new row that is duplicating older one except its id, user_that_updated_version and changed column (engine here).

Set older version current column (or all others with same parent_id) to false and new version current column to true.

On 1) i tried and failed with following query:

```<code>WITH new_version_id AS (INSERT INTO car_expanded (user_that_updated_version, parent_id, current, engine, color, length, wheelbase)
                        SELECT user_that_updated_version, parent_id,    current, engine, color, length, wheelbase
                        FROM car_expanded where id = (SELECT MAX(id) FROM car_expanded WHERE parent_id = 1)
                        RETURNING id)
UPDATE car_expanded SET user_that_updated_version ='mike',engine = 6.5
WHERE id = (SELECT * FROM  new_version_id);
</code>```

It inserts new row, but does not update it.

And i cant even imagine how to implement task 2) in that single query.

Yes, im trying to do it in single query because it is executed from java code.

I would be grateful for any ideas. Thanks in advance.

-----update-----

Feels like following query can solve it:

```<code>WITH prev_version AS (SELECT user_that_updated_version, parent_id, current, engine, color, length,  wheelbase
    FROM car_expanded
    WHERE parent_id = 1 AND current = true
    LIMIT 1),
     unmark_all AS (UPDATE car_expanded SET current = false WHERE parent_id = 1)
INSERT INTO car_expanded (user_that_updated_version, parent_id, current, engine, color, length, wheelbase)
VALUES (
        'mike',
        prev_version.parent_id,
        true,
        6.5,
        prev_version.color,
        prev_version.length,
        prev_version.wheelbase
       )
</code>```

But now im getting [42P01] ERROR: missing FROM-clause entry for table "prev_version".

答:
in simple approach:

first update the current to false in the latest current record in table "upd".

insert the new record with some new values and some values from table "upd".

```<code> create table car_consistent (id smallint, type varchar(10), brand varchar(10));
 create table car_expanded (version_id serial, user_that_updated_version varchar(10), parent_id smallint,
 current boolean, engine varchar(10), color varchar(10), length integer, wheelbase integer);

 insert into car_consistent values (1, 'dream', 'ferrari');
 insert into car_expanded (user_that_updated_version, parent_id, current, engine,
                 color, length, wheelbase)
                 values  ('prime', 1, true, '4.7', 'red', 4480, 2581);

 -- insert 2nd record to update engine to 6.5:
 with upd as (update car_expanded set current = false where parent_id = 1 and
             version_id = (SELECT MAX(version_id) FROM car_expanded WHERE parent_id = 1)
             returning *
     )
 INSERT INTO car_expanded (user_that_updated_version, parent_id, current, engine,
                 color, length, wheelbase)
                 SELECT 'mike', parent_id,
                 true, '6.5' , color, length, wheelbase
                 from upd where parent_id = 1 and version_id = (SELECT MAX(version_id)
                 FROM car_expanded
                 WHERE parent_id = 1);

 select * from car_expanded;

 -- insert 3rd record to update engine to 7.5:
 with upd as (update car_expanded set current = false where parent_id = 1 and
             version_id = (SELECT MAX(version_id) FROM car_expanded WHERE parent_id = 1)
             returning *
     )
 INSERT INTO car_expanded (user_that_updated_version, parent_id, current, engine,
                 color, length, wheelbase)
                 SELECT 'john', parent_id,
                 true, '7.5' , color, length, wheelbase
                 from upd where parent_id = 1 and version_id = (SELECT MAX(version_id)
                 FROM car_expanded
                 WHERE parent_id = 1);

 select * from car_expanded;
</code>```

Body:
I have two tables:

car_consistent (it gets filled and never changes)

id
type
brand

1
dream
ferrari

car_expanded

version_id (pk\seq)
user_that_updated_version
parent_id (id from car_consistent)
current (boolean)
engine
color
length
wheelbase

1
prime
1
true
4.7
red
4,480
2,581

When new car version shows up - older is not replaced, you get something like this:

version_id(pk\seq)
user_that_updated_version
parent_id (id from car_consistent)
current (boolean)
engine
color
length
wheelbase

1
prime
1
false
4.7
red
4,480
2,581

2
mike
1
true
6.5
red
4,480
2,581

So when you join tables on id = parent_id where current = true you get full representation of the car in its current state.
It helps me to track versions and users that made them. Also i can rollback fast.

I am getting updates in following format: "Mike said engine is 6.5 now."

So what i need to do:

Insert new row that is duplicating older one except its id, user_that_updated_version and changed column (engine here).

Set older version current column (or all others with same parent_id) to false and new version current column to true.

On 1) i tried and failed with following query:

WITH new_version_id AS (INSERT INTO car_expanded (user_that_updated_version, parent_id, current, engine, color, length, wheelbase)
                        SELECT user_that_updated_version, parent_id,    current, engine, color, length, wheelbase
                        FROM car_expanded where id = (SELECT MAX(id) FROM car_expanded WHERE parent_id = 1)
                        RETURNING id)
UPDATE car_expanded SET user_that_updated_version ='mike',engine = 6.5
WHERE id = (SELECT * FROM  new_version_id);

It inserts new row, but does not update it.

And i cant even imagine how to implement task 2) in that single query.

Yes, im trying to do it in single query because it is executed from java code.

I would be grateful for any ideas. Thanks in advance.

-----update-----

Feels like following query can solve it:

WITH prev_version AS (SELECT user_that_updated_version, parent_id, current, engine, color, length,  wheelbase
    FROM car_expanded
    WHERE parent_id = 1 AND current = true
    LIMIT 1),
     unmark_all AS (UPDATE car_expanded SET current = false WHERE parent_id = 1)
INSERT INTO car_expanded (user_that_updated_version, parent_id, current, engine, color, length, wheelbase)
VALUES (
        'mike',
        prev_version.parent_id,
        true,
        6.5,
        prev_version.color,
        prev_version.length,
        prev_version.wheelbase
       )

But now im getting [42P01] ERROR: missing FROM-clause entry for table "prev_version".

Body:
in simple approach:

first update the current to false in the latest current record in table "upd".

insert the new record with some new values and some values from table "upd".

 create table car_consistent (id smallint, type varchar(10), brand varchar(10));
 create table car_expanded (version_id serial, user_that_updated_version varchar(10), parent_id smallint,
 current boolean, engine varchar(10), color varchar(10), length integer, wheelbase integer);

 insert into car_consistent values (1, 'dream', 'ferrari');
 insert into car_expanded (user_that_updated_version, parent_id, current, engine,
                 color, length, wheelbase)
                 values  ('prime', 1, true, '4.7', 'red', 4480, 2581);

 -- insert 2nd record to update engine to 6.5:
 with upd as (update car_expanded set current = false where parent_id = 1 and
             version_id = (SELECT MAX(version_id) FROM car_expanded WHERE parent_id = 1)
             returning *
     )
 INSERT INTO car_expanded (user_that_updated_version, parent_id, current, engine,
                 color, length, wheelbase)
                 SELECT 'mike', parent_id,
                 true, '6.5' , color, length, wheelbase
                 from upd where parent_id = 1 and version_id = (SELECT MAX(version_id)
                 FROM car_expanded
                 WHERE parent_id = 1);

 select * from car_expanded;

 -- insert 3rd record to update engine to 7.5:
 with upd as (update car_expanded set current = false where parent_id = 1 and
             version_id = (SELECT MAX(version_id) FROM car_expanded WHERE parent_id = 1)
             returning *
     )
 INSERT INTO car_expanded (user_that_updated_version, parent_id, current, engine,
                 color, length, wheelbase)
                 SELECT 'john', parent_id,
                 true, '7.5' , color, length, wheelbase
                 from upd where parent_id = 1 and version_id = (SELECT MAX(version_id)
                 FROM car_expanded
                 WHERE parent_id = 1);

 select * from car_expanded;