问:
Question about file reading and comparing
First Off I have a File That Looks Like This:

```<code>//Manager Ids

ManagerName: FirstName_LastName
ManagerLoginId: 12345
</code>```

And a Text Box That has a five digit code(ex. 12345) That gets entered. When the Enter Key Is pressed it is assigned to a String called: "EnteredEmployeeId", Then What I need is to search the Entire file above for "EnteredEmployeeId" and if it matches then it will open another page, if it doesn't find that number then display a message(That tells you no employee Id found).

So essentially Im trying to open a file search the entire document for the Id then return true or false to allow it too either display an error or open a new page, and reset the EnteredEmployeeId to nothing.

My Code So Far:

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Rent_a_Car
{
    public partial class Employee_Login_Page : Form
    {
        public Employee_Login_Page()
        {
            InitializeComponent();
        }
        string ManagersPath = @"C:\Users\Name\Visual Studios Project Custom Files\Rent A Car Employee Id's\Managers\Manager_Ids.txt"; //Path To Manager Logins
        string EnteredEmployeeId;

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void Employee_Id_TextBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) &&           //Checks Characters entered are Numbers Only and allows them
                (e.KeyChar != '0'))
            {
                e.Handled = true;
            }
            else if (e.KeyChar == (char)13)                                         //Checks if The "Enter" Key is pressed
            {
                EnteredEmployeeId = Employee_Id_TextBox.Text;                         //Assigns EnteredEmployeeId To the Entered Numbes In Text Box

                bool result = ***IsNumberInFile***(EnteredEmployeeId, "ManagerLoginId:", ManagersPath);
                if (result)
                {
                             //open new window
                }
                else
                {
                    MessageBox.Show("User Not Found");
                }
            }
        }
    }
}
</code>```

答:
If your Manager_Ids.txt is in the following format, you can use File.ReadLine() method to traverse the text and query it.

```<code>ManagerName: FirstName_LastName1
ManagerLoginId: 12345
ManagerName: FirstName_LastName2
ManagerLoginId: 23456
...
</code>```

Here is the demo that traverse the .txt.

```<code>string ManagersPath = @"D:\Manager_Ids.txt";
string EnteredEmployeeId;

private void textBox_id_KeyDown(object sender, KeyEventArgs e)
{
    int counter = 0;
    bool exist = false;
    string line;
    string str = "";

    if (e.KeyCode == Keys.Enter)
    {
        EnteredEmployeeId = textBox_id.Text;

        System.IO.StreamReader file =
            new System.IO.StreamReader(ManagersPath);
        while ((line = file.ReadLine()) != null)
        {
            str += line + "|";

            if (counter % 2 != 0)
            {
                if (str.Split('|')[1].Split(':')[1].Trim() == EnteredEmployeeId)
                {
                    str = str.Replace("|", "\n");
                    MessageBox.Show(str);
                    exist = true;
                    break;
                }
                str = "";
            }
            counter++;
        }

        if (!exist)
        {
            MessageBox.Show("No such id");
        }

        file.Close();
    }
}
</code>```

Besides, I recommend to use "xml", "json" or other formats to serialize the data. About storing the data in "xml", you can refer to the following simple demo.

```<code><?xml version="1.0"?>
<Managers>
  <Manager>
    <ManagerName>FirstName_LastName1</ManagerName>
    <ManagerLoginId>12345</ManagerLoginId>
  </Manager>
  <Manager>
    <ManagerName>FirstName_LastName2</ManagerName>
    <ManagerLoginId>23456</ManagerLoginId>
  </Manager>
</Managers>
</code>```

And then use LINQ to XML to query the id.

```<code>string ManagersPath = @"D:\Manager_Ids.xml";
string EnteredEmployeeId;

private void textBox_id_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        EnteredEmployeeId = textBox_id.Text;

        XElement root = XElement.Load(ManagersPath);
        IEnumerable<XElement> manager =
            from el in root.Elements("Manager")
            where (string)el.Element("ManagerLoginId") == EnteredEmployeeId
            select el;
        if(manager.Count() == 0)
        {
            MessageBox.Show("No such id");
        }
        foreach (XElement el in manager)
            MessageBox.Show("ManagerName: " + (string)el.Element("ManagerName") + "\n"
                + "ManagerLoginId: " + (string)el.Element("ManagerLoginId"));
    }
}
</code>```

Body:
First Off I have a File That Looks Like This:

//Manager Ids

ManagerName: FirstName_LastName
ManagerLoginId: 12345

And a Text Box That has a five digit code(ex. 12345) That gets entered. When the Enter Key Is pressed it is assigned to a String called: "EnteredEmployeeId", Then What I need is to search the Entire file above for "EnteredEmployeeId" and if it matches then it will open another page, if it doesn't find that number then display a message(That tells you no employee Id found).

So essentially Im trying to open a file search the entire document for the Id then return true or false to allow it too either display an error or open a new page, and reset the EnteredEmployeeId to nothing.

My Code So Far:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Rent_a_Car
{
    public partial class Employee_Login_Page : Form
    {
        public Employee_Login_Page()
        {
            InitializeComponent();
        }
        string ManagersPath = @"C:\Users\Name\Visual Studios Project Custom Files\Rent A Car Employee Id's\Managers\Manager_Ids.txt"; //Path To Manager Logins
        string EnteredEmployeeId;

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void Employee_Id_TextBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) &&           //Checks Characters entered are Numbers Only and allows them
                (e.KeyChar != '0'))
            {
                e.Handled = true;
            }
            else if (e.KeyChar == (char)13)                                         //Checks if The "Enter" Key is pressed
            {
                EnteredEmployeeId = Employee_Id_TextBox.Text;                         //Assigns EnteredEmployeeId To the Entered Numbes In Text Box

                bool result = ***IsNumberInFile***(EnteredEmployeeId, "ManagerLoginId:", ManagersPath);
                if (result)
                {
                             //open new window
                }
                else
                {
                    MessageBox.Show("User Not Found");
                }
            }
        }
    }
}

Body:
If your Manager_Ids.txt is in the following format, you can use File.ReadLine() method to traverse the text and query it.

ManagerName: FirstName_LastName1
ManagerLoginId: 12345
ManagerName: FirstName_LastName2
ManagerLoginId: 23456
...

Here is the demo that traverse the .txt.

string ManagersPath = @"D:\Manager_Ids.txt";
string EnteredEmployeeId;

private void textBox_id_KeyDown(object sender, KeyEventArgs e)
{
    int counter = 0;
    bool exist = false;
    string line;
    string str = "";

    if (e.KeyCode == Keys.Enter)
    {
        EnteredEmployeeId = textBox_id.Text;

        System.IO.StreamReader file =
            new System.IO.StreamReader(ManagersPath);
        while ((line = file.ReadLine()) != null)
        {
            str += line + "|";

            if (counter % 2 != 0)
            {
                if (str.Split('|')[1].Split(':')[1].Trim() == EnteredEmployeeId)
                {
                    str = str.Replace("|", "\n");
                    MessageBox.Show(str);
                    exist = true;
                    break;
                }
                str = "";
            }
            counter++;
        }

        if (!exist)
        {
            MessageBox.Show("No such id");
        }

        file.Close();
    }
}

Besides, I recommend to use "xml", "json" or other formats to serialize the data. About storing the data in "xml", you can refer to the following simple demo.

<?xml version="1.0"?>
<Managers>
  <Manager>
    <ManagerName>FirstName_LastName1</ManagerName>
    <ManagerLoginId>12345</ManagerLoginId>
  </Manager>
  <Manager>
    <ManagerName>FirstName_LastName2</ManagerName>
    <ManagerLoginId>23456</ManagerLoginId>
  </Manager>
</Managers>

And then use LINQ to XML to query the id.

string ManagersPath = @"D:\Manager_Ids.xml";
string EnteredEmployeeId;

private void textBox_id_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        EnteredEmployeeId = textBox_id.Text;

        XElement root = XElement.Load(ManagersPath);
        IEnumerable<XElement> manager =
            from el in root.Elements("Manager")
            where (string)el.Element("ManagerLoginId") == EnteredEmployeeId
            select el;
        if(manager.Count() == 0)
        {
            MessageBox.Show("No such id");
        }
        foreach (XElement el in manager)
            MessageBox.Show("ManagerName: " + (string)el.Element("ManagerName") + "\n"
                + "ManagerLoginId: " + (string)el.Element("ManagerLoginId"));
    }
}


来源: stackexchange

问:
Pandas Check Excel import for isnumeric() data in Dataframe
I am importing data into Pandas from Excel and I need to verify that the data is numeric based on the Columns.

```<code>        month      value        dp        wd  ...      mg   fee      pr      comment

0  2013-07-31  208372.33   4206.84   4692.22  ...       0     0       0    some comment
1  2013-08-31  210669.77      0.00   1270.28  ...       0     0       0
</code>```

There are about 20 columns and I only need to exclude the "month" and "comment" columns.

Is there something like:  df.iloc[:, 2: 18].isnumeric() or will this require a loop?

I would like to get a True / False response.

thank you.

答:
You can use apply method to apply series methods to columns of a dataframe.</p>

```<code>df2 = df.drop(["month", "comment"], axis=1)
df2 = df2.apply(lambda x: x.str.isnumeric())
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am importing data into Pandas from Excel and I need to verify that the data is numeric based on the Columns.

        month      value        dp        wd  ...      mg   fee      pr      comment

0  2013-07-31  208372.33   4206.84   4692.22  ...       0     0       0    some comment
1  2013-08-31  210669.77      0.00   1270.28  ...       0     0       0

There are about 20 columns and I only need to exclude the "month" and "comment" columns.

Is there something like:  df.iloc[:, 2: 18].isnumeric() or will this require a loop?

I would like to get a True / False response.

thank you.

Body:
You can use apply method to apply series methods to columns of a dataframe.

df2 = df.drop(["month", "comment"], axis=1)
df2 = df2.apply(lambda x: x.str.isnumeric())


问:
Adding marquee using javaScript
```<code>How can I print the data in the array one by one into the scrolling text using javascript.
How can I print the data in the array one by one into the scrolling text using javascript.
How can I print the data in the array one by one into the scrolling text using javascript.
How can I print the data in the array one by one into the scrolling text using javascript.
</code>```

var arrayList=[
 ["Ambitioni dedisse scripsisse iudicaretur."],
 ["Ambitioni dedisse scripsisse iudicaretur."],
 ["Ambitioni dedisse scripsisse iudicaretur."],
 ["Ambitioni dedisse scripsisse iudicaretur."],
 ["Ambitioni dedisse scripsisse iudicaretur."],
 ["Ambitioni dedisse scripsisse iudicaretur."],
 ["Ambitioni dedisse scripsisse iudicaretur."]
];```
<pre class="snippet-code-css lang-css prettyprint-override"><code>  .quetoBody{
      width: 300px;
      margin-left: 150px;
      margin-top: 40px;
      background-color: aqua;
      padding: 15px;
  }
  @keyframes slydeAnimation {
    0%   { text-indent: 430px }
    100% { text-indent: -485px }
  }

  @-webkit-keyframes slydeAnimation {
    0%   { text-indent: 430px }
    100% { text-indent: -485px }
  }

  .slyde {
    overflow: hidden;
    white-space: nowrap;
    animation: slydeAnimation 17s linear infinite;
    -webkit-animation: slydeAnimation 17s linear infinite;
  }

  .slyde:hover {
    -webkit-animation-play-state: paused;
    animation-play-state: paused;
  }</code>```

    Ambitioni dedisse scripsisse iudicaretur.

```
</div>
</div>
</p>

```How can I print the data in the array one by one into the scrolling text using javascript.
How can I print the data in the array one by one into the scrolling text using javascript.
How can I print the data in the array one by one into the scrolling text using javascript.
How can I print the data in the array one by one into the scrolling text using javascript.
```

答:
Just change the timing for your need and you're good to go

function run() {
    setInterval(() => {
        document.querySelector("p").textContent = arrayList[count];
        if (count + 1 == arrayList.length) {
            count = 0;
        } else {
            count++;
        }
    }, 5000);
}

var count = 0;

var arrayList = [
   ["Ambitioni dedisse scripsisse iudicaretur. 1"],
   ["Ambitioni dedisse scripsisse iudicaretur. 2"],
   ["Ambitioni dedisse scripsisse iudicaretur. 3"],
   ["Ambitioni dedisse scripsisse iudicaretur. 4"],
   ["Ambitioni dedisse scripsisse iudicaretur. 5"],
   ["Ambitioni dedisse scripsisse iudicaretur. 6"],
   ["Ambitioni dedisse scripsisse iudicaretur. 7"]
];```
<pre class="snippet-code-css lang-css prettyprint-override"><code>  .quetoBody{
      width: 300px;
      margin-left: 150px;
      margin-top: 40px;
      background-color: aqua;
      padding: 15px;
  }
  @keyframes slydeAnimation {
    0%   { text-indent: 430px }
    100% { text-indent: -485px }
  }

  @-webkit-keyframes slydeAnimation {
    0%   { text-indent: 430px }
    100% { text-indent: -485px }
  }

  .slyde {
    overflow: hidden;
    white-space: nowrap;
    animation: slydeAnimation 5s linear infinite;
    -webkit-animation: slydeAnimation 5s linear infinite;
  }

  .slyde:hover {
    -webkit-animation-play-state: paused;
    animation-play-state: paused;
  }</code>```

```

Title: Adding marquee using javaScript

Body:
How can I print the data in the array one by one into the scrolling text using javascript.
How can I print the data in the array one by one into the scrolling text using javascript.
How can I print the data in the array one by one into the scrolling text using javascript.
How can I print the data in the array one by one into the scrolling text using javascript.

var arrayList=[
 ["Ambitioni dedisse scripsisse iudicaretur."],
 ["Ambitioni dedisse scripsisse iudicaretur."],
 ["Ambitioni dedisse scripsisse iudicaretur."],
 ["Ambitioni dedisse scripsisse iudicaretur."],
 ["Ambitioni dedisse scripsisse iudicaretur."],
 ["Ambitioni dedisse scripsisse iudicaretur."],
 ["Ambitioni dedisse scripsisse iudicaretur."]
];

  .quetoBody{
      width: 300px;
      margin-left: 150px;
      margin-top: 40px;
      background-color: aqua;
      padding: 15px;
  }
  @keyframes slydeAnimation {
    0%   { text-indent: 430px }
    100% { text-indent: -485px }
  }

  @-webkit-keyframes slydeAnimation {
    0%   { text-indent: 430px }
    100% { text-indent: -485px }
  }

  .slyde {
    overflow: hidden;
    white-space: nowrap;
    animation: slydeAnimation 17s linear infinite;
    -webkit-animation: slydeAnimation 17s linear infinite;
  }

  .slyde:hover {
    -webkit-animation-play-state: paused;
    animation-play-state: paused;
  }

    Ambitioni dedisse scripsisse iudicaretur.

How can I print the data in the array one by one into the scrolling text using javascript.
How can I print the data in the array one by one into the scrolling text using javascript.
How can I print the data in the array one by one into the scrolling text using javascript.
How can I print the data in the array one by one into the scrolling text using javascript.

Body:
Just change the timing for your need and you're good to go

function run() {
    setInterval(() => {
        document.querySelector("p").textContent = arrayList[count];
        if (count + 1 == arrayList.length) {
            count = 0;
        } else {
            count++;
        }
    }, 5000);
}

var count = 0;

var arrayList = [
   ["Ambitioni dedisse scripsisse iudicaretur. 1"],
   ["Ambitioni dedisse scripsisse iudicaretur. 2"],
   ["Ambitioni dedisse scripsisse iudicaretur. 3"],
   ["Ambitioni dedisse scripsisse iudicaretur. 4"],
   ["Ambitioni dedisse scripsisse iudicaretur. 5"],
   ["Ambitioni dedisse scripsisse iudicaretur. 6"],
   ["Ambitioni dedisse scripsisse iudicaretur. 7"]
];

  .quetoBody{
      width: 300px;
      margin-left: 150px;
      margin-top: 40px;
      background-color: aqua;
      padding: 15px;
  }
  @keyframes slydeAnimation {
    0%   { text-indent: 430px }
    100% { text-indent: -485px }
  }

  @-webkit-keyframes slydeAnimation {
    0%   { text-indent: 430px }
    100% { text-indent: -485px }
  }

  .slyde {
    overflow: hidden;
    white-space: nowrap;
    animation: slydeAnimation 5s linear infinite;
    -webkit-animation: slydeAnimation 5s linear infinite;
  }

  .slyde:hover {
    -webkit-animation-play-state: paused;
    animation-play-state: paused;
  }

<html>
<head></head>
<body onload=run()>
 <div class="quetoBody">
   <p id="queto" class="slyde">

  </p>
 </div>
</body>
</html>


问:
Ruby file force copy
Is there a way to get ruby to do a forced copy? FileUtils.cp_r seems not to have a :force => true option.</p>

答: No, but it does have :remove_destination as an option, which does much the same thing.

OwnerDisplayName: Aaron Lee

ContentLicense: CC BY-SA 2.5

Title: Ruby file force copy

LastEditorDisplayName: Aaron Lee

OwnerDisplayName: Pesto


问:
Regex to replace %variables%
I've been yanking clumps of hair out for 30 minutes doing this one...

I have a dictionary, like so:

```<code>{'search': 'replace',
 'foo':    'bar'}
</code>```

And a string like this:

```<code>Foo bar %foo% % search %.
</code>```

I'd like to replace each variable with it's equivalent text from the dictionary:

```<code>Foo bar bar replace.
</code>```

My current regex fails, so here it is (key and value are from dictionary.items()):

```<code> re.sub(r'%\d+' + key + '[^%]\d+%', value, text)
</code>```

Any help would be appreciated, as this regex stuff is driving me nuts...

答:
Using the replacement function support of re.sub:

```<code>def replace(s, kw, pattern=re.compile(r'%\s*(\w+)\s*%')):
    """
    Replace delimited keys in a string with values from kw.

    Any pattern may be used, as long as the first group defines the lookup key.
    """
    lookup = lambda match: kw.get(match.group(1), match.group())
    return pattern.sub(lookup, s)

>>> replace('Foo bar %foo% % search %.', {'search': 'replace', 'foo': 'bar'})
'Foo bar bar replace.'
</code>```

You can change the lookup function to customize how lookup errors are treated, and so on.

ContentLicense: CC BY-SA 3.0

Title: Regex to replace %variables%

Body:
I've been yanking clumps of hair out for 30 minutes doing this one...

I have a dictionary, like so:

{'search': 'replace',
 'foo':    'bar'}

And a string like this:

Foo bar %foo% % search %.

I'd like to replace each variable with it's equivalent text from the dictionary:

Foo bar bar replace.

My current regex fails, so here it is (key and value are from dictionary.items()):

 re.sub(r'%\d+' + key + '[^%]\d+%', value, text)

Any help would be appreciated, as this regex stuff is driving me nuts...

Body:
Using the replacement function support of re.sub:

def replace(s, kw, pattern=re.compile(r'%\s*(\w+)\s*%')):
    """
    Replace delimited keys in a string with values from kw.

    Any pattern may be used, as long as the first group defines the lookup key.
    """
    lookup = lambda match: kw.get(match.group(1), match.group())
    return pattern.sub(lookup, s)

>>> replace('Foo bar %foo% % search %.', {'search': 'replace', 'foo': 'bar'})
'Foo bar bar replace.'

You can change the lookup function to customize how lookup errors are treated, and so on.


问:
python unit test with mock for checking file path
I have following python function in 'au.py' :

```<code>import os

def resolv_conf_audit():
    ALT_PATH = "/etc/monitor/etc/resolv.conf.{}".format(os.uname()[1])
    RES_PATH = "/data/bin/resolvconf"
    if os.path.isfile(RES_PATH):

        return "PASSED", "/data/bin/resolvconf is present"

    elif os.path.isfile(ALT_PATH):
        return "PASSED", "/etc/monitor/etc/resolv.conf. is present"

    else:
        return "FAILED"
</code>```

I need to write a unit test with mock which can check the path exists or not
following is the unit test which I wrote

```<code>from au import resolv_conf_audit
import unittest
from unittest.mock import patch

class TestResolvConf(unittest.TestCase):
    @patch('os.path.isfile.ALT_PATH')
    def test_both_source_files_not(self, mock_os_is_file):
        mock_os_is_file.return_value =  False
        assert resolv_conf_audit() == "FAILED"
</code>```

but I am getting following error

```<code>AttributeError: <function isfile at 0x10bdea6a8> does not have the attribute 'ALT_PATH'
</code>```

How do I mock to check the presence of ALT_PATH and RES_PATH so that I can validate the function. In future this unit test should have the capability to mock removal some files, before writing that I am testing this simple one

答:
Thanks @ Mauro Baraldi, as per your suggestion, I changed the code little bit and it works fine now </p>

```<code>    def test_both_source_files_not(self, mock_os_is_file):
        mock_os_is_file.side_effect = [False , False]
        assert resolv_conf_audit() == "FAILED"
</code>```

Body:
I have following python function in 'au.py' :

import os

def resolv_conf_audit():
    ALT_PATH = "/etc/monitor/etc/resolv.conf.{}".format(os.uname()[1])
    RES_PATH = "/data/bin/resolvconf"
    if os.path.isfile(RES_PATH):

        return "PASSED", "/data/bin/resolvconf is present"

    elif os.path.isfile(ALT_PATH):
        return "PASSED", "/etc/monitor/etc/resolv.conf. is present"

    else:
        return "FAILED"

I need to write a unit test with mock which can check the path exists or not
following is the unit test which I wrote

from au import resolv_conf_audit
import unittest
from unittest.mock import patch

class TestResolvConf(unittest.TestCase):
    @patch('os.path.isfile.ALT_PATH')
    def test_both_source_files_not(self, mock_os_is_file):
        mock_os_is_file.return_value =  False
        assert resolv_conf_audit() == "FAILED"

but I am getting following error

AttributeError: <function isfile at 0x10bdea6a8> does not have the attribute 'ALT_PATH'

How do I mock to check the presence of ALT_PATH and RES_PATH so that I can validate the function. In future this unit test should have the capability to mock removal some files, before writing that I am testing this simple one

Body:
Thanks @ Mauro Baraldi, as per your suggestion, I changed the code little bit and it works fine now

    def test_both_source_files_not(self, mock_os_is_file):
        mock_os_is_file.side_effect = [False , False]
        assert resolv_conf_audit() == "FAILED"


问:
Visual Studio Code: Java Extension Pack can't locate java sdk when started over SSH
I'm trying to start a JAVA program on my Raspberry 4 from my Windows laptop using a SSH Connection in Visual Studio Code.
The connection works (I can see I'm on the Raspberry in the Terminal) and I installed the Java Extension Pack on the Raspberry:

Now I would like to run the Java Project that is located on my Raspy, but when I open it, I get this error message:

And when I click on "open settings", the settings.json file located on my laptop gets opened:

```<code>{
"window.zoomLevel": 1,
"extensions.ignoreRecommendations": false,
"typescript.updateImportsOnFileMove.enabled": "always",
"git.enableSmartCommit": true,
"files.autoSave": "afterDelay",
"git.autofetch": true,
"editor.suggestSelection": "first",
"vsintellicode.modify.editor.suggestSelection": "automaticallyOverrodeDefaultValue",
"java.semanticHighlighting.enabled": true,
"java.home": "C:/Program Files/Java/jdk-11.0.7",
"files.exclude": {
    "**/.classpath": true,
    "**/.project": true,
    "**/.settings": true,
    "**/.factorypath": true
},
"remote.SSH.remotePlatform": {
    "pi4": "linux",
}
}
</code>```

So I tried changing "java.home": "C:/Program Files/Java/jdk-11.0.7" to the location where java SDK 11 is saved on the raspberry. But my first problem is, I'm not sure which to use here and if that's even the correct path to use on raspberry?:

And it also doesn't work, I think I just change the settings of my windows VSC and not the settings of the remote VSC.
I know this is a very specific problem, but maybe somebody had the same issue?

答:
Solution:

1.Install JDK in WSL

2.Export the path of JDK in WSL (write export JDK_HOME=/path/to/jdk/) in ~/.bashrc file and source it

3.Restart VS Code

from here

Body:
I'm trying to start a JAVA program on my Raspberry 4 from my Windows laptop using a SSH Connection in Visual Studio Code.
The connection works (I can see I'm on the Raspberry in the Terminal) and I installed the Java Extension Pack on the Raspberry:

Now I would like to run the Java Project that is located on my Raspy, but when I open it, I get this error message:

And when I click on "open settings", the settings.json file located on my laptop gets opened:

{
"window.zoomLevel": 1,
"extensions.ignoreRecommendations": false,
"typescript.updateImportsOnFileMove.enabled": "always",
"git.enableSmartCommit": true,
"files.autoSave": "afterDelay",
"git.autofetch": true,
"editor.suggestSelection": "first",
"vsintellicode.modify.editor.suggestSelection": "automaticallyOverrodeDefaultValue",
"java.semanticHighlighting.enabled": true,
"java.home": "C:/Program Files/Java/jdk-11.0.7",
"files.exclude": {
    "**/.classpath": true,
    "**/.project": true,
    "**/.settings": true,
    "**/.factorypath": true
},
"remote.SSH.remotePlatform": {
    "pi4": "linux",
}
}

So I tried changing "java.home": "C:/Program Files/Java/jdk-11.0.7" to the location where java SDK 11 is saved on the raspberry. But my first problem is, I'm not sure which to use here and if that's even the correct path to use on raspberry?:

And it also doesn't work, I think I just change the settings of my windows VSC and not the settings of the remote VSC.
I know this is a very specific problem, but maybe somebody had the same issue?


问:
How to pass a property as a method parameter then set it to nil in a block in Objective-C?
I have the following situation where I'm sending in the property self.view, which holds some view, as a parameter to the below method:

```<code>- (void) someMethod:(UIView *)view
{
    [UIView animateWithDuration:.25 delay:0 options: UIViewAnimationOptionAllowUserInteraction animations:^
     {
        //blablabla
     }
    completion:^(BOOL finished)
     {
        [view removeFromSuperview];
        view = nil;
     }];
}
</code>```

Where the compiler is telling me:

Variable is not assignable (missing __block type specifier)

I do try adding the block type specifier to the parameter and that doesn't work. I'm wanting it so that when I set view to nil, it will also set the property self.view to nil. I am having trouble wrapping my head around this situation especially when you throw the block into it, I think normally I would need a double pointer?

I'm wondering what is the best way to approach this where I can self.view to nil using the parameter in the method block.

答: in objective-C, __ make your variable shared between the lexical scope of the variable and all blocks and block copies declared or created within the variable’s lexical scope. In this case i suggest you should create a flag and in block, you call another function to do something with the view. I think it's a bad way to keep a UI component as a shared variable. It may crash your apps sometimes.</p>

Body:
I have the following situation where I'm sending in the property self.view, which holds some view, as a parameter to the below method:

- (void) someMethod:(UIView *)view
{
    [UIView animateWithDuration:.25 delay:0 options: UIViewAnimationOptionAllowUserInteraction animations:^
     {
        //blablabla
     }
    completion:^(BOOL finished)
     {
        [view removeFromSuperview];
        view = nil;
     }];
}

Where the compiler is telling me:

Variable is not assignable (missing __block type specifier)

I do try adding the block type specifier to the parameter and that doesn't work. I'm wanting it so that when I set view to nil, it will also set the property self.view to nil. I am having trouble wrapping my head around this situation especially when you throw the block into it, I think normally I would need a double pointer?

I'm wondering what is the best way to approach this where I can self.view to nil using the parameter in the method block.


问:
Assign type level parameter to data structure tree
I have a remote microcontroller that exposes some properties in a tree like view. These properties can all be read and some of them can be written to. A property is just a string where each level of the tree is delimited by a ..

As an example the property tree looks something like this:

```<code>Properties.prop1 = 0
Properties.prop2.foo = 1337
Properties.prop2.bar.baz1 = "hello"
Properties.prop2.bar.baz2 = "world"
</code>```

Where Properties.prop1 and Properties.prop2.foo are readable only. Properties.prop2.bar.baz1 and Properties.prop2.bar.baz2 are readable and writeable. Anyway I want to encode this in Haskell using strong typing.

```<code>data Bar = Baz1 String | Baz2 String
data Prop2 = Foo Int | Bar Bar
data Properties = Prop1 Int | Prop2 Prop2
</code>```

Now you can pretty nicely create a property:

```<code>p = Prop2 $ Bar $ Baz1 "hello"
</code>```

But what I'm missing is how I can associate a single "path" through these constructors as either a readable property or a read/writeable property. Ideally I would like to have a class or type family "ReadableProp" and "WriteableProp" which would allow me to write something like:

```<code>writeProp :: WriteableProp a => a -> IO ()
writeProp = ...

readProp :: ReadableProp a => IO a
readProp = ...
</code>```

I know this doesn't work at all right now. But I'm open to change the data structure or use something else to achieve something like this.

Does anyone have any idea?

Thank you for reading!

答:
Expanding on my comment, one approach might be something like

```<code>{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}

import Data.Kind (Constraint)
import Data.Type.Bool (If)
import Type.Errors (DelayError, ErrorMessage(ShowType, Text, (:<>:)))

data Bar = Baz1 String | Baz2 String deriving (Read, Show)
data Prop2 = Foo Int | Bar Bar deriving (Read, Show)

data RW = Read_ | Write_
data Props = Prop1_ | Prop2_
data Properties (a :: Props) where
  Prop1 :: Int -> Properties Prop1_
  Prop2 :: Prop2 -> Properties Prop2_
deriving instance Show (Properties a)

type family Permissions (a :: Props) :: [RW] where
  Permissions Prop1_ = '[Read_]
  Permissions Prop2_ = '[Read_, Write_]

type family Contains (x :: k) (xs :: [k]) where
  Contains _ '[] = False
  Contains x (x ': _) = True
  Contains x (_ ': xs) = Contains x xs

type HasPermission (a :: Props) (b :: RW) =
  If
    (Contains b (Permissions a))
    (() :: Constraint)
    (DelayError (ShowType a :<>: Text " does not have required permission " :<>: ShowType b))

class Writeable (a :: Props)
instance (HasPermission a Write_) => Writeable a

class ReadProp (a :: Props) where
  read_ :: String -> Properties a
instance ReadProp Prop1_ where read_ = Prop1 . read
instance ReadProp Prop2_ where read_ = Prop2 . read

class ReadProp a => Readable (a :: Props)
instance (ReadProp a, HasPermission a Read_) => Readable a
</code>```

There's a bit of extra pain setting up the read instances because there's no guarantee of a unique way to construct (eg.) a Properties Prop1_, so you have to dictate which constructor to use.

Then we can use it:

```<code>writeProp :: Writeable x => Properties x -> IO ()
writeProp x = print x

readProp :: Readable x => IO (Properties x)
readProp = read_ <$> readFile "a.txt"

:t readProp @Prop1_
readProp @Prop1_ :: IO (Properties 'Prop1_)
:t readProp @Prop2_
readProp @Prop2_ :: IO (Properties 'Prop2_)

:t writeProp (Prop1 5)
* 'Prop1_ does not have required permission 'Write_
:t writeProp (Prop2 $ Bar $ Baz1 "")
writeProp (Prop2 $ Bar $ Baz1 "") :: IO ()
</code>```

Body:
I have a remote microcontroller that exposes some properties in a tree like view. These properties can all be read and some of them can be written to. A property is just a string where each level of the tree is delimited by a ..

As an example the property tree looks something like this:

Properties.prop1 = 0
Properties.prop2.foo = 1337
Properties.prop2.bar.baz1 = "hello"
Properties.prop2.bar.baz2 = "world"

Where Properties.prop1 and Properties.prop2.foo are readable only. Properties.prop2.bar.baz1 and Properties.prop2.bar.baz2 are readable and writeable. Anyway I want to encode this in Haskell using strong typing.

data Bar = Baz1 String | Baz2 String
data Prop2 = Foo Int | Bar Bar
data Properties = Prop1 Int | Prop2 Prop2

Now you can pretty nicely create a property:

p = Prop2 $ Bar $ Baz1 "hello"

But what I'm missing is how I can associate a single "path" through these constructors as either a readable property or a read/writeable property. Ideally I would like to have a class or type family "ReadableProp" and "WriteableProp" which would allow me to write something like:

writeProp :: WriteableProp a => a -> IO ()
writeProp = ...

readProp :: ReadableProp a => IO a
readProp = ...

I know this doesn't work at all right now. But I'm open to change the data structure or use something else to achieve something like this.

Does anyone have any idea?

Thank you for reading!

Body:
Expanding on my comment, one approach might be something like

{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}

import Data.Kind (Constraint)
import Data.Type.Bool (If)
import Type.Errors (DelayError, ErrorMessage(ShowType, Text, (:<>:)))

data Bar = Baz1 String | Baz2 String deriving (Read, Show)
data Prop2 = Foo Int | Bar Bar deriving (Read, Show)

data RW = Read_ | Write_
data Props = Prop1_ | Prop2_
data Properties (a :: Props) where
  Prop1 :: Int -> Properties Prop1_
  Prop2 :: Prop2 -> Properties Prop2_
deriving instance Show (Properties a)

type family Permissions (a :: Props) :: [RW] where
  Permissions Prop1_ = '[Read_]
  Permissions Prop2_ = '[Read_, Write_]

type family Contains (x :: k) (xs :: [k]) where
  Contains _ '[] = False
  Contains x (x ': _) = True
  Contains x (_ ': xs) = Contains x xs

type HasPermission (a :: Props) (b :: RW) =
  If
    (Contains b (Permissions a))
    (() :: Constraint)
    (DelayError (ShowType a :<>: Text " does not have required permission " :<>: ShowType b))

class Writeable (a :: Props)
instance (HasPermission a Write_) => Writeable a

class ReadProp (a :: Props) where
  read_ :: String -> Properties a
instance ReadProp Prop1_ where read_ = Prop1 . read
instance ReadProp Prop2_ where read_ = Prop2 . read

class ReadProp a => Readable (a :: Props)
instance (ReadProp a, HasPermission a Read_) => Readable a

There's a bit of extra pain setting up the read instances because there's no guarantee of a unique way to construct (eg.) a Properties Prop1_, so you have to dictate which constructor to use.

Then we can use it:

writeProp :: Writeable x => Properties x -> IO ()
writeProp x = print x

readProp :: Readable x => IO (Properties x)
readProp = read_ <$> readFile "a.txt"

:t readProp @Prop1_
readProp @Prop1_ :: IO (Properties 'Prop1_)
:t readProp @Prop2_
readProp @Prop2_ :: IO (Properties 'Prop2_)

:t writeProp (Prop1 5)
* 'Prop1_ does not have required permission 'Write_
:t writeProp (Prop2 $ Bar $ Baz1 "")
writeProp (Prop2 $ Bar $ Baz1 "") :: IO ()


问:
webpack bundle typescript to ts-loader but get module is not defined on browser?
follow webpack typescript doc

when i use webpack ts-loader to convert typescript it's can't work cause module is not defined?

but when i just command tsc, this result can work on browser

also this issues is already use gulp to fix

but gulp use browserify to transform typescript

so i want to use webpack to bundle my express server and client typescript!

why webpack ts-loader to transform typescript get "module is not defined" on browser?

this repositories on github

webpack.config.js

```<code>const nodeeExternals = require('webpack-node-externals');
const path = require('path');
const CopyWebpackPlugin = require('copy-webpack-plugin');

const serverConfig = {
  target: 'node',
  devtool: 'eval-source-map',
  node: {
    __dirname: false,
    __filename: true,
  },
  externals: [nodeExternals()],
  entry: {
    'index': './src/index.js',
    // 'public/javascripts/temibroad': './src/client/typescript/temibroad/temibroad.ts'
  },
  output: {
    path: path.join(__dirname, 'dist'),
    filename: '[name].bundle.js',
    libraryTarget: 'commonjs2',
  },
  module: {   //設定你的檔案選項
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: 'babel-loader'
      }
    ],
  },
  // plugins: [
  //   new CopyWebpackPlugin([
  //     { from: 'src/client/views', to: 'views' },
  //     { from: 'src/client/static', to: 'public' },
  //   ])
  // ],
  optimization: {
    minimize: true,
  }
}

const clientConfig = {
  target: 'web',
  devtool: 'eval-source-map',
  node: {
    __dirname: false,
    __filename: true,
  },
  externals: [nodeExternals()],
  entry: {
    // 'index': './src/index.js',
    'public/javascripts/temibroad': './src/client/typescript/temibroad/temibroad.ts'
  },
  output: {
    path: path.join(__dirname, 'dist'),
    filename: '[name].bundle.js',
    libraryTarget: 'commonjs2',
  },
  module: {   //設定你的檔案選項
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: 'babel-loader'
      },
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
        exclude: /node_modules/,
      },
    ],
  },
  resolve: {
    extensions: [ '.tsx', '.ts', '.js' ],
  },
  plugins: [
    new CopyWebpackPlugin([
      { from: 'src/client/views', to: 'views' },
      { from: 'src/client/static', to: 'public' },
    ])
  ],
  optimization: {
    minimize: true,
  }
}

module.exports = [serverConfig, clientConfig];
</code>```

tsconfig.json

```<code>{
  "compilerOptions": {
  "target": "es5",
  "module": "commonjs",
  "sourceMap": true,
  "noEmitOnError" : false,
  "strict": true,
  "noImplicitAny": true,
  "strictNullChecks": true,
  "esModuleInterop": true,
  "forceConsistentCasingInFileNames": true
  }
}
</code>```

答:
Mh...i know why got "module is not defined" on browser, cause my output library setting.

When my project done, then I research webpack doc, step by step check my setting, i find why i setting "commonjs2"(2??) on browser?

Commonjs can't work on browser immediately, so when i setting libraryTarget to "var", also setting library:'myLibrary' to call TS function, problem is solved.

Check out the settings below

```<code>/* webpack.config.js ： Webpack 的設定檔 */
// const webpack = require('webpack');
const path = require('path');

const clientConfig = {
  target: 'web',
  devtool: 'eval-source-map',
  entry: {
    // 'index': './src/index.js',
    'index': './src/index.ts'
  },
  output: {
    path: path.join(__dirname, 'dist'),
    filename: '[name].bundle.js',
    library :'aaa',
    libraryTarget: 'var'
  },
  module: {   //設定你的檔案選項
    rules: [
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
        exclude: /node_modules/,
      },
    ],
  },
  resolve: {
    extensions: [ '.tsx', '.ts', '.js' ],
  },
}

module.exports = [clientConfig];
</code>```

index.ts

```<code>import { gogogo } from './import';

gogogo();

export { gogogo };

console.log('你好');
</code>```

import.ts

```<code>function gogogo(str = 'gogogog'){
  console.log(str);
}

export {gogogo};
</code>```

index.html

```<code><script src="./dist/index.bundle.js"></script>
<script>
  console.log(aaa);
  aaa.gogogo('外面傳入');
</script>
</code>```

Browser Console

```<code>gogogog             import.ts?661f:6
好                  index.ts?71bd:7
{__esModule: true}  index.html:11
外面傳入             import.ts?661f:6
</code>```

update on 2020/06/30 with require.js

webpack.config.js

```<code>  output: {
    path: path.join(__dirname, 'dist'),
    filename: '[name].bundle.js',
    // library :'aaa',
    libraryTarget: 'amd'
  },
</code>```

index.html

```<code>  <script src='https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.min.js'></script>
  <script>
    require(['./dist/index.bundle'], function(aaa){
      console.log(aaa);
      aaa.gogogo('from aaa');
    })
  </script>
</code>```

Body:
follow webpack typescript doc

when i use webpack ts-loader to convert typescript it's can't work cause module is not defined?

but when i just command tsc, this result can work on browser

also this issues is already use gulp to fix

but gulp use browserify to transform typescript

so i want to use webpack to bundle my express server and client typescript!

why webpack ts-loader to transform typescript get "module is not defined" on browser?

this repositories on github

webpack.config.js

const nodeeExternals = require('webpack-node-externals');
const path = require('path');
const CopyWebpackPlugin = require('copy-webpack-plugin');

const serverConfig = {
  target: 'node',
  devtool: 'eval-source-map',
  node: {
    __dirname: false,
    __filename: true,
  },
  externals: [nodeExternals()],
  entry: {
    'index': './src/index.js',
    // 'public/javascripts/temibroad': './src/client/typescript/temibroad/temibroad.ts'
  },
  output: {
    path: path.join(__dirname, 'dist'),
    filename: '[name].bundle.js',
    libraryTarget: 'commonjs2',
  },
  module: {   //設定你的檔案選項
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: 'babel-loader'
      }
    ],
  },
  // plugins: [
  //   new CopyWebpackPlugin([
  //     { from: 'src/client/views', to: 'views' },
  //     { from: 'src/client/static', to: 'public' },
  //   ])
  // ],
  optimization: {
    minimize: true,
  }
}

const clientConfig = {
  target: 'web',
  devtool: 'eval-source-map',
  node: {
    __dirname: false,
    __filename: true,
  },
  externals: [nodeExternals()],
  entry: {
    // 'index': './src/index.js',
    'public/javascripts/temibroad': './src/client/typescript/temibroad/temibroad.ts'
  },
  output: {
    path: path.join(__dirname, 'dist'),
    filename: '[name].bundle.js',
    libraryTarget: 'commonjs2',
  },
  module: {   //設定你的檔案選項
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: 'babel-loader'
      },
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
        exclude: /node_modules/,
      },
    ],
  },
  resolve: {
    extensions: [ '.tsx', '.ts', '.js' ],
  },
  plugins: [
    new CopyWebpackPlugin([
      { from: 'src/client/views', to: 'views' },
      { from: 'src/client/static', to: 'public' },
    ])
  ],
  optimization: {
    minimize: true,
  }
}

module.exports = [serverConfig, clientConfig];

tsconfig.json

{
  "compilerOptions": {
  "target": "es5",
  "module": "commonjs",
  "sourceMap": true,
  "noEmitOnError" : false,
  "strict": true,
  "noImplicitAny": true,
  "strictNullChecks": true,
  "esModuleInterop": true,
  "forceConsistentCasingInFileNames": true
  }
}

Body:
Mh...i know why got "module is not defined" on browser, cause my output library setting.

When my project done, then I research webpack doc, step by step check my setting, i find why i setting "commonjs2"(2??) on browser?

Commonjs can't work on browser immediately, so when i setting libraryTarget to "var", also setting library:'myLibrary' to call TS function, problem is solved.

Check out the settings below

/* webpack.config.js ： Webpack 的設定檔 */
// const webpack = require('webpack');
const path = require('path');

const clientConfig = {
  target: 'web',
  devtool: 'eval-source-map',
  entry: {
    // 'index': './src/index.js',
    'index': './src/index.ts'
  },
  output: {
    path: path.join(__dirname, 'dist'),
    filename: '[name].bundle.js',
    library :'aaa',
    libraryTarget: 'var'
  },
  module: {   //設定你的檔案選項
    rules: [
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
        exclude: /node_modules/,
      },
    ],
  },
  resolve: {
    extensions: [ '.tsx', '.ts', '.js' ],
  },
}

module.exports = [clientConfig];

index.ts

import { gogogo } from './import';

gogogo();

export { gogogo };

console.log('你好');

import.ts

function gogogo(str = 'gogogog'){
  console.log(str);
}

export {gogogo};

index.html

<script src="./dist/index.bundle.js"></script>
<script>
  console.log(aaa);
  aaa.gogogo('外面傳入');
</script>

Browser Console

gogogog             import.ts?661f:6
好                  index.ts?71bd:7
{__esModule: true}  index.html:11
外面傳入             import.ts?661f:6

update on 2020/06/30 with require.js

webpack.config.js

  output: {
    path: path.join(__dirname, 'dist'),
    filename: '[name].bundle.js',
    // library :'aaa',
    libraryTarget: 'amd'
  },

index.html

  <script src='https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.min.js'></script>
  <script>
    require(['./dist/index.bundle'], function(aaa){
      console.log(aaa);
      aaa.gogogo('from aaa');
    })
  </script>


问:
How to add dummy values to a table in SQL
Probably not the most descriptive title but sometimes it's hard to put stupid SQL problems(the kind that make you want to put booze in your coffee to get through the day) into english. I basically have the following two tables:

TABLE1

```<code>studentid   firstname   lastname    counter cmid    score   lessond
328000            Jacob           GG             5  189 90  103950
328111            Jacob           GG            6   189 80  103951
3283333           Tyler           GR            5   189 70  103950
3244444            William    FL               5    189 70  103950
3280000            Sean           DA           5    189 80  103950
3283333            Sean           DA             6  189 90  103951
</code>```

TABLE 2

```<code>Lesson2ClassroomAssignmentId    Counter
103956                      1
103947                           2
103948                          3
103949                          4
103950                          5
103951                          6
</code>```

The first table is basically a list of students and their scores for certain lessons(numbered 1-6 and denoted by counter). The second table is a list of all possible lessons(numbered 1-6 and denoted by counter).

What I need to do is get a table that has a row for each student and each lesson, regardless of whether or not the student has a row in table 1 for that lesson or not.

Ive tried doing something like selecting * from table 1 and UNIONING it with the results of the 2nd table LEFT OUTER JOINED with the first table where counter <> counter but havent been able to get the results I desired.

If anyone has any suggestions(dont need the full answer, just pointed in the right direction) I'd owe ya one!! Alternatively, feel free to make fun of me if this post is unintelligable as it barely makes sense to me and I'm the one who has been staring at it for the past 6 hours ;)

Ciao Ciao,

Tim

DESIRED OUTPUT:

The Desired output would be:

TABLE FINAL

```<code> studentid     firstname   lastname    counter cmid    score   lessond
    3280000         Jacob       GG      1 NULL, NULL, NULL
    3280000         Jacob       GG 2 NULL, NULL, NULL
    3280000         Jacob       GG 3 NULL, NULL, NULL
    3280000         Jacob       GG 4 NULL, NULL, NULL
    3280000         Jacob       GG 5 189, 90, 103950
    3280000         Jacob       GG 6 189, 80, 103951
    3283333         Tyler       GR 1, NULL, NULL, NULL
    3283333         Tyler       GR 2, NULL, NULL, NULL
    3283333         Tyler       GR 3, NULL, NULL, NULL
    3283333         Tyler       GR 4, NULL, NULL, NULL
    3283333         Tyler       GR 5, 189, 70, 103950
    3283333         Tyler       GR 6, NULL, NULL, NULL
</code>```

So basically taking any row with actual lesson data for a student from table one and supplementing it with dummy rows with no score data for each lesson(from table 2) that the student didnt have a score for.

答:
Try using Cross Join

e.g:
I have added a pseudo column IsMatch to identify if the current row is a matched row or not just in case....

```<code>SELECT  a.*,
        b.*,
        a.counter-b.counter AS IsMatch
  FROM TABLE1 a  CROSS JOIN TABLE2 b
ORDER BY studentid
</code>```

Body:
Probably not the most descriptive title but sometimes it's hard to put stupid SQL problems(the kind that make you want to put booze in your coffee to get through the day) into english. I basically have the following two tables:

TABLE1

studentid   firstname   lastname    counter cmid    score   lessond
328000            Jacob           GG             5  189 90  103950
328111            Jacob           GG            6   189 80  103951
3283333           Tyler           GR            5   189 70  103950
3244444            William    FL               5    189 70  103950
3280000            Sean           DA           5    189 80  103950
3283333            Sean           DA             6  189 90  103951

TABLE 2

Lesson2ClassroomAssignmentId    Counter
103956                      1
103947                           2
103948                          3
103949                          4
103950                          5
103951                          6

The first table is basically a list of students and their scores for certain lessons(numbered 1-6 and denoted by counter). The second table is a list of all possible lessons(numbered 1-6 and denoted by counter).

What I need to do is get a table that has a row for each student and each lesson, regardless of whether or not the student has a row in table 1 for that lesson or not.

Ive tried doing something like selecting * from table 1 and UNIONING it with the results of the 2nd table LEFT OUTER JOINED with the first table where counter <> counter but havent been able to get the results I desired.

If anyone has any suggestions(dont need the full answer, just pointed in the right direction) I'd owe ya one!! Alternatively, feel free to make fun of me if this post is unintelligable as it barely makes sense to me and I'm the one who has been staring at it for the past 6 hours ;)

Ciao Ciao,

Tim

DESIRED OUTPUT:

The Desired output would be:

TABLE FINAL

 studentid     firstname   lastname    counter cmid    score   lessond
    3280000         Jacob       GG      1 NULL, NULL, NULL
    3280000         Jacob       GG 2 NULL, NULL, NULL
    3280000         Jacob       GG 3 NULL, NULL, NULL
    3280000         Jacob       GG 4 NULL, NULL, NULL
    3280000         Jacob       GG 5 189, 90, 103950
    3280000         Jacob       GG 6 189, 80, 103951
    3283333         Tyler       GR 1, NULL, NULL, NULL
    3283333         Tyler       GR 2, NULL, NULL, NULL
    3283333         Tyler       GR 3, NULL, NULL, NULL
    3283333         Tyler       GR 4, NULL, NULL, NULL
    3283333         Tyler       GR 5, 189, 70, 103950
    3283333         Tyler       GR 6, NULL, NULL, NULL

So basically taking any row with actual lesson data for a student from table one and supplementing it with dummy rows with no score data for each lesson(from table 2) that the student didnt have a score for.

Body:
Try using Cross Join

e.g:
I have added a pseudo column IsMatch to identify if the current row is a matched row or not just in case....

SELECT  a.*,
        b.*,
        a.counter-b.counter AS IsMatch
  FROM TABLE1 a  CROSS JOIN TABLE2 b
ORDER BY studentid


问:
How React Testing Library can assert children props and Redux store updates?
I just started exploring a unit testing framework for my react application. I locked my choice at @testing-library/react instead of Enzyme as it is recommended by React and helps writing more robust tests. I'm also planning to use Jest for completeness.

But before I could proceed with React Testing Library, I'm stuck at few questions. Can someone please help?

For instance,

There is an Editor component which updates Redux store based on user input.

There is another component Preview which reads value directly from store.

There is a third component Container which contains both of the above components passing some props.

Questions:

How to test if user input in Editor component actually updates store?

How to test if Preview component can render value reading from store?

How to test if Container component passes props correctly to its children?

Container.jsx

```<code>import React from 'react';
import Editor from './Editor';
import Preview from './Preview';

const Container = ({editorType}) => {
  return (
    <div>
      <Editor type={editorType} />
      <Preview />
    </div>
  );
};
export default Container;
</code>```

Editor.jsx

```<code>import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import {setName} from './actions';

const Editor = ({type}) => {
  const name = useSelector(state => state.name);
  const dispatch = useDispatch();

  return (
    <div>
      <h1>Type: {type}</h1>
      <input value={name} onChange={evt => dispatch(setName(evt.target.value))} />
    </div>
  );
};
export default Editor;
</code>```

Preview.jsx

```<code>import React from 'react';
import { useSelector } from 'react-redux';

const Editor = ({type}) => {
  const name = useSelector(state => state.name);

  return (
    <div>
      <h1>Name: {name}</h1>
    </div>
  );
};
export default Preview;
</code>```

答:
Here is how I would do it :

How to test if user input in Editor component actually updates store?

Looking at your code, Editor does not update store, it does not call useDispatch. But assuming it does, using https://github.com/reduxjs/redux-mock-store I would setup a mocked store provider to the component in the test, then trigger user input and check the mocked store if the correct action have been dispatched, with the correct payload :

```<code>describe('<Editor />', () => {
  let store: MockStoreEnhanced;
  let rtl: RenderResult;

  beforeEach(() => {
    store = mockStore({ /* your store structure */ });

    rtl = render(
      <Provider store={store}>
        <Editor type={...} />
      </Provider>
    );
  });

  test('dispatch action correctly', () => {
    fireEvent.change(rtl.container.querySelector('input'), { target: {value: 'test' } });

    // check actions that were dispatched by change event
    // getActions return an array avec redux actions (type, payload)
    expect(store.getActions()).toEqual(...);
  }
}
</code>```

Beside of this you should test your store reducer and action creators, to ensure that the action modifies the store correctly.

How to test if Preview component can render value reading from store?

Same principle, setup your test with a mocked store, init this store with relevant value, and just test that the component displays what's in the store :

```<code>describe('<Preview />', () => {
  let store: MockStoreEnhanced;
  let rtl: RenderResult;

   beforeEach(() => {
     store = mockStore({ name: 'This is name from store' });

     rtl = render(
       <Provider store={store}>
         <Preview type={...} />
       </Provider>
     );
   });

   test('displays store content correctly', () => {
     expect(rtl.getByText('This is name from store')).toBeTruthy();
   }
 }
</code>```

How to test if Container component passes props correctly to its children?

Here you should test Container + Preview + Editor together, and find something visual to test (as a real user would perceive it), involving the props passed by Container to its children.

For example, if Preview displays props.type, which comes from Container editorType props :

```<code>describe('<Container />', () => {
  // mocked store may not be necessary here, depending on your use case
  let store: MockStoreEnhanced;
  let rtl: RenderResult;

   beforeEach(() => {
     store = mockStore({ name: 'This is name from store' });

     rtl = render(
       <Provider store={store}>
         <Container editorType={'toTest'} />
       </Provider>
     );
   });

   test('displays store content correctly', () => {
     // check that 'toTest' exists in DOM because it is rendered by Preview component, a child of Container
     expect(rtl.getByText('toTest')).toBeTruthy();
   }
 }
</code>```

To sum it up, my approach would be :

Test actions and reducers alone (very simple to test, state machines, just plain Jest tests)

Test that components dispatch correct actions with correct payloads on correct user inputs

Mock store to setup relevant use cases (init store value) for components reading data from store

For the last 2 items I use https://github.com/reduxjs/redux-mock-store.

Body:
I just started exploring a unit testing framework for my react application. I locked my choice at @testing-library/react instead of Enzyme as it is recommended by React and helps writing more robust tests. I'm also planning to use Jest for completeness.

But before I could proceed with React Testing Library, I'm stuck at few questions. Can someone please help?

For instance,

There is an Editor component which updates Redux store based on user input.

There is another component Preview which reads value directly from store.

There is a third component Container which contains both of the above components passing some props.

Questions:

How to test if user input in Editor component actually updates store?

How to test if Preview component can render value reading from store?

How to test if Container component passes props correctly to its children?

Container.jsx

import React from 'react';
import Editor from './Editor';
import Preview from './Preview';

const Container = ({editorType}) => {
  return (

      <Editor type={editorType} />
      <Preview />

  );
};
export default Container;

Editor.jsx

import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import {setName} from './actions';

const Editor = ({type}) => {
  const name = useSelector(state => state.name);
  const dispatch = useDispatch();

  return (

Type: {type}

      <input value={name} onChange={evt => dispatch(setName(evt.target.value))} />

  );
};
export default Editor;

Preview.jsx

import React from 'react';
import { useSelector } from 'react-redux';

const Editor = ({type}) => {
  const name = useSelector(state => state.name);

  return (

Name: {name}

  );
};
export default Preview;

Body:
Here is how I would do it :

How to test if user input in Editor component actually updates store?

Looking at your code, Editor does not update store, it does not call useDispatch. But assuming it does, using https://github.com/reduxjs/redux-mock-store I would setup a mocked store provider to the component in the test, then trigger user input and check the mocked store if the correct action have been dispatched, with the correct payload :

describe('<Editor />', () => {
  let store: MockStoreEnhanced;
  let rtl: RenderResult;

  beforeEach(() => {
    store = mockStore({ /* your store structure */ });

    rtl = render(
      <Provider store={store}>
        <Editor type={...} />
      </Provider>
    );
  });

  test('dispatch action correctly', () => {
    fireEvent.change(rtl.container.querySelector('input'), { target: {value: 'test' } });

    // check actions that were dispatched by change event
    // getActions return an array avec redux actions (type, payload)
    expect(store.getActions()).toEqual(...);
  }
}

Beside of this you should test your store reducer and action creators, to ensure that the action modifies the store correctly.

How to test if Preview component can render value reading from store?

Same principle, setup your test with a mocked store, init this store with relevant value, and just test that the component displays what's in the store :

describe('<Preview />', () => {
  let store: MockStoreEnhanced;
  let rtl: RenderResult;

   beforeEach(() => {
     store = mockStore({ name: 'This is name from store' });

     rtl = render(
       <Provider store={store}>
         <Preview type={...} />
       </Provider>
     );
   });

   test('displays store content correctly', () => {
     expect(rtl.getByText('This is name from store')).toBeTruthy();
   }
 }

How to test if Container component passes props correctly to its children?

Here you should test Container + Preview + Editor together, and find something visual to test (as a real user would perceive it), involving the props passed by Container to its children.

For example, if Preview displays props.type, which comes from Container editorType props :

describe('<Container />', () => {
  // mocked store may not be necessary here, depending on your use case
  let store: MockStoreEnhanced;
  let rtl: RenderResult;

   beforeEach(() => {
     store = mockStore({ name: 'This is name from store' });

     rtl = render(
       <Provider store={store}>
         <Container editorType={'toTest'} />
       </Provider>
     );
   });

   test('displays store content correctly', () => {
     // check that 'toTest' exists in DOM because it is rendered by Preview component, a child of Container
     expect(rtl.getByText('toTest')).toBeTruthy();
   }
 }

To sum it up, my approach would be :

Test actions and reducers alone (very simple to test, state machines, just plain Jest tests)

Test that components dispatch correct actions with correct payloads on correct user inputs

Mock store to setup relevant use cases (init store value) for components reading data from store

For the last 2 items I use https://github.com/reduxjs/redux-mock-store.


问:
Difficulty aligning xticks to edge of Histogram bin
I am trying to show the frequency of my data throughout the hours of the day, using a histogram, in 3 hour intervals. I therefore use 8 bins.

```<code>plt.style.use('seaborn-colorblind')

plt.figure(figsize=(10,5))
plt.hist(comments19['comment_hour'], bins = 8, alpha = 1, align='mid', edgecolor = 'white', label = '2019', density=True)
plt.title('2019 comments, 8 bins')
plt.xticks([0,3,6,9,12,15,18,21,24])
plt.xlabel('Hours of Day')
plt.ylabel('Relative Frequency')
plt.tight_layout()
plt.legend()
plt.show()
</code>```

However, the ticks are not aligning with the bin edges, as seen from the image below.

答:
You can do either:

```<code>plt.figure(figsize=(10,5))

# define the bin and pass to plt.hist
bins = [0,3,6,9,12,15,18,21,24]
plt.hist(comments19['comment_hour'], bins = bins, alpha = 1, align='mid',

# remove this line
# plt.xticks([0,3,6,9,12,15,18,21,24])
edgecolor = 'white', label = '2019', density=True)
plt.title('2019 comments, 8 bins')
plt.xlabel('Hours of Day')
plt.ylabel('Relative Frequency')
plt.tight_layout()
plt.legend()
plt.show()
</code>```

Or:

```<code>fig, ax = plt.subplots()

bins = np.arange(0,25,3)
comments19['comment_hour'].plot.hist(ax=ax,bins=bins)

# other plt format
</code>```

Body:
I am trying to show the frequency of my data throughout the hours of the day, using a histogram, in 3 hour intervals. I therefore use 8 bins.

plt.style.use('seaborn-colorblind')

plt.figure(figsize=(10,5))
plt.hist(comments19['comment_hour'], bins = 8, alpha = 1, align='mid', edgecolor = 'white', label = '2019', density=True)
plt.title('2019 comments, 8 bins')
plt.xticks([0,3,6,9,12,15,18,21,24])
plt.xlabel('Hours of Day')
plt.ylabel('Relative Frequency')
plt.tight_layout()
plt.legend()
plt.show()

However, the ticks are not aligning with the bin edges, as seen from the image below.

Body:
You can do either:

plt.figure(figsize=(10,5))

# define the bin and pass to plt.hist
bins = [0,3,6,9,12,15,18,21,24]
plt.hist(comments19['comment_hour'], bins = bins, alpha = 1, align='mid',

# remove this line
# plt.xticks([0,3,6,9,12,15,18,21,24])
edgecolor = 'white', label = '2019', density=True)
plt.title('2019 comments, 8 bins')
plt.xlabel('Hours of Day')
plt.ylabel('Relative Frequency')
plt.tight_layout()
plt.legend()
plt.show()

Or:

fig, ax = plt.subplots()

bins = np.arange(0,25,3)
comments19['comment_hour'].plot.hist(ax=ax,bins=bins)

# other plt format


问:
Link in PDF (using wijmo PDF) does not work
In IE, the length limit of the URL is about 2048 bytes, Query string may exceed 2048 bytes.

I use lz-string to compress strings, However, the link in the pdf does not work, Or maybe use another way to compress the string?

```<code>var compressed = LZString.compress(query)
</code>```

https://jsfiddle.net/p9e4a8dg/11

答:
Try reading this link.

If you want pure ASCII you can try compressToBase64

Body:
In IE, the length limit of the URL is about 2048 bytes, Query string may exceed 2048 bytes.

I use lz-string to compress strings, However, the link in the pdf does not work, Or maybe use another way to compress the string?

var compressed = LZString.compress(query)

https://jsfiddle.net/p9e4a8dg/11


问:
Using "with" statement for CSV files in Python
Is it possible to use the with statement directly with CSV files? It seems natural to be able to do something like this:

```<code>import csv
with csv.reader(open("myfile.csv")) as reader:
    # do things with reader
</code>```

But csv.reader doesn't provide the __enter__ and __exit__ methods, so this doesn't work. I can however do it in two steps:

```<code>import csv
with open("myfile.csv") as f:
    reader = csv.reader(f)
    # do things with reader
</code>```

Is this second way the ideal way to do it? Why wouldn't they make csv.reader directly compatible with the with statement?

答:
```<code>import csv

class CSV(object):
    def __init__(self,path,mode):
        self.path = path
        self.mode = mode
        self.file = None

    def __enter__(self):
        self.file = open(self.path,self.mode)
        if self.mode == 'r':
            return csv.reader(self.file)
        elif self.mode == 'w':
            return csv.writer(self.file)

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.file.close()

with CSV('data.csv','r') as reader:
    for row in reader:
        print row
</code>```

OwnerDisplayName: Kiv

Body:
Is it possible to use the with statement directly with CSV files? It seems natural to be able to do something like this:

import csv
with csv.reader(open("myfile.csv")) as reader:
    # do things with reader

But csv.reader doesn't provide the __enter__ and __exit__ methods, so this doesn't work. I can however do it in two steps:

import csv
with open("myfile.csv") as f:
    reader = csv.reader(f)
    # do things with reader

Is this second way the ideal way to do it? Why wouldn't they make csv.reader directly compatible with the with statement?


问:
Add XML element and save the file?
I'm pretty new to XML parsing with Python with minidom.

I have got this XML:

<filelist>
    <file id="1.jpg"></file>
</filelist>
```

<p>I would like to add and then save to the same file the following row for example:</p>

<pre class="lang-xml prettyprint-override"><code>    <file id="2.jpg"></file>
</code>```

I am doing the parsing using:

```<code>doc = minidom.parse('filelist.xml')
files = doc.getElementsByTagName('file')
for file in files:
      idFile = file.getAttribute("id")
      print(idFile)
</code>```

How I can add that "element" and then save to same file?

答:
Starting with your original code, the following additions were added to your code to accomplish adding an element and saving it back to the original file:

Create a new 'file' element

Set the new 'file' element 'id' attribute

Retrieve the document root ('filelist') node

Append the new 'file' element to the 'filelist' node

Write updated XML back to original file

See updated code following with comments to match this list of additions.

```<code>from xml.dom import minidom

doc = minidom.parse('filelist.xml')
# 1. Create a new 'file' element
new_file_element = doc.createElement('file')
# 2. Set the new 'file' element 'id' attribute
new_file_element.setAttribute('id', '2.jpg')
# 3. Retrieve the document root ('filelist') node
filelist_element = doc.documentElement
# 4. Append the new 'file' element to the 'filelist' node
filelist_element.appendChild(new_file_element)
files = doc.getElementsByTagName('file')
for file in files:
    idFile = file.getAttribute('id')
    print(idFile)
# 5. Write updated XML back to original file
with open('filelist.xml', 'w') as xml_file:
    doc.writexml(xml_file, encoding='utf-8')
</code>```

Title: Add XML element and save the file?

Body:
I'm pretty new to XML parsing with Python with minidom.

I have got this XML:

<filelist>
    <file id="1.jpg"></file>
</filelist>

I would like to add and then save to the same file the following row for example:

    <file id="2.jpg"></file>

I am doing the parsing using:

doc = minidom.parse('filelist.xml')
files = doc.getElementsByTagName('file')
for file in files:
      idFile = file.getAttribute("id")
      print(idFile)

How I can add that "element" and then save to same file?

Body:
Starting with your original code, the following additions were added to your code to accomplish adding an element and saving it back to the original file:

Create a new 'file' element

Set the new 'file' element 'id' attribute

Retrieve the document root ('filelist') node

Append the new 'file' element to the 'filelist' node

Write updated XML back to original file

See updated code following with comments to match this list of additions.

from xml.dom import minidom

doc = minidom.parse('filelist.xml')
# 1. Create a new 'file' element
new_file_element = doc.createElement('file')
# 2. Set the new 'file' element 'id' attribute
new_file_element.setAttribute('id', '2.jpg')
# 3. Retrieve the document root ('filelist') node
filelist_element = doc.documentElement
# 4. Append the new 'file' element to the 'filelist' node
filelist_element.appendChild(new_file_element)
files = doc.getElementsByTagName('file')
for file in files:
    idFile = file.getAttribute('id')
    print(idFile)
# 5. Write updated XML back to original file
with open('filelist.xml', 'w') as xml_file:
    doc.writexml(xml_file, encoding='utf-8')


问:
android vulkan vertex shader can't get all input data
I have my Vertex data defined like this:

```<code>struct Vertex{
    glm::vec4 pos;
    glm::vec2 texcoord;
    glm::vec2 texcoordex;
    float alpha;
    float idx;
};
</code>```

my problem is:
            vertex buffer has read all data, but vertex shader only gets the first one pos as input, others are 0.0f

vertex shader input

```<code>layout (location = 0) in vec4 pos;
layout (location = 1) in vec2 attr;
layout (location = 2) in vec2 attrex;
layout (location = 3) in float alph;
layout (location = 4) in float id;
</code>```

some code snippets

```<code>VkVertexInputBindingDescription vertex_input_bindings{
.binding = 0,
.stride = sizeof(Vertex),
.inputRate = VK_VERTEX_INPUT_RATE_VERTEX,
};

VkVertexInputAttributeDescription vertex_input_attributes[5]{
{
.binding = 0,
.location = 0,
.format = VK_FORMAT_R32G32B32A32_SFLOAT,
.offset = offsetof(Vertex, pos),
},
{
.binding = 0,
.location = 1,
.format = VK_FORMAT_R32G32_SFLOAT,
.offset = offsetof(Vertex, texcoord),
},
{
.binding = 0,
.location = 2,
.format = VK_FORMAT_R32G32_SFLOAT,
.offset = offsetof(Vertex, texcoordex),
},
{
.binding = 0,
.location = 3,
.format = VK_FORMAT_R32_SFLOAT,
.offset = offsetof(Vertex, alpha),
},
{
.binding = 0,
.location = 4,
.format = VK_FORMAT_R32_SFLOAT,
.offset = offsetof(Vertex, idx),
}};

VkPipelineVertexInputStateCreateInfo vertexInputInfo{
.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO,
.pNext = nullptr,
.vertexBindingDescriptionCount = 1,
.pVertexBindingDescriptions = &vertex_input_bindings,
.vertexAttributeDescriptionCount = 5,
.pVertexAttributeDescriptions = vertex_input_attributes,
};

VkDeviceSize offset = 0;
vkCmdBindVertexBuffers(render.cmdBuffer_[bufferIndex], 0, 1, &buffers.vertexBuf_, &offset);
</code>```

How can I solve the problem? Thanks for any help.

update

I get some information from Renderdoc by capturing frame. The result shows that vertex shader doesn't output correct data.(The vertex shader is a pass.)
But Renderdoc shows that vertex buffer has correct data.
Meanwhile, the vertex shader output varies each run, and never gets right.
Is it a sync issue? Where might the mistake be.

vertex shader data from Renderdoc

```<code>// Draw one frame
bool VulkanDrawFrame(void) {
    uint32_t nextIndex;
    // Get the framebuffer index we should draw in
    CALL_VK(vkAcquireNextImageKHR(device.device_, swapchain.swapchain_,
                                  UINT64_MAX, render.semaphore_, VK_NULL_HANDLE,
                                  &nextIndex));
    CALL_VK(vkResetFences(device.device_, 1, &render.fence_));

    VkPipelineStageFlags waitStageMask =
        VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
    VkSubmitInfo submit_info = {.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
                                .pNext = nullptr,
                                .waitSemaphoreCount = 1,
                                .pWaitSemaphores = &render.semaphore_,
                                .pWaitDstStageMask = &waitStageMask,
                                .commandBufferCount = 1,
                                .pCommandBuffers = &render.cmdBuffer_[nextIndex],
                                .signalSemaphoreCount = 0,
                                .pSignalSemaphores = nullptr};
    CALL_VK(vkQueueSubmit(device.queue_, 1, &submit_info, render.fence_));
    CALL_VK(
        vkWaitForFences(device.device_, 1, &render.fence_, VK_TRUE, 100000000));

    LOGI("Drawing frames......");

    VkResult result;
    VkPresentInfoKHR presentInfo{
        .sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
        .pNext = nullptr,
        .swapchainCount = 1,
        .pSwapchains = &swapchain.swapchain_,
        .pImageIndices = &nextIndex,
        .waitSemaphoreCount = 0,
        .pWaitSemaphores = nullptr,
        .pResults = &result,
        };
    vkQueuePresentKHR(device.queue_, &presentInfo);
    return true;
}

    // Create the pipeline
    VkGraphicsPipelineCreateInfo pipelineCreateInfo{
        .sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO,
        .pNext = nullptr,
        .flags = 0,
        .stageCount = 2,
        .pStages = shaderStages,
        .pVertexInputState = &vertexInputInfo,
        .pInputAssemblyState = &inputAssemblyInfo,
        .pTessellationState = nullptr,
        .pViewportState = &viewportInfo,
        .pRasterizationState = &rasterInfo,
        .pMultisampleState = &multisampleInfo,
        .pDepthStencilState = nullptr,
        .pColorBlendState = &colorBlendInfo,
        .pDynamicState = &dynamicStateInfo,
        .layout = gfxPipeline.layout_,
        .renderPass = render.renderPass_,
        .subpass = 0,
        .basePipelineHandle = VK_NULL_HANDLE,
        .basePipelineIndex = 0,
    };

  VkResult pipelineResult = vkCreateGraphicsPipelines(
      device.device_, gfxPipeline.cache_, 1, &pipelineCreateInfo, nullptr,
      &gfxPipeline.pipeline_);
</code>```

答:
I have sovled this.
The driver optimizes useless inputs. I delete operations concerning to them to simplify the debug, so the driver finds they are useless. </p>

Body:
I have my Vertex data defined like this:

struct Vertex{
    glm::vec4 pos;
    glm::vec2 texcoord;
    glm::vec2 texcoordex;
    float alpha;
    float idx;
};

my problem is:
            vertex buffer has read all data, but vertex shader only gets the first one pos as input, others are 0.0f

vertex shader input

layout (location = 0) in vec4 pos;
layout (location = 1) in vec2 attr;
layout (location = 2) in vec2 attrex;
layout (location = 3) in float alph;
layout (location = 4) in float id;

some code snippets

VkVertexInputBindingDescription vertex_input_bindings{
.binding = 0,
.stride = sizeof(Vertex),
.inputRate = VK_VERTEX_INPUT_RATE_VERTEX,
};

VkVertexInputAttributeDescription vertex_input_attributes[5]{
{
.binding = 0,
.location = 0,
.format = VK_FORMAT_R32G32B32A32_SFLOAT,
.offset = offsetof(Vertex, pos),
},
{
.binding = 0,
.location = 1,
.format = VK_FORMAT_R32G32_SFLOAT,
.offset = offsetof(Vertex, texcoord),
},
{
.binding = 0,
.location = 2,
.format = VK_FORMAT_R32G32_SFLOAT,
.offset = offsetof(Vertex, texcoordex),
},
{
.binding = 0,
.location = 3,
.format = VK_FORMAT_R32_SFLOAT,
.offset = offsetof(Vertex, alpha),
},
{
.binding = 0,
.location = 4,
.format = VK_FORMAT_R32_SFLOAT,
.offset = offsetof(Vertex, idx),
}};

VkPipelineVertexInputStateCreateInfo vertexInputInfo{
.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO,
.pNext = nullptr,
.vertexBindingDescriptionCount = 1,
.pVertexBindingDescriptions = &vertex_input_bindings,
.vertexAttributeDescriptionCount = 5,
.pVertexAttributeDescriptions = vertex_input_attributes,
};

VkDeviceSize offset = 0;
vkCmdBindVertexBuffers(render.cmdBuffer_[bufferIndex], 0, 1, &buffers.vertexBuf_, &offset);

How can I solve the problem? Thanks for any help.

update

I get some information from Renderdoc by capturing frame. The result shows that vertex shader doesn't output correct data.(The vertex shader is a pass.)
But Renderdoc shows that vertex buffer has correct data.
Meanwhile, the vertex shader output varies each run, and never gets right.
Is it a sync issue? Where might the mistake be.

vertex shader data from Renderdoc

// Draw one frame
bool VulkanDrawFrame(void) {
    uint32_t nextIndex;
    // Get the framebuffer index we should draw in
    CALL_VK(vkAcquireNextImageKHR(device.device_, swapchain.swapchain_,
                                  UINT64_MAX, render.semaphore_, VK_NULL_HANDLE,
                                  &nextIndex));
    CALL_VK(vkResetFences(device.device_, 1, &render.fence_));

    VkPipelineStageFlags waitStageMask =
        VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
    VkSubmitInfo submit_info = {.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
                                .pNext = nullptr,
                                .waitSemaphoreCount = 1,
                                .pWaitSemaphores = &render.semaphore_,
                                .pWaitDstStageMask = &waitStageMask,
                                .commandBufferCount = 1,
                                .pCommandBuffers = &render.cmdBuffer_[nextIndex],
                                .signalSemaphoreCount = 0,
                                .pSignalSemaphores = nullptr};
    CALL_VK(vkQueueSubmit(device.queue_, 1, &submit_info, render.fence_));
    CALL_VK(
        vkWaitForFences(device.device_, 1, &render.fence_, VK_TRUE, 100000000));

    LOGI("Drawing frames......");

    VkResult result;
    VkPresentInfoKHR presentInfo{
        .sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
        .pNext = nullptr,
        .swapchainCount = 1,
        .pSwapchains = &swapchain.swapchain_,
        .pImageIndices = &nextIndex,
        .waitSemaphoreCount = 0,
        .pWaitSemaphores = nullptr,
        .pResults = &result,
        };
    vkQueuePresentKHR(device.queue_, &presentInfo);
    return true;
}

    // Create the pipeline
    VkGraphicsPipelineCreateInfo pipelineCreateInfo{
        .sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO,
        .pNext = nullptr,
        .flags = 0,
        .stageCount = 2,
        .pStages = shaderStages,
        .pVertexInputState = &vertexInputInfo,
        .pInputAssemblyState = &inputAssemblyInfo,
        .pTessellationState = nullptr,
        .pViewportState = &viewportInfo,
        .pRasterizationState = &rasterInfo,
        .pMultisampleState = &multisampleInfo,
        .pDepthStencilState = nullptr,
        .pColorBlendState = &colorBlendInfo,
        .pDynamicState = &dynamicStateInfo,
        .layout = gfxPipeline.layout_,
        .renderPass = render.renderPass_,
        .subpass = 0,
        .basePipelineHandle = VK_NULL_HANDLE,
        .basePipelineIndex = 0,
    };

  VkResult pipelineResult = vkCreateGraphicsPipelines(
      device.device_, gfxPipeline.cache_, 1, &pipelineCreateInfo, nullptr,
      &gfxPipeline.pipeline_);


问:
How do I count conditionally in R
I have a list </p>

```<code>x <- c(1,2,3,4,5)
</code>```

<p>How do I count how many elements are over 3. So the output would be 2. </p>

答:
Take advantage of the fact logical are represented by 1 and 0
sum(1:5 > 3)

Title: How do I count conditionally in R

Body:
I have a list

x <- c(1,2,3,4,5)

How do I count how many elements are over 3. So the output would be 2.


问:
How to assign url parameter value and load in iframe using radio buttons
Using select/option tag works fine but no success when I use radio buttons.

function xxx(){
 var base_url = 'https://example.com/?test=';
 var select_value = document.getElementById('myid').value;
 var target_url = base_url + select_value;
 var ifr = document.getElementById('myiframe');
 ifr.src = target_url;
 return false;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <form>
      <select id="myid" onchange="xxx();">
        <option value="VALUE1">Featured</option>
        <option value="VALUE2">Hey</option>
        <option value="VALUE3">Wish</option>
      </select>
    </form>
<iframe src="" id="myiframe" width="460" height="300"></iframe></code>```

I want to use below format but the result is "undefined"...

```<code><form id="myid" onchange="xxx();">
  <input type="radio" name="name1" value="VALUE1"> featured<br>
  <input type="radio" name="name1" value="VALUE2"> hey<br>
  <input type="radio" name="name1" value="VALUE3"> wish
</form>
</code>```

I'm getting this

https://example.com/?test=UNDEFINED

instead of

https://example.com/?test=VALUE1 or VALUE2 or VALUE3

答:
Use formdata together with the get method to get the form's value like this:

function xxx(){
 let data = new FormData(document.querySelector('form'))
 var base_url = 'https://example.com/?test=';
 var target_url = base_url + data.get('name1');
 var ifr = document.getElementById('myiframe');
 console.log(target_url);
 ifr.src = target_url;
 return false;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <form id="myid" onchange="xxx();">
  <input type="radio" name="name1" value="VALUE1"> featured<br>
  <input type="radio" name="name1" value="VALUE2"> hey<br>
  <input type="radio" name="name1" value="VALUE3"> wish
</form>
<iframe src="" id="myiframe" width="460" height="300"></iframe></code>```

Body:
Using select/option tag works fine but no success when I use radio buttons.

function xxx(){
 var base_url = 'https://example.com/?test=';
 var select_value = document.getElementById('myid').value;
 var target_url = base_url + select_value;
 var ifr = document.getElementById('myiframe');
 ifr.src = target_url;
 return false;
}

    <form>
      <select id="myid" onchange="xxx();">
        <option value="VALUE1">Featured</option>
        <option value="VALUE2">Hey</option>
        <option value="VALUE3">Wish</option>
      </select>
    </form>

I want to use below format but the result is "undefined"...

<form id="myid" onchange="xxx();">
  <input type="radio" name="name1" value="VALUE1"> featured

  <input type="radio" name="name1" value="VALUE2"> hey

  <input type="radio" name="name1" value="VALUE3"> wish
</form>

I'm getting this

https://example.com/?test=UNDEFINED

instead of

https://example.com/?test=VALUE1 or VALUE2 or VALUE3

Body:
Use formdata together with the get method to get the form's value like this:

function xxx(){
 let data = new FormData(document.querySelector('form'))
 var base_url = 'https://example.com/?test=';
 var target_url = base_url + data.get('name1');
 var ifr = document.getElementById('myiframe');
 console.log(target_url);
 ifr.src = target_url;
 return false;
}

 <form id="myid" onchange="xxx();">
  <input type="radio" name="name1" value="VALUE1"> featured<br>
  <input type="radio" name="name1" value="VALUE2"> hey<br>
  <input type="radio" name="name1" value="VALUE3"> wish
</form>
<iframe src="" id="myiframe" width="460" height="300"></iframe>


问:
Executing a command when a list is equal to one line of a matrix in python
If all 3 of the values in the list below are equal to any of the 3 values in one line of the matrix, I want it to print 'hello'. </p>

```<code>#if x is equal to the 1st line of the matrix I want it to print hello. If x is equal to the 2nd part and not the 1st I still want it to print the same string.

x = [1, 2, 3]
y = [
    [1, 2, 3],
    [4, 5, 6],
    [3, 4, 5],
    [7, 8, 9]
]
if x == (y):
    print('hello')
</code>```

<p>As shown above, the x list value is equal to one of the lines in the matrix but it won't print hello. How would I get the program to do that. </p>

答:
The comparison you're making - x == (y) fails, because (y) evaluates to y, and x == y is False (as y is a nested list).

What you want to do is iterate over the lines:

```<code>x = [1,2,3]
y = [
    [1, 2, 3],
    [4, 5, 6],
    [3, 4, 5],
    [7, 8, 9]
]

for yi in y:
    if x == yi:
        print("Hello")
</code>```

For the given input this prints Hello once. If [1,2,3] appears multiple times, it prints Hello every time it finds one.

Note that this assumes that [1,2,3] != [3,2,1] (which is what Python assumes internally). You have to tweak it if order doesn't matter.

Body:
If all 3 of the values in the list below are equal to any of the 3 values in one line of the matrix, I want it to print 'hello'.

#if x is equal to the 1st line of the matrix I want it to print hello. If x is equal to the 2nd part and not the 1st I still want it to print the same string.

x = [1, 2, 3]
y = [
    [1, 2, 3],
    [4, 5, 6],
    [3, 4, 5],
    [7, 8, 9]
]
if x == (y):
    print('hello')

As shown above, the x list value is equal to one of the lines in the matrix but it won't print hello. How would I get the program to do that.

Body:
The comparison you're making - x == (y) fails, because (y) evaluates to y, and x == y is False (as y is a nested list).

What you want to do is iterate over the lines:

x = [1,2,3]
y = [
    [1, 2, 3],
    [4, 5, 6],
    [3, 4, 5],
    [7, 8, 9]
]

for yi in y:
    if x == yi:
        print("Hello")

For the given input this prints Hello once. If [1,2,3] appears multiple times, it prints Hello every time it finds one.

Note that this assumes that [1,2,3] != [3,2,1] (which is what Python assumes internally). You have to tweak it if order doesn't matter.


问:
Uppercase and lowercase string
Is there a way to convert a string to a sequence of uppercase and lowercase letters inside a command? For example, al_sp "Kilometers" → KiLoMeTeRs

Here is what I tried so far but I am not getting any output, any help is appreciated

```<code>@commands.command()
    async def rand(self, c, upperlower):
        upperlower = upperlower.join([char.upper() if i%2==0 else char.lower() for i, char in enumerate(upperlower)])
        await c.message.delete()
        await c.send(upperlower)
</code>```

答:
Thank you Patrick Haugh for pointing this out

I needed to replace upperlower.join with ''.join

Title: Uppercase and lowercase string

Body:
Is there a way to convert a string to a sequence of uppercase and lowercase letters inside a command? For example, al_sp "Kilometers" → KiLoMeTeRs

Here is what I tried so far but I am not getting any output, any help is appreciated

@commands.command()
    async def rand(self, c, upperlower):
        upperlower = upperlower.join([char.upper() if i%2==0 else char.lower() for i, char in enumerate(upperlower)])
        await c.message.delete()
        await c.send(upperlower)


问:
How to display different column data as tool tip in ag grid pivot mode?
```<code>var ColDef = [{
    headerName: "colA",
    field: 'colA',
    rowGroup: true
  },
  {
    headerName: "colB",
    field: 'colB',
    pivot: true,
    enablePivot: true
  },
  {
    headerName: "colC",
    field: 'colC',
    rowGroup: true
  },
  {
    field: 'colD',
    aggFunc: 'first',
    valueFormatter: currencyFormatter,
    tooltip: function(params) {
      return (params.valueFormatted);
    },
  },
  {
    field: 'comment'
  },
  {
    field: 'colF'
  }
];
function currencyFormatter(params) {
  return params.value;
}
</code>```

<p>above code is from different question. it works but i want to use different 'comment' field as tool tip to current 'colD' . also this is a group and pivot agGrid,if it is normal grid this is not a problem. I would appreciate any ideas for group and pivot agGrid? </p>

答:
Not sure if there is good way for the grid to get the data in your scenario then, as your rows and columns are different than original model after pivot.

Maybe you can consider retrieve this information outside of grid. Assume you also want some aggregated information displays in the tooltip, the tooltip function may eventually look like this:

```<code>tooltip: params => {
  const country = params.node.key;
  const year = params.colDef.pivotKeys[0];
  const athletesWithNumbers = this.state.rowData
    .filter(d => d.year == year)
    .filter(d => d.country === country)
    .filter(d => d.gold > 0)
    .map(d => d.athlete + ': ' + d.gold);
  return athletesWithNumbers.join(', ');
}
</code>```

See this plunker for what I am talking about - again, not sure if this is what you want but just an FYI.

Body:
var ColDef = [{
    headerName: "colA",
    field: 'colA',
    rowGroup: true
  },
  {
    headerName: "colB",
    field: 'colB',
    pivot: true,
    enablePivot: true
  },
  {
    headerName: "colC",
    field: 'colC',
    rowGroup: true
  },
  {
    field: 'colD',
    aggFunc: 'first',
    valueFormatter: currencyFormatter,
    tooltip: function(params) {
      return (params.valueFormatted);
    },
  },
  {
    field: 'comment'
  },
  {
    field: 'colF'
  }
];
function currencyFormatter(params) {
  return params.value;
}

above code is from different question. it works but i want to use different 'comment' field as tool tip to current 'colD' . also this is a group and pivot agGrid,if it is normal grid this is not a problem. I would appreciate any ideas for group and pivot agGrid?

Body:
Not sure if there is good way for the grid to get the data in your scenario then, as your rows and columns are different than original model after pivot.

Maybe you can consider retrieve this information outside of grid. Assume you also want some aggregated information displays in the tooltip, the tooltip function may eventually look like this:

tooltip: params => {
  const country = params.node.key;
  const year = params.colDef.pivotKeys[0];
  const athletesWithNumbers = this.state.rowData
    .filter(d => d.year == year)
    .filter(d => d.country === country)
    .filter(d => d.gold > 0)
    .map(d => d.athlete + ': ' + d.gold);
  return athletesWithNumbers.join(', ');
}

See this plunker for what I am talking about - again, not sure if this is what you want but just an FYI.


答:
If you set bins=8, seaborn will set 9 evenly spread boundaries, from the lowest value in the input array (0) to the highest (23), so at [0.0, 2.875, 5.75, 8.625, 11.5, 14.375, 17.25, 20.125, 23.0]. To get the 9 boundaries at 0, 3, 6, ... you need to set them explicitly.

import numpy as np
import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt

plt.style.use('seaborn-colorblind')

comments19 = pd.DataFrame({'comment_hour': np.random.randint(0, 24, 100)})

plt.figure(figsize=(10, 5))
plt.hist(comments19['comment_hour'], bins=np.arange(0, 25, 3), alpha=1, align='mid', edgecolor='white', label='2019',
         density=True)
plt.title('2019 comments, 8 bins')
plt.xticks(np.arange(0, 25, 3))
plt.xlabel('Hours of Day')
plt.ylabel('Relative Frequency')
plt.tight_layout()
plt.legend()
plt.show()
```

<p><img src="https://i.stack.imgur.com/EMV5l.png" alt="example plot"></p>

<p>Note that your <code>density=True</code> means that the total area of the histogram is 1. As each bin is 3 hours wide, the sum of all the bin heights will be <code>0.33</code> and not <code>1.00</code> as you might expect. To really get a y-axis with relative frequencies, you could make the internal bin widths <code>1</code> by dividing the hours by <code>3</code>. Afterwards you can relabel the x-axis back to hours.</p>

<p>So, following changes could be made for all the bins to sum to 100 %:</p>

<pre class="lang-py prettyprint-override"><code>from matplotlib.ticker import PercentFormatter

plt.hist(comments19['comment_hour'] / 3, bins=np.arange(9), alpha=1, align='mid', edgecolor='white', label='2019',
         density=True)
plt.xticks(np.arange(9), np.arange(0, 25, 3))
plt.gca().yaxis.set_major_formatter(PercentFormatter(1))
</code>```

Title: Difficulty aligning xticks to edge of Histogram bin

Body:
If you set bins=8, seaborn will set 9 evenly spread boundaries, from the lowest value in the input array (0) to the highest (23), so at [0.0, 2.875, 5.75, 8.625, 11.5, 14.375, 17.25, 20.125, 23.0]. To get the 9 boundaries at 0, 3, 6, ... you need to set them explicitly.

import numpy as np
import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt

plt.style.use('seaborn-colorblind')

comments19 = pd.DataFrame({'comment_hour': np.random.randint(0, 24, 100)})

plt.figure(figsize=(10, 5))
plt.hist(comments19['comment_hour'], bins=np.arange(0, 25, 3), alpha=1, align='mid', edgecolor='white', label='2019',
         density=True)
plt.title('2019 comments, 8 bins')
plt.xticks(np.arange(0, 25, 3))
plt.xlabel('Hours of Day')
plt.ylabel('Relative Frequency')
plt.tight_layout()
plt.legend()
plt.show()

Note that your density=True means that the total area of the histogram is 1. As each bin is 3 hours wide, the sum of all the bin heights will be 0.33 and not 1.00 as you might expect. To really get a y-axis with relative frequencies, you could make the internal bin widths 1 by dividing the hours by 3. Afterwards you can relabel the x-axis back to hours.

So, following changes could be made for all the bins to sum to 100 %:

from matplotlib.ticker import PercentFormatter

plt.hist(comments19['comment_hour'] / 3, bins=np.arange(9), alpha=1, align='mid', edgecolor='white', label='2019',
         density=True)
plt.xticks(np.arange(9), np.arange(0, 25, 3))
plt.gca().yaxis.set_major_formatter(PercentFormatter(1))