问:
impossible open excel file through getOpenFilename
I'm trying to open in another application an excel file through a dialog window an excel.
I found this code in another post. However I don't get to open the file.
I think the issues are in these lines of the code:If sFilePath = False Then and Set wb = excelApp.Workbooks.Open(sFilePath, False)
I'm also trying to open a file .xlsx

```<code>Sub OpenFile()

' Create Excel object
'    On Error Resume Next
    Dim excelApp As Excel.Application
    Set excelApp = GetObject(, "Excel.Application")

    ' Prompt user to select Excel file to read from
    ' Alternatively, you could hard code the filepath like this:
    Dim sFilePath As String
    sFilePath = excelApp.GetOpenFilename(FileFilter:="Excel Files (*.xls*),*.xls*", Title:="Select excel file")
'    ' Open Excel file invisibly
    If sFilePath = False Then
        Exit Sub
    Else
        Set wb = excelApp.Workbooks.Open(sFilePath, False)
    End If

   End Sub
</code>```

答:
You need to change your code a little bit, you may have the problem on the line where you're trying to evaluate a string to a boolean value as stated by @FunThomas, but I could think of at least another scenario that may be happening/will happen: the file may be opened by another process. I modified your code a little to address that scenario, this should be working or display the proper message if it doesn't.</p>
```<code>Sub OpenFile()
Dim VarValueFromMsg As Variant
Dim WBToImport As Workbook
Dim TxtFileToImport As String
' Create Excel object
'    On Error Resume Next
    Dim excelApp As Excel.Application
    Set excelApp = GetObject(, "Excel.Application")
    ' Prompt user to select Excel file to read from
    ' Alternatively, you could hard code the filepath like this:
    VarValueFromMsg = excelApp.GetOpenFilename(Title:="Select excel file", FileFilter:="Excel Files (*.xls*),*.xls*", MultiSelect:=False)
    On Error GoTo Err01OpenFile
    If VarValueFromMsg = False Then Exit Sub
Err01OpenFile:
    TxtFileToImport = CStr(VarValueFromMsg)
    If Return_IsExcelFileLocked(TxtFileToImport) = True Then Exit Sub
    Set WBToImport = excelApp.Workbooks.Open(Filename:=TxtFileToImport)
End Sub
Function Return_IsExcelFileLocked(TxtFile As String) As Boolean
    On Error Resume Next
    ' If the file is already opened by another process,
    ' and the specified type of access is not allowed,
    ' the Open operation fails and an error occurs.
    If Dir(TxtFile) = "" Then MsgBox "Error01Return_IsExcelFileLocked: File does not exist.": Return_IsExcelFileLocked = True: Exit Function
    Open TxtFile For Binary Access Read Write Lock Read Write As #1
    Close #1
    ' If an error occurs, the document is currently open.
    If Err.Number <> 0 Then
    ' Display the error number and description.
    MsgBox "Error02Return_IsExcelFileLocked: #" & Str(Err.Number) & " - " & Err.Description & ": If file is open please close it."
    Return_IsExcelFileLocked = True
    Err.Clear
    End If
End Function
</code>```

Body:
I'm trying to open in another application an excel file through a dialog window an excel.
I found this code in another post. However I don't get to open the file.
I think the issues are in these lines of the code:If sFilePath = False Then and Set wb = excelApp.Workbooks.Open(sFilePath, False)
I'm also trying to open a file .xlsx

Sub OpenFile()

' Create Excel object
'    On Error Resume Next
    Dim excelApp As Excel.Application
    Set excelApp = GetObject(, "Excel.Application")

    ' Prompt user to select Excel file to read from
    ' Alternatively, you could hard code the filepath like this:
    Dim sFilePath As String
    sFilePath = excelApp.GetOpenFilename(FileFilter:="Excel Files (*.xls*),*.xls*", Title:="Select excel file")
'    ' Open Excel file invisibly
    If sFilePath = False Then
        Exit Sub
    Else
        Set wb = excelApp.Workbooks.Open(sFilePath, False)
    End If

   End Sub

Body:
You need to change your code a little bit, you may have the problem on the line where you're trying to evaluate a string to a boolean value as stated by @FunThomas, but I could think of at least another scenario that may be happening/will happen: the file may be opened by another process. I modified your code a little to address that scenario, this should be working or display the proper message if it doesn't.

Sub OpenFile()
Dim VarValueFromMsg As Variant
Dim WBToImport As Workbook
Dim TxtFileToImport As String
' Create Excel object
'    On Error Resume Next
    Dim excelApp As Excel.Application
    Set excelApp = GetObject(, "Excel.Application")
    ' Prompt user to select Excel file to read from
    ' Alternatively, you could hard code the filepath like this:
    VarValueFromMsg = excelApp.GetOpenFilename(Title:="Select excel file", FileFilter:="Excel Files (*.xls*),*.xls*", MultiSelect:=False)
    On Error GoTo Err01OpenFile
    If VarValueFromMsg = False Then Exit Sub
Err01OpenFile:
    TxtFileToImport = CStr(VarValueFromMsg)
    If Return_IsExcelFileLocked(TxtFileToImport) = True Then Exit Sub
    Set WBToImport = excelApp.Workbooks.Open(Filename:=TxtFileToImport)
End Sub
Function Return_IsExcelFileLocked(TxtFile As String) As Boolean
    On Error Resume Next
    ' If the file is already opened by another process,
    ' and the specified type of access is not allowed,
    ' the Open operation fails and an error occurs.
    If Dir(TxtFile) = "" Then MsgBox "Error01Return_IsExcelFileLocked: File does not exist.": Return_IsExcelFileLocked = True: Exit Function
    Open TxtFile For Binary Access Read Write Lock Read Write As #1
    Close #1
    ' If an error occurs, the document is currently open.
    If Err.Number <> 0 Then
    ' Display the error number and description.
    MsgBox "Error02Return_IsExcelFileLocked: #" & Str(Err.Number) & " - " & Err.Description & ": If file is open please close it."
    Return_IsExcelFileLocked = True
    Err.Clear
    End If
End Function


来源: stackexchange

问:
Why not sprite larger images that are page content?
The typical rule of thumb when it comes to using CSS sprites for images is that you should only do it for smaller images (like icons) and that actual image content should always be represented through  elements. My question is: why? Aren't the advantages of spriting worthwhile for content images as well?

One reason I have read is to enable the use of alt text, to be more syntactically correct and accessible to screen-readers. However, when that is a concern, couldn't you just as easily use a single tiny transparent image with all the syntactical sugar atop a sprite that presents the real visual content?

答: One additional reason I can think of, is search-engines; if you have an image with a descriptive alt-tag or a figure element with a figcaption, search engines will be able to find, classify and show it.

ContentLicense: CC BY-SA 3.0


问:
Github action: Post comment to PR with pylint result
I am setting up my github CI pipeline, currently I am trying to setup pylint to be ran automatically on pull requests.  How do I write the results from pylint into a PR comment?

This is what I have.  I try to use the github action on mshick/add-pr-comment@v1.  However, I am not sure how to pipe the result from the previous step.  Is it possible to only write the final score instead of the whole result, because it's very long.

```<code>name: Python Linting

on:
  pull_request:
    branches: [ main, dev ]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v2
    - name: Set up Python 3.10
      uses: actions/setup-python@v2
      with:
        python-version: "3.10"
    - name: Install dependencies
      run: |
        python -m pip install --upgrade pip
        if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
    - name: Lint with pylint
      run: |
        pip install pylint
        pylint ./src --exit-zero
    - name: Post result to PR
    - uses: mshick/add-pr-comment@v1
      with:
        message: |
          **Hello**
        repo-token: ${{ secrets.GITHUB_TOKEN }}
        repo-token-user-login: 'github-actions[bot]' # The user.login for temporary GitHub tokens
        allow-repeats: false # This is the default
</code>```

This is my pylint result, at least he last line, the full result is really long:

```<code>-----------------------------------
Your code has been rated at 3.31/10
</code>```

答:
To achieve what you want, you would have to use a sceipt or a shell command (which I don't know as it depends on the context) to extract just the part of the command output you want (e.g: Your code has been rated at 3.31/10), then add it as env variable (or output) to use it in the next step.

I would do something like this in your job:

    - name: Lint with pylint
      run: |
        pip install pylint
        OUTPUT=$(pylint ./src --exit-zero)
        #OUTPUT=$(shell command or script to extract the part your want)
        echo "MESSAGE=$OUTPUT" >> $GITHUB_ENV
    - name: Post result to PR
      uses: mshick/add-pr-comment@v1
      with:
        message: ${{ env.MESSAGE }}
        repo-token: ${{ secrets.GITHUB_TOKEN }}
        repo-token-user-login: 'github-actions[bot]' # The user.login for temporary GitHub tokens
        allow-repeats: false # This is the default
```

Where the echo "MESSAGE=$OUTPUT" >> $GITHUB_ENV would add the MESSAGE to the github context environment, to be able to use in the next step with ${{ env.MESSAGE }}.

ContentLicense: CC BY-SA 4.0

Body:
I am setting up my github CI pipeline, currently I am trying to setup pylint to be ran automatically on pull requests.  How do I write the results from pylint into a PR comment?

This is what I have.  I try to use the github action on mshick/add-pr-comment@v1.  However, I am not sure how to pipe the result from the previous step.  Is it possible to only write the final score instead of the whole result, because it's very long.

name: Python Linting

on:
  pull_request:
    branches: [ main, dev ]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v2
    - name: Set up Python 3.10
      uses: actions/setup-python@v2
      with:
        python-version: "3.10"
    - name: Install dependencies
      run: |
        python -m pip install --upgrade pip
        if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
    - name: Lint with pylint
      run: |
        pip install pylint
        pylint ./src --exit-zero
    - name: Post result to PR
    - uses: mshick/add-pr-comment@v1
      with:
        message: |
          **Hello**
        repo-token: ${{ secrets.GITHUB_TOKEN }}
        repo-token-user-login: 'github-actions[bot]' # The user.login for temporary GitHub tokens
        allow-repeats: false # This is the default

This is my pylint result, at least he last line, the full result is really long:

-----------------------------------
Your code has been rated at 3.31/10

Body:
To achieve what you want, you would have to use a sceipt or a shell command (which I don't know as it depends on the context) to extract just the part of the command output you want (e.g: Your code has been rated at 3.31/10), then add it as env variable (or output) to use it in the next step.

I would do something like this in your job:

    - name: Lint with pylint
      run: |
        pip install pylint
        OUTPUT=$(pylint ./src --exit-zero)
        #OUTPUT=$(shell command or script to extract the part your want)
        echo "MESSAGE=$OUTPUT" >> $GITHUB_ENV
    - name: Post result to PR
      uses: mshick/add-pr-comment@v1
      with:
        message: ${{ env.MESSAGE }}
        repo-token: ${{ secrets.GITHUB_TOKEN }}
        repo-token-user-login: 'github-actions[bot]' # The user.login for temporary GitHub tokens
        allow-repeats: false # This is the default

Where the echo "MESSAGE=$OUTPUT" >> $GITHUB_ENV would add the MESSAGE to the github context environment, to be able to use in the next step with ${{ env.MESSAGE }}.


问:
How do I add text last in a text element in html via js
I want to add text last in a p element, not first, but i only know how to add last using +=

var pEL = document.querySelector("#text");
pEL.innerHTML += "1";```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="text">text</p></code>```

now the p element says "text1" but i want "1text", how do i add something first in a text element?

答:
```<code>
pE1.innerHTML += "1";

</code>```

is simply shorthand for saying "the new html will be the old html + "1"

```<code>pEl.innerHTML = pEl.innerHTML + "1"
</code>```

so instead, something like

```<code>
pEL.innerHTML = "1" + pEl.innerHTML

</code>```

should do the trick.

Body:
I want to add text last in a p element, not first, but i only know how to add last using +=

var pEL = document.querySelector("#text");
pEL.innerHTML += "1";

text

now the p element says "text1" but i want "1text", how do i add something first in a text element?

Body:
pE1.innerHTML += "1";

is simply shorthand for saying "the new html will be the old html + "1"

pEl.innerHTML = pEl.innerHTML + "1"

so instead, something like

pEL.innerHTML = "1" + pEl.innerHTML

should do the trick.


问:
C# 8 switch expression: Handle multiple cases at once?
C# 8 introduced pattern matching, and I already found good places to use it, like this one:

private static GameType UpdateGameType(GameType gameType)
{
    switch (gameType)
    {
        case GameType.RoyalBattleLegacy:
        case GameType.RoyalBattleNew:
            return GameType.RoyalBattle;
        case GameType.FfaLegacy:
        case GameType.FfaNew:
            return GameType.Ffa;
        default:
            return gameType;
    }
}
```

<p>which then becomes</p>

<pre class="lang-cs prettyprint-override"><code>private static GameType UpdateGameType(GameType gameType) => gameType switch
{
    GameType.RoyalBattleLegacy => GameType.RoyalBattle,
    GameType.RoyalBattleNew => GameType.RoyalBattle,
    GameType.FfaLegacy => GameType.Ffa,
    GameType.FfaNew => GameType.Ffa,
    _ => gameType;
};
</code>```

However, you can see I now have to mention GameType.RoyalBattle and GameType.Ffa twice. Is there a way to handle multiple cases at once in pattern matching? I'm thinking of anything like this, but it is not valid syntax:

private static GameType UpdateGameType(GameType gameType) => gameType switch
{
    GameType.RoyalBattleLegacy, GameType.RoyalBattleNew => GameType.RoyalBattle,
    GameType.FfaLegacy, GameType.FfaNew => GameType.Ffa,
    _ => gameType;
};
```

<p>I also tried things like</p>

<pre class="lang-cs prettyprint-override"><code>[GameType.RoyalBattleLegacy, GameType.RoyalBattleNew] => GameType.RoyalBattle
</code>```

or

GameType.FfaLegacy || GameType.FfaNew => GameType.Ffa
```

but none are valid.

Also did not find any example on this. Is it even supported?

答:
As of C#9, you can do exactly what you wanted via "disjunctive or" patterns:

```<code>private static GameType UpdateGameType(GameType gameType) => gameType switch
{
    GameType.RoyalBattleLegacy or GameType.RoyalBattleNew => GameType.RoyalBattle,
    GameType.FfaLegacy or GameType.FfaNew => GameType.Ffa,
    _ => gameType;
};
</code>```

Further reading:

What's new in C# 9.0: pattern matching enhancements

Patterns C# reference

Body:
C# 8 introduced pattern matching, and I already found good places to use it, like this one:

private static GameType UpdateGameType(GameType gameType)
{
    switch (gameType)
    {
        case GameType.RoyalBattleLegacy:
        case GameType.RoyalBattleNew:
            return GameType.RoyalBattle;
        case GameType.FfaLegacy:
        case GameType.FfaNew:
            return GameType.Ffa;
        default:
            return gameType;
    }
}

which then becomes

private static GameType UpdateGameType(GameType gameType) => gameType switch
{
    GameType.RoyalBattleLegacy => GameType.RoyalBattle,
    GameType.RoyalBattleNew => GameType.RoyalBattle,
    GameType.FfaLegacy => GameType.Ffa,
    GameType.FfaNew => GameType.Ffa,
    _ => gameType;
};

However, you can see I now have to mention GameType.RoyalBattle and GameType.Ffa twice. Is there a way to handle multiple cases at once in pattern matching? I'm thinking of anything like this, but it is not valid syntax:

private static GameType UpdateGameType(GameType gameType) => gameType switch
{
    GameType.RoyalBattleLegacy, GameType.RoyalBattleNew => GameType.RoyalBattle,
    GameType.FfaLegacy, GameType.FfaNew => GameType.Ffa,
    _ => gameType;
};

I also tried things like

[GameType.RoyalBattleLegacy, GameType.RoyalBattleNew] => GameType.RoyalBattle

or

GameType.FfaLegacy || GameType.FfaNew => GameType.Ffa

but none are valid.

Also did not find any example on this. Is it even supported?

Body:
As of C#9, you can do exactly what you wanted via "disjunctive or" patterns:

private static GameType UpdateGameType(GameType gameType) => gameType switch
{
    GameType.RoyalBattleLegacy or GameType.RoyalBattleNew => GameType.RoyalBattle,
    GameType.FfaLegacy or GameType.FfaNew => GameType.Ffa,
    _ => gameType;
};

Further reading:

What's new in C# 9.0: pattern matching enhancements

Patterns C# reference


问:
Can i use more than once $(document).ready() of jquery in a single html page?
i have one html page named "text.html"

```<code><html>
    <body>
        <script type="text/javascript" src="jquery.js"></script>
        <script type="text/javascript" src="js/Photos.js"></script>
        <script type="text/javascript" src="js/Animations.js"></script>
    </body>
</html>
</code>```

Both Photos.js and Animations.js start with "$(document).ready()" like this

```<code>//Javascript File Photos.js
$(document).ready(function() {
    //My code here ....
});

//Javascript File Animations.js
$(document).ready(function() {
    //My code here ....
});
</code>```

Does it matter if i use multiple $(document).ready(function() { in a single html page??

Thanks, in advance

答: Not in the slightest. They're both just going to trigger on the same event. That's fine. :)</p>

Body:
i have one html page named "text.html"

Both Photos.js and Animations.js start with "$(document).ready()" like this

//Javascript File Photos.js
$(document).ready(function() {
    //My code here ....
});

//Javascript File Animations.js
$(document).ready(function() {
    //My code here ....
});

Does it matter if i use multiple $(document).ready(function() { in a single html page??

Thanks, in advance


问:
TextEditingController not passing text into named parameters
I am really struggling to understand why my code isn't working. I'm trying to pass the text from two controllers into another widget with named parameters which writes to Firebase.

My "Test" button properly prints both _titleController.text and _descriptionController.text

```<code>TextButton(
                    onPressed: (){
                      print(_titleController.text); //works fine
                      print(_descriptionController.text); //works fine
                    },
                    child: Text('test')
                ),
</code>```

However when I pass these into my next widget it's blank! If I hardcore strings into these parameters it works properly:

```<code>PushNewE3 (
                 changeTitle: _titleController.text, //does not work (empty)
                 changeDescription: _descriptionController.text, //does not work (empty)
                )
</code>```

Full code:

```<code>class CreateE3 extends StatefulWidget {
  const CreateE3({Key? key}) : super(key: key);

  @override
  _CreateE3State createState() => _CreateE3State();
}

class _CreateE3State extends State<CreateE3> {
  final _titleController = TextEditingController();
  final _descriptionController = TextEditingController();

  @override
  void initState(){
    super.initState();
    _titleController.addListener(_printLatestValue);
  }

  @override
  void dispose(){
    _titleController.dispose();
    super.dispose();
  }

  void _printLatestValue(){
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('So Frustrating'),
      ),

      body: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Container(
            width: 800,
            child: Column(
              children: [
                Text('Originator: **Add Current User**')      ,
                TextField(
                  maxLength: 40,
                  decoration: InputDecoration(
                    border: OutlineInputBorder(),
                    labelText: 'Change Title'
                  ),
                  controller: _titleController,
                  onEditingComplete: (){
                    //_title = _titleController.text;
                  },
                ),
                Padding(
                  padding: const EdgeInsets.fromLTRB(0,10,0,0),
                  child: TextFormField(
                    maxLines: 5,
                    decoration: InputDecoration(
                        border: OutlineInputBorder(),
                        labelText: 'Detailed Description'
                    ),
                    controller: _descriptionController,
                  ),
                ),
                TextButton(
                    onPressed: (){
                      print(_titleController.text); //successfully prints
                      print(_descriptionController.text); //successfully prints

                    },
                    child: Text('test')
                ),
                PushNewE3 (
                 changeTitle: _titleController.text, //DOES NOT WORK (empty)
                 changeDescription: _descriptionController.text, //DOES NOT WORK (empty)
                )

              ],
            ),
          ),
        ],
      ),

    );
  }
}

class PushNewE3 extends StatelessWidget {
  final String changeTitle;
  final String changeDescription;

  PushNewE3({
    required this.changeTitle,
    required this.changeDescription
  });

  @override
  Widget build(BuildContext context) {
    // Create a CollectionReference called users that references the firestore collection
    CollectionReference notificationsE3 = FirebaseFirestore.instance.collection('notificationsE3');

    Future<void> pushNewE3() {
      // Call the notifications CollectionReference to add a new E3 notification
      return notificationsE3
          .add({
        //'originator': FirebaseAuth.instance.currentUser,
        'changeTitle': changeTitle,
        'changeDescription': changeDescription,
      })
          .then((value) => print("E3 Created"))
          .catchError((error) => print("Failed to create E3: $error"));
    }

    return TextButton(
      onPressed: (){
        print('start:');
        print(changeTitle);
        print(changeDescription);
        print('-end');

      },
      child: Text(
        "Create E3",
      ),
    );
  }
}

</code>```

EDIT:
I still don't understand why the above code doesn't work. I refactored my code into a single widget and now it's working. If anyone can explain why I would still appreciate understanding as there is clearly a gap in my knowledge.

If anyone in the future runs into the same problem here is the refactored code:

```<code>import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';

import 'main.dart';

var global = 'blank';

class CreateE3 extends StatefulWidget {
  const CreateE3({Key? key}) : super(key: key);

  @override
  _CreateE3State createState() => _CreateE3State();
}

class _CreateE3State extends State<CreateE3> {
  final _titleController = TextEditingController();
  final _descriptionController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    // Create a CollectionReference called users that references the firestore collection
    CollectionReference notificationsE3 = FirebaseFirestore.instance.collection('notificationsE3');

    Future<void> pushNewE3() {
      // Call the notifications CollectionReference to add a new E3 notification
      return notificationsE3
          .add({
        //'originator': FirebaseAuth.instance.currentUser,
        'changeTitle': _titleController.text,
        'changeDescription': _descriptionController.text,
      })
          .then((value) => print("E3 Created"))
          .catchError((error) => print("Failed to create E3: $error"));
    }

    return Scaffold(
      appBar: AppBar(
        title: Text(_titleController.text),
      ),

      body: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Container(
            width: 800,
            child: Column(
              children: [
                Text('Originator: **Add Current User**')      ,
                TextField(
                  maxLength: 40,
                  decoration: InputDecoration(
                      border: OutlineInputBorder(),
                      labelText: 'Change Title'
                  ),
                  controller: _titleController,
                  onChanged: (text){
                    setState(() {

                    });
                  },

                ),
                Padding(
                  padding: const EdgeInsets.fromLTRB(0,10,0,0),
                  child: TextFormField(
                    maxLines: 5,
                    decoration: InputDecoration(
                        border: OutlineInputBorder(),
                        labelText: 'Detailed Description'
                    ),
                    controller: _descriptionController,
                  ),
                ),
                TextButton(
                    onPressed: (){
                      pushNewE3();
                    },
                    child: Text('SAVE')
                ),

              ],
            ),
          ),
        ],
      ),

    );
  }
}
</code>```

答:
in the onPressed To pass a value and show it, you have to use setState(() { _myState = newValue; });

Something like this

```<code>TextButton(
                onPressed: (){
                  print(_titleController.text);
                  print(_descriptionController.text);
                  setState(() { _myNewText = _titleController.text; });

                },
                child: Text('test')
            ),
</code>```

Body:
I am really struggling to understand why my code isn't working. I'm trying to pass the text from two controllers into another widget with named parameters which writes to Firebase.

My "Test" button properly prints both _titleController.text and _descriptionController.text

TextButton(
                    onPressed: (){
                      print(_titleController.text); //works fine
                      print(_descriptionController.text); //works fine
                    },
                    child: Text('test')
                ),

However when I pass these into my next widget it's blank! If I hardcore strings into these parameters it works properly:

PushNewE3 (
                 changeTitle: _titleController.text, //does not work (empty)
                 changeDescription: _descriptionController.text, //does not work (empty)
                )

Full code:

class CreateE3 extends StatefulWidget {
  const CreateE3({Key? key}) : super(key: key);

  @override
  _CreateE3State createState() => _CreateE3State();
}

class _CreateE3State extends State<CreateE3> {
  final _titleController = TextEditingController();
  final _descriptionController = TextEditingController();

  @override
  void initState(){
    super.initState();
    _titleController.addListener(_printLatestValue);
  }

  @override
  void dispose(){
    _titleController.dispose();
    super.dispose();
  }

  void _printLatestValue(){
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('So Frustrating'),
      ),

      body: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Container(
            width: 800,
            child: Column(
              children: [
                Text('Originator: **Add Current User**')      ,
                TextField(
                  maxLength: 40,
                  decoration: InputDecoration(
                    border: OutlineInputBorder(),
                    labelText: 'Change Title'
                  ),
                  controller: _titleController,
                  onEditingComplete: (){
                    //_title = _titleController.text;
                  },
                ),
                Padding(
                  padding: const EdgeInsets.fromLTRB(0,10,0,0),
                  child: TextFormField(
                    maxLines: 5,
                    decoration: InputDecoration(
                        border: OutlineInputBorder(),
                        labelText: 'Detailed Description'
                    ),
                    controller: _descriptionController,
                  ),
                ),
                TextButton(
                    onPressed: (){
                      print(_titleController.text); //successfully prints
                      print(_descriptionController.text); //successfully prints

                    },
                    child: Text('test')
                ),
                PushNewE3 (
                 changeTitle: _titleController.text, //DOES NOT WORK (empty)
                 changeDescription: _descriptionController.text, //DOES NOT WORK (empty)
                )

              ],
            ),
          ),
        ],
      ),

    );
  }
}

class PushNewE3 extends StatelessWidget {
  final String changeTitle;
  final String changeDescription;

  PushNewE3({
    required this.changeTitle,
    required this.changeDescription
  });

  @override
  Widget build(BuildContext context) {
    // Create a CollectionReference called users that references the firestore collection
    CollectionReference notificationsE3 = FirebaseFirestore.instance.collection('notificationsE3');

    Future<void> pushNewE3() {
      // Call the notifications CollectionReference to add a new E3 notification
      return notificationsE3
          .add({
        //'originator': FirebaseAuth.instance.currentUser,
        'changeTitle': changeTitle,
        'changeDescription': changeDescription,
      })
          .then((value) => print("E3 Created"))
          .catchError((error) => print("Failed to create E3: $error"));
    }

    return TextButton(
      onPressed: (){
        print('start:');
        print(changeTitle);
        print(changeDescription);
        print('-end');

      },
      child: Text(
        "Create E3",
      ),
    );
  }
}

EDIT:
I still don't understand why the above code doesn't work. I refactored my code into a single widget and now it's working. If anyone can explain why I would still appreciate understanding as there is clearly a gap in my knowledge.

If anyone in the future runs into the same problem here is the refactored code:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';

import 'main.dart';

var global = 'blank';

class CreateE3 extends StatefulWidget {
  const CreateE3({Key? key}) : super(key: key);

  @override
  _CreateE3State createState() => _CreateE3State();
}

class _CreateE3State extends State<CreateE3> {
  final _titleController = TextEditingController();
  final _descriptionController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    // Create a CollectionReference called users that references the firestore collection
    CollectionReference notificationsE3 = FirebaseFirestore.instance.collection('notificationsE3');

    Future<void> pushNewE3() {
      // Call the notifications CollectionReference to add a new E3 notification
      return notificationsE3
          .add({
        //'originator': FirebaseAuth.instance.currentUser,
        'changeTitle': _titleController.text,
        'changeDescription': _descriptionController.text,
      })
          .then((value) => print("E3 Created"))
          .catchError((error) => print("Failed to create E3: $error"));
    }

    return Scaffold(
      appBar: AppBar(
        title: Text(_titleController.text),
      ),

      body: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Container(
            width: 800,
            child: Column(
              children: [
                Text('Originator: **Add Current User**')      ,
                TextField(
                  maxLength: 40,
                  decoration: InputDecoration(
                      border: OutlineInputBorder(),
                      labelText: 'Change Title'
                  ),
                  controller: _titleController,
                  onChanged: (text){
                    setState(() {

                    });
                  },

                ),
                Padding(
                  padding: const EdgeInsets.fromLTRB(0,10,0,0),
                  child: TextFormField(
                    maxLines: 5,
                    decoration: InputDecoration(
                        border: OutlineInputBorder(),
                        labelText: 'Detailed Description'
                    ),
                    controller: _descriptionController,
                  ),
                ),
                TextButton(
                    onPressed: (){
                      pushNewE3();
                    },
                    child: Text('SAVE')
                ),

              ],
            ),
          ),
        ],
      ),

    );
  }
}

Body:
in the onPressed To pass a value and show it, you have to use setState(() { _myState = newValue; });

Something like this

TextButton(
                onPressed: (){
                  print(_titleController.text);
                  print(_descriptionController.text);
                  setState(() { _myNewText = _titleController.text; });

                },
                child: Text('test')
            ),


问:
jq: Format a JSON file with the output replacing the input file
I want to use jq to format a JSON file in Windows.  So far, I haven't been able to find a way to perform this task using a single jq command.

Thus, I wrote this batch file:

```<code>rem create formatted JSON output file
jq-win64.exe . "%1" >"temp.tmp"

rem replace the unformatted JSON input file with the formatted JSON output file
del "%1"
ren "temp.tmp" "%1"
</code>```

Is there a way to instruct jq to do this without performing these gymnastics?

答:
You want the following:

```<code>jq . "%1" >"%1".tmp
if not errorlevel 1 move /y "%1".tmp "%1" >nul
</code>```

jq has no option to do this for you.

Body:
I want to use jq to format a JSON file in Windows.  So far, I haven't been able to find a way to perform this task using a single jq command.

Thus, I wrote this batch file:

rem create formatted JSON output file
jq-win64.exe . "%1" >"temp.tmp"

rem replace the unformatted JSON input file with the formatted JSON output file
del "%1"
ren "temp.tmp" "%1"

Is there a way to instruct jq to do this without performing these gymnastics?

Body:
You want the following:

jq . "%1" >"%1".tmp
if not errorlevel 1 move /y "%1".tmp "%1" >nul

jq has no option to do this for you.


问:
Beautiful soup returns none even when there is an element
Trying to filter the products name list using the header tags, but it always returns none.

source : https://www.tendercuts.in/chicken

code :

```<code>import requests
from bs4 import BeautifulSoup
def ExtractData(url):
response = requests.get(url=url).content
soup = BeautifulSoup(response, 'lxml')
header = soup.find("mat-card-header", {"class": "mat-card-header ng-tns- c9-188"})
print(header)
ExtractData(url="https://www.tendercuts.in/chicken")
</code>```

答:
Here's code to iterate all the <mat-card-header> items showing the class id and the associated text of the card-title. You can further filter on the child elements in each of header items to find particular products.

soup = BeautifulSoup(response, 'lxml')
headers = soup.find_all("mat-card-header")
for header in headers:
   print(header.get('class'), header.find('mat-card-title').text)
```
<p><strong>Output:</strong></p>
```['mat-card-header', 'ng-tns-c9-3'] Chicken Curry Cut (Skin Off)
['mat-card-header', 'ng-tns-c9-3'] Chicken Curry Cut (Skin Off)
...
['mat-card-header', 'ng-tns-c9-19'] Chicken Wings
```

Body:
Trying to filter the products name list using the header tags, but it always returns none.

source : https://www.tendercuts.in/chicken

code :

import requests
from bs4 import BeautifulSoup
def ExtractData(url):
response = requests.get(url=url).content
soup = BeautifulSoup(response, 'lxml')
header = soup.find("mat-card-header", {"class": "mat-card-header ng-tns- c9-188"})
print(header)
ExtractData(url="https://www.tendercuts.in/chicken")

Body:
Here's code to iterate all the <mat-card-header> items showing the class id and the associated text of the card-title. You can further filter on the child elements in each of header items to find particular products.

soup = BeautifulSoup(response, 'lxml')
headers = soup.find_all("mat-card-header")
for header in headers:
   print(header.get('class'), header.find('mat-card-title').text)

Output:

['mat-card-header', 'ng-tns-c9-3'] Chicken Curry Cut (Skin Off)
['mat-card-header', 'ng-tns-c9-3'] Chicken Curry Cut (Skin Off)
...
['mat-card-header', 'ng-tns-c9-19'] Chicken Wings


问:
check if object exist before saving django rest framework
When i post new data i want to check create new man object and  dok object related to  man objects but if man object alredy exist i want to append related dok to it
any idea how to start i'm totally new to rest_framework

```<code>class Man(ListCreateAPIView):
    queryset =  Man.objects.all()
    serializer_class = ManSerial
</code>```

model.py

```<code>
class Man(models.Model):
    name = models.CharField(max_length=50,unique=True)
    age = models.IntegerField()
    def __str__(self):
        return self.name

class Dok(models.Model):
    man = models.ForeignKey(Man,on_delete=models.CASCADE,related_name="dok_man")
    cool =  models.CharField(max_length=400)
    def __str__(self) :
        return str(self.man)

</code>```

serializer.py

```<code>class Dokserial(serializers.ModelSerializer):
    class Meta:
        model = Dok
        fields ='__all__'

class ManSerial(serializers.ModelSerializer):
    data = Dokserial(source="dok_man",many=True)
    class Meta:
        model = Man
        fields = '__all__'
</code>```

答:
```<code>man = Man.objects.get_or_create(name=new_man_name, age=new_man_age)
Dok.objects.create(man=man, cool=new_cool)
</code>```

This will select an existing man if present (with name and age attributes) or will create a new one if not.

Body:
When i post new data i want to check create new man object and  dok object related to  man objects but if man object alredy exist i want to append related dok to it
any idea how to start i'm totally new to rest_framework

class Man(ListCreateAPIView):
    queryset =  Man.objects.all()
    serializer_class = ManSerial

model.py

class Man(models.Model):
    name = models.CharField(max_length=50,unique=True)
    age = models.IntegerField()
    def __str__(self):
        return self.name

class Dok(models.Model):
    man = models.ForeignKey(Man,on_delete=models.CASCADE,related_name="dok_man")
    cool =  models.CharField(max_length=400)
    def __str__(self) :
        return str(self.man)

serializer.py

class Dokserial(serializers.ModelSerializer):
    class Meta:
        model = Dok
        fields ='__all__'

class ManSerial(serializers.ModelSerializer):
    data = Dokserial(source="dok_man",many=True)
    class Meta:
        model = Man
        fields = '__all__'

Body:
man = Man.objects.get_or_create(name=new_man_name, age=new_man_age)
Dok.objects.create(man=man, cool=new_cool)

This will select an existing man if present (with name and age attributes) or will create a new one if not.


问:
Is it possible to remove embed value?
I have been trying to remobe the value of an embed because I don't like it there but I cant find a way to "bypass" it.

Does anyone have a solution?

https://i.stack.imgur.com/eQxrG.png

答: Use \u200b, this is a white space like a space bar, but as a unicode character.

Title: Is it possible to remove embed value?


问:
Problem looping through web controls
I've got a web page where I am dynamically creating controls during Page_Load event (this is done so because I do not know how many controls I will need until session is active and certain variables are accessible)

I need to be able to loop through these controls to find Checkbox when a button click is processed. Looping through the Form.Controls does not appear to be sufficient. I would think that Request.Form might work but it does not appear to be accessible in my C# block?

What should code for Request.Form look like? OR

Has anyone done this before with dynamically created controls?

Any insight is appreciated.

答: You should have access to Request["xyz"] anywhere in your aspx.cs code. You can either find control as described above and read it's value or do so directly from Request using the Control.UniqueID property. For example if it's a checkbox that's within the repeater then the UniqueID would look like dtgData$ctl02$txtAmount

Title: Problem looping through web controls


问:
Minkowski Sum of 3D(+) convex polygons
My goal is to obtain the representations of all faces (in the form of A[x,y,z]'>b) of a polyhedron that is the result of the convex difference between two convex polyhedra. Meaning, finding the intersection of all planes that are the result of the Minkowski difference of P1 - P2  = { x - y | x \in P1, y \in P2 }.

I'm looking for either an established library (Python?) or an idea on how to do this efficiently. I thought about doing something similar to the GJK algorithm but I need all of the faces, and not just compute whether the origin is inside quickly. Moreover, seems inefficient to use this support function in a methodological way in 3D, or higher dimensions. Also, let's say I got the vertices, do I now need to form the plane equation from two vectors on it with the cross product, for every face, or is there a way to obtain it from the Minkowski sum itself? (keeping in mind the need for higher dimensions).

答:
Ok, it seems I was finally able to solve it, and I'm posting in case it would interest anyone in the future:

First, I pip installed the pypoman library.
With it, we are able to move easily between vertices and faces with compute_polytope_halfspaces (aka, the H-representation of a polytope). So I get the representation P_i: H_i x < h_i for i=1,2 from the vertices (or skip it if it's already in the correct format).

Now  if we set P_sum = {[x1;x2] \in R^2n | [H_1 0; 0 H_2] [x1;x2]' < [h_1,h_2]'}, notice that the Minkowski sum is equivalent to P1+P2 = [I,I] P_sum (idea from this paper IV.B). So I can use pypoman's project_polytope function to get the Minkwoski sum with H_sum x < h_sum in the original dimensions.

Title: Minkowski Sum of 3D(+) convex polygons


问:
Type hinting on Python subclasses
The List[Geometry] type hint on the code below does not cause self.items.append(line) to complain because line is a Line which is subclass of Geometry.

The same type hint causes the item.is_horizontal on the last line to say Unresolved attribute reference 'is_horizontal' for class 'Geometry'.

I think this happens because the is_horizontal property exists only in one of the subclasses of Geometry.

What is the correct way to avoid this warning?

With List[Union[Geometry, Line, Circle]] the warning goes away, but I'm not sure this is the correct solution. Listing a set of classes is not like saying <Geometry> and all subclasses.

class Geometry:
    is_circle = is_line = False

class Line(Geometry):
    is_line = True          # property on Geometry and subclasses
    is_horizontal = True    # property only on Line

class Circle(Geometry):
    is_circle = True        # property on Geometry and subclasses
    radius = 10             # property only on Line

class Geometries:
    def __init__(self):
        self.items: List[Geometry] = []

    def add_line(self, line: Line):
        self.items.append(line)

    def horizontal_lines(self):
        return [item for item in self.items if item.is_line and item.is_horizontal]
```

答:
Use an actual type check, with isinstance:

```<code>def horizontal_lines(self):
    return [item for item in self.items if isinstance(item, Line) and item.is_horizontal]
</code>```

From a static typing perspective, there is no connection between an is_line attribute and whether or not an object is an instance of Line. There could be other subclasses of Geometry somewhere else in the program with is_line = True but no is_horizontal, or instances could have is_line set at the instance level.

Title: Type hinting on Python subclasses

Body:
Use an actual type check, with isinstance:

def horizontal_lines(self):
    return [item for item in self.items if isinstance(item, Line) and item.is_horizontal]

From a static typing perspective, there is no connection between an is_line attribute and whether or not an object is an instance of Line. There could be other subclasses of Geometry somewhere else in the program with is_line = True but no is_horizontal, or instances could have is_line set at the instance level.


问:
Laravel: redirect from controller to named route with params in URL
how can I redirect from my controller to a named route and include variables in the URL, e.g.

```<code>return Redirect::to('admin/articles/create/'.$article_type.'/'.$area_id.'/'.$area_type);
</code>```

this works, but I think that I missed a shortcut or something?

答:
In Laravel 9 you can use the to_route() helper function.

return to_route('route.name', [$param]);
```

Body:
how can I redirect from my controller to a named route and include variables in the URL, e.g.

return Redirect::to('admin/articles/create/'.$article_type.'/'.$area_id.'/'.$area_type);

this works, but I think that I missed a shortcut or something?


问:
Identifying duplicates in a list of character vectors in R
I have a list of character vectors like this:

```<code>my_list <- list(c('a','b','c','d','e'),c('e','f','g'),c('h','i','j'))
names(my_list) <- c("group1","group2","group3")
</code>```

And I want to have a simple way to test my_list for duplicates in the letters across any of the 3 groups/vectors in my list.  So for instance, "e" appears in both group 1 and group 2 so that would be a duplicate.  Anything simple that just returns a logical if there is at least one or more duplicates across 2 or more groups would be ideal.  So a FALSE return would mean that the letters in each group are unique to that group only (this isn't the case in my example here obviously).

Thanks so much!

答:
Another possible solution, based on tidyr::expand_grid and purrr::pmap_lgl:

library(tidyverse)

my_list <- list(c('a','b','c','d','e'),c('e','f','g'),c('h','i','j'))
names(my_list) <- c("group1","group2","group3")

expandg <- expand_grid(names(my_list), names(my_list))

pmap_lgl(expandg, ~ any(my_list[[.x]] %in% my_list[[.y]])) %>%
  bind_cols(id1 = expandg[[1]], id2 = expandg[[2]], value = .) %>%
  group_by(Group = id1) %>% summarise(value = any(value[id1 != id2]))

#> # A tibble: 3 × 2
#>   Group  value
#>   <chr>  <lgl>
#> 1 group1 TRUE
#> 2 group2 TRUE
#> 3 group3 FALSE
```

Body:
I have a list of character vectors like this:

my_list <- list(c('a','b','c','d','e'),c('e','f','g'),c('h','i','j'))
names(my_list) <- c("group1","group2","group3")

And I want to have a simple way to test my_list for duplicates in the letters across any of the 3 groups/vectors in my list.  So for instance, "e" appears in both group 1 and group 2 so that would be a duplicate.  Anything simple that just returns a logical if there is at least one or more duplicates across 2 or more groups would be ideal.  So a FALSE return would mean that the letters in each group are unique to that group only (this isn't the case in my example here obviously).

Thanks so much!


问:
Mapbox with Angular 6. "map container not found" error
I am developing my first angular web app and I want to introduce something similar to Google maps. I dón´t want to use this last one because of new billing politics, so I have tried MapBox.

Following the tutorial, I managed to create the map I need; the problem is, I don´t know how to display it on an angular component.

I generated this file for the map, and works perfectly with the browser and when I paste it directly on the index.html of my angular project. But when I try to use it on a component, I don´t know how to do it.

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset='utf-8' />
    <title>Points on a map</title>
    <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
    <script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.47.0/mapbox-gl.js'></script>
    <link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.47.0/mapbox-gl.css' rel='stylesheet' />
    <style>
      body {
        margin: 0;
        padding: 0;
      }

      #map {
        position: absolute;
        top: 0;
        bottom: 0;
        width: 100%;
      }
    </style>
  </head>
  <body>
      <div id='map'></div>
      <script>
        mapboxgl.accessToken = 'myToken'; // replace this with your access token
        var map = new mapboxgl.Map({
        container: 'map',
        style: 'my style URL', // replace this with your style URL
        center: [-2.8662684, 43.2806562],
        zoom: 15
});
// code from the next step will go here

        map.on('click', function(e) {
          var features = map.queryRenderedFeatures(e.point, {
          layers: ['rhynux'] // replace this with the name of the layer
      });

        if (!features.length) {
          return;
         }

      var feature = features[0];

      var popup = new mapboxgl.Popup({ offset: [0, -15] })
.setLngLat(feature.geometry.coordinates)
.setHTML('<h3>' + feature.properties.title +      '</h3><p>' + feature.properties.description +     '</p>')
.setLngLat(feature.geometry.coordinates)
        .addTo(map);
    });

    </script>
  </body>
</html>
</code>```

I moved

 to the component; but error is thrown "map container not found".

I also tried to install some nom packages like this one but it has not enough information on how to use it for newbies like me.

This another one has no documentation either...

And I looked on several SO posts but found no understanding on how to do it.

Thanks. Your help is very appreciated

答: I had the same problem, it turned out that I had put an empty space in the id attribute like this: id="map "</p>

Body:
I am developing my first angular web app and I want to introduce something similar to Google maps. I dón´t want to use this last one because of new billing politics, so I have tried MapBox.

Following the tutorial, I managed to create the map I need; the problem is, I don´t know how to display it on an angular component.

I generated this file for the map, and works perfectly with the browser and when I paste it directly on the index.html of my angular project. But when I try to use it on a component, I don´t know how to do it.

<!DOCTYPE html>

    <meta charset='utf-8' />
    <title>Points on a map</title>
    <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />

    <link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.47.0/mapbox-gl.css' rel='stylesheet' />

I moved

 to the component; but error is thrown "map container not found".

I also tried to install some nom packages like this one but it has not enough information on how to use it for newbies like me.

This another one has no documentation either...

And I looked on several SO posts but found no understanding on how to do it.

Thanks. Your help is very appreciated


问:
Flask Dynamic URL routing - bad request 400
I'm using Flask to build a web app and having issues with dynamic routing with variables.
I'm getting a bad request when I run the program.

The whole goal is to create a dynamic URL. The hope is to get dynamic URLs based on user selection. Running the program shows the correct URL (webapp.com/result/ko) but will not show the contents of the page.

Python:

```<code>from flask import Flask, redirect, render_template, request, url_for

app = Flask(__name__)
# This saves the users requested ticker choice in a varible to be used later
def users_request():
    global ticker_choice
    ticker_choice = request.form["variable"]
    return("Your choosen ticker: " + ticker_choice.upper())

class companySearch:

    # Stock price function
    def stock_price_func(self):
        try:
            with urlopen(base_url + quote + ticker_choice.upper() + api_key) as response:
                source = response.read()
                data = json.loads(source)

            price = "$" + str((data[0]["price"]))
            return(price)
        except:
            return("-")

# Routing to the homepage
@app.route("/", methods = ["GET", "POST"])
def market_hours_today():
    if request.method == "POST":
        result = request.form["variable"]
        return redirect(url_for("ticker_result", variable=result))

    return render_template(
        "index.html")

# Routing to the result page
@app.route("/result/<variable>", methods = ["GET", "POST"])
def ticker_result(variable):
    users_ticker_choice = users_request()
    stock_price = companySearch().stock_price_func()
    if request.method == "POST":
        result = request.form["variable"]
        return render_template(
            "result.html",
            result=result,
            users_ticker_choice=users_ticker_choice,
            stock_price=stock_price)

if __name__ == '__main__':
    app.run(debug=True)
</code>```

HTML:

```<code><!DOCTYPE html>
<html lang="en">
</head>
<body>
    <div class="container">
        <div class="cell" id="cell-1-2">
            <span class="data" style="text-align: center;">
                <form action="{{ url_for('market_hours_today') }}" method="POST">
                <input type="text" name="variable" placeholder="search ticker or company" maxlength="4" font-size="24px" onkeypress="return (event.charCode > 64 &&
                event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)" style="text-transform:uppercase">
                <input class="button" type="submit" value="Search" onclick="tickerSymbol();">
                </form>
            </span>
        </div>
    </div>
</body>
</html>
</code>```

答: as far as I can see the ticker_result function does not return anything for GET requests.</p>

Body:
I'm using Flask to build a web app and having issues with dynamic routing with variables.
I'm getting a bad request when I run the program.

The whole goal is to create a dynamic URL. The hope is to get dynamic URLs based on user selection. Running the program shows the correct URL (webapp.com/result/ko) but will not show the contents of the page.

Python:

from flask import Flask, redirect, render_template, request, url_for

app = Flask(__name__)
# This saves the users requested ticker choice in a varible to be used later
def users_request():
    global ticker_choice
    ticker_choice = request.form["variable"]
    return("Your choosen ticker: " + ticker_choice.upper())

class companySearch:

    # Stock price function
    def stock_price_func(self):
        try:
            with urlopen(base_url + quote + ticker_choice.upper() + api_key) as response:
                source = response.read()
                data = json.loads(source)

            price = "$" + str((data[0]["price"]))
            return(price)
        except:
            return("-")

# Routing to the homepage
@app.route("/", methods = ["GET", "POST"])
def market_hours_today():
    if request.method == "POST":
        result = request.form["variable"]
        return redirect(url_for("ticker_result", variable=result))

    return render_template(
        "index.html")

# Routing to the result page
@app.route("/result/<variable>", methods = ["GET", "POST"])
def ticker_result(variable):
    users_ticker_choice = users_request()
    stock_price = companySearch().stock_price_func()
    if request.method == "POST":
        result = request.form["variable"]
        return render_template(
            "result.html",
            result=result,
            users_ticker_choice=users_ticker_choice,
            stock_price=stock_price)

if __name__ == '__main__':
    app.run(debug=True)

HTML:

<!DOCTYPE html>

                <form action="{{ url_for('market_hours_today') }}" method="POST">
                <input type="text" name="variable" placeholder="search ticker or company" maxlength="4" font-size="24px" onkeypress="return (event.charCode > 64 &&
                event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)" style="text-transform:uppercase">
                <input class="button" type="submit" value="Search" onclick="tickerSymbol();">
                </form>


问:
How do you create a new line in f-strings?
I'm trying to create new lines using python for the variable "profile" using the 'new_line' variable, but I haven't been successful.

The code below does not produce errors. It gives me all 3 strings in one line and I'd like to get 3 lines.

I would like the output to look like this with a new line for each string.

```<code>        response: response
        Lat/Lon: 1293.2312,123123.432
        City: New York"
</code>```
```<code>from flask import Flask
from flask import jsonify
import requests
import json
import os

app = Flask(__name__)

@app.route('/change/')
def he():
    API_KEY = "API_KEY"
    CITY_NAME = "oakland"
    url = f"http://api.openweathermap.org/data/2.5/weather?q={CITY_NAME}&appid={API_KEY}"
    response = requests.get(url).json()
    new_line='\n'
    profile = (

        f"response: {response} ============== {new_line}"
        f"Lat/Lon: {response['coord']} ========={new_line}"
        f"City: {CITY_NAME}========{new_line}"

    )

    return profile
</code>```

答:
Try new_line='
'.

If you're viewing it in browser, it may interpret the page as badly formatted HTML and ignore line breaks and whitespaces, therefore you will need to use tags for that.

Body:
I'm trying to create new lines using python for the variable "profile" using the 'new_line' variable, but I haven't been successful.

The code below does not produce errors. It gives me all 3 strings in one line and I'd like to get 3 lines.

I would like the output to look like this with a new line for each string.

        response: response
        Lat/Lon: 1293.2312,123123.432
        City: New York"

from flask import Flask
from flask import jsonify
import requests
import json
import os

app = Flask(__name__)

@app.route('/change/')
def he():
    API_KEY = "API_KEY"
    CITY_NAME = "oakland"
    url = f"http://api.openweathermap.org/data/2.5/weather?q={CITY_NAME}&appid={API_KEY}"
    response = requests.get(url).json()
    new_line='\n'
    profile = (

        f"response: {response} ============== {new_line}"
        f"Lat/Lon: {response['coord']} ========={new_line}"
        f"City: {CITY_NAME}========{new_line}"

    )

    return profile

Body:
Try new_line='</br>'.

If you're viewing it in browser, it may interpret the page as badly formatted HTML and ignore line breaks and whitespaces, therefore you will need to use tags for that.


问:
Constant already defined in function prototype
I have this code :

<?php

define('LOG_DEBUG','DEBUG');
define('LOG_ERROR','ERROR');

function trace($message,$level=LOG_DEBUG){
    echo '['.date('Y-m-d H:i:s').' '.$level.'] '.$message."\n";
}

trace('test debug message');
trace('test error message', LOG_ERROR);
```
<p>Output (Running in PHP 7.4) :</p>
```PHP Notice:  Constant LOG_DEBUG already defined in /var/www/mail_dumper/PHPMailDumper.php on line 3
[2022-02-11 22:00:33 7] test debug message
[2022-02-11 22:00:33 ERROR] test error message
```

I don't understand the notice...

I tried to affect LOG_DEBUG to default value and not try to reaffect?

And... In trace test we see a "7" in output?

答: You're getting this warning because LOG_DEBUG is a predefined PHP constant for the syslog function.

Body:
I have this code :

<?php

define('LOG_DEBUG','DEBUG');
define('LOG_ERROR','ERROR');

function trace($message,$level=LOG_DEBUG){
    echo '['.date('Y-m-d H:i:s').' '.$level.'] '.$message."\n";
}

trace('test debug message');
trace('test error message', LOG_ERROR);

Output (Running in PHP 7.4) :

PHP Notice:  Constant LOG_DEBUG already defined in /var/www/mail_dumper/PHPMailDumper.php on line 3
[2022-02-11 22:00:33 7] test debug message
[2022-02-11 22:00:33 ERROR] test error message

I don't understand the notice...

I tried to affect LOG_DEBUG to default value and not try to reaffect?

And... In trace test we see a "7" in output?


问:
Bash: match in a list of files, cases including and excluding pattern
I'd need to find the cleanest way in bash to extract from hundred of files, the files matching some patterns in their contents AND NOT matching some others.

for instance:

```<code>  for transaction in "TXNA" "TXNB" "TXNC" "TXND" "TXNE" ; do
      echo "--> ${transaction}"
      grep -L "EXCLUDE_PATTERN1" $(grep -lL "EXCLUDE_PATTERN2" $(grep -Rl --include \*.txt "+${transaction}:" myDir/))   >> myReport.txt
    done
</code>```

so here:

```<code>grep -Rl --include \*.txt "+${transaction}:" myDir/
</code>```

grep in myDir recursively all the files.txt matching the TXNA..B

Then

```<code>$(grep -lL "EXCLUDE_PATTERN2" $(grep -Rl --include \*.txt "+${transaction}:" myDir/)
</code>```

Exclude in the list found before the files containing the patterns EXCLUDE_PATTERN2

and finally:

```<code>grep -L "EXCLUDE_PATTERN1"
</code>```

Exclude in the list found before the files containing the patterns EXCLUDE_PATTERN1

This is quite ugly as I have around 10 patterns to exclude it will become not readable at all.

Any idea for making this code more readable and easy to debug?

Thanks a lot.

答:
You could use grep and xargs command to get your result, i.e.:

```<code>grep -lHZR -e 'firstpattern' yourdir |xargs -0 grep -lHZ 'secondpattern' |xargs -0 grep -lHZ 'thirdpattern' |xargs -0 grep -LHZ  firstantipattern ... |xargs -0 grep -LH  lastantipattern
</code>```

All but first and last grep have same switches (-lHZ, and optionally -LHZ for antipatterns). First also have R, to list files in your directory, and last one does not have Z, to your final output is not null-terminated.

Z options enables passing output as null-terminated, to allow work with files containing blanks in names, and H enforces grep to print filename even if only one file is found.

Body:
I'd need to find the cleanest way in bash to extract from hundred of files, the files matching some patterns in their contents AND NOT matching some others.

for instance:

  for transaction in "TXNA" "TXNB" "TXNC" "TXND" "TXNE" ; do
      echo "--> ${transaction}"
      grep -L "EXCLUDE_PATTERN1" $(grep -lL "EXCLUDE_PATTERN2" $(grep -Rl --include \*.txt "+${transaction}:" myDir/))   >> myReport.txt
    done

so here:

grep -Rl --include \*.txt "+${transaction}:" myDir/

grep in myDir recursively all the files.txt matching the TXNA..B

Then

$(grep -lL "EXCLUDE_PATTERN2" $(grep -Rl --include \*.txt "+${transaction}:" myDir/)

Exclude in the list found before the files containing the patterns EXCLUDE_PATTERN2

and finally:

grep -L "EXCLUDE_PATTERN1"

Exclude in the list found before the files containing the patterns EXCLUDE_PATTERN1

This is quite ugly as I have around 10 patterns to exclude it will become not readable at all.

Any idea for making this code more readable and easy to debug?

Thanks a lot.

Body:
You could use grep and xargs command to get your result, i.e.:

grep -lHZR -e 'firstpattern' yourdir |xargs -0 grep -lHZ 'secondpattern' |xargs -0 grep -lHZ 'thirdpattern' |xargs -0 grep -LHZ  firstantipattern ... |xargs -0 grep -LH  lastantipattern

All but first and last grep have same switches (-lHZ, and optionally -LHZ for antipatterns). First also have R, to list files in your directory, and last one does not have Z, to your final output is not null-terminated.

Z options enables passing output as null-terminated, to allow work with files containing blanks in names, and H enforces grep to print filename even if only one file is found.


问:
How to extract the value when there is no value tag using Selenium and Java
I want to get value of input tag and compare with sum of 2 numbers. But there is no value tag, or I can not see result number. I tried to get but I got null. The picture and Input tag is like under.

```<code><input _ngcontent-lbg-c92="" matinput="" type="number" class="mat-input-element mat-form-field-autofill-control ng-tns-c35-2 cdk-text-field-autofill-monitored ng-untouched ng-pristine" style="text-align: center;" id="mat-input-2" aria-invalid="false" aria-required="false" disabled="">
</code>```

Element snapshot:

答:
To print the value i.e. 1626 you can use either of the following locator strategies:

Using cssSelector:

```<code>System.out.println(driver.findElement(By.cssSelector("input.mat-input-element[id^='mat-input'][type='number'][matinput]")).getAttribute("value"));
</code>```

Using xpath:

```<code>System.out.println(driver.findElement(By.xpath("//input[contains(@class, 'mat-input-element') and starts-with(@id, 'mat-input')][@type='number' and @matinput]")).getAttribute("value"));
</code>```

However, as the element is a dynamic element so to identify the element you need to induce WebDriverWait for the presenceOfElementLocated() and you can use either of the following locator strategies:

Using cssSelector:

```<code>System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("input[id*='Empty'][value='emptyAssembly']"))).getAttribute("value"));
</code>```

Using xpath:

```<code>System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.presenceOfElementLocated(By.xpath("//input[@value='emptyAssembly' and contains(@id, 'Empty')]"))).getAttribute("value"));
</code>```

Body:
I want to get value of input tag and compare with sum of 2 numbers. But there is no value tag, or I can not see result number. I tried to get but I got null. The picture and Input tag is like under.

<input _ngcontent-lbg-c92="" matinput="" type="number" class="mat-input-element mat-form-field-autofill-control ng-tns-c35-2 cdk-text-field-autofill-monitored ng-untouched ng-pristine" style="text-align: center;" id="mat-input-2" aria-invalid="false" aria-required="false" disabled="">

Element snapshot:

Body:
To print the value i.e. 1626 you can use either of the following locator strategies:

Using cssSelector:

System.out.println(driver.findElement(By.cssSelector("input.mat-input-element[id^='mat-input'][type='number'][matinput]")).getAttribute("value"));

Using xpath:

System.out.println(driver.findElement(By.xpath("//input[contains(@class, 'mat-input-element') and starts-with(@id, 'mat-input')][@type='number' and @matinput]")).getAttribute("value"));

However, as the element is a dynamic element so to identify the element you need to induce WebDriverWait for the presenceOfElementLocated() and you can use either of the following locator strategies:

Using cssSelector:

System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("input[id*='Empty'][value='emptyAssembly']"))).getAttribute("value"));

Using xpath:

System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.presenceOfElementLocated(By.xpath("//input[@value='emptyAssembly' and contains(@id, 'Empty')]"))).getAttribute("value"));


问:
What's the usage of three dots (...) in dart List?
I have my code written like this but it gives an error saying:

Error: A value of type 'List' can't be assigned to a variable of type 'Widget'.

Column(
  children: [
    Question(
      questions[_questionIndex]['questionText'],
    ),
    ...(questions[_questionIndex]['answers'] as List<String>)
        .map((answer) {
      return Answer(_answerQuestion, answer);
    }).toList()
  ],
)
```

答:
```<code>var x = [20,30,40];
var list = [1,2,3,x];

// Using the spread operator, adds the items individually not as a list
var separatedList = [1,2,3,...x];

print(list); // length = 4
print(separatedList); // length = 6
</code>```

Results

```<code>[1, 2, 3, [20, 30, 40]]
[1, 2, 3, 20, 30, 40]
</code>```

Body:
var x = [20,30,40];
var list = [1,2,3,x];

// Using the spread operator, adds the items individually not as a list
var separatedList = [1,2,3,...x];

print(list); // length = 4
print(separatedList); // length = 6

Results

[1, 2, 3, [20, 30, 40]]
[1, 2, 3, 20, 30, 40]


问:
How to extend ESP32 heap size?
I'm writing a code about play gif from SDCard on TFT Screen, so I create a array to put the gif file. (Using Nodemcu-32s 4MB)

```<code>#include<TFT_eSPI.h>
#include<SPI.h>
#include<AnimatedGIF.h>

TFT_eSPI tft;
AnimatedGIF gif;
uint8_t *gifArray;
int gifArrayLen;

void setup(){
  tft.init();
  tft.setRotation(2);
  tft.fillScreen(TFT_BLACK);

  File fgif=SD.open("/test.gif",FILE_READ);
  gifArrayLen=fgif.size();
  gifArray=(uint8_t *)malloc(gifArrayLen);
  for(int i=0;i<gifArrayLen;i++) gifArray[i]=fgif.read();
  fgif.close();
}

void loop(){
  tft.startWrite();
  gif.open(gifArray,gifArrayLen*sizeof(uint8_t),GIFDraw);
  while(gif.playFrame(true,NULL)) yield();
  gif.close();
  tft.endWrite();
}
</code>```

But if gif size > 131KB, it will trigger fatal error like this.

Guru Meditation Error: Core  1 panic'ed (StoreProhibited). Exception was unhandled.

After malloc the array, when I set a value on it, it triggered.

I found some forum says it's because it over the FreeRTOS heap size.

Can I extend the heap size or use another storage method to replace it?

答:
The "4MB" in NodeMCU refers to the size of flash, the size of RAM on ESP32 is fixed at 512KB, roughly 200KB of which is used by IRAM cache/code sections, leaving around 320KB for program memory, half of which is available for dynamic allocation.

From documentation Heap Memory - Available Heap:

Due to a technical limitation, the maximum statically allocated DRAM
usage is 160KB. The remaining 160KB (for a total of 320KB of DRAM) can
only be allocated at runtime as heap.

There is a way to connect more RAM via SPI, but it's going to be very slow. You might want to look into a larger SoC with more RAM instead.

Title: How to extend ESP32 heap size?

Body:
I'm writing a code about play gif from SDCard on TFT Screen, so I create a array to put the gif file. (Using Nodemcu-32s 4MB)

#include<TFT_eSPI.h>
#include<SPI.h>
#include<AnimatedGIF.h>

TFT_eSPI tft;
AnimatedGIF gif;
uint8_t *gifArray;
int gifArrayLen;

void setup(){
  tft.init();
  tft.setRotation(2);
  tft.fillScreen(TFT_BLACK);

  File fgif=SD.open("/test.gif",FILE_READ);
  gifArrayLen=fgif.size();
  gifArray=(uint8_t *)malloc(gifArrayLen);
  for(int i=0;i<gifArrayLen;i++) gifArray[i]=fgif.read();
  fgif.close();
}

void loop(){
  tft.startWrite();
  gif.open(gifArray,gifArrayLen*sizeof(uint8_t),GIFDraw);
  while(gif.playFrame(true,NULL)) yield();
  gif.close();
  tft.endWrite();
}

But if gif size > 131KB, it will trigger fatal error like this.

Guru Meditation Error: Core  1 panic'ed (StoreProhibited). Exception was unhandled.

After malloc the array, when I set a value on it, it triggered.

I found some forum says it's because it over the FreeRTOS heap size.

Can I extend the heap size or use another storage method to replace it?


问:
Unit Testing TSQL
Is there anybody out there writing unit tests for their TSQL stored procedures, triggers, functions ... etc.

I've recently started making database and restores and installs part of our automated Cruise Control build process.  Now I'm thinking about taking it to the next level where we do the install, then run through a list of stored procedure tests etc.

I was going to just roll my own using MsBuild Extensions to invoke the tests.  However I'm aware of http://www.tsqltest.org/ and http://tsqlunit.sourceforge.net/.  I'm also aware that TFS has sql testing.

I just wanted to see what people in the real world are doing and if they have any suggestions.

Thanks

答:
Stored procedures. I generally include test queries in comments in the SP header, and record correct results and query times. This still leaves it as a manual exercise, however.)

Functions. Again, put SQL statements in the header with the same info.

Triggers. I avoid them for a number of reasons, one of them being that they are so hard to test and debug for so little benefit compared to putting the same logic in another tier. It's like asking how to test for Referential Integrity.

This is still a manual process, however. But since I think one should intentionally design SQL artifacts to be totally uncoupled (e.g. no SPs calling SPs, same with functions, and another strike against triggers IMHO) it's relatively less complex.

OwnerDisplayName: Richard

ContentLicense: CC BY-SA 2.5

Title: Unit Testing TSQL

OwnerDisplayName: le dorfier

LastEditorDisplayName: le dorfier


问:
React select onChange is getting triggered for the second time with old value
I am using React Select to show list of items . On change of item , i want to show a warning based on some flag . If flag is true , Dialog box will be displayed and and confirm of that , I want to allow the change . For every on on change , i am storing the selected item in local state use effect . On click of confirm from dialog box or if flag is false , i am dispatching actions to store them in redux store .

I am having issue when Dialog box is appearing and on click of confirm, item in dropdown is changing , but onChange is getting called again with first value ,Hence dropdown is going back to initial value .

Why is onChange getting called twice .

Tried event.preventDefault , but not working.

```<code>const [name, setName] = React.useState();

const changeValue = (event,selectedItem) => {
    event.preventDefault()
    setName(selectedItem) // storing in UseState hook
    if(flag){
        props.toggleWarningDialog(true);
    }
    else {
        props.onChangeItem(selectedItem);
    }
}

const handleConfirmChange = (event) => {
        event.preventDefault()
        props.onChangeItem(name); //getting from useState hook and storing in redux by dispatching an action
 }
</code>```

答:
stopPropagation prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
We can use event.isPropagationStopped() to determine if this method was ever called (on that event object).

Note that this will not prevent other handlers on the same element from running.

```<code>event.stopPropagation();
</code>```

Body:
I am using React Select to show list of items . On change of item , i want to show a warning based on some flag . If flag is true , Dialog box will be displayed and and confirm of that , I want to allow the change . For every on on change , i am storing the selected item in local state use effect . On click of confirm from dialog box or if flag is false , i am dispatching actions to store them in redux store .

I am having issue when Dialog box is appearing and on click of confirm, item in dropdown is changing , but onChange is getting called again with first value ,Hence dropdown is going back to initial value .

Why is onChange getting called twice .

Tried event.preventDefault , but not working.

const [name, setName] = React.useState();

const changeValue = (event,selectedItem) => {
    event.preventDefault()
    setName(selectedItem) // storing in UseState hook
    if(flag){
        props.toggleWarningDialog(true);
    }
    else {
        props.onChangeItem(selectedItem);
    }
}

const handleConfirmChange = (event) => {
        event.preventDefault()
        props.onChangeItem(name); //getting from useState hook and storing in redux by dispatching an action
 }

Body:
stopPropagation prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
We can use event.isPropagationStopped() to determine if this method was ever called (on that event object).

Note that this will not prevent other handlers on the same element from running.

event.stopPropagation();


问:
How do you stream your screen via python and nodejs (both with socket.io) to a webpage
I'm working on a website that turns my ipad into a drawing tablet for my laptop.

Most of the program is done, but I don't know how I'm gonna share my screen with my ipad.

Does one of you guys know how to do that?
If so then please let me know how

for the website I'm using nodejs & socket.io (html, css and js) and for actually moving the mouse I'm using python (pynput, python-socketio)

答:
Well,
you can capture 24 screenshots a second with PyAutoGUI and then send the data through a socket connection(see this and this)...

But i don't see the reason to do so. If you want to use your ipad as a drawing tablet you also need to sync the input and the latency will be substantial.
You will be better off by just using teamviewer or some other remote control app. Those services are much better at handling latency and input.

Sorry, but it will save you a ton of work and pain.


问:
ngx-perfect-scrollbar: How to reference to the directive from typescript?
I'm using ngx-perfect-scrollbar with my Angular 5 project. I want to scroll the div to top when the route changes.

dashboard.html

```<code><div class="main-panel" [perfectScrollbar] #perfectscroll>
    <router-outlet></router-outlet>
</div>
</code>```

dashboard.ts

```<code>@Component({
    selector: 'app-dashboard',
    templateUrl: './dashboard.component.html',
})
export class DashboardComponent implements OnInit {
    @ViewChild('perfectscroll') perfectscroll: PerfectScrollbarDirective;

    ngOnInit() {
        this.router.events.subscribe((evt) => {
            if (!(evt instanceof NavigationEnd)) {
                return;
            }
            this.perfectscroll.scrollToTop()
        });
    }
}
</code>```

But I get this error :

TypeError: _this.perfectscroll.scrollToTop is not a function

答:
It worked for me</p>
```<code>  @ViewChild(PerfectScrollbarDirective, { static: false }) perfectScrollbarDirectiveRef?: PerfectScrollbarDirective;
</code>```

Body:
I'm using ngx-perfect-scrollbar with my Angular 5 project. I want to scroll the div to top when the route changes.

dashboard.html

    <router-outlet></router-outlet>

dashboard.ts

@Component({
    selector: 'app-dashboard',
    templateUrl: './dashboard.component.html',
})
export class DashboardComponent implements OnInit {
    @ViewChild('perfectscroll') perfectscroll: PerfectScrollbarDirective;

    ngOnInit() {
        this.router.events.subscribe((evt) => {
            if (!(evt instanceof NavigationEnd)) {
                return;
            }
            this.perfectscroll.scrollToTop()
        });
    }
}

But I get this error :

TypeError: _this.perfectscroll.scrollToTop is not a function

Body:
It worked for me

  @ViewChild(PerfectScrollbarDirective, { static: false }) perfectScrollbarDirectiveRef?: PerfectScrollbarDirective;


问:
How to add values from an array as textContent with JavaScript
I'm having trouble figuring out how to add the values from an array as .textContent of a div.

What I want to happen is if I receive an array (topics) I want the contents of the array to be set as the .textContent of the elements with class="tab".

I feel like this code is correct, but doesn't seem to be working. Any ideas?

const Tabs = (topics) => {
  const tabsTopics = document.createElement("div");
  const tabsOne = document.createElement("div");
  const tabsTwo = document.createElement("div");
  const tabsThree = document.createElement("div");

  tabsTopics.classList.add("topics");
  tabsOne.classList.add("tab");
  tabsTwo.classList.add("tab");
  tabsThree.classList.add("tab");

  tabsTopics.appendChild(tabsOne);
  tabsTopics.appendChild(tabsTwo);
  tabsTopics.appendChild(tabsThree);

  document.querySelectorAll(".tab").forEach((el, i) => {
      el.textContent = topics[i];
    });

  return tabsTopics;
}

const topics = ['1', '2', '3'];

document.getElementById('container').appendChild(Tabs(topics));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container"></div></code>```

答:
The  shorter way...

const Tabs = (topics) =>
  {
  const tabsTopics = document.createElement('div')

  for (topic in topics)
    tabsTopics.appendChild(
       Object.assign(
          document.createElement('div')
          , { className:'tab', textContent: topic }
          )
       );
  return tabsTopics;
  }
const topics = ['1', '2', '3']

document.getElementById('container').appendChild(Tabs(topics));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.tab {
  color : blue;
  }</code>```

```

Body:
The  shorter way...

const Tabs = (topics) =>
  {
  const tabsTopics = document.createElement('div')

  for (topic in topics)
    tabsTopics.appendChild(
       Object.assign(
          document.createElement('div')
          , { className:'tab', textContent: topic }
          )
       );
  return tabsTopics;
  }
const topics = ['1', '2', '3']

document.getElementById('container').appendChild(Tabs(topics));

.tab {
  color : blue;
  }

<div id="container"></div>


问:
Bigquery SQL: Calculate the average recency and latency of customer transactions by month
I'm trying to calculate monthly averages of - customer recency (days since last order) and customer latency (days between last order and previous order).

Calculating recency on the last day of each reporting month.

Including customers in the monthly calculation where:

max(order_date) is BETWEEN reporting mth_end_date (i.e. not in future) and 12 months prior.

latency for the max(order_date) IS NOT NULL (i.e. it has a prior order)

Below is my progress to date using sample data.

EDIT: Updated query below now works for an individual month, but not across a range of dates.
I can't figure out how to join the date array and also use it in the calculations.

The values for Dec-2021 are (showing workings):

```<code>With input_data AS (

SELECT '#1238' as order_id, DATE('2021-12-15') as order_date, 'c12345' as cust_id, 18 as order_value
UNION ALL SELECT '#1201' as order_id, DATE('2021-10-10') as order_date, 'c12345' as cust_id, 18 as order_value
UNION ALL SELECT '#1198' as order_id, DATE('2021-07-05') as order_date, 'c12345' as cust_id, 20 as order_value
UNION ALL SELECT '#1134' as order_id, DATE('2020-10-15') as order_date, 'c12345' as cust_id, 10 as order_value
UNION ALL SELECT '#1112' as order_id, DATE('2019-08-10') as order_date, 'c12345' as cust_id, 5 as order_value
UNION ALL SELECT '#1234' as order_id, DATE('2021-07-05') as order_date, 'c11111' as cust_id, 118 as order_value
UNION ALL SELECT '#1294' as order_id, DATE('2021-01-05') as order_date, 'c11111' as cust_id, 68 as order_value
UNION ALL SELECT '#1290' as order_id, DATE('2021-01-01') as order_date, 'c11111' as cust_id, 82 as order_value
UNION ALL SELECT '#1284' as order_id, DATE('2020-01-15') as order_date, 'c22222' as cust_id, 98 as order_value),

-- date array that I'm trying to use to group by in final step but not used yet
dates AS (
  SELECT
   LAST_DAY(array_date, month) AS mth_end_date
  FROM
    UNNEST(GENERATE_DATE_ARRAY(
      (SELECT MIN(order_date) FROM input_data),
      (SELECT MAX(order_date) FROM input_data), INTERVAL 1 MONTH)) as array_date),

-- for each order record add the date of that customers prior order
-- exclude all orders in the future (relative to the report date)
enhanced_orders AS (
SELECT
*
,lag(order_date) OVER (PARTITION by cust_id ORDER BY order_date) AS cust_prev_order_date
FROM input_data
WHERE order_date < Date('2021-12-31')),

-- for each customer determine the most recent, and the next most recent, order dates
cust_calc as (
SELECT
cust_id
, max(order_date) as max_order_date
, max(cust_prev_order_date) as max_prev_order_date
FROM enhanced_orders
GROUP by 1),

-- for each customer calculate how many days ago their most recent order was from the report date,
-- and calculate the days between their last two most recent orders
-- exclude customers if their most recent order was >12m ago, or they don't have an order prior to their most recent one
cust_calc2 AS (
SELECT
cust_id
, date_diff(Date('2021-12-31'),  max_order_date, day) as recency
, date_diff(max_order_date, max_prev_order_date, day) as latency
FROM cust_calc
WHERE max_prev_order_date IS NOT NULL
AND max_order_date > date_sub(Date('2021-12-31'), INTERVAL 1 YEAR))

-- average the recency and latency of all customers at the report date
SELECT
avg(recency) AS monthly_recency
,avg(latency) AS monthly_latency
FROM cust_calc2
</code>```

答:
Here's some pseudo-code that I think will help:

```<code>with allorders as (
    select *, lag(orderdate) over (order by orderdate) as lastorderdate
    from T
    -- this is probably more efficient
    where orderdate between <one year ago> and <end of current month>
        and exists (
            select 1 from T t2
            -- this query isn't restricted by the one-year range
            where t2.customerid = T.customerid and t2.orderdate < T.orderdate
        )
)
select customerid, avg(<difference in lastorderdate and orderdate>)
from allorders
group by customerid
</code>```

This ought to work but it might be slow:

```<code>with recentorders as (
    select *, lag(orderdate) over (order by orderdate) as lastorderdate
    from T
)
select customerid, avg(<difference in lastorderdate and orderdate>)
from recentorders
where orderdate between <one year ago> and <end of current month>
    and lastorderdate is not null
group by customerid
</code>```

Body:
I'm trying to calculate monthly averages of - customer recency (days since last order) and customer latency (days between last order and previous order).

Calculating recency on the last day of each reporting month.

Including customers in the monthly calculation where:

max(order_date) is BETWEEN reporting mth_end_date (i.e. not in future) and 12 months prior.

latency for the max(order_date) IS NOT NULL (i.e. it has a prior order)

Below is my progress to date using sample data.

EDIT: Updated query below now works for an individual month, but not across a range of dates.
I can't figure out how to join the date array and also use it in the calculations.

The values for Dec-2021 are (showing workings):

With input_data AS (

SELECT '#1238' as order_id, DATE('2021-12-15') as order_date, 'c12345' as cust_id, 18 as order_value
UNION ALL SELECT '#1201' as order_id, DATE('2021-10-10') as order_date, 'c12345' as cust_id, 18 as order_value
UNION ALL SELECT '#1198' as order_id, DATE('2021-07-05') as order_date, 'c12345' as cust_id, 20 as order_value
UNION ALL SELECT '#1134' as order_id, DATE('2020-10-15') as order_date, 'c12345' as cust_id, 10 as order_value
UNION ALL SELECT '#1112' as order_id, DATE('2019-08-10') as order_date, 'c12345' as cust_id, 5 as order_value
UNION ALL SELECT '#1234' as order_id, DATE('2021-07-05') as order_date, 'c11111' as cust_id, 118 as order_value
UNION ALL SELECT '#1294' as order_id, DATE('2021-01-05') as order_date, 'c11111' as cust_id, 68 as order_value
UNION ALL SELECT '#1290' as order_id, DATE('2021-01-01') as order_date, 'c11111' as cust_id, 82 as order_value
UNION ALL SELECT '#1284' as order_id, DATE('2020-01-15') as order_date, 'c22222' as cust_id, 98 as order_value),

-- date array that I'm trying to use to group by in final step but not used yet
dates AS (
  SELECT
   LAST_DAY(array_date, month) AS mth_end_date
  FROM
    UNNEST(GENERATE_DATE_ARRAY(
      (SELECT MIN(order_date) FROM input_data),
      (SELECT MAX(order_date) FROM input_data), INTERVAL 1 MONTH)) as array_date),

-- for each order record add the date of that customers prior order
-- exclude all orders in the future (relative to the report date)
enhanced_orders AS (
SELECT
*
,lag(order_date) OVER (PARTITION by cust_id ORDER BY order_date) AS cust_prev_order_date
FROM input_data
WHERE order_date < Date('2021-12-31')),

-- for each customer determine the most recent, and the next most recent, order dates
cust_calc as (
SELECT
cust_id
, max(order_date) as max_order_date
, max(cust_prev_order_date) as max_prev_order_date
FROM enhanced_orders
GROUP by 1),

-- for each customer calculate how many days ago their most recent order was from the report date,
-- and calculate the days between their last two most recent orders
-- exclude customers if their most recent order was >12m ago, or they don't have an order prior to their most recent one
cust_calc2 AS (
SELECT
cust_id
, date_diff(Date('2021-12-31'),  max_order_date, day) as recency
, date_diff(max_order_date, max_prev_order_date, day) as latency
FROM cust_calc
WHERE max_prev_order_date IS NOT NULL
AND max_order_date > date_sub(Date('2021-12-31'), INTERVAL 1 YEAR))

-- average the recency and latency of all customers at the report date
SELECT
avg(recency) AS monthly_recency
,avg(latency) AS monthly_latency
FROM cust_calc2

Body:
Here's some pseudo-code that I think will help:

with allorders as (
    select *, lag(orderdate) over (order by orderdate) as lastorderdate
    from T
    -- this is probably more efficient
    where orderdate between <one year ago> and <end of current month>
        and exists (
            select 1 from T t2
            -- this query isn't restricted by the one-year range
            where t2.customerid = T.customerid and t2.orderdate < T.orderdate
        )
)
select customerid, avg(<difference in lastorderdate and orderdate>)
from allorders
group by customerid

This ought to work but it might be slow:

with recentorders as (
    select *, lag(orderdate) over (order by orderdate) as lastorderdate
    from T
)
select customerid, avg(<difference in lastorderdate and orderdate>)
from recentorders
where orderdate between <one year ago> and <end of current month>
    and lastorderdate is not null
group by customerid


问:
Hybrid algorithm that combines Insertion Sort and Quick Sort
I'm trying to implement a hybrid algorithm that combines Insertion Sort and Quick Sort to get the desired features of both in such a way so that when the elements are fewer than 50 in a quicksort step, Insertion Sort is used and for greater than 50 the elements are merged using the Quick Sort algorithm. I attempt to sort the elements to the left of the pivot_index and those to the right of the pivot_index using insertion sort if they are less than 50 by passing a slice instance of the original list as a parameter into my insertionSort function but my list remains the same, partitioned yet unsorted. Any indictors to fix this issue would be deeply appreciated.</p>
```<code>from random import randint

def insertionSort(arr):

    for i in range(1, len(arr)):
        key = arr[i]
        j = i - 1

        while j >= 0 and key < arr[j]:
            arr[j+1] = arr[j]
            j = j - 1

        arr[j+1] = key

def partition(a, low, high): #lomuto partition scheme
    i = low - 1 #directly to the left of our specified low-high range
    pivot = a[high] #pivot is the last value in our range, the index equal to high parameter
    for j in range(low, high):
        if a[j] <= pivot:
            i += 1
            a[i], a[j] = a[j], a[i]
    a[i+1], a[high] = a[high], a[i+1]
    return i+1

def quicksort_inplace(a, low=0, high=None):
    if high == None:
        high = len(a) - 1

    if low < high:
        pivot_index = partition(a, low, high) #partition around pivot
        print("The pivot_index is:", pivot_index)
        print("Low is:", low)
        print("High is:", high)

        if pivot_index - low <= 50:
            insertionSort(a[low:pivot_index])

        elif high - pivot_index <= 50:
            insertionSort(a[pivot_index+1:high])

        else:
            quicksort_inplace(a, low, pivot_index - 1) #sort lower half
            quicksort_inplace(a, pivot_index + 1, high) #sort upper half

def create_arr(size=10):
    return [randint(0,50) for _ in range(size)]

arr = create_arr()
print(arr)
quicksort_inplace(arr)
print()
print("The sorted array is:", arr)

</code>```

答:
Slicing a list results in shallow copies of the original sublist, so the original will not be modified by passing a slice instance to insertionSort. That is why the list is not sorted after partitioning in your code.

To apply insertion sort in-place, you can pass low and high as arguments:

def insertion_sort(arr, low, high):
    for i in range(low + 1, high + 1):
        j = i
        while j > low and arr[j] < arr[j - 1]:
            arr[j], arr[j - 1] = arr[j - 1], arr[j]
            j -= 1
```
<p>It would also be more efficient to check if the size is below the threshold before partitioning. The <code>quicksort_inplace</code> function can then be rewritten as follows (with <code>THRESHOLD = 50</code> in this case):</p>
<pre class="lang-py prettyprint-override"><code>def quicksort_inplace(a, low=0, high=None):
    if high is None:
        high = len(a) - 1

    if low < high:
        if high - low + 1 < THRESHOLD:
            # Size of the subarray is less than the threshold, insertion sort
            insertion_sort(a, low, high)
            return
        # Size of the subarray is greater than the threshold, quicksort
        pivot_index = partition(a, low, high)
        print("The pivot_index is:", pivot_index)
        print("Low is:", low)
        print("High is:", high)
        quicksort_inplace(a, low, pivot_index - 1)
        quicksort_inplace(a, pivot_index + 1, high)
</code>```

If the threshold is 50, the test array should obviously be much larger than 10 to properly test the function, otherwise you are only testing insertion sort.

Body:
I'm trying to implement a hybrid algorithm that combines Insertion Sort and Quick Sort to get the desired features of both in such a way so that when the elements are fewer than 50 in a quicksort step, Insertion Sort is used and for greater than 50 the elements are merged using the Quick Sort algorithm. I attempt to sort the elements to the left of the pivot_index and those to the right of the pivot_index using insertion sort if they are less than 50 by passing a slice instance of the original list as a parameter into my insertionSort function but my list remains the same, partitioned yet unsorted. Any indictors to fix this issue would be deeply appreciated.

from random import randint

def insertionSort(arr):

    for i in range(1, len(arr)):
        key = arr[i]
        j = i - 1

        while j >= 0 and key < arr[j]:
            arr[j+1] = arr[j]
            j = j - 1

        arr[j+1] = key

def partition(a, low, high): #lomuto partition scheme
    i = low - 1 #directly to the left of our specified low-high range
    pivot = a[high] #pivot is the last value in our range, the index equal to high parameter
    for j in range(low, high):
        if a[j] <= pivot:
            i += 1
            a[i], a[j] = a[j], a[i]
    a[i+1], a[high] = a[high], a[i+1]
    return i+1

def quicksort_inplace(a, low=0, high=None):
    if high == None:
        high = len(a) - 1

    if low < high:
        pivot_index = partition(a, low, high) #partition around pivot
        print("The pivot_index is:", pivot_index)
        print("Low is:", low)
        print("High is:", high)

        if pivot_index - low <= 50:
            insertionSort(a[low:pivot_index])

        elif high - pivot_index <= 50:
            insertionSort(a[pivot_index+1:high])

        else:
            quicksort_inplace(a, low, pivot_index - 1) #sort lower half
            quicksort_inplace(a, pivot_index + 1, high) #sort upper half

def create_arr(size=10):
    return [randint(0,50) for _ in range(size)]

arr = create_arr()
print(arr)
quicksort_inplace(arr)
print()
print("The sorted array is:", arr)

Body:
Slicing a list results in shallow copies of the original sublist, so the original will not be modified by passing a slice instance to insertionSort. That is why the list is not sorted after partitioning in your code.

To apply insertion sort in-place, you can pass low and high as arguments:

def insertion_sort(arr, low, high):
    for i in range(low + 1, high + 1):
        j = i
        while j > low and arr[j] < arr[j - 1]:
            arr[j], arr[j - 1] = arr[j - 1], arr[j]
            j -= 1

It would also be more efficient to check if the size is below the threshold before partitioning. The quicksort_inplace function can then be rewritten as follows (with THRESHOLD = 50 in this case):

def quicksort_inplace(a, low=0, high=None):
    if high is None:
        high = len(a) - 1

    if low < high:
        if high - low + 1 < THRESHOLD:
            # Size of the subarray is less than the threshold, insertion sort
            insertion_sort(a, low, high)
            return
        # Size of the subarray is greater than the threshold, quicksort
        pivot_index = partition(a, low, high)
        print("The pivot_index is:", pivot_index)
        print("Low is:", low)
        print("High is:", high)
        quicksort_inplace(a, low, pivot_index - 1)
        quicksort_inplace(a, pivot_index + 1, high)

If the threshold is 50, the test array should obviously be much larger than 10 to properly test the function, otherwise you are only testing insertion sort.