问:
Which is the correct code structure to be followed for getting the best output using TestModules in Canoe?
I am using CANoe 10.0 to do some Diagnostic testing and I have to generate reports for the tests. So, I am using Test Setup to create my test cases using CAPL.
I know that the test starts from the function "MainTest".
After this, I don't know how to structure my test case and which functions to use to get the correct format in the report.
For example, I want to send a Diagnostic request and expecting a particular response. I want to be able to show in the report, the sending of the message, what response was received and what response was expected. Based on this, the verdict should be displayed.</p>

答:
Below you can find simple example. More examples and another use cases you can find in CANoe 'Help' and "Sample Configurations" provided by Vector.Before first try  please remember to add CDD file which will allow you to import diagnostics services to CANoe environment(Ive used example Vector CDD).   </p>

```<code>void MainTest()
{
TestModuleTitle ("ECU DIAGNOSTICS TEST");
TestModuleDescription ("Basic Diagnostics Test");

TestGroupBegin("ECU Extended session", "ReadPartNubmers");
ExtendedDiagnosticSession_Start();
//testcase
//testcase
//...
//testcase n
TestGroupEnd();

TestGroupBegin("ECU Identification", "ReadPartNubmers");
ReadSerialPartNumber();
//testcase eg  ReadSerialPartNumber()...
//testcase
//...
//testcase
TestGroupEnd();
}

testcase  ReadSerialPartNumber()
{
diagRequest ABS_ESP.Serial_Number_Read req; //Service from CDD

TestCaseTitle("TEST 1 ReadPartNumber", "Read Serial Part Number");

diagSendRequest(req);

if (TestWaitForDiagResponse(req, 2000)== 1)
{
  testReportWriteDiagResponse(req);

  if(DiagGetLastResponseCode(req) == -1) // Positive response
  {
    byte DataBuffer[50];

    diagGetRespParameterRaw(req,"SerialNumber",DataBuffer,20);// get data from response

      if(DataBuffer[0] == 0xAA)//dummy response verification
      {
         TestStepPass("Serial Number is correct");
      }
      else
      {
         TestStepFail("Wrong Part number ");
      }
  }
  else if(DiagGetLastResponseCode(req) > 0)//Negative response
  {
    TestStepFail("Negative response received");
  }

}
else
{
  TestStepFail("No answer from ECU!");
}
}

testcase ExtendedDiagnosticSession_Start()
{
  diagRequest ABS_ESP.ExtendedDiagnosticSession_Start req; //Service from CDD,

 TestCaseTitle("Test no 1", "Set Extended session");

diagSendRequest(req);

if (TestWaitForDiagResponse(req, 2000)== 1)
{
  testReportWriteDiagResponse(req);

  if(DiagGetLastResponseCode(req) == -1) // Positive response
  {

   TestStepPass("Positive");

  }
  else if(DiagGetLastResponseCode(req) > 0)//Negative response
  {

    TestStepFail("ExtendedDiagnosticSession","Negative response received");
  }

}
else
{
  TestStepFail("ExtendedDiagnosticSession","No answer from ECU!");
}

}
</code>```

Body:
Below you can find simple example. More examples and another use cases you can find in CANoe 'Help' and "Sample Configurations" provided by Vector.Before first try  please remember to add CDD file which will allow you to import diagnostics services to CANoe environment(Ive used example Vector CDD).

void MainTest()
{
TestModuleTitle ("ECU DIAGNOSTICS TEST");
TestModuleDescription ("Basic Diagnostics Test");

TestGroupBegin("ECU Extended session", "ReadPartNubmers");
ExtendedDiagnosticSession_Start();
//testcase
//testcase
//...
//testcase n
TestGroupEnd();

TestGroupBegin("ECU Identification", "ReadPartNubmers");
ReadSerialPartNumber();
//testcase eg  ReadSerialPartNumber()...
//testcase
//...
//testcase
TestGroupEnd();
}

testcase  ReadSerialPartNumber()
{
diagRequest ABS_ESP.Serial_Number_Read req; //Service from CDD

TestCaseTitle("TEST 1 ReadPartNumber", "Read Serial Part Number");

diagSendRequest(req);

if (TestWaitForDiagResponse(req, 2000)== 1)
{
  testReportWriteDiagResponse(req);

  if(DiagGetLastResponseCode(req) == -1) // Positive response
  {
    byte DataBuffer[50];

    diagGetRespParameterRaw(req,"SerialNumber",DataBuffer,20);// get data from response

      if(DataBuffer[0] == 0xAA)//dummy response verification
      {
         TestStepPass("Serial Number is correct");
      }
      else
      {
         TestStepFail("Wrong Part number ");
      }
  }
  else if(DiagGetLastResponseCode(req) > 0)//Negative response
  {
    TestStepFail("Negative response received");
  }

}
else
{
  TestStepFail("No answer from ECU!");
}
}

testcase ExtendedDiagnosticSession_Start()
{
  diagRequest ABS_ESP.ExtendedDiagnosticSession_Start req; //Service from CDD,

 TestCaseTitle("Test no 1", "Set Extended session");

diagSendRequest(req);

if (TestWaitForDiagResponse(req, 2000)== 1)
{
  testReportWriteDiagResponse(req);

  if(DiagGetLastResponseCode(req) == -1) // Positive response
  {

   TestStepPass("Positive");

  }
  else if(DiagGetLastResponseCode(req) > 0)//Negative response
  {

    TestStepFail("ExtendedDiagnosticSession","Negative response received");
  }

}
else
{
  TestStepFail("ExtendedDiagnosticSession","No answer from ECU!");
}

}


来源: stackexchange

问:
How to change reference frame value?
Hi I am trying to change reference frames from 4 to 3 but it didn't work.

Have tried to change gop, b frames with reference frames but didn't work

```<code>ffmpeg8 -report -ss 00:00:00.000 -t 00:04:47.000 -i /input1 -ss 00:04:47.001 -t 00:04:00.000 -i /input2 -filter_complex "[0:v:0]crop=out_h=576:y=32,yadif=1:-1:0[part1crop]; [1:v:0]crop=out_h=576:y=32,yadif=1:-1:0[part2crop]; [0:a:0]pan=stereo|c0=c0|c1=c1[part1audioStereo]; [1:a:0]pan=stereo|c0=c0|c1=c1[part2audioStereo]; [part1crop][part1audioStereo][part2crop][part2audioStereo]concat=n=2:v=1:a=1[vconcat][aconcat]" -map '[vconcat]' -codec:v libx264 -profile:v high -level 4.1 -coder 1 -pix_fmt yuv420p -g 50 -bf 3 -b:v 1500k -video_track_timescale 25 -r 25 -s:v 1024x768 -aspect 4:3 -x264opts keyint=50:ref=4:bframes=3:subq=6:trellis=2:8x8dct=1:b-pyramid=0:vbv-bufsize=1500:nal-hrd=cbr -map '[aconcat]' -codec:a libfdk_aac -ar 48000 -ac 2 -b:a 128K -write_tmcd off output.mp4
</code>```

result:

Video
ID                                       : 226 (0xE2)
Format                                   : AVC
Format/Info                              : Advanced Video Codec
Format profile                           : High@L4.1
Format settings                          : 4 Ref Frames
Format settings, CABAC                   : No
Format settings, RefFrames               : 4 frames
Duration                                 : 35 s 80 ms
Nominal bit rate                         : 15.0 Mb/s
Width                                    : 1 024 pixels
Height                                   : 576 pixels
Display aspect ratio                     : 16:9
Frame rate mode                          : Variable
Color space                              : YUV
Chroma subsampling                       : 4:2:0
Bit depth                                : 8 bits
Scan type                                : Progressive
Writing library                          : x264 core 148

答: Works here by changing to ref=3 within -x264opts.

ContentLicense: CC BY-SA 4.0

Title: How to change reference frame value?

Body:
Hi I am trying to change reference frames from 4 to 3 but it didn't work.

Have tried to change gop, b frames with reference frames but didn't work

ffmpeg8 -report -ss 00:00:00.000 -t 00:04:47.000 -i /input1 -ss 00:04:47.001 -t 00:04:00.000 -i /input2 -filter_complex "[0:v:0]crop=out_h=576:y=32,yadif=1:-1:0[part1crop]; [1:v:0]crop=out_h=576:y=32,yadif=1:-1:0[part2crop]; [0:a:0]pan=stereo|c0=c0|c1=c1[part1audioStereo]; [1:a:0]pan=stereo|c0=c0|c1=c1[part2audioStereo]; [part1crop][part1audioStereo][part2crop][part2audioStereo]concat=n=2:v=1:a=1[vconcat][aconcat]" -map '[vconcat]' -codec:v libx264 -profile:v high -level 4.1 -coder 1 -pix_fmt yuv420p -g 50 -bf 3 -b:v 1500k -video_track_timescale 25 -r 25 -s:v 1024x768 -aspect 4:3 -x264opts keyint=50:ref=4:bframes=3:subq=6:trellis=2:8x8dct=1:b-pyramid=0:vbv-bufsize=1500:nal-hrd=cbr -map '[aconcat]' -codec:a libfdk_aac -ar 48000 -ac 2 -b:a 128K -write_tmcd off output.mp4

result:

Video
ID                                       : 226 (0xE2)
Format                                   : AVC
Format/Info                              : Advanced Video Codec
Format profile                           : High@L4.1
Format settings                          : 4 Ref Frames
Format settings, CABAC                   : No
Format settings, RefFrames               : 4 frames
Duration                                 : 35 s 80 ms
Nominal bit rate                         : 15.0 Mb/s
Width                                    : 1 024 pixels
Height                                   : 576 pixels
Display aspect ratio                     : 16:9
Frame rate mode                          : Variable
Color space                              : YUV
Chroma subsampling                       : 4:2:0
Bit depth                                : 8 bits
Scan type                                : Progressive
Writing library                          : x264 core 148


问:
Getting a list of XML tags in file, using xml.etree.ElementTree
As mentioned, I need to get the list of XML tags in file, using library xml.etree.ElementTree.

I am aware that there are properties and methods like ETVar.child, ETVar.getroot(), ETVar.tag, ETVar.attrib.

But to be able to use them and get at least name of tags on level 2, I had to use nested for.

At the moment I have something like

```<code>for xmlChild in xmlRootTag:
    if xmlChild.tag:
        print(xmlChild.tag)
</code>```

Goal would be to get a list of ALL, even deeply nested XML tags in file, eliminating duplicates.

For a better idea, I add the possible example of XML code:

```<code><root>
 <firstLevel>
  <secondlevel level="2">
    <thirdlevel>
      <fourth>text</fourth>
      <fourth2>text</fourth>
    </thirdlevel>
  </secondlevel>
 </firstlevel>
</root>
</code>```

答:
You could use the built-in Python set comprehension:

```<code>import xml.etree.ElementTree as ET

xmlTree = ET.parse('myXMLFile.xml')
tags = {elem.tag for elem in xmlTree.iter()}
</code>```

If you specifically need a list, you can cast it to a list:

```<code>import xml.etree.ElementTree as ET

xmlTree = ET.parse('myXMLFile.xml')
tags = list({elem.tag for elem in xmlTree.iter()})
</code>```

Body:
As mentioned, I need to get the list of XML tags in file, using library xml.etree.ElementTree.

I am aware that there are properties and methods like ETVar.child, ETVar.getroot(), ETVar.tag, ETVar.attrib.

But to be able to use them and get at least name of tags on level 2, I had to use nested for.

At the moment I have something like

for xmlChild in xmlRootTag:
    if xmlChild.tag:
        print(xmlChild.tag)

Goal would be to get a list of ALL, even deeply nested XML tags in file, eliminating duplicates.

For a better idea, I add the possible example of XML code:

<root>
 <firstLevel>
  <secondlevel level="2">
    <thirdlevel>
      <fourth>text</fourth>
      <fourth2>text</fourth>
    </thirdlevel>
  </secondlevel>
 </firstlevel>
</root>

Body:
You could use the built-in Python set comprehension:

import xml.etree.ElementTree as ET

xmlTree = ET.parse('myXMLFile.xml')
tags = {elem.tag for elem in xmlTree.iter()}

If you specifically need a list, you can cast it to a list:

import xml.etree.ElementTree as ET

xmlTree = ET.parse('myXMLFile.xml')
tags = list({elem.tag for elem in xmlTree.iter()})


问:
How to compile Curl with legacy SSL support on Ubuntu?
I have the following error, when attempting to connect to an old HTTPS-enabled web site using Curl:

```<code>curl https://10.11.1.44
curl: (35) error:1425F102:SSL routines:ssl_choose_client_version:unsupported protocol
</code>```

More verbosely:

```<code>* Expire in 0 ms for 6 (transfer 0x55a4192abdd0)
*   Trying 10.11.1.44...
* TCP_NODELAY set
* Expire in 200 ms for 4 (transfer 0x55a4192abdd0)
* Connected to 10.11.1.44 (10.11.1.44) port 443 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* successfully set certificate verify locations:
*   CAfile: none
  CApath: /etc/ssl/certs
* TLSv1.3 (OUT), TLS handshake, Client hello (1):
* TLSv1.3 (IN), TLS handshake, Server hello (2):
* TLSv1.3 (OUT), TLS alert, protocol version (582):
* error:1425F102:SSL routines:ssl_choose_client_version:unsupported protocol
* Closing connection 0
curl: (35) error:1425F102:SSL routines:ssl_choose_client_version:unsupported protocol
</code>```

If I try to use the --ssl2 or --ssl3 options, I get the following error:

```<code>root@kali:~# curl https://10.11.1.44/ --sslv2
curl: (4) OpenSSL was built without SSLv2 support
root@kali:~# curl https://10.11.1.44/ --sslv3
curl: (4) OpenSSL was built without SSLv3 support
</code>```

I've consulted the following page for how to build Curl with SSL2/3 support, but I'm not sure how to enable it?

https://curl.haxx.se/docs/install.html

Any ideas?

答:
Update: curl dropped support for --sslv2 / sslv3 sometime after curl version 7.76.1 was released, so you must make sure to also compile curl version 7.76.1 or older. instructions has been updated to make sure curl 7.76.1 is generated. (thanks to Matias Barros for the update)

you'll need to compile both curl and your ssl backend from source, obviously you'll need a C compiler, and probably more stuff but idk what, hopefully this should cover it:

```<code>sudo apt-get install gcc build-essential make cmake autoconf git automake libtool
</code>```

this can probably be done with several ssl backends, but since i'm most familiar with OpenSSL, i'll proceed with OpenSSL, to build openssl go to the openssl repo at https://github.com/openssl/openssl and find an appropriate openssl version, in this example i chose version 1.1.1k (which is the latest stable openssl release as of writing),

```<code>git clone -b 'OpenSSL_1_1_1k' --single-branch --depth 1 https://github.com/openssl/openssl
cd openssl
./config no-shared enable-ssl2 enable-ssl3 enable-ssl3-method
make -j $(nproc)
</code>```

(the last step may take a while) but openSSL's build script does not create a lib folder, but curl's build script expect the lib files to be in a lib folder inside the openssl folder, so after the make, run

```<code>mkdir lib
cp *.a lib;
</code>```

once that's done, it's time to make curl, so cd .. out of there and clone the last version of curl supporting the --sslv2 / --sslv3 switches 7.76.1,

```<code>git clone -b 'curl-7_76_1' --single-branch --depth 1 https://github.com/curl/curl.git
cd curl
./buildconf
LDFLAGS="-static" ./configure --with-ssl=$(realpath ../openssl) --disable-shared  --enable-static
make -j $(nproc)
</code>```

(if you wonder why i used realpath: there appears to be a bug in curl's buildscript that makes it fail if you supply a relative path, so an absolute path is required, it seems. if you wonder why i made a static build aka --disable-shared --enable-static, you may have a different libopenssl library in your $PATH, so to avoid a conflict with ubuntu's built-in libopenssl, a static build is safer.)

and finally,

```<code>/temp2/curl# ./src/curl --sslv3 https://google.com
curl: (35) error:1409442E:SSL routines:ssl3_read_bytes:tlsv1 alert protocol version
</code>```

(because https://google.com no longer supports sslv3, at all.)

TL;DR

```<code>git clone -b 'OpenSSL_1_1_1k' --single-branch --depth 1 https://github.com/openssl/openssl
cd openssl
./config no-shared enable-ssl2 enable-ssl3 enable-ssl3-method
make -j $(nproc)
mkdir lib
cp *.a lib;
cd ..
git clone -b 'curl-7_76_1' --single-branch --depth 1 https://github.com/curl/curl.git
cd curl
./buildconf
LDFLAGS="-static" ./configure --with-ssl=$(realpath ../openssl) --disable-shared  --enable-static
make -j $(nproc)
./src/curl --sslv3 https://google.com
</code>```

Body:
I have the following error, when attempting to connect to an old HTTPS-enabled web site using Curl:

curl https://10.11.1.44
curl: (35) error:1425F102:SSL routines:ssl_choose_client_version:unsupported protocol

More verbosely:

* Expire in 0 ms for 6 (transfer 0x55a4192abdd0)
*   Trying 10.11.1.44...
* TCP_NODELAY set
* Expire in 200 ms for 4 (transfer 0x55a4192abdd0)
* Connected to 10.11.1.44 (10.11.1.44) port 443 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* successfully set certificate verify locations:
*   CAfile: none
  CApath: /etc/ssl/certs
* TLSv1.3 (OUT), TLS handshake, Client hello (1):
* TLSv1.3 (IN), TLS handshake, Server hello (2):
* TLSv1.3 (OUT), TLS alert, protocol version (582):
* error:1425F102:SSL routines:ssl_choose_client_version:unsupported protocol
* Closing connection 0
curl: (35) error:1425F102:SSL routines:ssl_choose_client_version:unsupported protocol

If I try to use the --ssl2 or --ssl3 options, I get the following error:

root@kali:~# curl https://10.11.1.44/ --sslv2
curl: (4) OpenSSL was built without SSLv2 support
root@kali:~# curl https://10.11.1.44/ --sslv3
curl: (4) OpenSSL was built without SSLv3 support

I've consulted the following page for how to build Curl with SSL2/3 support, but I'm not sure how to enable it?

https://curl.haxx.se/docs/install.html

Any ideas?

Body:
Update: curl dropped support for --sslv2 / sslv3 sometime after curl version 7.76.1 was released, so you must make sure to also compile curl version 7.76.1 or older. instructions has been updated to make sure curl 7.76.1 is generated. (thanks to Matias Barros for the update)

you'll need to compile both curl and your ssl backend from source, obviously you'll need a C compiler, and probably more stuff but idk what, hopefully this should cover it:

sudo apt-get install gcc build-essential make cmake autoconf git automake libtool

this can probably be done with several ssl backends, but since i'm most familiar with OpenSSL, i'll proceed with OpenSSL, to build openssl go to the openssl repo at https://github.com/openssl/openssl and find an appropriate openssl version, in this example i chose version 1.1.1k (which is the latest stable openssl release as of writing),

git clone -b 'OpenSSL_1_1_1k' --single-branch --depth 1 https://github.com/openssl/openssl
cd openssl
./config no-shared enable-ssl2 enable-ssl3 enable-ssl3-method
make -j $(nproc)

(the last step may take a while) but openSSL's build script does not create a lib folder, but curl's build script expect the lib files to be in a lib folder inside the openssl folder, so after the make, run

mkdir lib
cp *.a lib;

once that's done, it's time to make curl, so cd .. out of there and clone the last version of curl supporting the --sslv2 / --sslv3 switches 7.76.1,

git clone -b 'curl-7_76_1' --single-branch --depth 1 https://github.com/curl/curl.git
cd curl
./buildconf
LDFLAGS="-static" ./configure --with-ssl=$(realpath ../openssl) --disable-shared  --enable-static
make -j $(nproc)

(if you wonder why i used realpath: there appears to be a bug in curl's buildscript that makes it fail if you supply a relative path, so an absolute path is required, it seems. if you wonder why i made a static build aka --disable-shared --enable-static, you may have a different libopenssl library in your $PATH, so to avoid a conflict with ubuntu's built-in libopenssl, a static build is safer.)

and finally,

/temp2/curl# ./src/curl --sslv3 https://google.com
curl: (35) error:1409442E:SSL routines:ssl3_read_bytes:tlsv1 alert protocol version

(because https://google.com no longer supports sslv3, at all.)

TL;DR

git clone -b 'OpenSSL_1_1_1k' --single-branch --depth 1 https://github.com/openssl/openssl
cd openssl
./config no-shared enable-ssl2 enable-ssl3 enable-ssl3-method
make -j $(nproc)
mkdir lib
cp *.a lib;
cd ..
git clone -b 'curl-7_76_1' --single-branch --depth 1 https://github.com/curl/curl.git
cd curl
./buildconf
LDFLAGS="-static" ./configure --with-ssl=$(realpath ../openssl) --disable-shared  --enable-static
make -j $(nproc)
./src/curl --sslv3 https://google.com


问:
How to make iPhone to communicate to server by using socket?
I know how to make a Java socket in server.
But how to make a socket in iPhone to communicate to server by using socket?</p>

答:
Some resources related to communications on the iPhone:

NSURLConnection

Stream Programming Guide

CFNetwork specifically CFStreamCreatePairWithSocketToHost()

ContentLicense: CC BY-SA 3.0


问:
Pandas groupby scatter plot in a single plot
This is a followup question on this solution. There is automatic assignment of different colors when kind=line but for scatter plot that's not the case.

```<code>import pandas as pd
import matplotlib.pylab as plt
import numpy as np

# random df
df = pd.DataFrame(np.random.randint(0,10,size=(25, 3)), columns=['label','x','y'])

# plot groupby results on the same canvas
fig, ax = plt.subplots(figsize=(8,6))
df.groupby('label').plot(kind='scatter', x = "x", y = "y", ax=ax)
</code>```

There is a connected issue here. Is there any simple workaround for this?

Update:

When I try the solution recommended by @ImportanceOfBeingErnest for a label column with strings, its not working!

```<code>df = pd.DataFrame(np.random.randint(0,10,size=(5, 2)), columns=['x','y'])
df['label'] = ['yes','no','yes','yes','no']
fig, ax = plt.subplots(figsize=(8,6))
ax.scatter(x='x', y='y', c='label', data=df)
</code>```

It throws following error,

ValueError: Invalid RGBA argument: 'yes'

During handling of the above exception, another exception occurred:

答:
You can loop over groupby and create a scatter per group. That is efficient for less than ~10 categories.

```<code>import pandas as pd
import matplotlib.pylab as plt
import numpy as np

# random df
df = pd.DataFrame(np.random.randint(0,10,size=(5, 2)), columns=['x','y'])
df['label'] = ['yes','no','yes','yes','no']

# plot groupby results on the same canvas
fig, ax = plt.subplots(figsize=(8,6))

for n, grp in df.groupby('label'):
    ax.scatter(x = "x", y = "y", data=grp, label=n)
ax.legend(title="Label")

plt.show()
</code>```

Alternatively you can create a single scatter like

```<code>import pandas as pd
import matplotlib.pylab as plt
import numpy as np

# random df
df = pd.DataFrame(np.random.randint(0,10,size=(5, 2)), columns=['x','y'])
df['label'] = ['yes','no','yes','yes','no']

# plot groupby results on the same canvas
fig, ax = plt.subplots(figsize=(8,6))

u, df["label_num"] = np.unique(df["label"], return_inverse=True)

sc = ax.scatter(x = "x", y = "y", c = "label_num", data=df)
ax.legend(sc.legend_elements()[0], u, title="Label")

plt.show()
</code>```

Body:
This is a followup question on this solution. There is automatic assignment of different colors when kind=line but for scatter plot that's not the case.

import pandas as pd
import matplotlib.pylab as plt
import numpy as np

# random df
df = pd.DataFrame(np.random.randint(0,10,size=(25, 3)), columns=['label','x','y'])

# plot groupby results on the same canvas
fig, ax = plt.subplots(figsize=(8,6))
df.groupby('label').plot(kind='scatter', x = "x", y = "y", ax=ax)

There is a connected issue here. Is there any simple workaround for this?

Update:

When I try the solution recommended by @ImportanceOfBeingErnest for a label column with strings, its not working!

df = pd.DataFrame(np.random.randint(0,10,size=(5, 2)), columns=['x','y'])
df['label'] = ['yes','no','yes','yes','no']
fig, ax = plt.subplots(figsize=(8,6))
ax.scatter(x='x', y='y', c='label', data=df)

It throws following error,

ValueError: Invalid RGBA argument: 'yes'

During handling of the above exception, another exception occurred:

Body:
You can loop over groupby and create a scatter per group. That is efficient for less than ~10 categories.

import pandas as pd
import matplotlib.pylab as plt
import numpy as np

# random df
df = pd.DataFrame(np.random.randint(0,10,size=(5, 2)), columns=['x','y'])
df['label'] = ['yes','no','yes','yes','no']

# plot groupby results on the same canvas
fig, ax = plt.subplots(figsize=(8,6))

for n, grp in df.groupby('label'):
    ax.scatter(x = "x", y = "y", data=grp, label=n)
ax.legend(title="Label")

plt.show()

Alternatively you can create a single scatter like

import pandas as pd
import matplotlib.pylab as plt
import numpy as np

# random df
df = pd.DataFrame(np.random.randint(0,10,size=(5, 2)), columns=['x','y'])
df['label'] = ['yes','no','yes','yes','no']

# plot groupby results on the same canvas
fig, ax = plt.subplots(figsize=(8,6))

u, df["label_num"] = np.unique(df["label"], return_inverse=True)

sc = ax.scatter(x = "x", y = "y", c = "label_num", data=df)
ax.legend(sc.legend_elements()[0], u, title="Label")

plt.show()


问:
My HTML website does not scroll in the mobile
This website does not scroll on mobile device. I have been searching for some solutions but none of them work.

The website scrolls and bit, then stops, then you can, is not working properly.

答:
The scroll happens only on the right top and right bottom check whether it is due to the hotjar.js or try adding this to the
-webkit-overflow-scrolling: touch; in css for html element


问:
How can I connect to database from Arduino?
I want to transfer the data from the database to Arduino. For this, I am using MYSQL_Connector library in Arduino. But I'm getting error like this: "Connection Failed". I cannot connect to database. Also, I'm using XAMPP server.

I checked MYSQL server's IP address, port and username-password.

```<code>#include <SPI.h>
#include <Ethernet.h>
#include <MySQL_Connection.h>
#include <MySQL_Cursor.h>

byte mac_addr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

IPAddress server_addr(x,x,x,x);  // the IP address to that of the system on which my MySQL server is set up
char user[] = "user";              // MySQL user login username
char password[] = "1234";        // MySQL user login password

// Sample query
char query[] = "SELECT id FROM world.city";

EthernetClient client;
MySQL_Connection conn((Client *)&client);

void setup() {
  Serial.begin(9600);
  while (!Serial); // wait for serial port to connect
  Ethernet.begin(mac_addr);
  Serial.println("Connecting...");
  if (conn.connect(server_addr, 8080, user, password)) {
    delay(1000);
  }
  else
    Serial.println("Connection failed.");
}
</code>```

答:
I have solved the problem. Problem is that you will also need to give the user access to whatever database that you want to access. Firstly, you will need to create user. You can use the link below.

https://st2.ning.com/topology/rest/1.0/file/get/2053761171?profile=original

```<code>#include <Ethernet.h>
#include <MySQL_Connection.h>
#include <MySQL_Cursor.h>

byte mac_addr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

IPAddress server_addr(x,x,x,x);  //the IP address to that of the system on which my MySQL server is set up
char user[] = "bob";              // MySQL user login username
char password[] = "secret";        // MySQL user login password

// Sample query
char query[] = "SELECT id FROM world.city";

EthernetClient client;
MySQL_Connection conn((Client *)&client);

void setup() {
  Serial.begin(9600);
  while (!Serial); // wait for serial port to connect
  Ethernet.begin(mac_addr);

  //while(!conn.connect(server_addr, 3306, user, password));

  Serial.println("Connecting...");
  if (conn.connect(server_addr, 3306, user, password)) {
    delay(1000);
  }
  else
    Serial.println("Connection failed.");
}
</code>```

Body:
I want to transfer the data from the database to Arduino. For this, I am using MYSQL_Connector library in Arduino. But I'm getting error like this: "Connection Failed". I cannot connect to database. Also, I'm using XAMPP server.

I checked MYSQL server's IP address, port and username-password.

#include <SPI.h>
#include <Ethernet.h>
#include <MySQL_Connection.h>
#include <MySQL_Cursor.h>

byte mac_addr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

IPAddress server_addr(x,x,x,x);  // the IP address to that of the system on which my MySQL server is set up
char user[] = "user";              // MySQL user login username
char password[] = "1234";        // MySQL user login password

// Sample query
char query[] = "SELECT id FROM world.city";

EthernetClient client;
MySQL_Connection conn((Client *)&client);

void setup() {
  Serial.begin(9600);
  while (!Serial); // wait for serial port to connect
  Ethernet.begin(mac_addr);
  Serial.println("Connecting...");
  if (conn.connect(server_addr, 8080, user, password)) {
    delay(1000);
  }
  else
    Serial.println("Connection failed.");
}

Body:
I have solved the problem. Problem is that you will also need to give the user access to whatever database that you want to access. Firstly, you will need to create user. You can use the link below.

https://st2.ning.com/topology/rest/1.0/file/get/2053761171?profile=original

#include <Ethernet.h>
#include <MySQL_Connection.h>
#include <MySQL_Cursor.h>

byte mac_addr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

IPAddress server_addr(x,x,x,x);  //the IP address to that of the system on which my MySQL server is set up
char user[] = "bob";              // MySQL user login username
char password[] = "secret";        // MySQL user login password

// Sample query
char query[] = "SELECT id FROM world.city";

EthernetClient client;
MySQL_Connection conn((Client *)&client);

void setup() {
  Serial.begin(9600);
  while (!Serial); // wait for serial port to connect
  Ethernet.begin(mac_addr);

  //while(!conn.connect(server_addr, 3306, user, password));

  Serial.println("Connecting...");
  if (conn.connect(server_addr, 3306, user, password)) {
    delay(1000);
  }
  else
    Serial.println("Connection failed.");
}


问:
Is it possible to add to IConfiguration after the WebHost has started?
I am using AWS Systems Manager Parameter Store to hold database connection strings which are used to dynamically build a DbContext in my .NET Core Application

I am using the .NET Core AWS configuration provider (from https://aws.amazon.com/blogs/developer/net-core-configuration-provider-for-aws-systems-manager/) which injects my parameters into the IConfiguration at runtime.

At the moment I am having to keep my AWS access key/secret in code so it can be accessed by the ConfigurationBuilder but would like to move this out of the code base and stored it in appsettings or similar.

Here is my method to create the webhost builder called at startup

```<code>public static IWebHostBuilder CreateWebHostBuilder(string[] args)
{
    var webHost = WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>();

    AWSCredentials credentials = new BasicAWSCredentials("xxxx", "xxxx");

    AWSOptions options = new AWSOptions()
    {
        Credentials = credentials,
        Region = Amazon.RegionEndpoint.USEast2
    };

    webHost.ConfigureAppConfiguration(config =>
    {
        config.AddJsonFile("appsettings.json");
        config.AddSystemsManager("/ParameterPath", options, reloadAfter: new System.TimeSpan(0, 1, 0)); // Reload every minute
    });

 return webHost;
}
</code>```

I need to be able to inject the BasicAWSCredentials parameter from somewhere.

答:
You need to access an already built configuration to be able to retrieve the information you seek.

Consider building one to retrieve the needed credentials

```<code>public static IWebHostBuilder CreateWebHostBuilder(string[] args) {
    var webHost = WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>();

    var configuration = new ConfigurationBuilder()
        .AddJsonFile("appsettings.json")
        .Build();

    var access_key = configuration.GetValue<string>("access_key:path_here");
    var secret_key = configuration.GetValue<string>("secret_key:path_here");

    AWSCredentials credentials = new BasicAWSCredentials(access_key, secret_key);

    AWSOptions options = new AWSOptions() {
        Credentials = credentials,
        Region = Amazon.RegionEndpoint.USEast2
    };

    webHost.ConfigureAppConfiguration(config => {
        config.AddJsonFile("appsettings.json");
        config.AddSystemsManager("/ParameterPath", options, reloadAfter: new System.TimeSpan(0, 1, 0)); // Reload every minute
    });

    return webHost;
}
</code>```

I would also suggest reviewing Configuring AWS Credentials from the docs to use the SDK  to find a possible alternative way to storing and retrieving the credentials.

Body:
I am using AWS Systems Manager Parameter Store to hold database connection strings which are used to dynamically build a DbContext in my .NET Core Application

I am using the .NET Core AWS configuration provider (from https://aws.amazon.com/blogs/developer/net-core-configuration-provider-for-aws-systems-manager/) which injects my parameters into the IConfiguration at runtime.

At the moment I am having to keep my AWS access key/secret in code so it can be accessed by the ConfigurationBuilder but would like to move this out of the code base and stored it in appsettings or similar.

Here is my method to create the webhost builder called at startup

public static IWebHostBuilder CreateWebHostBuilder(string[] args)
{
    var webHost = WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>();

    AWSCredentials credentials = new BasicAWSCredentials("xxxx", "xxxx");

    AWSOptions options = new AWSOptions()
    {
        Credentials = credentials,
        Region = Amazon.RegionEndpoint.USEast2
    };

    webHost.ConfigureAppConfiguration(config =>
    {
        config.AddJsonFile("appsettings.json");
        config.AddSystemsManager("/ParameterPath", options, reloadAfter: new System.TimeSpan(0, 1, 0)); // Reload every minute
    });

 return webHost;
}

I need to be able to inject the BasicAWSCredentials parameter from somewhere.

Body:
You need to access an already built configuration to be able to retrieve the information you seek.

Consider building one to retrieve the needed credentials

public static IWebHostBuilder CreateWebHostBuilder(string[] args) {
    var webHost = WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>();

    var configuration = new ConfigurationBuilder()
        .AddJsonFile("appsettings.json")
        .Build();

    var access_key = configuration.GetValue<string>("access_key:path_here");
    var secret_key = configuration.GetValue<string>("secret_key:path_here");

    AWSCredentials credentials = new BasicAWSCredentials(access_key, secret_key);

    AWSOptions options = new AWSOptions() {
        Credentials = credentials,
        Region = Amazon.RegionEndpoint.USEast2
    };

    webHost.ConfigureAppConfiguration(config => {
        config.AddJsonFile("appsettings.json");
        config.AddSystemsManager("/ParameterPath", options, reloadAfter: new System.TimeSpan(0, 1, 0)); // Reload every minute
    });

    return webHost;
}

I would also suggest reviewing Configuring AWS Credentials from the docs to use the SDK  to find a possible alternative way to storing and retrieving the credentials.


问:
Error in dropping a database in MySQL (can't rmdir '.\oro', errno: 41)
I can't delete a database from mysql. The error is like

ERROR 1010 (HY000): Error dropping database (can't rmdir '.\oro', errno: 41)

I tried to drop the database 'oro' using phpmyadmin and it also showing the same error message and alerts

"DROP DATABASE" statements are disabled.

答:
Go to

C:\wampXY\bin\mysql\mysqlx.y.z\data

(XY.. refer versions)

Rename the file you want to delete to anything else.(optional only for special cases)

Now simply delete the renamed file.


问:
How to deal with null values using TO_DATE function?
I want to create DATETIME by parts but in some cases these parts are null.

Example

```<code>SELECT TO_DATE(STARTDATEMONTH||'-01-'||STARTDATEYEAR, 'MM-DD-YYYY' ) AS BEGIN_DATE FROM V_MYCC_CNPHISTORY_03
</code>```

When the STARTDATEMONTH column is null,

get the not a valid month

error

When the STARTDATEYEAR column is null, i get the:

input value not long enough for date format

error

In the cases the values are null, i would like to set a default value. Is that possible or is there some workaround?

I hope to have explained my problem well. Thanks in advance

答:
Can you try the following:

SELECT TO_DATE(coalesce(STARTDATEMONTH,'01') ||'-01-'||
  coalesce(STARTDATEYEAR,'1700'), 'MM-DD-YYYY' ) AS BEGIN_DATE FROM
  V_MYCC_CNPHISTORY_03

Body:
I want to create DATETIME by parts but in some cases these parts are null.

Example

SELECT TO_DATE(STARTDATEMONTH||'-01-'||STARTDATEYEAR, 'MM-DD-YYYY' ) AS BEGIN_DATE FROM V_MYCC_CNPHISTORY_03

When the STARTDATEMONTH column is null,

get the not a valid month

error

When the STARTDATEYEAR column is null, i get the:

input value not long enough for date format

error

In the cases the values are null, i would like to set a default value. Is that possible or is there some workaround?

I hope to have explained my problem well. Thanks in advance


问:
how to restore soft delete with one more column?
I have a table named data and I am using soft delete to delete the record.i have one more field in my data table which is also updated when a record is deleted. but when I restore that soft deleted record, it updates my deleted_at field but doesn't update the other field.
I use this code

```<code>Data::withTrashed()->find($id)->restore();
</code>```

How can I do this?

答:
You could write an observer that hooks into the restored event:

 <?php

namespace App\Observers;

class DataObserver
{
    public function restored($data)
    {
        // Update field here
    }

}
```

<p>And of course register it a <code>boot()</code> method of a service provider:</p>

<pre class="lang-php prettyprint-override"><code>Data::observe(DataObserver::class);
</code>```

Note: Depending on the timing, you may prefer the restoring event instead

Body:
I have a table named data and I am using soft delete to delete the record.i have one more field in my data table which is also updated when a record is deleted. but when I restore that soft deleted record, it updates my deleted_at field but doesn't update the other field.
I use this code

Data::withTrashed()->find($id)->restore();

How can I do this?

Body:
You could write an observer that hooks into the restored event:

 <?php

namespace App\Observers;

class DataObserver
{
    public function restored($data)
    {
        // Update field here
    }

}

And of course register it a boot() method of a service provider:

Data::observe(DataObserver::class);

Note: Depending on the timing, you may prefer the restoring event instead


答:
Use coalesce:

```<code>select TO_DATE(coalesce(STARTDATEMONTH,'01')||'-01-'||coalesce(STARTDATEYEAR, '2019'), 'MM-DD-YYYY' ) AS BEGIN_DATE
from Mytable
</code>```

Coalesce and nvl are similar, but coalesce is both ansi friendly, and terminates when it finds a value. Note, the values must be the same data type, eg:

```<code>coalesce(stringvalue1, stringvalue2)
</code>```

Title: How to deal with null values using TO_DATE function?

Body:
Use coalesce:

select TO_DATE(coalesce(STARTDATEMONTH,'01')||'-01-'||coalesce(STARTDATEYEAR, '2019'), 'MM-DD-YYYY' ) AS BEGIN_DATE
from Mytable

Coalesce and nvl are similar, but coalesce is both ansi friendly, and terminates when it finds a value. Note, the values must be the same data type, eg:

coalesce(stringvalue1, stringvalue2)


答:
Use coalesce():

```<code>SELECT TO_DATE(COALESCE(STARTDATEMONTH, '01') || '-01-' || COALESCE(STARTDATEYEAR, '2000')), 'MM-DD-YYYY' ) AS BEGIN_DATE
FROM V_MYCC_CNPHISTORY_03
</code>```

Body:
Use coalesce():

SELECT TO_DATE(COALESCE(STARTDATEMONTH, '01') || '-01-' || COALESCE(STARTDATEYEAR, '2000')), 'MM-DD-YYYY' ) AS BEGIN_DATE
FROM V_MYCC_CNPHISTORY_03


问:
How to use array filter criteria agaist object in lodash?
How to filter object ageist another object in lodash? but the criteria object is array..

```<code>var form = { type: ['xyz', 'abc'], name: 'pre-1' }

var items = [
 { type: 'xyz', name: 'pre-1' },
 { type: 'abc', name: 'pre-1' },
 { type: 'xyz', name: 'pre-2' },
]

const results = lodash.filter(items, form);
</code>```

The results should be xyz and abc:

```<code>results = [{ type: 'xyz', name: 'pre-1' }, { type: 'abc', name: 'pre-1' }]
</code>```

Is it something I can do using filter method?

答:
```<code>var form = { type: ['xyz', 'abc'], name: 'pre-1' }

var items = [
 { type: 'xyz', name: 'pre-1' },
 { type: 'abc', name: 'pre-1' },
 { type: 'xyz', name: 'pre-2' },
]

var item = _.filter(items, i => {
 return form.type.indexOf(i.type) > -1 && form.name === i.name
});

console.log(item)
</code>```

Body:
How to filter object ageist another object in lodash? but the criteria object is array..

var form = { type: ['xyz', 'abc'], name: 'pre-1' }

var items = [
 { type: 'xyz', name: 'pre-1' },
 { type: 'abc', name: 'pre-1' },
 { type: 'xyz', name: 'pre-2' },
]

const results = lodash.filter(items, form);

The results should be xyz and abc:

results = [{ type: 'xyz', name: 'pre-1' }, { type: 'abc', name: 'pre-1' }]

Is it something I can do using filter method?


问:
Return list of instances from generic method
I need to return a coordinate list of rectangle in generic method. Coordinate is a class 'cart' instance.

I try return it with make-instance

(defclass line ()
  ((start :initarg :start :accessor line-start)
   (end   :initarg :end   :accessor line-end)))

(defmethod print-object ((lin line) stream)
  (format stream "[LINE ~s ~s]"
          (line-start lin) (line-end lin)))

(defclass cart ()
  ((x :initarg :x :reader cart-x)
   (y :initarg :y :reader cart-y)))

(defmethod print-object ((c cart) stream)
  (format stream "[CART x ~d y ~d]"
          (cart-x c) (cart-y c)))

(setq lin (make-instance 'line
             :start (make-instance 'cart :x 4 :y 3)
             :end (make-instance 'cart :x 7 :y 5)))

(defgeneric containing-rect (shape))

(defmethod containing-rect ((l line))
  (let ((x1 (cart-x (line-start l)))
        (y1 (cart-y (line-start l)))
        (x2 (cart-x (line-end l)))
        (y2 (cart-y (line-end l))))
    (cond ((= x1 x2)
           '((make-instance 'cart :x (1- x1) :y y1)
             (make-instance 'cart :x (1+ x1) :y y1)
             (make-instance 'cart :x (1- x2) :y y2)
             (make-instance 'cart :x (1+ x2) :y y2)))
          ((= y1 y2)
           '((make-instance 'cart :x x1 :y (1- y1))
             (make-instance 'cart :x x1 :y (1+ y1))
             (make-instance 'cart :x x2 :y (1- y2))
             (make-instance 'cart :x x2 :y (1+ y2))))
          (t
           (rect '((make-instance 'cart :x x1 :y y1)
                   (make-instance 'cart :x x1 :y y2)
                   (make-instance 'cart :x x2 :y y2)
                   (make-instance 'cart :x x2 :y y1)))))))

(print (containing-rect lin))
```

<p>I suppose <code>make-instance</code> should assign an instance to something</p>

<p>So i get incorrect result</p>

<pre class="lang-lisp prettyprint-override"><code>((MAKE-INSTANCE 'CART :X X1 :Y Y1) (MAKE-INSTANCE 'CART :X X1 :Y Y2)
 (MAKE-INSTANCE 'CART :X X2 :Y Y2) (MAKE-INSTANCE 'CART :X X2 :Y Y1))
</code>```

but I need an output like that

([CART x 4 y 3] [CART x 4 y 3] [CART x 4 y 3] [CART x 4 y 3])
```

答:
If you quote something, it is not evaluated.

This:

```<code>'((make-instance 'cart :x (1- x1) :y y1)
  (make-instance 'cart :x (1+ x1) :y y1)
  (make-instance 'cart :x (1- x2) :y y2)
  (make-instance 'cart :x (1+ x2) :y y2))
</code>```

is a literal list of four literal lists, each of which starts with the symbol MAKE-INSTANCE, then has a list (QUOTE CART), etc.  This is exactly the result you see.

You seem to want to actually evaluate this.  The simplest thing would be to do that and make a list:

```<code>(list (make-instance 'cart :x (1- x1) :y y1)
      (make-instance 'cart :x (1+ x1) :y y1)
      (make-instance 'cart :x (1- x2) :y y2)
      (make-instance 'cart :x (1+ x2) :y y2))
</code>```

This is a fundamentally different thing from quoting something.

Body:
I need to return a coordinate list of rectangle in generic method. Coordinate is a class 'cart' instance.

I try return it with make-instance

(defclass line ()
  ((start :initarg :start :accessor line-start)
   (end   :initarg :end   :accessor line-end)))

(defmethod print-object ((lin line) stream)
  (format stream "[LINE ~s ~s]"
          (line-start lin) (line-end lin)))

(defclass cart ()
  ((x :initarg :x :reader cart-x)
   (y :initarg :y :reader cart-y)))

(defmethod print-object ((c cart) stream)
  (format stream "[CART x ~d y ~d]"
          (cart-x c) (cart-y c)))

(setq lin (make-instance 'line
             :start (make-instance 'cart :x 4 :y 3)
             :end (make-instance 'cart :x 7 :y 5)))

(defgeneric containing-rect (shape))

(defmethod containing-rect ((l line))
  (let ((x1 (cart-x (line-start l)))
        (y1 (cart-y (line-start l)))
        (x2 (cart-x (line-end l)))
        (y2 (cart-y (line-end l))))
    (cond ((= x1 x2)
           '((make-instance 'cart :x (1- x1) :y y1)
             (make-instance 'cart :x (1+ x1) :y y1)
             (make-instance 'cart :x (1- x2) :y y2)
             (make-instance 'cart :x (1+ x2) :y y2)))
          ((= y1 y2)
           '((make-instance 'cart :x x1 :y (1- y1))
             (make-instance 'cart :x x1 :y (1+ y1))
             (make-instance 'cart :x x2 :y (1- y2))
             (make-instance 'cart :x x2 :y (1+ y2))))
          (t
           (rect '((make-instance 'cart :x x1 :y y1)
                   (make-instance 'cart :x x1 :y y2)
                   (make-instance 'cart :x x2 :y y2)
                   (make-instance 'cart :x x2 :y y1)))))))

(print (containing-rect lin))

I suppose make-instance should assign an instance to something

So i get incorrect result

((MAKE-INSTANCE 'CART :X X1 :Y Y1) (MAKE-INSTANCE 'CART :X X1 :Y Y2)
 (MAKE-INSTANCE 'CART :X X2 :Y Y2) (MAKE-INSTANCE 'CART :X X2 :Y Y1))

but I need an output like that

([CART x 4 y 3] [CART x 4 y 3] [CART x 4 y 3] [CART x 4 y 3])

Body:
If you quote something, it is not evaluated.

This:

'((make-instance 'cart :x (1- x1) :y y1)
  (make-instance 'cart :x (1+ x1) :y y1)
  (make-instance 'cart :x (1- x2) :y y2)
  (make-instance 'cart :x (1+ x2) :y y2))

is a literal list of four literal lists, each of which starts with the symbol MAKE-INSTANCE, then has a list (QUOTE CART), etc.  This is exactly the result you see.

You seem to want to actually evaluate this.  The simplest thing would be to do that and make a list:

(list (make-instance 'cart :x (1- x1) :y y1)
      (make-instance 'cart :x (1+ x1) :y y1)
      (make-instance 'cart :x (1- x2) :y y2)
      (make-instance 'cart :x (1+ x2) :y y2))

This is a fundamentally different thing from quoting something.


问:
In Java, how to populate available tags based on cursor location in XML using DTD?
I am using XOM (or JDOM) to construct an XML editor. I am trying to allow user to avoid typing in XML code, but select available tags from a side-pane to insert tags/attributes into the XML code. The side pane will likely be generated from a set of DTD (or Schema) files.

Is there a module that can populate available tags/attributes based on DTD and currently selected node location?

Thanks,

Jason

答:
You can use Apache XMLSchema (e.g.) to wander around in a schema.

You can convert a DTD to an XML schema using trang.

To see more about how to use xml schema, I recommend reading the unit tests.

Consider for example this one. Note the call to schemaCol.getElementByQName(elementQName) to find a particular element.

To visit all the elements, you'd start with org.apache.ws.commons.schema.XmlSchema.getElements() and iterate the map.

There are much meatier examples inside of Apache CXF.


问:
Mail Merged Documents Created By Excel Macro Not Being Released By Excel?
I have a userform with a series of toggle buttons, each one representing a different report option, in my userform. When the user selects one (or more) reports by pressing that report's associated button that report query is put into a cue for which the code will loop through to process each.
Within the loop, a Word mail merge is executed for that particular report. The mail merge is executed, the document created, and subsequently saved. Those newly created Word documents remain open. The preference is for the user to close those word documents by clicking the previously depressed toggle button corresponding to that particular report in the userform. This appears to be working OK.

Now the user has the ability to access these documents once created (and before being closed) and edit and print them. They print fine, but they are unable to save any changes. The user can click the save icon in the menu of the open word document until their mouse batteries go dead and nothing saves. However, if you go back to Excel, click on the worksheet, and then go back to the Word document, you can save it. (almost like doing so broke a tether between the two docs)

If the user accesses these Word documents from the location they were saved (ie from the directory) from a closed state, they open, and can be edited, but again, cannot be saved. That is as long as Excel is open to the application that created the docs. EDIT: This is not the case. Even with EXCEL closed, these previosuly created mail merged documents, although editable editable. cannot be resaved due to file permission errors.

What I have discovered is, if my Excel application is closed, these files no longer exhibit the difficulties saving due to file permission errors. It would appear that once Excel has initiated and generated these reports, that it has some "lock" on them. These documents, as long as the Excel application used to generate them is open, they appear not to be fully released from the Excel generation code.

```<code>Sub merge2(ByVal i As Long, ByVal rpt_od As String, objWord As Object, ByVal dest As Long)

    Dim oDoc As Object, oDoc2 As Object
    Dim StrSQL As String, fName As String, StrSrc As String, strFilename As String, myPath As String
    Dim qfile As String, st_srchfn As String, wb_qfile2 As Workbook, itype As String, isubresp As String
    'Dim wb_qfile2 As Workbook
    Dim HdFt As Variant
    Dim wdSendToNewDocument

    Const wdSendtToNewDocument = 0
    Const wdSendToPrinter = 1
    Const wdFormLetters = 0
    Const wdDirectory = 3
    Const wdMergeSubTypeAccess = 1
    Const wdOpenFormatAuto = 0

    work_fn = ws_vh.Range("N2")
    Set wb_nwb = Workbooks(work_fn)

    'create workorders folder
    myPath = "u:\fff\ffff\ffffffffffff\fffff\fffff\WORKORDERS\" & format(ws_vh.Range("B17"), "ddd dd-mmm-yy")
    If Dir(myPath, vbDirectory) = "" Then 'if not already created ...
        MkDir myPath
    End If

    'close data file
    st_srchfn = "u:\u:\fff\ffff\ffffffffffff\fffff\fffff\DATA\" & ws_vh.Range("N2")
    If wb_nwb Is Nothing Then
        MsgBox wb_nwb & " is NOT open."
    Else
        wb_nwb.Close True 'saves data workbook after TYPE was updated for GS
        With ws_base
            .Range("B24:D24").Value = ws_vh.Range("A57:C57").Value
        End With
    End If

    itype = Right(ws_th.Range("A" & i), 2)
    isubresp = Left(ws_th.Range("A" & i), 3)

    If itype = "DR" Then
        fName = "u:\fff\ffff\ffffffffffff\fffff\fffff\REPORTS\NG\DR15NG.docx"
    ElseIf itype = "DT" Then
        fName = "u:\fff\ffff\ffffffffffff\fffff\fffff\REPORTS\NG\DT15NG.docx"
    ElseIf itype = "FR" Then
        fName = "u:\fff\ffff\ffffffffffff\fffff\fffff\REPORTS\NG\FR15NG.docx"
    ElseIf itype = "FT" Then
        fName = "u:\fff\ffff\ffffffffffff\fffff\fffff\REPORTS\NG\FT15NG.docx"
    ElseIf itype = "CR" Then
        fName = "u:\fff\ffff\ffffffffffff\fffff\fffff\REPORTS\NG\CR15NG.docx"
    ElseIf itype = "CT" Then
        fName = "u:\fff\ffff\ffffffffffff\fffff\fffff\REPORTS\NG\CT15NG.docx"
    ElseIf itype = "GS" Then
        If isubresp = "HPE" Or isubresp = "HPL" Then
            fName = "u:\fff\ffff\ffffffffffff\fffff\fffff\REPORTS\NG\GS15NG_GSH.docx" 'Passive : Hillside
        Else
            fName = "u:\fff\ffff\ffffffffffff\fffff\fffff\REPORTS\NG\GS15NG_GS.docx" 'Passive : Wloo Park
        End If
    Else
        fName = "u:\fff\ffff\ffffffffffff\fffff\fffff\REPORTS\NG\GS15NG_GM.docx"
    End If

    StrSrc = "u:\fff\ffff\ffffffffffff\fffff\fffff\DATA\" & ws_vh.Range("N2")

    StrSQL = "SELECT * FROM [DATA$] WHERE [TYPE]='" & itype & "' AND [SIG_CREW]='" & isubresp & "' " & _
        "ORDER BY [STARTS] ASC, [COMPLEX] ASC, [UNIT] ASC"

    Set objWord = CreateObject("Word.Application")
    With objWord
        .DisplayAlerts = False
        .Visible = True
        Set oDoc = .Documents.Open(Filename:=fName, ConfirmConversions:=False, _
            ReadOnly:=True, AddToRecentFiles:=False, Visible:=True)
        With oDoc
            With .MailMerge
                .MainDocumentType = wdFormLetters
                .Destination = wdSendToNewDocument
                .SuppressBlankLines = True
                .OpenDataSource Name:=StrSrc, AddToRecentFiles:=False, LinkToSource:=False, ConfirmConversions:=False, _
                    ReadOnly:=True, format:=wdOpenFormatAuto, Connection:="Provider=Microsoft.ACE.OLEDB.12.0;" & _
                    "User ID=Admin;Data Source=" & StrSrc & ";Mode=Read;Extended Properties=""HDR=YES;IMEX=1;"";", _
                    SQLStatement:=StrSQL, SQLStatement1:="", SubType:=wdMergeSubTypeAccess
                .Execute Pause:=False
            End With
            .Close False
        End With
        .DisplayAlerts = True

        'page break routine only for sports reports
        If (Left(itype, 1) <> "G") And (itype <> "DT") Then   'exclude GS reports
            With .activedocument
                If .Sections.count > 1 Then
                    For Each HdFt In .Sections(.Sections.count).Headers
                        If HdFt.Exists Then
                            HdFt.Range.FormattedText = .Sections(1).Headers(HdFt.index).Range.FormattedText
                            HdFt.Range.Characters.Last.Delete
                        End If
                    Next
                    For Each HdFt In .Sections(.Sections.count).Footers
                        If HdFt.Exists Then
                            HdFt.Range.FormattedText = .Sections(1).Footers(HdFt.index).Range.FormattedText
                            HdFt.Range.Characters.Last.Delete
                        End If
                    Next
                End If
                Do While .Sections.count > 1
                    .Sections(1).Range.Characters.Last.Delete
                    DoEvents
                Loop
                .Range.Characters.Last.Delete
            End With
        End If

    End With

    Set oDoc2 = objWord.activedocument

    'save newly created document
    With oDoc2
        myPath = "u:\fff\ffff\ffffffffffff\fffff\fffff\WORKORDERS\" & format(ws_vh.Range("B17"), "ddd dd-mmm-yy")
        .SaveAs myPath & "\" & rpt_od & ".docx"
        If dest = 2 Then
            .PrintOut
        End If
        '.Close
    End With

    Set oDoc = Nothing: Set oDoc2 = Nothing ': Set objWord = Nothing

End Sub
</code>```

答: The problem is that you're creating a new Word session to generate the documents, but you never close them or exit the new Word session, leaving it orphaned in the background with the document still open. </p>

Body:
I have a userform with a series of toggle buttons, each one representing a different report option, in my userform. When the user selects one (or more) reports by pressing that report's associated button that report query is put into a cue for which the code will loop through to process each.
Within the loop, a Word mail merge is executed for that particular report. The mail merge is executed, the document created, and subsequently saved. Those newly created Word documents remain open. The preference is for the user to close those word documents by clicking the previously depressed toggle button corresponding to that particular report in the userform. This appears to be working OK.

Now the user has the ability to access these documents once created (and before being closed) and edit and print them. They print fine, but they are unable to save any changes. The user can click the save icon in the menu of the open word document until their mouse batteries go dead and nothing saves. However, if you go back to Excel, click on the worksheet, and then go back to the Word document, you can save it. (almost like doing so broke a tether between the two docs)

If the user accesses these Word documents from the location they were saved (ie from the directory) from a closed state, they open, and can be edited, but again, cannot be saved. That is as long as Excel is open to the application that created the docs. EDIT: This is not the case. Even with EXCEL closed, these previosuly created mail merged documents, although editable editable. cannot be resaved due to file permission errors.

What I have discovered is, if my Excel application is closed, these files no longer exhibit the difficulties saving due to file permission errors. It would appear that once Excel has initiated and generated these reports, that it has some "lock" on them. These documents, as long as the Excel application used to generate them is open, they appear not to be fully released from the Excel generation code.

Sub merge2(ByVal i As Long, ByVal rpt_od As String, objWord As Object, ByVal dest As Long)

    Dim oDoc As Object, oDoc2 As Object
    Dim StrSQL As String, fName As String, StrSrc As String, strFilename As String, myPath As String
    Dim qfile As String, st_srchfn As String, wb_qfile2 As Workbook, itype As String, isubresp As String
    'Dim wb_qfile2 As Workbook
    Dim HdFt As Variant
    Dim wdSendToNewDocument

    Const wdSendtToNewDocument = 0
    Const wdSendToPrinter = 1
    Const wdFormLetters = 0
    Const wdDirectory = 3
    Const wdMergeSubTypeAccess = 1
    Const wdOpenFormatAuto = 0

    work_fn = ws_vh.Range("N2")
    Set wb_nwb = Workbooks(work_fn)

    'create workorders folder
    myPath = "u:\fff\ffff\ffffffffffff\fffff\fffff\WORKORDERS\" & format(ws_vh.Range("B17"), "ddd dd-mmm-yy")
    If Dir(myPath, vbDirectory) = "" Then 'if not already created ...
        MkDir myPath
    End If

    'close data file
    st_srchfn = "u:\u:\fff\ffff\ffffffffffff\fffff\fffff\DATA\" & ws_vh.Range("N2")
    If wb_nwb Is Nothing Then
        MsgBox wb_nwb & " is NOT open."
    Else
        wb_nwb.Close True 'saves data workbook after TYPE was updated for GS
        With ws_base
            .Range("B24:D24").Value = ws_vh.Range("A57:C57").Value
        End With
    End If

    itype = Right(ws_th.Range("A" & i), 2)
    isubresp = Left(ws_th.Range("A" & i), 3)

    If itype = "DR" Then
        fName = "u:\fff\ffff\ffffffffffff\fffff\fffff\REPORTS\NG\DR15NG.docx"
    ElseIf itype = "DT" Then
        fName = "u:\fff\ffff\ffffffffffff\fffff\fffff\REPORTS\NG\DT15NG.docx"
    ElseIf itype = "FR" Then
        fName = "u:\fff\ffff\ffffffffffff\fffff\fffff\REPORTS\NG\FR15NG.docx"
    ElseIf itype = "FT" Then
        fName = "u:\fff\ffff\ffffffffffff\fffff\fffff\REPORTS\NG\FT15NG.docx"
    ElseIf itype = "CR" Then
        fName = "u:\fff\ffff\ffffffffffff\fffff\fffff\REPORTS\NG\CR15NG.docx"
    ElseIf itype = "CT" Then
        fName = "u:\fff\ffff\ffffffffffff\fffff\fffff\REPORTS\NG\CT15NG.docx"
    ElseIf itype = "GS" Then
        If isubresp = "HPE" Or isubresp = "HPL" Then
            fName = "u:\fff\ffff\ffffffffffff\fffff\fffff\REPORTS\NG\GS15NG_GSH.docx" 'Passive : Hillside
        Else
            fName = "u:\fff\ffff\ffffffffffff\fffff\fffff\REPORTS\NG\GS15NG_GS.docx" 'Passive : Wloo Park
        End If
    Else
        fName = "u:\fff\ffff\ffffffffffff\fffff\fffff\REPORTS\NG\GS15NG_GM.docx"
    End If

    StrSrc = "u:\fff\ffff\ffffffffffff\fffff\fffff\DATA\" & ws_vh.Range("N2")

    StrSQL = "SELECT * FROM [DATA$] WHERE [TYPE]='" & itype & "' AND [SIG_CREW]='" & isubresp & "' " & _
        "ORDER BY [STARTS] ASC, [COMPLEX] ASC, [UNIT] ASC"

    Set objWord = CreateObject("Word.Application")
    With objWord
        .DisplayAlerts = False
        .Visible = True
        Set oDoc = .Documents.Open(Filename:=fName, ConfirmConversions:=False, _
            ReadOnly:=True, AddToRecentFiles:=False, Visible:=True)
        With oDoc
            With .MailMerge
                .MainDocumentType = wdFormLetters
                .Destination = wdSendToNewDocument
                .SuppressBlankLines = True
                .OpenDataSource Name:=StrSrc, AddToRecentFiles:=False, LinkToSource:=False, ConfirmConversions:=False, _
                    ReadOnly:=True, format:=wdOpenFormatAuto, Connection:="Provider=Microsoft.ACE.OLEDB.12.0;" & _
                    "User ID=Admin;Data Source=" & StrSrc & ";Mode=Read;Extended Properties=""HDR=YES;IMEX=1;"";", _
                    SQLStatement:=StrSQL, SQLStatement1:="", SubType:=wdMergeSubTypeAccess
                .Execute Pause:=False
            End With
            .Close False
        End With
        .DisplayAlerts = True

        'page break routine only for sports reports
        If (Left(itype, 1) <> "G") And (itype <> "DT") Then   'exclude GS reports
            With .activedocument
                If .Sections.count > 1 Then
                    For Each HdFt In .Sections(.Sections.count).Headers
                        If HdFt.Exists Then
                            HdFt.Range.FormattedText = .Sections(1).Headers(HdFt.index).Range.FormattedText
                            HdFt.Range.Characters.Last.Delete
                        End If
                    Next
                    For Each HdFt In .Sections(.Sections.count).Footers
                        If HdFt.Exists Then
                            HdFt.Range.FormattedText = .Sections(1).Footers(HdFt.index).Range.FormattedText
                            HdFt.Range.Characters.Last.Delete
                        End If
                    Next
                End If
                Do While .Sections.count > 1
                    .Sections(1).Range.Characters.Last.Delete
                    DoEvents
                Loop
                .Range.Characters.Last.Delete
            End With
        End If

    End With

    Set oDoc2 = objWord.activedocument

    'save newly created document
    With oDoc2
        myPath = "u:\fff\ffff\ffffffffffff\fffff\fffff\WORKORDERS\" & format(ws_vh.Range("B17"), "ddd dd-mmm-yy")
        .SaveAs myPath & "\" & rpt_od & ".docx"
        If dest = 2 Then
            .PrintOut
        End If
        '.Close
    End With

    Set oDoc = Nothing: Set oDoc2 = Nothing ': Set objWord = Nothing

End Sub


问:
go to another activity on Menu Item selection in kotlin
l added Options menu item Selected in toolbar of my app . l want add action on click on item even go to another activity . l Intent but does not work

```<code>override fun onOptionsItemSelected(item: MenuItem): {

            when (item.itemId) {
                R.id.flightarrbeforbgw ->
                    Intent intent = new Intent(this, FlightsArrivelBeforBGW.class);
                this.startActivity(intent)

                else ->
                    return null
            }
        }
</code>```

答:
Your intent is not formatted correctly. This is how it's supposed to be:

```<code>Intent (this, YourActivity::class.java)
</code>```

So your code should look like this:

```<code>when (item.itemId) {
    R.id.flightarrbeforbgw ->{
        this.startActivity(Intent(this,FlightsArrivelBeforBGW::class.java))
        return true
    }
    else -> super.onOptionsItemSelected(item)
}
</code>```

Body:
l added Options menu item Selected in toolbar of my app . l want add action on click on item even go to another activity . l Intent but does not work

override fun onOptionsItemSelected(item: MenuItem): {

            when (item.itemId) {
                R.id.flightarrbeforbgw ->
                    Intent intent = new Intent(this, FlightsArrivelBeforBGW.class);
                this.startActivity(intent)

                else ->
                    return null
            }
        }

Body:
Your intent is not formatted correctly. This is how it's supposed to be:

Intent (this, YourActivity::class.java)

So your code should look like this:

when (item.itemId) {
    R.id.flightarrbeforbgw ->{
        this.startActivity(Intent(this,FlightsArrivelBeforBGW::class.java))
        return true
    }
    else -> super.onOptionsItemSelected(item)
}


答:
You can try this-</p>

```<code>SELECT TO_DATE(NVL(STARTDATEMONTH,'01')||'-01-'||NVL(STARTDATEYEAR,'2019'), 'MM-DD-YYYY' ) AS BEGIN_DATE
FROM V_MYCC_CNPHISTORY_03
</code>```

Body:
You can try this-

SELECT TO_DATE(NVL(STARTDATEMONTH,'01')||'-01-'||NVL(STARTDATEYEAR,'2019'), 'MM-DD-YYYY' ) AS BEGIN_DATE
FROM V_MYCC_CNPHISTORY_03


问:
How can I invalidate flow layout with animation like in ios?
I'm making an app in Xcode for Mojave OSX.

I want to make a resize of a collectionview and items position of that.
Currently I call to invalidateLayout() method, but it recalculate and set sizes and positions without animations.

In the GIF you could see what is the current behavior, I need that the last item go to second row, in an animated way.

For this i try to override this methods of NSCollectionViewFlowLayout

```<code>  open override func prepare(forAnimatedBoundsChange oldBounds: NSRect){

    }

    open override func finalizeAnimatedBoundsChange() {

    }
</code>```

But these never get called, and I don't know what code I need to animate this transition.

答:
(Moved from question to an answer.)

You could override the viewDidLayout of your viewController (or assign an observer to the frame view) and execute this:

```<code> collectionView.animator().performBatchUpdates(nil)
</code>```

This reloads your collectionviewLayout with an animation.

Body:
I'm making an app in Xcode for Mojave OSX.

I want to make a resize of a collectionview and items position of that.
Currently I call to invalidateLayout() method, but it recalculate and set sizes and positions without animations.

In the GIF you could see what is the current behavior, I need that the last item go to second row, in an animated way.

For this i try to override this methods of NSCollectionViewFlowLayout

  open override func prepare(forAnimatedBoundsChange oldBounds: NSRect){

    }

    open override func finalizeAnimatedBoundsChange() {

    }

But these never get called, and I don't know what code I need to animate this transition.

Body:
(Moved from question to an answer.)

You could override the viewDidLayout of your viewController (or assign an observer to the frame view) and execute this:

 collectionView.animator().performBatchUpdates(nil)

This reloads your collectionviewLayout with an animation.


问:
How to loop through a list where data points are dependent on each other?
I have a list, a = [5, 4, 9, 3, 6, 6, 8, 2], and I essentially want to sum the first three numbers, and that sum will be the first value in the new list. The next value in the new list will be the sum of 4, 9, and 3...etc. etc. How to loop this in Python?</p>

答:
One liner:

```<code>list(map(sum, zip(a, a[1:], a[2:])))
</code>```

Output:

```<code>[18, 16, 18, 15, 20, 16]
</code>```

So you are creating the required sublists of the numbers you want to add up and then you sum each sublist using the high-order function map.

Body:
One liner:

list(map(sum, zip(a, a[1:], a[2:])))

Output:

[18, 16, 18, 15, 20, 16]

So you are creating the required sublists of the numbers you want to add up and then you sum each sublist using the high-order function map.


问:
Precompilation and startup times on ASP.Net
I am developping a (relatively small) website in ASP.Net 2.0. I am also using nAnt to perform some easy tweaking on my project before delivering executables. In its current state, the website is "precompiled" using

aspnet_compiler.exe -nologo -v ${Appname} -u ${target}

I have noticed that after the IIS pool is restarted (after a idle shutdown or a recycle), the application takes up to 20 seconds before it is back online (and Application_start is reached).

I don't have the same issue when I am debugging directly within Visual Studio (it takes 2 seconds to start) so I am wondering if the aspnet_compiler is really such a good idea.

I couldn't find much on MSDN. How do you compile your websites for production?

答: If your website is compiled as updatable, you'll see a bunch of .ASPX files in your virtual directory.  These must be compiled on startup.  That's so you can come in and alter the web UI itself.  This is default for both websites and web applications.</p>

OwnerDisplayName: lucasbfr

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: ScottCher


问:
Storing word documents
I'm working on job site (using asp.net 3.5) in which a user can upload one or more resumes.
Database is sql server 2005.
Whats the recommendation regarding storage of these documents?
Shall i store it as a blob in the database or just store the path in database and keep the document in the physical folder?
Can someone please mention the pros and cons of each wrt performance and scalability?

Thanks!

答:
I recommend storing it in the database to keep things together.

One additional point to consider when storing in the the database is that a SQL database can be comprised of multiple files. What I would advise is to create A second file (.ndf) on this database that houses the tables that contain BLOB data.

This provides some key benefits in that it can (1) be run on a separate disk array if increased demand ever calls for it. (2) can be backed up and restored separately. (3) will not bloat your main OLTP database file.

OwnerDisplayName: Patrick

Title: Storing word documents

OwnerDisplayName: James


问:
Creating div overlays over any video (similar to Google ads in YouTube)
I would like to create a div overlay over videos in a html page. The videos could be embedded YouTube videos, or from any other source. Any ideas on how to do this? I have done a similar task of overlaying divs on images but never did for videos. Would greatly appreciate if anyone could point me in the right direction.</p>

答:
Just make sure wmode="Opaque" or wmode="Transparent" is set on the video embed and the video will recognize its parents' z-index css property.

wmode - Possible values: window,
  opaque, transparent. Sets the Window
  Mode property of the Flash movie for
  transparency, layering, and
  positioning in the browser.


问:
How can I get a List of subelements from a subdictionary?
I want to get a list of subelements from a subdictionary

I have this:

```<code>Dictionary<string, Dictionary<string, List<InstanceLog>>> dic;
</code>```

And I want something like this (Fetch all InstanceLog-Lists from the subdictinary in one big list.):

```<code>List<InstanceLog> logList = GetValues(dic);
</code>```

I have tried something like this but it don't work:

```<code>List<InstanceLog> logList = GetFetchtedList()
  .Select(x => x.Value.ToList())
  .Cast<InstanceLog>()
  .ToList()
</code>```

Thanks a lot for the help!

答:
SelectMany is the keyword. What it does is group as one list if the select is an collection of some sort. If you like it return like you would do Union.

```<code>Dictionary<string, Dictionary<string, List<InstanceLog>>> dic;

var instanceLogs = dic.SelectMany(d => d.Value.Select(subd => subd.Value)).ToList();
</code>```

The SelectMany on dic tell linq :

"Hey i will have a collection result within those parenthesis so group them as 1 collection"

The Select on the sub dictionary just return the collection 1 for the SelectMany to grab and process.

This iterate the collection only once and does not use any extra operations that is not needed (linq wise)

Body:
I want to get a list of subelements from a subdictionary

I have this:

Dictionary<string, Dictionary<string, List<InstanceLog>>> dic;

And I want something like this (Fetch all InstanceLog-Lists from the subdictinary in one big list.):

List<InstanceLog> logList = GetValues(dic);

I have tried something like this but it don't work:

List<InstanceLog> logList = GetFetchtedList()
  .Select(x => x.Value.ToList())
  .Cast<InstanceLog>()
  .ToList()

Thanks a lot for the help!

Body:
SelectMany is the keyword. What it does is group as one list if the select is an collection of some sort. If you like it return like you would do Union.

Dictionary<string, Dictionary<string, List<InstanceLog>>> dic;

var instanceLogs = dic.SelectMany(d => d.Value.Select(subd => subd.Value)).ToList();

The SelectMany on dic tell linq :

"Hey i will have a collection result within those parenthesis so group them as 1 collection"

The Select on the sub dictionary just return the collection 1 for the SelectMany to grab and process.

This iterate the collection only once and does not use any extra operations that is not needed (linq wise)


答:
If I understood what you want:</p>

```<code>b = [sum(a[i : i+3]) for i in range(0, len(a)-2)]
</code>```

Title: How to loop through a list where data points are dependent on each other?

Body: I have a list, a = [5, 4, 9, 3, 6, 6, 8, 2], and I essentially want to sum the first three numbers, and that sum will be the first value in the new list. The next value in the new list will be the sum of 4, 9, and 3...etc. etc. How to loop this in Python?

Body:
If I understood what you want:

b = [sum(a[i : i+3]) for i in range(0, len(a)-2)]


问:
How to know when a JTable has been sorted
I need to know when a JTable has been sorted, after the new row order is shown on the table.

I tried with:

```<code> getModel().addTableModelListener(new TableModelListener() {
        @Override
        public void tableChanged(TableModelEvent e) {
            System.out.println("change");
        }
    });
</code>```

But the method tableChanged(TableModelEvent e) seemed not to be called after sorting.

答:
Sorting and related events in a JTable are handled by a RowSorter. They can be set using JTable.setRowSorter.

A RowSorter allows you to listen to sorting events, by subscribing a listener using RowSorter.addRowSorterListener.

This listener is of interface RowSorterListener, the listener method receives an instance of RowSorterEvent. When the Type of this event is Sorted, this indicates that:

[...] the contents have been newly sorted or transformed in some way.

For your understanding: a traditional JTable (i.e. an implementation that follows the specification) will not sort the model. Instead, an array of indexes to the model is sorted instead. This is typical for UI elements that following the Model/View paradigm.

Body:
I need to know when a JTable has been sorted, after the new row order is shown on the table.

I tried with:

 getModel().addTableModelListener(new TableModelListener() {
        @Override
        public void tableChanged(TableModelEvent e) {
            System.out.println("change");
        }
    });

But the method tableChanged(TableModelEvent e) seemed not to be called after sorting.


问:
UITableView does not populate with data
I am trying to make a simple UITableView with custom cells (including two labels and one image view) but I can't get the table to be populated with data.

I have created the following struct for my data:

```<code>struct feed {
  var title: String
  var subtitle: String
  var image: String
}
</code>```

and here I have defined some sample data:

```<code>var myfeed = [feed(title: "Test Feed", subtitle: "Welcome to feedFeed", image: "https://www.demo.com/imnage1.png"), feed(title: "Number 2", subtitle: "Demo?", image: "https://www.demo.com/imnage2.png")]
</code>```

I have created an UITableView in my Storyboard, have configured the Custom cell and am using the Cell identifier "LabelCell".
I have created a separate cocoaTouchclass file for the UITableViewCell class:

```<code>import UIKit

class ehappyTableViewCell: UITableViewCell {

    @IBOutlet weak var headlineTitleLabel: UILabel!
    @IBOutlet weak var headlineTextLabel: UILabel!
    @IBOutlet weak var headlineImageView: UIImageView!

    override func awakeFromNib() {
       super.awakeFromNib()
       func tableView(_ tableView: UITableViewCell, heightForRowAt indexPath: IndexPath) -> CGFloat
           {
              return 100.0;//Choose your custom row height
            }
         // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        // Configure the view for the selected state
    }

}

</code>```

In my ViewController file I have the following code:

```<code>    @IBOutlet weak var table: UITableView!

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return myfeed.count
    }

    func tableView(_ tableViwq: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:ehappyTableViewCell = self.table.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath) as! ehappyTableViewCell!

        let headline = myfeed[indexPath.row]
        cell.headlineTitleLabel?.text = headline.title
        cell.headlineTextLabel?.text = headline.subtitle
        let urlWithoutHTTP = headline.image
        let httpAddition = "https:"
        let addition = "\(httpAddition)\(urlWithoutHTTP)"

        let url = URL(string: addition)

        DispatchQueue.global().async {
           let data = try? Data(contentsOf: url!) //make sure your image in this url does exist, otherwise unwrap in a if let check / try-catch
            DispatchQueue.main.async {
                cell.headlineImageView.image = UIImage(data: data!)
            }
        }
        return cell
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 140.0;//Choose your custom row height
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.table.delegate = self
        self.table.dataSource = self
    }
</code>```

When I run the app the table will not populate with the sample data I have created.
Any suggestions on what I can do?

答:
If your cell is an xib then you have to register the cell by writing the following code in the viewDidLoad

self.table.register(UINib(nibName: "ehappyTableViewCell", bundle: nil), forCellReuseIdentifier: "LabelCell")

If it is designed inside the viewcontroller in storyboard then no need to register

Check if delegate and dataSource are given

Try replacing the line with following line

let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell") as? ehappyTableViewCell

Title: UITableView does not populate with data

Body:
I am trying to make a simple UITableView with custom cells (including two labels and one image view) but I can't get the table to be populated with data.

I have created the following struct for my data:

struct feed {
  var title: String
  var subtitle: String
  var image: String
}

and here I have defined some sample data:

var myfeed = [feed(title: "Test Feed", subtitle: "Welcome to feedFeed", image: "https://www.demo.com/imnage1.png"), feed(title: "Number 2", subtitle: "Demo?", image: "https://www.demo.com/imnage2.png")]

I have created an UITableView in my Storyboard, have configured the Custom cell and am using the Cell identifier "LabelCell".
I have created a separate cocoaTouchclass file for the UITableViewCell class:

import UIKit

class ehappyTableViewCell: UITableViewCell {

    @IBOutlet weak var headlineTitleLabel: UILabel!
    @IBOutlet weak var headlineTextLabel: UILabel!
    @IBOutlet weak var headlineImageView: UIImageView!

    override func awakeFromNib() {
       super.awakeFromNib()
       func tableView(_ tableView: UITableViewCell, heightForRowAt indexPath: IndexPath) -> CGFloat
           {
              return 100.0;//Choose your custom row height
            }
         // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        // Configure the view for the selected state
    }

}

In my ViewController file I have the following code:

    @IBOutlet weak var table: UITableView!

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return myfeed.count
    }

    func tableView(_ tableViwq: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:ehappyTableViewCell = self.table.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath) as! ehappyTableViewCell!

        let headline = myfeed[indexPath.row]
        cell.headlineTitleLabel?.text = headline.title
        cell.headlineTextLabel?.text = headline.subtitle
        let urlWithoutHTTP = headline.image
        let httpAddition = "https:"
        let addition = "\(httpAddition)\(urlWithoutHTTP)"

        let url = URL(string: addition)

        DispatchQueue.global().async {
           let data = try? Data(contentsOf: url!) //make sure your image in this url does exist, otherwise unwrap in a if let check / try-catch
            DispatchQueue.main.async {
                cell.headlineImageView.image = UIImage(data: data!)
            }
        }
        return cell
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 140.0;//Choose your custom row height
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.table.delegate = self
        self.table.dataSource = self
    }

When I run the app the table will not populate with the sample data I have created.
Any suggestions on what I can do?


问:
Only extract those words from a list that include no repeating letters, using regex
I have a large word list file with one word per line. I would like to filter out the words with repeating alphabets.

```<code>INPUT:
  abducts
  abe
  abeam
  abel
  abele

OUTPUT:
  abducts
  abe
  abel
</code>```

I'd like to do this using Regex (grep or perl or python). Is that possible?

答:
```<code>$ egrep -vi '(.).*\1' wordlist
</code>```

Body:
I have a large word list file with one word per line. I would like to filter out the words with repeating alphabets.

INPUT:
  abducts
  abe
  abeam
  abel
  abele

OUTPUT:
  abducts
  abe
  abel

I'd like to do this using Regex (grep or perl or python). Is that possible?

Body: $ egrep -vi '(.).*\1' wordlist


问:
Creating pubsub subscription to topic failed with error: User not authorized to perform this action
When I try to deploy a dataflow job with a service account, it fails with the following error:

Workflow failed. Causes: Step
  "setup_resource_XXXXXX.subscription-1210256155950706891639" failed.,
  Step setup_resource_XXXXXX.subscription-1210256155950706891639: Set up
  of resource XXXXXX.subscription-12102561559507068916 failed, Creating
  pubsub subscription
  projects/XXXXXX/subscriptions/XXXXXX.subscription-12102561559507068916
  to topic projects/XXXXXX/topics/XXXXXX failed with error: User not
  authorized to perform this action.

I have given the service account "Pub/Sub Subscriber" permission for that topic.

答:
It looks like Dataflow is trying to create a subscription here :

Creating pubsub subscription projects/XXXXXX/subscriptions/XXXXXX.subscription-12102561559507068916

However, role roles/pubsub.subscriber is not sufficient to create subscriptions, because it does not have pubsub.subscriptions.create permission.

You might need to grant your service account the role roles/pubsub.editor instead (pubsub.subscriptions.create permissions is assigned to that role).


问:
Bootstrap dropdown menu hidden behind other elements
I have a problem similar to this . But the solutions there does not work for my issue. And that discussion has been closed for further suggestions.
Unfortunately I can't show my code exactly as it is on jsfiddle. However the issue is something like this. When trying to expand the dropdown inside first panel section, the dropdown hidden behind other elements.
I've spent hours trying different suggestions concerning "stacking context", "position", and "z-index".
I would really appreciate if anyone could point me to any resources that could help.</p>

```<code><div class="btn-group">
                    <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown"> <span data-bind="label">Select One</span> <span class="caret"></span>

                    </button>
                    <ul class="dropdown-menu" role="menu">
                        <li><a href="#">Item 1</a>
                        </li>
                        <li><a href="#">Another item</a>
                        </li>
                        <li><a href="#">This is a longer item that will not fit properly</a>
                        </li>
                    </ul>
                </div>
</code>```

答:
You need to add only:

```<code>.panel.panel-default{
      overflow: inherit !important;
    }
</code>```

JSFIDDLE DEMO

Body:
I have a problem similar to this . But the solutions there does not work for my issue. And that discussion has been closed for further suggestions.
Unfortunately I can't show my code exactly as it is on jsfiddle. However the issue is something like this. When trying to expand the dropdown inside first panel section, the dropdown hidden behind other elements.
I've spent hours trying different suggestions concerning "stacking context", "position", and "z-index".
I would really appreciate if anyone could point me to any resources that could help.

                    <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown"> Select One

                    </button>

Item 1

Another item

This is a longer item that will not fit properly

Body:
You need to add only:

.panel.panel-default{
      overflow: inherit !important;
    }

JSFIDDLE DEMO


问:
How to use Opencv, qt creator, ming gw windows together?
I have been working with Opencv 3.7, Windows 8/10 and QT Creator 5.12 and MVS C++ Compiler for a long time now without any problems.

However I, if I switch my compiler to QT Mingw 73_64 C++ Compiler, building my projects does not work as all opencv references are undefined, even though under the mvs compiler it works.

I tested this on a different windows system with mingw and the same errors showed.

Is this commonly reproducible? How can one resolve this problem and work with mingw?

答: You need to compile OpenCV with that compiler.</p>


问:
listening for a function execution
I have a function doSomething() that can be triggered by
many different DOM events.
Is it possible to listen not to an event, but to a moment, when that function is being called/ listen to a function execution?

I mean - I cannot edit the original function and looking for a solution on don't want to reapeat everything attatching another function to all those events.

答: From what i can tell from this answer you need something that implements "aspect oriented programming (AOP)" https://github.com/cujojs/meld</p>

Title: listening for a function execution


问:
Is it possible to use function input to create a variable name?
Pretty sure that my title is misleading... Oh well.
So basically, I'm trying to create a game and I have a bunch of arrays with names like ItemsInG5Array, ItemsInB2Array where G5 and B2 are nodes of the map. So, what I'm trying to do is to create a function that will give you a list of items in one specific node where the player is.

```<code>function options(location)
locationPickups: while(true) {
pick = prompt("There are few items laying around.\n" + itemsInG6Array + "\nWould ou like to pick something up?");
...
</code>```

Where  location is the name of the node. Is there anything simple I can put instead of ItemsInG6Array to make it dynamic, to make it change depending on the location variable.
ItemsIn(location)Array

答:
The typical solution here is to have an object with keys, and then dynamically pick one of those keys.</p>

```<code>const example = {
  itemsInG6Array: [],
  itemsInB2Array: [],
}

function options(location) {
  const key = 'itemsIn' + location + 'Array';
  const items = example[key];
  const pick = prompt("There are few items laying around.\n" + items + "\nWould ou like to pick something up?");
}
</code>```

Body:
Pretty sure that my title is misleading... Oh well.
So basically, I'm trying to create a game and I have a bunch of arrays with names like ItemsInG5Array, ItemsInB2Array where G5 and B2 are nodes of the map. So, what I'm trying to do is to create a function that will give you a list of items in one specific node where the player is.

function options(location)
locationPickups: while(true) {
pick = prompt("There are few items laying around.\n" + itemsInG6Array + "\nWould ou like to pick something up?");
...

Where  location is the name of the node. Is there anything simple I can put instead of ItemsInG6Array to make it dynamic, to make it change depending on the location variable.
ItemsIn(location)Array

Body:
The typical solution here is to have an object with keys, and then dynamically pick one of those keys.

const example = {
  itemsInG6Array: [],
  itemsInB2Array: [],
}

function options(location) {
  const key = 'itemsIn' + location + 'Array';
  const items = example[key];
  const pick = prompt("There are few items laying around.\n" + items + "\nWould ou like to pick something up?");
}


问:
Override function in a module with complex file tree
I have a module module containing 2 functions a and b splited into 2 different files m1.py and m2.py.

The module's file tree:

```<code>module/
    __init__.py
    m1.py
    m2.py
</code>```

__init__.py contains:

```<code>from .m1 import a
from .m2 import b
</code>```

m1.py contains:

```<code>def a():
    print('a')
</code>```

m2.py contains:

```<code>from . import a

def b():
   a()
</code>```

Now, I want to override the function a in a main.py file, such that the function b uses the new function a. I tried the following:

```<code>import module

module.a = lambda: print('c')
module.b()
</code>```

But it doesn't work, module.b() still print a.

答:
I found a solution, that consists in not importing with from . import a but with import module.

m2.py becomes:

```<code>import module

def b():
    module.a()
</code>```

Body:
I have a module module containing 2 functions a and b splited into 2 different files m1.py and m2.py.

The module's file tree:

module/
    __init__.py
    m1.py
    m2.py

__init__.py contains:

from .m1 import a
from .m2 import b

m1.py contains:

def a():
    print('a')

m2.py contains:

from . import a

def b():
   a()

Now, I want to override the function a in a main.py file, such that the function b uses the new function a. I tried the following:

import module

module.a = lambda: print('c')
module.b()

But it doesn't work, module.b() still print a.

Body:
I found a solution, that consists in not importing with from . import a but with import module.

m2.py becomes:

import module

def b():
    module.a()


问:
Regex validation pattern only allows one character
I'm trying to make functions for validating usernames, emails, and passwords and my regex isn't working. My regex for usernames is ^[a-zA-Z0-9 _-]$ and when I put anything through that should work it always returns false.

As I understand it, the ^ and $ at the beginning and the end means that it makes sure the entire string matches this regular expression, the a-z and A-Z allows all letters, 0-9 allows all numbers, and the last three characters (the space, underscore, and dash) allow the respective characters.

Why is my regular expression not evaluating properly?

答:
You're not specifying the character count. Lets try this instead:

```<code>^[A-z0-9]*$
</code>```

Where [A-z0-9] states that you can use any alphanumeric characters and that it is case sensitive.

The * specifies how many characters, and in this case is unlimited. If you wanted to max out your username length to 10 characters, then you could change it to:

```<code>^[A-z0-9]{10}$
</code>```

Whereby the {10} is specifying a maximum of 10 characters.

UPDATE

To also allow the use of underscores, hyphens and blank spaces (anywhere in the string) - use the below:

```<code>^[A-z0-9 _-]{10}$
</code>```

Body:
You're not specifying the character count. Lets try this instead:

^[A-z0-9]*$

Where [A-z0-9] states that you can use any alphanumeric characters and that it is case sensitive.

The * specifies how many characters, and in this case is unlimited. If you wanted to max out your username length to 10 characters, then you could change it to:

^[A-z0-9]{10}$

Whereby the {10} is specifying a maximum of 10 characters.

UPDATE

To also allow the use of underscores, hyphens and blank spaces (anywhere in the string) - use the below:

^[A-z0-9 _-]{10}$


问:
Dynamic route with React Navigation
I have a react native app running with react navigation 3.9 with 2 components Signup and Event:

```<code>export default class Signup extends React.Component {
}

export default class Event extends React.Component {
}
</code>```

Also there is a splash component which retrieve local token.

Whenever there is a token retrieved from local drive, then the initial route is Event. Otherwise the it is Signup.

```<code>const stack = createStackNavigator ({
   Event: Event,
   Signup: Signup,
},{
  InitialRouteName: InitRoute  //<<either Event or Signup
})

const initScreen = createSwitchNavigator({
  Splash: Splash,
  App: stack,
})

export default createAppContainer(initScreen)
</code>```

Here InitRoute needs to be set by checking local token which is retrieved in splash component. Dynamic routes is not very straight forward with react navigation. What is a good way to implement it with react navigation?

答:
You can create dynamic routes based on the token. You'll need a screen that renders those two routes. Like

```<code>// app renders createStackNavigator with Event and Signup
const routes = {
  Event: {
    screen: Event,
    navigationOptions: {
      title: 'Event',
    },
  },
  Signup: {
    screen: Signup,
    navigationOptions: {
      title: 'Signup',
    },
  },
};

class App extends React.Component {

  // creates dynamic routes
  createDynamicRoutes = initiaRoute => {
    return createAppContainer(
      createStackNavigator(routes, {
        initialRouteName: initiaRoute,
      })
    );
  };

  render() {
    // get initial route from splash screen
    // this.props.navigation.navigate('App', { init: 'init screen' });
    const initiaRoute = this.props.navigation.state.params.init || 'Event';

    // create routes and set initial route
    const AppContainer = this.createDynamicRoutes(initiaRoute);
    return <AppContainer />;
  }
}
</code>```

InitScreen navigator renders App and Splash

```<code>const InitScreen = createSwitchNavigator({
  Splash: Splash,
  App: App,
})

export default createAppContainer(InitScreen);
</code>```

Demo

Title: Dynamic route with React Navigation

Body:
I have a react native app running with react navigation 3.9 with 2 components Signup and Event:

export default class Signup extends React.Component {
}

export default class Event extends React.Component {
}

Also there is a splash component which retrieve local token.

Whenever there is a token retrieved from local drive, then the initial route is Event. Otherwise the it is Signup.

const stack = createStackNavigator ({
   Event: Event,
   Signup: Signup,
},{
  InitialRouteName: InitRoute  //<<either Event or Signup
})

const initScreen = createSwitchNavigator({
  Splash: Splash,
  App: stack,
})

export default createAppContainer(initScreen)

Here InitRoute needs to be set by checking local token which is retrieved in splash component. Dynamic routes is not very straight forward with react navigation. What is a good way to implement it with react navigation?

Body:
You can create dynamic routes based on the token. You'll need a screen that renders those two routes. Like

// app renders createStackNavigator with Event and Signup
const routes = {
  Event: {
    screen: Event,
    navigationOptions: {
      title: 'Event',
    },
  },
  Signup: {
    screen: Signup,
    navigationOptions: {
      title: 'Signup',
    },
  },
};

class App extends React.Component {

  // creates dynamic routes
  createDynamicRoutes = initiaRoute => {
    return createAppContainer(
      createStackNavigator(routes, {
        initialRouteName: initiaRoute,
      })
    );
  };

  render() {
    // get initial route from splash screen
    // this.props.navigation.navigate('App', { init: 'init screen' });
    const initiaRoute = this.props.navigation.state.params.init || 'Event';

    // create routes and set initial route
    const AppContainer = this.createDynamicRoutes(initiaRoute);
    return <AppContainer />;
  }
}

InitScreen navigator renders App and Splash

const InitScreen = createSwitchNavigator({
  Splash: Splash,
  App: App,
})

export default createAppContainer(InitScreen);

Demo