问:
Selenium Grid: MaxSessions vs MaxInstances
I was wondering if anybody could shed some light on a Selenium question that has been giving us a bit of head scratching.

We're confused on meaning of MaxSession and MaxInstances of Selenium Grid.  We think that the MaxSession is the total number of test sessions that can run on a single node.  And we also think that the MaxInstances is the total number of browsers that a test can open.

Or is MaxInstances the total number of browsers available to the node?

The command that we are using is:

```<code>java -Xrs -jar selenium-server.jar -role node -port 44506 -hub http://localhost:44500
/grid/register -firefoxProfileTemplate SeleniumProfile -timeout 300000 -browser
"browserName=firefox,maxInstances=10,platform=ANY,seleniumProtocol=WebDriver" -browser
"browserName=chrome,maxInstances=10,platform=ANY,seleniumProtocol=WebDriver"
</code>```

We think the way we are using our node (above) is 5 concurrent test sessions by default.

Does each test have 20 browsers available to it?

Or does each test session share the 20 browsers (10 chrome/10 FF) in a pool - with the other test sessions?

答:
As per the documentation in Configuring the nodes by default, starting a Selenium Grid Node allows for concurrent usage of 11 browsers:

5 Firefox

5 Chrome

1 Internet Explorer

The maximum number of concurrent tests is set to 5 by default. To change this and other browser settings, you can pass in parameters to each -browser switch (each switch represents a node based on your parameters). If you use the -browser parameter, the default browsers will be ignored and only what you specify command line will be used.

maxInstances

maxInstances is an optional parameter which can be passed through the -browser optional parameter.

Usecase 1

To configure a Selenium Grid Node for 20 instances of Firefox version=X.Y.Z you can use the following solution:

Command:

```<code>java -Dwebdriver.gecko.driver=geckodriver.exe -jar selenium-server-standalone-3.141.59.jar -role node -hub http://192.168.1.125:4444/grid/register -browser browserName=firefox,version=X.Y.Z,maxInstances=20,platform=WINDOWS
</code>```

Node Console Logs:

```<code>C:\Utility\SeleniumGrid>java -Dwebdriver.gecko.driver=geckodriver.exe -jar selenium-server-standalone-3.141.59.jar -role node -hub http://192.168.1.125:4444/grid/register -browser browserName=firefox,version=X.Y.Z,maxInstances=20,platform=WINDOWS
16:54:11.843 INFO [GridLauncherV3.parse] - Selenium server version: 3.141.59, revision: e82be7d358
16:54:12.003 INFO [GridLauncherV3.lambda$buildLaunchers$7] - Launching a Selenium Grid node on port 6318
2020-02-14 16:54:12.523:INFO::main: Logging initialized @1022ms to org.seleniumhq.jetty9.util.log.StdErrLog
16:54:12.860 INFO [WebDriverServlet.<init>] - Initialising WebDriverServlet
16:54:12.974 INFO [SeleniumServer.boot] - Selenium Server is up and running on port 6318
16:54:12.974 INFO [GridLauncherV3.lambda$buildLaunchers$7] - Selenium Grid nodeis up and ready to register to the hub
16:54:13.161 INFO [SelfRegisteringRemote$1.run] - Starting auto registration thread. Will try to register every 5000 ms.
16:54:13.765 INFO [SelfRegisteringRemote.registerToHub] - Registering the node to the hub: http://192.168.1.125:4444/grid/register
16:54:13.962 INFO [SelfRegisteringRemote.registerToHub] - The node is registered to the hub and ready to use
</code>```

Grid Console Snapshot:

Usecase 2

To configure a Selenium Grid Node for 10 instances of Firefox version=A.B.C  and 20 instances of Chrome version=X.Y.Z you can use the following solution:

Command:

```<code>java -Dwebdriver.gecko.driver=geckodriver.exe -Dwebdriver.chrome.driver=chromedriver.exe -jar selenium-server-standalone-3.141.59.jar -role node -hub http://192.168.1.125:4444/grid/register -browser browserName=firefox,version=X.Y.Z,maxInstances=10,platform=WINDOWS -browser browserName=chrome,version=X.Y.Z,maxInstances=20,platform=WINDOWS
</code>```

Grid Console Snapshot:

-maxSession

-maxSession is also an optional parameter which can be passed as a main parameter to configure the maximum number of browsing contexts that can run in parallel on a particular node. This is different from the maxInstance of supported browsers (Example: For a node that supporting Firefox version A.B.C, Firefox version P.Q.R  and Chrome version X.Y.Z, maxSession=1 will ensure that you never have more than 1 browser running. With maxSession=2 you can have 2 Firefox tests executing at the same time, or 1 Firefox and 1 Chrome test).

Example:

```<code>java -Dwebdriver.gecko.driver=geckodriver.exe -Dwebdriver.chrome.driver=chromedriver.exe -jar selenium-server-standalone-3.141.59.jar -role node -hub http://192.168.1.125:4444/grid/register -browser "browserName=firefox,version=A.B.C,maxInstances=10,platform=WINDOWS" -browser "browserName=firefox,version=P.Q.R,maxInstances=10,platform=WINDOWS" -browser "browserName=chrome,version=X.Y.Z,maxInstances=20,platform=WINDOWS" -maxSession 2
</code>```

Grid Console Snapshot:

Body:
I was wondering if anybody could shed some light on a Selenium question that has been giving us a bit of head scratching.

We're confused on meaning of MaxSession and MaxInstances of Selenium Grid.  We think that the MaxSession is the total number of test sessions that can run on a single node.  And we also think that the MaxInstances is the total number of browsers that a test can open.

Or is MaxInstances the total number of browsers available to the node?

The command that we are using is:

java -Xrs -jar selenium-server.jar -role node -port 44506 -hub http://localhost:44500
/grid/register -firefoxProfileTemplate SeleniumProfile -timeout 300000 -browser
"browserName=firefox,maxInstances=10,platform=ANY,seleniumProtocol=WebDriver" -browser
"browserName=chrome,maxInstances=10,platform=ANY,seleniumProtocol=WebDriver"

We think the way we are using our node (above) is 5 concurrent test sessions by default.

Does each test have 20 browsers available to it?

Or does each test session share the 20 browsers (10 chrome/10 FF) in a pool - with the other test sessions?

Body:
As per the documentation in Configuring the nodes by default, starting a Selenium Grid Node allows for concurrent usage of 11 browsers:

5 Firefox

5 Chrome

1 Internet Explorer

The maximum number of concurrent tests is set to 5 by default. To change this and other browser settings, you can pass in parameters to each -browser switch (each switch represents a node based on your parameters). If you use the -browser parameter, the default browsers will be ignored and only what you specify command line will be used.

maxInstances

maxInstances is an optional parameter which can be passed through the -browser optional parameter.

Usecase 1

To configure a Selenium Grid Node for 20 instances of Firefox version=X.Y.Z you can use the following solution:

Command:

java -Dwebdriver.gecko.driver=geckodriver.exe -jar selenium-server-standalone-3.141.59.jar -role node -hub http://192.168.1.125:4444/grid/register -browser browserName=firefox,version=X.Y.Z,maxInstances=20,platform=WINDOWS

Node Console Logs:

C:\Utility\SeleniumGrid>java -Dwebdriver.gecko.driver=geckodriver.exe -jar selenium-server-standalone-3.141.59.jar -role node -hub http://192.168.1.125:4444/grid/register -browser browserName=firefox,version=X.Y.Z,maxInstances=20,platform=WINDOWS
16:54:11.843 INFO [GridLauncherV3.parse] - Selenium server version: 3.141.59, revision: e82be7d358
16:54:12.003 INFO [GridLauncherV3.lambda$buildLaunchers$7] - Launching a Selenium Grid node on port 6318
2020-02-14 16:54:12.523:INFO::main: Logging initialized @1022ms to org.seleniumhq.jetty9.util.log.StdErrLog
16:54:12.860 INFO [WebDriverServlet.<init>] - Initialising WebDriverServlet
16:54:12.974 INFO [SeleniumServer.boot] - Selenium Server is up and running on port 6318
16:54:12.974 INFO [GridLauncherV3.lambda$buildLaunchers$7] - Selenium Grid nodeis up and ready to register to the hub
16:54:13.161 INFO [SelfRegisteringRemote$1.run] - Starting auto registration thread. Will try to register every 5000 ms.
16:54:13.765 INFO [SelfRegisteringRemote.registerToHub] - Registering the node to the hub: http://192.168.1.125:4444/grid/register
16:54:13.962 INFO [SelfRegisteringRemote.registerToHub] - The node is registered to the hub and ready to use

Grid Console Snapshot:

Usecase 2

To configure a Selenium Grid Node for 10 instances of Firefox version=A.B.C  and 20 instances of Chrome version=X.Y.Z you can use the following solution:

Command:

java -Dwebdriver.gecko.driver=geckodriver.exe -Dwebdriver.chrome.driver=chromedriver.exe -jar selenium-server-standalone-3.141.59.jar -role node -hub http://192.168.1.125:4444/grid/register -browser browserName=firefox,version=X.Y.Z,maxInstances=10,platform=WINDOWS -browser browserName=chrome,version=X.Y.Z,maxInstances=20,platform=WINDOWS

Grid Console Snapshot:

-maxSession

-maxSession is also an optional parameter which can be passed as a main parameter to configure the maximum number of browsing contexts that can run in parallel on a particular node. This is different from the maxInstance of supported browsers (Example: For a node that supporting Firefox version A.B.C, Firefox version P.Q.R  and Chrome version X.Y.Z, maxSession=1 will ensure that you never have more than 1 browser running. With maxSession=2 you can have 2 Firefox tests executing at the same time, or 1 Firefox and 1 Chrome test).

Example:

java -Dwebdriver.gecko.driver=geckodriver.exe -Dwebdriver.chrome.driver=chromedriver.exe -jar selenium-server-standalone-3.141.59.jar -role node -hub http://192.168.1.125:4444/grid/register -browser "browserName=firefox,version=A.B.C,maxInstances=10,platform=WINDOWS" -browser "browserName=firefox,version=P.Q.R,maxInstances=10,platform=WINDOWS" -browser "browserName=chrome,version=X.Y.Z,maxInstances=20,platform=WINDOWS" -maxSession 2

Grid Console Snapshot:


来源: stackexchange

问:
Updating data source on multiple pivot tables within Excel
Is there an easy way to update the data source for multiple pivot tables on a single Excel sheet at the same time?

All of the pivot tables reference the same named range, but I need to create a second worksheet that has the same pivot tables, but accessing a different named range.

Ideally I would like to be able to do some kind of search and replace operation (like you can do on formulae), rather than updating each individual pivot table by hand.

Any suggestions?

答:
I combined both the above codes and now with the below code you can use either table or range reference for your source data. All you have to do is put in your source data by replacing the * sign and you're good to go.

```<code>Sub Change_Pivot_Source()

Dim pt As PivotTable
Dim ws As Worksheet

For Each ws In ActiveWorkbook.Worksheets

For Each pt In ws.PivotTables
         pt.ChangePivotCache ActiveWorkbook.PivotCaches.Create _
            (SourceType:=xlDatabase, SourceData:="*****")
Next pt
Next ws

End Sub
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I combined both the above codes and now with the below code you can use either table or range reference for your source data. All you have to do is put in your source data by replacing the * sign and you're good to go.

Sub Change_Pivot_Source()

Dim pt As PivotTable
Dim ws As Worksheet

For Each ws In ActiveWorkbook.Worksheets

For Each pt In ws.PivotTables
         pt.ChangePivotCache ActiveWorkbook.PivotCaches.Create _
            (SourceType:=xlDatabase, SourceData:="*****")
Next pt
Next ws

End Sub

ContentLicense: CC BY-SA 4.0


问:
setPhotoTimeIntervalSettings returns Param Illegal
I'm using the SDK version 4.11 and havent changed this code bit since 4.10:

```<code>int shootInterval = 2;
SettingsDefinitions.PhotoTimeIntervalSettings mSettings = new SettingsDefinitions.PhotoTimeIntervalSettings(255, shootInterval);
DJIApplication.getCameraInstance().setPhotoTimeIntervalSettings(mSettings, djiError -> {
    if (djiError == null) {
        Log.d(MainActivity.TAG, "Camera interval set to " + mSettings.getTimeIntervalInSeconds() + " seconds");
    } else {
        Log.e(MainActivity.TAG, "ERROR! Message: " + djiError.getDescription())
    }
});
</code>```

The error I'm getting:

"Param Illegal"

Am I doing something wrong or is this a bug in the SDK?

答:
So I talked with DJI Support and the issue is that on the Phantom 4 RTK the minimum interval is 3 and not 2 seconds.
2 months ago they promised to change the documentation but this never happened until today:
https://developer.dji.com/api-reference/android-api/Components/Camera/DJICamera_DJICameraPhotoIntervalParam.html#djicamera_djicameraphotointervalparam_timeintervalinseconds_inline

So using 3 instead of 2 seconds as an interval on the Phantom 4 RTK is the solution.

Body:
I'm using the SDK version 4.11 and havent changed this code bit since 4.10:

int shootInterval = 2;
SettingsDefinitions.PhotoTimeIntervalSettings mSettings = new SettingsDefinitions.PhotoTimeIntervalSettings(255, shootInterval);
DJIApplication.getCameraInstance().setPhotoTimeIntervalSettings(mSettings, djiError -> {
    if (djiError == null) {
        Log.d(MainActivity.TAG, "Camera interval set to " + mSettings.getTimeIntervalInSeconds() + " seconds");
    } else {
        Log.e(MainActivity.TAG, "ERROR! Message: " + djiError.getDescription())
    }
});

The error I'm getting:

"Param Illegal"

Am I doing something wrong or is this a bug in the SDK?


问:
Apache virtualHost ignored or pointing to the default one
I'm trying to setup my Apache on OSX, but I'm not able to make my local url 'awr.local' point to the correct path. I mean whether I type http://localhost or http://awr.local, it always shows me the index.html page in my 'localhost' vhost path.
I've restarted my httpd service countless times, with or without sudo.

Any help would be greatly appreciated, thanks :'|

I've been following a tutorial (https://getgrav.org/blog/macos-sierra-apache-multiple-php-versions), here are the steps about Apache :

Disabling the bundled Apache and installing the one from homebrew :

```<code>sudo apachectl stop
sudo launchctl unload -w /System/Library/LaunchDaemons/org.apache.httpd.plist 2>/dev/null
brew install httpd
</code>```

Then, some httpd.conf modifications :

```<code># changed Listen 8080 to :
Listen 80
[...]
# changed DocumentRoot "/usr/local/var/www" to :
DocumentRoot "/Users/wallace/dev/default"
[...]
# changed <Directory "/usr/local/var/www"> to :
<Directory "/Users/wallace/dev/default">
[...]
# changed AllowOverride None to :
AllowOverride All
# uncommented :
LoadModule rewrite_module lib/httpd/modules/mod_rewrite.so
[...]
# changed
# User _www
# Group _www
# to :
User wallace
Group staff
[...]
# added the missing line :
ServerName localhost
</code>```

Until this point everything seemed to be working fine, I've installed PHP and MariaDB without any problem.

Then came the virtual hosts part :

Some other httpd.conf modifications :

```<code># uncommenting these lines
LoadModule vhost_alias_module lib/httpd/modules/mod_vhost_alias.so
[...]
Include /usr/local/etc/httpd/extra/httpd-vhosts.conf
</code>```

Editing the file /usr/local/etc/httpd/extra/httpd-vhosts.conf :

```<code><VirtualHost *:80>
    DocumentRoot "/Users/wallace/dev/default"
    ServerName localhost
</VirtualHost>

<VirtualHost *:80>
    DocumentRoot "/Users/wallace/dev/awr"
    ServerName awr.local
</VirtualHost>
</code>```

The /etc/hosts file :

```<code>127.0.0.1       localhost
255.255.255.255 broadcasthost
::1             localhost
127.0.0.1       awr.local
::1             awr.local
</code>```

The output of 'httpd -S' :

```<code>VirtualHost configuration:
*:80                   is a NameVirtualHost
         default server localhost (/usr/local/etc/httpd/extra/httpd-vhosts.conf:25)
         port 80 namevhost localhost (/usr/local/etc/httpd/extra/httpd-vhosts.conf:25)
         port 80 namevhost awr.local (/usr/local/etc/httpd/extra/httpd-vhosts.conf:30)
ServerRoot: "/usr/local/opt/httpd"
Main DocumentRoot: "/Users/wallace/dev/default"
Main ErrorLog: "/usr/local/var/log/httpd/error_log"
Mutex rewrite-map: using_defaults
Mutex default: dir="/usr/local/var/run/httpd/" mechanism=default
Mutex mpm-accept: using_defaults
PidFile: "/usr/local/var/run/httpd/httpd.pid"
Define: DUMP_VHOSTS
Define: DUMP_RUN_CFG
User: name="wallace" id=501 not_used
Group: name="staff" id=20 not_used
</code>```

答: I had the same problem and couldn't get it to work no matter what I tried. Stopping, starting or restarting httpd did not work. Even though httpd -S always reported the correct settings, all browsers loaded the default docroot, regardless of the virtualhost settings. Then I noticed something strange. After stopping httpd with brew services stop httpd I reloaded localhost in the browser and it still loaded without a problem. This gave me the idea to sudo killall httpd then start it again with brew services start httpd. After this, all was fine.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to setup my Apache on OSX, but I'm not able to make my local url 'awr.local' point to the correct path. I mean whether I type http://localhost or http://awr.local, it always shows me the index.html page in my 'localhost' vhost path.
I've restarted my httpd service countless times, with or without sudo.

Any help would be greatly appreciated, thanks :'|

I've been following a tutorial (https://getgrav.org/blog/macos-sierra-apache-multiple-php-versions), here are the steps about Apache :

Disabling the bundled Apache and installing the one from homebrew :

sudo apachectl stop
sudo launchctl unload -w /System/Library/LaunchDaemons/org.apache.httpd.plist 2>/dev/null
brew install httpd

Then, some httpd.conf modifications :

# changed Listen 8080 to :
Listen 80
[...]
# changed DocumentRoot "/usr/local/var/www" to :
DocumentRoot "/Users/wallace/dev/default"
[...]
# changed <Directory "/usr/local/var/www"> to :
<Directory "/Users/wallace/dev/default">
[...]
# changed AllowOverride None to :
AllowOverride All
# uncommented :
LoadModule rewrite_module lib/httpd/modules/mod_rewrite.so
[...]
# changed
# User _www
# Group _www
# to :
User wallace
Group staff
[...]
# added the missing line :
ServerName localhost

Until this point everything seemed to be working fine, I've installed PHP and MariaDB without any problem.

Then came the virtual hosts part :

Some other httpd.conf modifications :

# uncommenting these lines
LoadModule vhost_alias_module lib/httpd/modules/mod_vhost_alias.so
[...]
Include /usr/local/etc/httpd/extra/httpd-vhosts.conf

Editing the file /usr/local/etc/httpd/extra/httpd-vhosts.conf :

<VirtualHost *:80>
    DocumentRoot "/Users/wallace/dev/default"
    ServerName localhost
</VirtualHost>

<VirtualHost *:80>
    DocumentRoot "/Users/wallace/dev/awr"
    ServerName awr.local
</VirtualHost>

The /etc/hosts file :

127.0.0.1       localhost
255.255.255.255 broadcasthost
::1             localhost
127.0.0.1       awr.local
::1             awr.local

The output of 'httpd -S' :

VirtualHost configuration:
*:80                   is a NameVirtualHost
         default server localhost (/usr/local/etc/httpd/extra/httpd-vhosts.conf:25)
         port 80 namevhost localhost (/usr/local/etc/httpd/extra/httpd-vhosts.conf:25)
         port 80 namevhost awr.local (/usr/local/etc/httpd/extra/httpd-vhosts.conf:30)
ServerRoot: "/usr/local/opt/httpd"
Main DocumentRoot: "/Users/wallace/dev/default"
Main ErrorLog: "/usr/local/var/log/httpd/error_log"
Mutex rewrite-map: using_defaults
Mutex default: dir="/usr/local/var/run/httpd/" mechanism=default
Mutex mpm-accept: using_defaults
PidFile: "/usr/local/var/run/httpd/httpd.pid"
Define: DUMP_VHOSTS
Define: DUMP_RUN_CFG
User: name="wallace" id=501 not_used
Group: name="staff" id=20 not_used


问:
how to change a button background and enable it after other buttons are pressed
How do I enable the "Next" button after 'Yes' or 'No' from each question is pressed? I want to make my "Next" button active (change the background and enable) only after all the questions have been answered. I don't know whether I should use loop or if it's possible by if-else. Any help is very appreciated.

I have developed my program in a way that users can either press the 'yes' or 'no' button and after answering all questions the "Next" button should get activated (change the background and enable).

```<code>int one = 0;
int two = 0;
int three = 0;
int four = 0;

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

    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        String phone_price = extras.getString("phone_price");
        final String numonly = phone_price.replaceAll("[^0-9]", "");

        final int phoneprice = Integer.parseInt(numonly);

        final Button ques_one_yes = (Button)findViewById(R.id.ques_one_yes);
        final Button ques_one_no = (Button)findViewById(R.id.ques_one_no);
        final Button ques_two_yes = (Button)findViewById(R.id.ques_two_yes);
        final Button ques_two_no = (Button)findViewById(R.id.ques_two_no);
        final Button ques_three_yes = (Button)findViewById(R.id.ques_three_yes);
        final Button ques_three_no = (Button)findViewById(R.id.ques_three_no);
        final Button ques_four_yes = (Button)findViewById(R.id.ques_four_yes);
        final Button ques_four_no = (Button)findViewById(R.id.ques_four_no);
        final Button nextstep = (Button)findViewById(R.id.next_step);

        ques_one_yes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                one = 1;
                ques_one_yes.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
                ques_one_yes.setBackground(getDrawable(R.drawable.button_background));
                ques_one_no.setTextColor(getApplication().getResources().getColor(R.color.black));
                ques_one_no.setBackground(getDrawable(R.drawable.inactive_button_background));
            }
        });

        ques_one_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                one = 1;
                ques_one_no.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
                ques_one_no.setBackground(getDrawable(R.drawable.button_background));
                ques_one_yes.setTextColor(getApplication().getResources().getColor(R.color.black));
                ques_one_yes.setBackground(getDrawable(R.drawable.inactive_button_background));

            }
        });

        ques_two_yes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                two = 1;
                ques_two_yes.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
                ques_two_yes.setBackground(getDrawable(R.drawable.button_background));
                ques_two_no.setTextColor(getApplication().getResources().getColor(R.color.black));
                ques_two_no.setBackground(getDrawable(R.drawable.inactive_button_background));

            }
        });

        ques_two_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                two = 1;
                ques_two_no.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
                ques_two_no.setBackground(getDrawable(R.drawable.button_background));
                ques_two_yes.setTextColor(getApplication().getResources().getColor(R.color.black));
                ques_two_yes.setBackground(getDrawable(R.drawable.inactive_button_background));
            }
        });

        ques_three_yes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                three = 1;
                ques_three_yes.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
                ques_three_yes.setBackground(getDrawable(R.drawable.button_background));
                ques_three_no.setTextColor(getApplication().getResources().getColor(R.color.black));
                ques_three_no.setBackground(getDrawable(R.drawable.inactive_button_background));
            }
        });

        ques_three_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                three = 1;
                ques_three_no.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
                ques_three_no.setBackground(getDrawable(R.drawable.button_background));
                ques_three_yes.setTextColor(getApplication().getResources().getColor(R.color.black));
                ques_three_yes.setBackground(getDrawable(R.drawable.inactive_button_background));
            }
        });

        ques_four_yes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                four = 1;
                ques_four_yes.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
                ques_four_yes.setBackground(getDrawable(R.drawable.button_background));
                ques_four_no.setTextColor(getApplication().getResources().getColor(R.color.black));
                ques_four_no.setBackground(getDrawable(R.drawable.inactive_button_background));
            }
        });

        ques_four_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                four = 1;
                ques_four_no.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
                ques_four_no.setBackground(getDrawable(R.drawable.button_background));
                ques_four_yes.setTextColor(getApplication().getResources().getColor(R.color.black));
                ques_four_yes.setBackground(getDrawable(R.drawable.inactive_button_background));

            }
        });

    }
}
</code>```

Quesions

答:
In general if you want to achieve this implementation you can try the following ,

To enable/disable the next button:

```<code>fun enableNextButton(isEnable: Boolean) {
    if(isEnable){
        button_next?.alpha = 1.0f
        button_next?.isEnabled = true
    }else{
        button_next?.alpha = 0.5f
        button_next?.isEnabled = false
    }
}
</code>```

So call enableNextButton(true) if you want to enable the next button otherwise pass the false param to method. Also alpha sets the button blur which helps you to show the disable button view.

Body:
How do I enable the "Next" button after 'Yes' or 'No' from each question is pressed? I want to make my "Next" button active (change the background and enable) only after all the questions have been answered. I don't know whether I should use loop or if it's possible by if-else. Any help is very appreciated.

I have developed my program in a way that users can either press the 'yes' or 'no' button and after answering all questions the "Next" button should get activated (change the background and enable).

int one = 0;
int two = 0;
int three = 0;
int four = 0;

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

    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        String phone_price = extras.getString("phone_price");
        final String numonly = phone_price.replaceAll("[^0-9]", "");

        final int phoneprice = Integer.parseInt(numonly);

        final Button ques_one_yes = (Button)findViewById(R.id.ques_one_yes);
        final Button ques_one_no = (Button)findViewById(R.id.ques_one_no);
        final Button ques_two_yes = (Button)findViewById(R.id.ques_two_yes);
        final Button ques_two_no = (Button)findViewById(R.id.ques_two_no);
        final Button ques_three_yes = (Button)findViewById(R.id.ques_three_yes);
        final Button ques_three_no = (Button)findViewById(R.id.ques_three_no);
        final Button ques_four_yes = (Button)findViewById(R.id.ques_four_yes);
        final Button ques_four_no = (Button)findViewById(R.id.ques_four_no);
        final Button nextstep = (Button)findViewById(R.id.next_step);

        ques_one_yes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                one = 1;
                ques_one_yes.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
                ques_one_yes.setBackground(getDrawable(R.drawable.button_background));
                ques_one_no.setTextColor(getApplication().getResources().getColor(R.color.black));
                ques_one_no.setBackground(getDrawable(R.drawable.inactive_button_background));
            }
        });

        ques_one_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                one = 1;
                ques_one_no.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
                ques_one_no.setBackground(getDrawable(R.drawable.button_background));
                ques_one_yes.setTextColor(getApplication().getResources().getColor(R.color.black));
                ques_one_yes.setBackground(getDrawable(R.drawable.inactive_button_background));

            }
        });

        ques_two_yes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                two = 1;
                ques_two_yes.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
                ques_two_yes.setBackground(getDrawable(R.drawable.button_background));
                ques_two_no.setTextColor(getApplication().getResources().getColor(R.color.black));
                ques_two_no.setBackground(getDrawable(R.drawable.inactive_button_background));

            }
        });

        ques_two_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                two = 1;
                ques_two_no.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
                ques_two_no.setBackground(getDrawable(R.drawable.button_background));
                ques_two_yes.setTextColor(getApplication().getResources().getColor(R.color.black));
                ques_two_yes.setBackground(getDrawable(R.drawable.inactive_button_background));
            }
        });

        ques_three_yes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                three = 1;
                ques_three_yes.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
                ques_three_yes.setBackground(getDrawable(R.drawable.button_background));
                ques_three_no.setTextColor(getApplication().getResources().getColor(R.color.black));
                ques_three_no.setBackground(getDrawable(R.drawable.inactive_button_background));
            }
        });

        ques_three_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                three = 1;
                ques_three_no.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
                ques_three_no.setBackground(getDrawable(R.drawable.button_background));
                ques_three_yes.setTextColor(getApplication().getResources().getColor(R.color.black));
                ques_three_yes.setBackground(getDrawable(R.drawable.inactive_button_background));
            }
        });

        ques_four_yes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                four = 1;
                ques_four_yes.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
                ques_four_yes.setBackground(getDrawable(R.drawable.button_background));
                ques_four_no.setTextColor(getApplication().getResources().getColor(R.color.black));
                ques_four_no.setBackground(getDrawable(R.drawable.inactive_button_background));
            }
        });

        ques_four_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                four = 1;
                ques_four_no.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
                ques_four_no.setBackground(getDrawable(R.drawable.button_background));
                ques_four_yes.setTextColor(getApplication().getResources().getColor(R.color.black));
                ques_four_yes.setBackground(getDrawable(R.drawable.inactive_button_background));

            }
        });

    }
}

Quesions

Body:
In general if you want to achieve this implementation you can try the following ,

To enable/disable the next button:

fun enableNextButton(isEnable: Boolean) {
    if(isEnable){
        button_next?.alpha = 1.0f
        button_next?.isEnabled = true
    }else{
        button_next?.alpha = 0.5f
        button_next?.isEnabled = false
    }
}

So call enableNextButton(true) if you want to enable the next button otherwise pass the false param to method. Also alpha sets the button blur which helps you to show the disable button view.


问:
Jquery clone original HTML not DOM
I need to clone a section of markup that has already been modified in the DOM. I want to get the original HTML source - what is seen in View > Source.

clone() uses what's in the DOM

答: you would need to copy that HTML into something before the changes are made to the DOM. what the DOM currently has at any given point in time is what you have access to, not past/future versions unless you explicitly saved them to something</p>

Title: Jquery clone original HTML not DOM


问:
Loop through database table in Laravel Vue js Component
This is an example of what I want to achieve in the vue component

```<code><div v-for="emotion in emotions" class="cb-row">
    <h2>{{ emotion.em_name }}</h2>
</div>
</code>```

I have created a function in the EmotionsController to return all data from the table

```<code>class EmotionsController extends Controller
{
    public function getEmotions() {

        $emotions = Emotions::all()->get();

        return $emotions;

    }
}
</code>```

How do I then get this data into my vue component? It's being loaded into a form

答:
You have to refer laravel documentation first. because it gave you everything what you want.
Here's the link of your question
https://laravel.com/docs/6.x/frontend#writing-vue-components</p>

Body:
This is an example of what I want to achieve in the vue component

{{ emotion.em_name }}

I have created a function in the EmotionsController to return all data from the table

class EmotionsController extends Controller
{
    public function getEmotions() {

        $emotions = Emotions::all()->get();

        return $emotions;

    }
}

How do I then get this data into my vue component? It's being loaded into a form


问:
Can't convert from BSON type string to Date on aggregation pipeline
I am using MongoDB 3.4.9, and I want to have monthly report w.r.t. customer info, and here are the Sample example mongodb records with nested items and error received is:

can't convert from BSON type string to Date

```<code>    {
"_id" : ObjectId("59da6a331c7a9ac0b6674fe8"),
"date" : ISODate("2017-10-08T18:10:59.899Z"),
"items" : [
    {
        "quantity" : 1,
        "price" : 47.11,
        "desc" : "Item #1"
    },
    {
        "quantity" : 2,
        "price" : 42.0,
        "desc" : "Item #2"
    }
],
"custInfo" : "Tobias Trelle, gold customer"
  }

{
"_id" : ObjectId("59da6a511c7a9ac0b6674fed"),
"date" : ISODate("2017-10-08T18:11:28.961Z"),
"items" : [
    {
        "quantity" : 1,
        "price" : 47.11,
        "desc" : "Item #1"
    },
    {
        "quantity" : 2,
        "price" : 42.0,
        "desc" : "Item #2"
    }
],
"custInfo" : "Tobias Trelle, gold customer"
  }

  {
"_id" : ObjectId("59da6a511c7a9ac0b6674ff0"),
"date" : ISODate("2017-10-08T18:11:29.133Z"),
"items" : [
    {
        "quantity" : 1,
        "price" : 47.11,
        "desc" : "Item #1"
    },
    {
        "quantity" : 2,
        "price" : 42.0,
        "desc" : "Item #2"
    }
],
"custInfo" : "Tobias Trelle, gold customer"
  }
</code>```

Here is the MongoDB query for calculating sum grouping by custInfo month wise

```<code>db.runCommand({aggregate:"order", pipeline :
[{$match : {$and : [{"date" : {$gte : ISODate("2016-10-08T18:10:59.899Z")}},
{"date" : {$lte : ISODate("2018-10-08T18:10:59.899Z")}}]}}
,
{ "$project" : { "custInfo" : 1 ,"count" : 1 ,   "date" : 1 ,
"duration" : {"$month" : [ "date"]}}},
{ "$group" : { "_id" :
    { "duration" : "$duration" , "custInfo" : "$custInfo"} ,"count" : { "$sum" : 1} }}

    ]}//,
    //cursor:{batchSize:1000}

 )
</code>```

Please help where I was wrong.

Regards
Kris

答:
Not related with your specific case, but with the generic solution to this BSON error...
Solve this problem with:</p>

```<code>{"project: { "y.dateFieldName":
 {"$cond":[{ $eq: [{$type: "$data.dateFieldName"},'date']},{"$year":"$data.dateFieldName"},-1]}}
</code>```

Body:
I am using MongoDB 3.4.9, and I want to have monthly report w.r.t. customer info, and here are the Sample example mongodb records with nested items and error received is:

can't convert from BSON type string to Date

    {
"_id" : ObjectId("59da6a331c7a9ac0b6674fe8"),
"date" : ISODate("2017-10-08T18:10:59.899Z"),
"items" : [
    {
        "quantity" : 1,
        "price" : 47.11,
        "desc" : "Item #1"
    },
    {
        "quantity" : 2,
        "price" : 42.0,
        "desc" : "Item #2"
    }
],
"custInfo" : "Tobias Trelle, gold customer"
  }

{
"_id" : ObjectId("59da6a511c7a9ac0b6674fed"),
"date" : ISODate("2017-10-08T18:11:28.961Z"),
"items" : [
    {
        "quantity" : 1,
        "price" : 47.11,
        "desc" : "Item #1"
    },
    {
        "quantity" : 2,
        "price" : 42.0,
        "desc" : "Item #2"
    }
],
"custInfo" : "Tobias Trelle, gold customer"
  }

  {
"_id" : ObjectId("59da6a511c7a9ac0b6674ff0"),
"date" : ISODate("2017-10-08T18:11:29.133Z"),
"items" : [
    {
        "quantity" : 1,
        "price" : 47.11,
        "desc" : "Item #1"
    },
    {
        "quantity" : 2,
        "price" : 42.0,
        "desc" : "Item #2"
    }
],
"custInfo" : "Tobias Trelle, gold customer"
  }

Here is the MongoDB query for calculating sum grouping by custInfo month wise

db.runCommand({aggregate:"order", pipeline :
[{$match : {$and : [{"date" : {$gte : ISODate("2016-10-08T18:10:59.899Z")}},
{"date" : {$lte : ISODate("2018-10-08T18:10:59.899Z")}}]}}
,
{ "$project" : { "custInfo" : 1 ,"count" : 1 ,   "date" : 1 ,
"duration" : {"$month" : [ "date"]}}},
{ "$group" : { "_id" :
    { "duration" : "$duration" , "custInfo" : "$custInfo"} ,"count" : { "$sum" : 1} }}

    ]}//,
    //cursor:{batchSize:1000}

 )

Please help where I was wrong.

Regards
Kris

Body:
Not related with your specific case, but with the generic solution to this BSON error...
Solve this problem with:

{"project: { "y.dateFieldName":
 {"$cond":[{ $eq: [{$type: "$data.dateFieldName"},'date']},{"$year":"$data.dateFieldName"},-1]}}


问:
Selectize is inserting a ? character in data-value attribute
I am using selectize.js to build a dropdown list of all cities in Belgium.

```<code>var cityselect = $('.city-select');
    if (cityselect.length) {
        $('.city-select').selectize({
            create: false,
            sortField: {
                field: 'text',
                direction: 'asc'
            },
            dropdownParent: 'body',
            plugins: ['remove_button']
        });
    }
</code>```

I create the selectize field as following:

```<code><div class="form-group">
    <label for="city"><?=lang("register_volunteer_select_city_or_commune")?></label>
    <select id="city" class="city-select" name="city" autocomplete="new-password" required data-validation-required-message="<?=lang("register_volunteer_select_city_or_commune_validation")?>">
        <option value="" selected><?=lang("register_volunteer_select_city_or_commune")?></option>
        <?php
        foreach ($citiesbe as $city) {
            if ($this->currentLanguage == 'fr') {
                $cityName = $city->name_fr;
            } else {
                $cityName = $city->name_nl;
            }
            $key = strtolower($cityName) . "," . $city->zip_code;
            echo "<option value=\"$key\"> $cityName ($city->zip_code)</option>";
        }
        ?>
    </select>
    <div class="help-block font-small-3"></div>
</div>
</code>```

In Belgium, there are a lot of cities with French names (eg: Léglise) that contain a special character (é, è, ç, ...) etc.
The variable $citiesbe, comes from my table "cities_be", and the entry for Léglise looks like this:

```<code>+--------------+----------+---------+---------+--------+-------+
| cities_be_id | zip_code | name_nl | name_fr |  lat   |  lng  |
+--------------+----------+---------+---------+--------+-------+
|         1786 |     6860 | Léglise | Léglise | 49,784 | 5,538 |
+--------------+----------+---------+---------+--------+-------+
</code>```

Then in my selectize, I can select Léglise and it looks great, but when I inspect the element, I will notice that the data-value is set to the following value:

```<code><div data-value="l�glise,6860" class="item"> Léglise (6860)</div>
</code>```

Because it inserts special characters (é in this example) as a ? it passes this through the POST variables as a ? and thus it generates a lot of errors.

How do I go about this problem?

I have set my database charset & collation to utf8mb4 , the connection with database via PHP is also set to utf8mb4, and my document contains a charset line:

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

I'm completely running out of idea's here on how to solve this issue.

答:
Have you tried using mb_strtolower()?

https://www.php.net/manual/en/function.mb-strtolower.php

```<code>$b = mb_strtolower($a);
echo $b;
</code>```

PHP5 is not UTF-8 compatible, doesn't work on multi-byte characters, so you still need to resort to the mb extension.

Body:
I am using selectize.js to build a dropdown list of all cities in Belgium.

var cityselect = $('.city-select');
    if (cityselect.length) {
        $('.city-select').selectize({
            create: false,
            sortField: {
                field: 'text',
                direction: 'asc'
            },
            dropdownParent: 'body',
            plugins: ['remove_button']
        });
    }

I create the selectize field as following:

    <?=lang("register_volunteer_select_city_or_commune")?>
    <select id="city" class="city-select" name="city" autocomplete="new-password" required data-validation-required-message="<?=lang("register_volunteer_select_city_or_commune_validation")?>">
        <option value="" selected><?=lang("register_volunteer_select_city_or_commune")?></option>
        <?php
        foreach ($citiesbe as $city) {
            if ($this->currentLanguage == 'fr') {
                $cityName = $city->name_fr;
            } else {
                $cityName = $city->name_nl;
            }
            $key = strtolower($cityName) . "," . $city->zip_code;
            echo "<option value=\"$key\"> $cityName ($city->zip_code)</option>";
        }
        ?>
    </select>

In Belgium, there are a lot of cities with French names (eg: Léglise) that contain a special character (é, è, ç, ...) etc.
The variable $citiesbe, comes from my table "cities_be", and the entry for Léglise looks like this:

+--------------+----------+---------+---------+--------+-------+
| cities_be_id | zip_code | name_nl | name_fr |  lat   |  lng  |
+--------------+----------+---------+---------+--------+-------+
|         1786 |     6860 | Léglise | Léglise | 49,784 | 5,538 |
+--------------+----------+---------+---------+--------+-------+

Then in my selectize, I can select Léglise and it looks great, but when I inspect the element, I will notice that the data-value is set to the following value:

 Léglise (6860)

Because it inserts special characters (é in this example) as a ? it passes this through the POST variables as a ? and thus it generates a lot of errors.

How do I go about this problem?

I have set my database charset & collation to utf8mb4 , the connection with database via PHP is also set to utf8mb4, and my document contains a charset line:

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

I'm completely running out of idea's here on how to solve this issue.

Body:
Have you tried using mb_strtolower()?

https://www.php.net/manual/en/function.mb-strtolower.php

$b = mb_strtolower($a);
echo $b;

PHP5 is not UTF-8 compatible, doesn't work on multi-byte characters, so you still need to resort to the mb extension.


问:
Difference between multitasking, multithreading and multiprocessing?
Whats the difference between multitasking, multiprogramming & multiprocessing

This comes regularly for my university OS exams and I can't find a good answer.
I know quite a bit about multitasking and multiprogramming, but need to confirm it.

答:
Paraphrasing wikipedia:

Multiprogramming - A computer running more than one program at a time (like running Excel and Firefox simultaneously)
http://en.wikipedia.org/wiki/Multiprogramming

Multiprocessing - A computer using more than one CPU at a time
http://en.wikipedia.org/wiki/Multiprocessing

Multitasking - Tasks sharing a common resource (like 1 CPU)
http://en.wikipedia.org/wiki/Computer_multitasking#Multithreading

Thus, something like multithreading is an extension of multitasking.


问:
is it possible to integrate Google Pay in C# window form desktop application
I have Develop a Desktop Application in C# window Form. the application about reservation of Pet`s. My Manager assign me a Task to integrate google pay in This desktop application. I need to know is it possible or Not, if Yes then How ? Because in Google pay Guide it is described that this integration is for Mobile and Web.
Please Help.

Thanks

答:
No.
What you can do is create an Api that will integrate with Google Pay and consume in your desktop application.</p>


问:
Laravel returning null token but user is being added
I use postman to add user in my Laravel project. I get null token but the user is added, why?

{
"token": null }

How I can fix this error? I use Laravel 5.6 and this is my user model:

```<code>    <?php

    namespace App;

    use Tymon\JWTAuth\Contracts\JWTSubject;
    use Illuminate\Notifications\Notifiable;
    use Illuminate\Foundation\Auth\User as Authenticatable;
    class User extends Authenticatable
    {
        use Notifiable;

        /**
         * The attributes that are mass assignable.
         *
         * @var array
         */
        protected $fillable = [
            'name', 'email', 'password','username','lastname','tel','tel',
        ];

        /**
         * The attributes that should be hidden for arrays.
         *
         * @var array
         */
        protected $hidden = [
            'password', 'remember_token',
        ];

        public function getJWTIdentifier()
        {
            return $this->getKey();
        }

        /**
         * Return a key value array, containing any custom claims to be added to the JWT.
         *
  * @return array
         */
        public function getJWTCustomClaims()
        {
            return [];
        }
    }
</code>```

and this is my register controller:

```<code>    <?php

    namespace App\Http\Controllers;
    use App\Http\Controllers\Controller;
    use Illuminate\Http\Request;
    use App\User;
    use JWTFactory;
    use JWTAuth;
    use Validator;
    use Response;

    class APIRegisterController extends Controller
    {
        //
        public function register( Request $request){
            $validator = Validator::make($request -> all(),[
             'email' => 'required|string|email|max:255|unique:users',
             'username' =>'required',
             'tel' => 'required',
             'name' => 'required',
             'lastname' => 'required',
             'adress' => 'required',
             'password'=> 'required'
            ]);

            if ($validator -> fails()) {
                # code...
                return response()->json($validator->errors());

            }

            User::create([
                'name' => $request->get('name'),
                'email' => $request->get('email'),
                'tel' => $request->get('tel'),
                'username' => $request->get('username'),
                'lastname' => $request->get('lastname'),
                'adress' => $request->get('adress'),
                'password'=> bcrypt($request->get('password'))
            ]);
            $user = User::first();
            $token = JWTAuth::fromUser($user);

            return Response::json( compact('token'));

        }
    }
</code>```

I already get an error and this is my question question and I fix it.

答:
I already had a similar problem before, but I realize my$user->password holds the encrypted password, not the plain text required for login(). Change your code to call

```<code>$token = JWTAuth::fromUser($user);
</code>```

with $user holding the plain text password comming from $request.

Body:
I use postman to add user in my Laravel project. I get null token but the user is added, why?

{
"token": null }

How I can fix this error? I use Laravel 5.6 and this is my user model:

    <?php

    namespace App;

    use Tymon\JWTAuth\Contracts\JWTSubject;
    use Illuminate\Notifications\Notifiable;
    use Illuminate\Foundation\Auth\User as Authenticatable;
    class User extends Authenticatable
    {
        use Notifiable;

        /**
         * The attributes that are mass assignable.
         *
         * @var array
         */
        protected $fillable = [
            'name', 'email', 'password','username','lastname','tel','tel',
        ];

        /**
         * The attributes that should be hidden for arrays.
         *
         * @var array
         */
        protected $hidden = [
            'password', 'remember_token',
        ];

        public function getJWTIdentifier()
        {
            return $this->getKey();
        }

        /**
         * Return a key value array, containing any custom claims to be added to the JWT.
         *
  * @return array
         */
        public function getJWTCustomClaims()
        {
            return [];
        }
    }

and this is my register controller:

    <?php

    namespace App\Http\Controllers;
    use App\Http\Controllers\Controller;
    use Illuminate\Http\Request;
    use App\User;
    use JWTFactory;
    use JWTAuth;
    use Validator;
    use Response;

    class APIRegisterController extends Controller
    {
        //
        public function register( Request $request){
            $validator = Validator::make($request -> all(),[
             'email' => 'required|string|email|max:255|unique:users',
             'username' =>'required',
             'tel' => 'required',
             'name' => 'required',
             'lastname' => 'required',
             'adress' => 'required',
             'password'=> 'required'
            ]);

            if ($validator -> fails()) {
                # code...
                return response()->json($validator->errors());

            }

            User::create([
                'name' => $request->get('name'),
                'email' => $request->get('email'),
                'tel' => $request->get('tel'),
                'username' => $request->get('username'),
                'lastname' => $request->get('lastname'),
                'adress' => $request->get('adress'),
                'password'=> bcrypt($request->get('password'))
            ]);
            $user = User::first();
            $token = JWTAuth::fromUser($user);

            return Response::json( compact('token'));

        }
    }

I already get an error and this is my question question and I fix it.

Body:
I already had a similar problem before, but I realize my$user->password holds the encrypted password, not the plain text required for login(). Change your code to call

$token = JWTAuth::fromUser($user);

with $user holding the plain text password comming from $request.


问:
Azure Devops Change the Deploy Folder
I am using Azure Devops for automatic build & deploy of asp.net core 3.1 web app to Azure App Service.

The problem is that it's deploying the app to strange folder. Instead of the wwwroot folder it is in
 /home/site/wwwroot/Content/D_C/a/1/s/ExampleFolder/ExampleFolder2/ExampleFolder3/obj/Staging/netcoreapp3.1/PubTmp/Out
The app service is on Linux if it matters.

How I can just fix/change it to be in the main folder?

答:
I solved my issue by creating new Pipeline which is using dotnet agents instead of Visual Studio build agents. When you are deploying to Linux App Service make sure to use CLI. You can see @martin-brandl answer for example pipeline.

You can also refer to this Devops SE question. The problem is similiar:
https://devops.stackexchange.com/questions/9598/azure-devops-artifact-zip-folder-structure-for-net-core-3-0-application

I'm looking this fact:

I have an ASP.NET Core 3.0 application for which I have a full CI/CD setup in Azure DevOps. The Application is hosted on a Ubuntu 18.04 server machine.

Therefore I can safely assume that you are developing ASP.NET Core 3.0 app to be hosted in Ubuntu. Any .NET Core 3.0 (or later) application means that you should rely on the dotnet build instead of using VSBuild.

Also you had stated that you will host the app on Ubuntu 18.x, then you should also run the build on Azure DevOps agent that runs on Ubuntu. This means you should only use dotnet build in DotNetCoreCLI@2 task, because VSBuild task only runs on Windows based agent, not Ubuntu and it is intended to compile .NET Framework and other platform other than .NET Core.

Please consult the official doc of DotNetCoreCLI@2 task at https://learn.microsoft.com/en-us/azure/devops/pipelines/tasks/build/dotnet-core-cli?view=azure-devops

After you use dotnet build, use dotnet publish to publish your artifact. It is much easier and it's also the best way to publish .NET Core apps.

I have sample usage of dotnet build and dotnet publish of this on my repo: https://github.com/eriawan/dotnetcore-cicd-samples/blob/master/yaml-samples/sample_pipelines_check.yml

Title: Azure Devops Change the Deploy Folder


问:
Read data from SqlDataReader
I have a SQL Server 2008 database and I am working on it in the backend. I am working on asp.net/C#

```<code>SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
   //how do I read strings here????
}
</code>```

I know that the reader has values. My SQL command is to select just 1 column from a table. The column contains strings ONLY. I want to read the strings (rows) in the reader one by one. How do I do this?

答:
You have to read database columnhere. You could have a look on following code snippet

```<code>                string connectionString = ConfigurationManager.ConnectionStrings["NameOfYourSqlConnectionString"].ConnectionString;
                using (var _connection = new SqlConnection(connectionString))
                {
                    _connection.Open();

                    using (SqlCommand command = new SqlCommand("SELECT SomeColumnName FROM TableName", _connection))
                    {

                        SqlDataReader sqlDataReader = command.ExecuteReader();
                        if (sqlDataReader.HasRows)
                        {
                            while (sqlDataReader.Read())
                            {
                                string YourFirstDataBaseTableColumn = sqlDataReader["SomeColumn"].ToString(); // Remember Type Casting is required here it has to be according to database column data type
                                string YourSecondDataBaseTableColumn = sqlDataReader["SomeColumn"].ToString();
                                string YourThridDataBaseTableColumn = sqlDataReader["SomeColumn"].ToString();

                            }
                        }
                        sqlDataReader.Close();
                    }
                    _connection.Close();
</code>```

Title: Read data from SqlDataReader

Body:
I have a SQL Server 2008 database and I am working on it in the backend. I am working on asp.net/C#

SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
   //how do I read strings here????
}

I know that the reader has values. My SQL command is to select just 1 column from a table. The column contains strings ONLY. I want to read the strings (rows) in the reader one by one. How do I do this?

Body:
You have to read database columnhere. You could have a look on following code snippet

                string connectionString = ConfigurationManager.ConnectionStrings["NameOfYourSqlConnectionString"].ConnectionString;
                using (var _connection = new SqlConnection(connectionString))
                {
                    _connection.Open();

                    using (SqlCommand command = new SqlCommand("SELECT SomeColumnName FROM TableName", _connection))
                    {

                        SqlDataReader sqlDataReader = command.ExecuteReader();
                        if (sqlDataReader.HasRows)
                        {
                            while (sqlDataReader.Read())
                            {
                                string YourFirstDataBaseTableColumn = sqlDataReader["SomeColumn"].ToString(); // Remember Type Casting is required here it has to be according to database column data type
                                string YourSecondDataBaseTableColumn = sqlDataReader["SomeColumn"].ToString();
                                string YourThridDataBaseTableColumn = sqlDataReader["SomeColumn"].ToString();

                            }
                        }
                        sqlDataReader.Close();
                    }
                    _connection.Close();


问:
How to fix 'Cannot read property '_wrapper' of undefined' error when using webpack with Vue?
I use axios to get information from DB. I get response from server in array:

My html tags:

Js code looks like this:

```<code>    data() {
        return {
            departments: {
                id: 0,
                name: "name of company",
                nameZod: "name of company dif"
                },
            };
       },
    created() {
        axios
            .get('/SomeController/Departments')
            .then(response => {
                this.departments = response.data;
                console.log(this.departments);
            })
        }
</code>```

I get an error: Cannot read property '_wrapper' of undefined. Its very strange cause I use similar code in other module and it works correctly.

答:
It happened to me too, but with different reason (Vue + Vuetify.
@click function must be attached to btn, not icon like below.</p>

```<code>   <v-btn fab small>
       <v-icon @click="sendMessage">send</v-icon>
   </v-btn>
</code>```

Body:
I use axios to get information from DB. I get response from server in array:

My html tags:

Js code looks like this:

    data() {
        return {
            departments: {
                id: 0,
                name: "name of company",
                nameZod: "name of company dif"
                },
            };
       },
    created() {
        axios
            .get('/SomeController/Departments')
            .then(response => {
                this.departments = response.data;
                console.log(this.departments);
            })
        }

I get an error: Cannot read property '_wrapper' of undefined. Its very strange cause I use similar code in other module and it works correctly.

Body:
It happened to me too, but with different reason (Vue + Vuetify.
@click function must be attached to btn, not icon like below.

   <v-btn fab small>
       <v-icon @click="sendMessage">send</v-icon>
   </v-btn>


问:
"Imported Content Is Empty"
I am trying to link a specific number from a site using the Xpath but it keeps saying the content is empty.

This is the xpath:

```<code>//*[@id="content"]/div[2]/div[2]/div[2]/div/div/div/div/div[2]/table/tbody/tr[2]/td[7]
</code>```

Using formula: importxml

This is what I have input into Google Sheets:

```<code>=IMPORTXML("https://scaletec.locateinv.com/app#/inventory/part/3031/inventory","/html/body/div[4]/div[2]/div/div/div[3]/div/div[2]/div[2]/div[2]/div/div/div/div/div[2]/table/tbody/tr[1]/th[7]")
</code>```

答: Google Sheets does not support scraping of data behind login page, nor JavaScript content therefore this is not possible.</p>

Title: "Imported Content Is Empty"

Body:
I am trying to link a specific number from a site using the Xpath but it keeps saying the content is empty.

This is the xpath:

//*[@id="content"]/div[2]/div[2]/div[2]/div/div/div/div/div[2]/table/tbody/tr[2]/td[7]

Using formula: importxml

This is what I have input into Google Sheets:

=IMPORTXML("https://scaletec.locateinv.com/app#/inventory/part/3031/inventory","/html/body/div[4]/div[2]/div/div/div[3]/div/div[2]/div[2]/div[2]/div/div/div/div/div[2]/table/tbody/tr[1]/th[7]")


问:
Android Studio not detecting my module
I cloned my repo and now Android studio (1.3.1) is having hard time detecting my module 'app'

It is not showing any module in edit configuration(as in image below).

It's already defined in 'Settings.gradle'

```<code>include ':app'
</code>```

I tried importing this app module but it says project already contains module with this name

Tried other solutions too. Stuck here.

Note: This repo doesn't have .iml file of project.

答:
Had a similar issue with Android Studio 3.5.3.

Deleting .iml and local.properties files along with .idea and .gradle folders before reopening the project fixed my issue.

Title: Android Studio not detecting my module

Body:
I cloned my repo and now Android studio (1.3.1) is having hard time detecting my module 'app'

It is not showing any module in edit configuration(as in image below).

It's already defined in 'Settings.gradle'

include ':app'

I tried importing this app module but it says project already contains module with this name

Tried other solutions too. Stuck here.

Note: This repo doesn't have .iml file of project.


问:
Fetch all columns into one column oracle
How do i achieve to fetch all columns into one column.

I have below sample query

```<code>WITH da AS(
SELECT 'a' col1, 'b' col2, 'c' col3 FROM dual UNION ALL
SELECT '1' col1, '2' col1, '3' col1 FROM dual UNION ALL
SELECT 'x' col1, 'y' col1, 'z' col1 FROM dual
)
SELECT * FROM da;

//RESULTS

COL1|COL2|COL3|
----|----|----|
a   |b   |c   |
1   |2   |3   |
x   |y   |z   |
</code>```

But what i want is the result to be as below with | as the delimiter.

```<code>ONE_COL|
-------|
a|b|c  |
1|2|3  |
x|y|z  |
</code>```

My biggest problem is i don't know the column names, therefore i cant do as:

```<code>SELECT  col1||'|'||col2||'|'||col3 AS ONE_COL  FROM da;
</code>```

how can i do this.

答:
The database knows the column names. So use the dbms_sql package and parse your sql.

https://docs.oracle.com/en/database/oracle/oracle-database/19/arpls/DBMS_SQL.html#GUID-C96D5BAA-29A9-4AB5-A69E-E31228ECC9E9

There are many solutions to extract the data afterwards so I don't get your point why you think that you don't know any column names

Body:
How do i achieve to fetch all columns into one column.

I have below sample query

WITH da AS(
SELECT 'a' col1, 'b' col2, 'c' col3 FROM dual UNION ALL
SELECT '1' col1, '2' col1, '3' col1 FROM dual UNION ALL
SELECT 'x' col1, 'y' col1, 'z' col1 FROM dual
)
SELECT * FROM da;

//RESULTS

COL1|COL2|COL3|
----|----|----|
a   |b   |c   |
1   |2   |3   |
x   |y   |z   |

But what i want is the result to be as below with | as the delimiter.

ONE_COL|
-------|
a|b|c  |
1|2|3  |
x|y|z  |

My biggest problem is i don't know the column names, therefore i cant do as:

SELECT  col1||'|'||col2||'|'||col3 AS ONE_COL  FROM da;

how can i do this.


问:
Plot getting bolder after each iteration
So, I am generating plots on the same figure over a given iteration. As I have multiple plots there, I want them to start faded and as the iteration goes further, they get bolder and bolder. It is important to have plots with the same color.

A made up code in case you have any want to try yourself:

```<code>from scipy.stats import norm
import matplotlib.pyplot as plt
import numpy as np

i = np.array([1,1.2,1.4,1.6,1.8,2.0,3.0,4.0,5.0,6.0,7.0])
x = np.arange(-10, 10, .1)

for i in range(0,len(i)):
    rv1 = norm(loc = 0., scale = 1.0*i)
    plt.plot(x,rv1.pdf(x),  color ='b')

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

I want my plot to resemble something like this:

答:
You can do that using the alpha argument to plot, e.g.:

```<code>from scipy.stats import norm
import matplotlib.pyplot as plt
import numpy as np

idx = np.array([1,1.2,1.4,1.6,1.8,2.0,3.0,4.0,5.0,6.0,7.0])
xxx = np.arange(-10, 10, .1)

for i in range(0,len(idx)):
    rv1 = norm(loc = 0., scale = 1.0*i)
    plt.plot(xxx,rv1.pdf(xxx),  color ='b', alpha=i / len(idx))

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

Note that I renamed some variables.

Body:
So, I am generating plots on the same figure over a given iteration. As I have multiple plots there, I want them to start faded and as the iteration goes further, they get bolder and bolder. It is important to have plots with the same color.

A made up code in case you have any want to try yourself:

from scipy.stats import norm
import matplotlib.pyplot as plt
import numpy as np

i = np.array([1,1.2,1.4,1.6,1.8,2.0,3.0,4.0,5.0,6.0,7.0])
x = np.arange(-10, 10, .1)

for i in range(0,len(i)):
    rv1 = norm(loc = 0., scale = 1.0*i)
    plt.plot(x,rv1.pdf(x),  color ='b')

plt.show()

I want my plot to resemble something like this:

Body:
You can do that using the alpha argument to plot, e.g.:

from scipy.stats import norm
import matplotlib.pyplot as plt
import numpy as np

idx = np.array([1,1.2,1.4,1.6,1.8,2.0,3.0,4.0,5.0,6.0,7.0])
xxx = np.arange(-10, 10, .1)

for i in range(0,len(idx)):
    rv1 = norm(loc = 0., scale = 1.0*i)
    plt.plot(xxx,rv1.pdf(xxx),  color ='b', alpha=i / len(idx))

plt.show()

Note that I renamed some variables.


问:
Customize adaptive card in microsoft bot framework
I am working on microsoft bot framework and I need to style the adaptive cards. But I am facing some challenges because in json file, I am unable to get the styling attribute. So, please suggest how I'll do this.</p>

答:
the style of Adaptive Cards is defined by the App the card is shown in. If you are using Bot Framework for like MS Teams, MS Teams defines the look and feel of a card. In the JSON layout you can select color for a button in terms of "Danger" or "Normal" but the actual color is defined by the host.

If you are showing cards in your own app however, you can define the layout by changing the host config. (see here for details : https://learn.microsoft.com/en-us/adaptive-cards/rendering-cards/host-config)

Only the rendering app can change the styling of cards.

Hope that answers your question.


问:
navigateByUrl doesnt work inside a loading service using IONIC4
I'm using ionic loadingCtr in my project,here's the service :

```<code>@Injectable({
providedIn: 'root'
})
export class LoadingServiceService {

  isLoading = false;
  spinner:any;
  constructor(
    public loadingController: LoadingController
  )
  { }

  async showLoading(loadingId: string, loadingMessage: string = 'Loading...') {
    const loading = await this.loadingController.create({
      id: loadingId,
      message: loadingMessage,
      spinner: 'circles'
    });
    return await loading.present();
}

  async dismissLoader(loadingId: string) {
      return await this.loadingController.dismiss(null, null, loadingId).then(() => console.log('loading dismissed'));
  }

}
</code>```

I'm calling this service, when I try to retrieve data from the server :

```<code> submit(value: IUserRegister, isValid: boolean) {

 this.loading2.showLoading('ifOfLoading')

 this.authenticationService.register(value)
 .pipe(first())
 .subscribe(
   data => {
     if (data) {
       console.log('OK.');
       this.loading2.dismissLoader('ifOfLoading')
       this.router.navigateByUrl('/phone-dialog');

     } else {
       console.log('Problem');
       this.loading2.dismissLoader('ifOfLoading')

     }
   },
   err => {
    this.loading2.dismissLoader('ifOfLoading')
     console.log('ERROR :', err);

   }
 );
 }
</code>```

but My problem is, when this code execute, this line: this.router.navigateByUrl('/phone-dialog'); doesnt work, but when I remove the loading service it works , can any one tell me please what is the problem ?

答:
You use async and await function but why ?

Thank to the ionic LoadingController documentation, they don't put async function when creating Popover or Loading Controllers.

Can you give a try without ?

Hope this help :)

Body:
I'm using ionic loadingCtr in my project,here's the service :

@Injectable({
providedIn: 'root'
})
export class LoadingServiceService {

  isLoading = false;
  spinner:any;
  constructor(
    public loadingController: LoadingController
  )
  { }

  async showLoading(loadingId: string, loadingMessage: string = 'Loading...') {
    const loading = await this.loadingController.create({
      id: loadingId,
      message: loadingMessage,
      spinner: 'circles'
    });
    return await loading.present();
}

  async dismissLoader(loadingId: string) {
      return await this.loadingController.dismiss(null, null, loadingId).then(() => console.log('loading dismissed'));
  }

}

I'm calling this service, when I try to retrieve data from the server :

 submit(value: IUserRegister, isValid: boolean) {

 this.loading2.showLoading('ifOfLoading')

 this.authenticationService.register(value)
 .pipe(first())
 .subscribe(
   data => {
     if (data) {
       console.log('OK.');
       this.loading2.dismissLoader('ifOfLoading')
       this.router.navigateByUrl('/phone-dialog');

     } else {
       console.log('Problem');
       this.loading2.dismissLoader('ifOfLoading')

     }
   },
   err => {
    this.loading2.dismissLoader('ifOfLoading')
     console.log('ERROR :', err);

   }
 );
 }

but My problem is, when this code execute, this line: this.router.navigateByUrl('/phone-dialog'); doesnt work, but when I remove the loading service it works , can any one tell me please what is the problem ?


问:
Text exceeding maximum height and width of the container
desktop:

mobile devices:

Hello I have a problem my text is passing my maximum height
I would like my container to follow the height and that my text has maximum width of my container my text

code:

```<code><div className="App">
  <div class="wrapper">
    <div className="text">
      <div class="card-info">
        <div class="card-about">
          <a class="card-tag tag-news">NEWS</a>
          <div class="card-time">6/11/2018</div>
        </div>
      </div>
      <h3 className="textxd">dasssssssssssssssss</h3>
      <p className="textxd">
        aaaaaaaaaaaaa dasuhdasudhu dasuhduashu aaaaaaaaaaaaa dasuhdasudhu
        dasuhduashu aaaaaaaaaaaaa da aaaaaaaaaaaaa dasuhdasudhu dasuhduashu
        aaaaaaaaaaaaa dasuhdasudhu dasuhduashu aaaaaaaaaaaaa dasuhdasudhu
        dasuhduashu aaaaaaaaaaaaa dasuhdasudhu dasuhduashusuhdasudhu
        dasuhduashu aaaaaaaaaaaaa dasuhdasudhu dasuhduashu
      </p>
    </div>
  </div>
</div>
</code>```

css:

```<code>.App {
  padding: 20px;
  font-family: sans-serif;
  text-align: center;
  background: red;
  height: 40vh;
}

.wrapper {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 30vh;
  max-height: 30vh;
  border-radius: 10px;
  cursor: pointer;
  background:blue;

}
.textxd {
  margin-top: 10px;
  margin-bottom: 5px;
}
.text {
  height: 100%;
  max-height: 30vh;
  padding: 0.15rem 1.25rem;
  color: white;
  transition: all 0.3s ease-in;
  ${({ isHover }) =>
    isHover &&
    `
  color:black;
  transition: all 0.3s ease-in;
   `}
}
.card-about {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.75rem 0;
}
.card-tag {
  width: 60px;
  max-width: 100px;
  padding: 0.2rem 0.5rem;
  font-size: 12px;
  text-align: center;
  text-transform: uppercase;
  letter-spacing: 1px;
  background: #ffab00;
  color: #fff;
}
.card-info {
  position: relative;
}
</code>```

I do not know how I could solve this I would need to leave my container and responsive text that my container follows the height of the text or that the text has a maximum height

答:
try This.added max-width to your div .class attribute was also given wrong as className

.App {
  padding: 20px;
  font-family: sans-serif;
  text-align: center;
  background: red;

}

.wrapper {
  display: flex;
  flex-direction: column;
  justify-content: space-between;

  border-radius: 10px;
  cursor: pointer;
  background:blue;

}
.textxd {
  margin-top: 10px;
  margin-bottom: 5px;
}
.text {
 height:auto;
  max-width:100px;

  padding: 0.15rem 1.25rem;
  color: white;
  transition: all 0.3s ease-in;
  ${({ isHover }) =>
    isHover &&
    `
  color:black;
  transition: all 0.3s ease-in;
   `}
}
.card-about {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.75rem 0;
}
.card-tag {
  width: 60px;
  max-width: 100px;
  padding: 0.2rem 0.5rem;
  font-size: 12px;
  text-align: center;
  text-transform: uppercase;
  letter-spacing: 1px;
  background: #ffab00;
  color: #fff;
}
.card-info {
  position: relative;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="App">
  <div class="wrapper">
    <div class="text">
      <div class="card-info">
        <div class="card-about">
          NEWS
          <div class="card-time">6/11/2018</div>
        </div>
      </div>
      <h3 className="textxd">dasssssssssssssssss</h3>
      <p className="textxd">
        aaaaaaaaaaaaa dasuhdasudhu dasuhduashu aaaaaaaaaaaaa dasuhdasudhu
        dasuhduashu aaaaaaaaaaaaa da aaaaaaaaaaaaa dasuhdasudhu dasuhduashu
        aaaaaaaaaaaaa dasuhdasudhu dasuhduashu aaaaaaaaaaaaa dasuhdasudhu
        dasuhduashu aaaaaaaaaaaaa dasuhdasudhu dasuhduashusuhdasudhu
        dasuhduashu aaaaaaaaaaaaa dasuhdasudhu dasuhduashu
      </p>
    </div>
  </div>
</div></code>```

Body:
desktop:

mobile devices:

Hello I have a problem my text is passing my maximum height
I would like my container to follow the height and that my text has maximum width of my container my text

code:

          NEWS

6/11/2018

dasssssssssssssssss

        aaaaaaaaaaaaa dasuhdasudhu dasuhduashu aaaaaaaaaaaaa dasuhdasudhu
        dasuhduashu aaaaaaaaaaaaa da aaaaaaaaaaaaa dasuhdasudhu dasuhduashu
        aaaaaaaaaaaaa dasuhdasudhu dasuhduashu aaaaaaaaaaaaa dasuhdasudhu
        dasuhduashu aaaaaaaaaaaaa dasuhdasudhu dasuhduashusuhdasudhu
        dasuhduashu aaaaaaaaaaaaa dasuhdasudhu dasuhduashu

css:

.App {
  padding: 20px;
  font-family: sans-serif;
  text-align: center;
  background: red;
  height: 40vh;
}

.wrapper {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 30vh;
  max-height: 30vh;
  border-radius: 10px;
  cursor: pointer;
  background:blue;

}
.textxd {
  margin-top: 10px;
  margin-bottom: 5px;
}
.text {
  height: 100%;
  max-height: 30vh;
  padding: 0.15rem 1.25rem;
  color: white;
  transition: all 0.3s ease-in;
  ${({ isHover }) =>
    isHover &&
    `
  color:black;
  transition: all 0.3s ease-in;
   `}
}
.card-about {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.75rem 0;
}
.card-tag {
  width: 60px;
  max-width: 100px;
  padding: 0.2rem 0.5rem;
  font-size: 12px;
  text-align: center;
  text-transform: uppercase;
  letter-spacing: 1px;
  background: #ffab00;
  color: #fff;
}
.card-info {
  position: relative;
}

I do not know how I could solve this I would need to leave my container and responsive text that my container follows the height of the text or that the text has a maximum height

Body:
try This.added max-width to your div .class attribute was also given wrong as className

.App {
  padding: 20px;
  font-family: sans-serif;
  text-align: center;
  background: red;

}

.wrapper {
  display: flex;
  flex-direction: column;
  justify-content: space-between;

  border-radius: 10px;
  cursor: pointer;
  background:blue;

}
.textxd {
  margin-top: 10px;
  margin-bottom: 5px;
}
.text {
 height:auto;
  max-width:100px;

  padding: 0.15rem 1.25rem;
  color: white;
  transition: all 0.3s ease-in;
  ${({ isHover }) =>
    isHover &&
    `
  color:black;
  transition: all 0.3s ease-in;
   `}
}
.card-about {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.75rem 0;
}
.card-tag {
  width: 60px;
  max-width: 100px;
  padding: 0.2rem 0.5rem;
  font-size: 12px;
  text-align: center;
  text-transform: uppercase;
  letter-spacing: 1px;
  background: #ffab00;
  color: #fff;
}
.card-info {
  position: relative;
}

<div class="App">
  <div class="wrapper">
    <div class="text">
      <div class="card-info">
        <div class="card-about">
          <a class="card-tag tag-news">NEWS</a>
          <div class="card-time">6/11/2018</div>
        </div>
      </div>
      <h3 className="textxd">dasssssssssssssssss</h3>
      <p className="textxd">
        aaaaaaaaaaaaa dasuhdasudhu dasuhduashu aaaaaaaaaaaaa dasuhdasudhu
        dasuhduashu aaaaaaaaaaaaa da aaaaaaaaaaaaa dasuhdasudhu dasuhduashu
        aaaaaaaaaaaaa dasuhdasudhu dasuhduashu aaaaaaaaaaaaa dasuhdasudhu
        dasuhduashu aaaaaaaaaaaaa dasuhdasudhu dasuhduashusuhdasudhu
        dasuhduashu aaaaaaaaaaaaa dasuhdasudhu dasuhduashu
      </p>
    </div>
  </div>
</div>


问:
filter show not the correct list after he did the filtering
I have edited my Adapter class and extended the filterable class. My search functionality works but i am unable to get the currect list.

here is my adapter class:

```<code>public class ListViewAdapter extends BaseAdapter implements Filterable{
Context context;
private List<Student> studentList;
private List<Student> orginStudentList;

public ListViewAdapter(Context context,List<Student> studentList)
{
    this.studentList = new ArrayList<>();
    this.studentList = studentList;
    this.orginStudentList = studentList;
    this.context = context;
}
@Override
public Filter getFilter() {
    if(nameFilter == null)
        nameFilter = new NameFilter();
    return nameFilter;
}
public void resetData() {
    studentList = orginStudentList;
}
private class NameFilter extends Filter {
    @Override
    protected FilterResults performFiltering(CharSequence constraint) {
        FilterResults results = new FilterResults();
        // We implement here the filter logic
        if ((constraint == null) || (constraint.length() == 0)) {
            // No filter implemented we return all the list
            results.values = orginStudentList;
            results.count = orginStudentList.size();
        }else if (Character.isDigit(constraint.charAt(constraint.length()-1))){
            results.values = studentList;
            results.count = studentList.size();
        }
        else {
            // We perform filtering operation
            List<Student> nStudentList = new ArrayList<Student>();
            for (Student stu : orginStudentList) {
                String name = stu.getName();
                if (name.contains(constraint))
                    nStudentList.add(stu);
            }
            results.values = nStudentList;
            results.count = nStudentList.size();
        }
        return results;
    }
    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {
        studentList = (List<Student>)results.values;
        notifyDataSetChanged();
    }
}
</code>```

}
I do check if the results are zero or null and if so to return the currect list? What am I missing?

答: add notifyDataSetChanged(); inside adapter</p>

Body:
I have edited my Adapter class and extended the filterable class. My search functionality works but i am unable to get the currect list.

here is my adapter class:

public class ListViewAdapter extends BaseAdapter implements Filterable{
Context context;
private List<Student> studentList;
private List<Student> orginStudentList;

public ListViewAdapter(Context context,List<Student> studentList)
{
    this.studentList = new ArrayList<>();
    this.studentList = studentList;
    this.orginStudentList = studentList;
    this.context = context;
}
@Override
public Filter getFilter() {
    if(nameFilter == null)
        nameFilter = new NameFilter();
    return nameFilter;
}
public void resetData() {
    studentList = orginStudentList;
}
private class NameFilter extends Filter {
    @Override
    protected FilterResults performFiltering(CharSequence constraint) {
        FilterResults results = new FilterResults();
        // We implement here the filter logic
        if ((constraint == null) || (constraint.length() == 0)) {
            // No filter implemented we return all the list
            results.values = orginStudentList;
            results.count = orginStudentList.size();
        }else if (Character.isDigit(constraint.charAt(constraint.length()-1))){
            results.values = studentList;
            results.count = studentList.size();
        }
        else {
            // We perform filtering operation
            List<Student> nStudentList = new ArrayList<Student>();
            for (Student stu : orginStudentList) {
                String name = stu.getName();
                if (name.contains(constraint))
                    nStudentList.add(stu);
            }
            results.values = nStudentList;
            results.count = nStudentList.size();
        }
        return results;
    }
    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {
        studentList = (List<Student>)results.values;
        notifyDataSetChanged();
    }
}

}
I do check if the results are zero or null and if so to return the currect list? What am I missing?


问:
Hibernate search across two entities without an embedded index
I am trying to use Hibernate Search 6 and elastic search
A simple example of what I am trying to build is as follows.

I have a Book entity, which has information like title, authorName, genre, price

I have a Shop entity which has information like shopName, phone, email, location

I have a "joining table" which does a many to many mapping between nooks and shops. ( A book can be at many shops, and a shop can have many books)

I am trying to do a search by name and location, ideally to find a book at a location nearest to the input. The standard book-author example in the documentation requires a IndexedEmbedded annotation, which is not really possible in my case because I am using a joining table.
Is there an alternative approach to solve this problem

答:
My entities   </p>

```<code>    @Indexed
    public class Book extends PanacheEntity{
      public String title;
      public String authorName;
    @OneToMany(mappedBy = "book", fetch = FetchType.LAZY, cascade = { CascadeType.REMOVE })
      public List<BookShopRelation> bookShopRelation = new ArrayList<>();
    }

    @Indexed
    public class Shop extends PanacheEntity{
      public String name;
      public String city;
      @OneToMany(mappedBy = "shop", fetch = FetchType.LAZY, cascade = { CascadeType.REMOVE })
      private List<BookShopRelation> bookShopRelation = new ArrayList<>();
    }

    @Indexed
    public class BookShopRelation extends PanacheEntity{
    @JoinColumn(name = "shop_id")
        @ManyToOne(fetch = FetchType.EAGER, optional = false)
        @IndexedEmbedded
        private Shop shop;

        @JoinColumn(name = "offer_id")
        @ManyToOne(fetch = FetchType.EAGER, optional = false)
        @IndexedEmbedded
        private Book book;
    }
</code>```

<p>For me what was key was to understand, was that the relation table could be indexed and used as the basis for the search  </p>

```<code> List<BookShopRelation> result = Search.session(entityManager)
                .search(BookShopRelation.class) .predicate(f ->
                        pattern == null || pattern.trim().isEmpty() ?
                                f.matchAll() :
                                f.simpleQueryString()
                                    .fields("book.title").matching(pattern)
                    )
                    .fetchHits(size.orElse(20));
</code>```

Body:
My entities

    @Indexed
    public class Book extends PanacheEntity{
      public String title;
      public String authorName;
    @OneToMany(mappedBy = "book", fetch = FetchType.LAZY, cascade = { CascadeType.REMOVE })
      public List<BookShopRelation> bookShopRelation = new ArrayList<>();
    }

    @Indexed
    public class Shop extends PanacheEntity{
      public String name;
      public String city;
      @OneToMany(mappedBy = "shop", fetch = FetchType.LAZY, cascade = { CascadeType.REMOVE })
      private List<BookShopRelation> bookShopRelation = new ArrayList<>();
    }

    @Indexed
    public class BookShopRelation extends PanacheEntity{
    @JoinColumn(name = "shop_id")
        @ManyToOne(fetch = FetchType.EAGER, optional = false)
        @IndexedEmbedded
        private Shop shop;

        @JoinColumn(name = "offer_id")
        @ManyToOne(fetch = FetchType.EAGER, optional = false)
        @IndexedEmbedded
        private Book book;
    }

For me what was key was to understand, was that the relation table could be indexed and used as the basis for the search

 List<BookShopRelation> result = Search.session(entityManager)
                .search(BookShopRelation.class) .predicate(f ->
                        pattern == null || pattern.trim().isEmpty() ?
                                f.matchAll() :
                                f.simpleQueryString()
                                    .fields("book.title").matching(pattern)
                    )
                    .fetchHits(size.orElse(20));


问:
View.draw(canvas) leaves gray border around circular png set in ImageView
I have an ImageView whose src is being set to a transparent square png with rounded corners.

I am calling View.draw(canvas) on the ImageView to take a screenshot. It leaves a gray border around the rounded corners like the image in the link

What can I do to remove the gray border?

Here is what I have tried..

```<code>        Bitmap viewBmp = Bitmap.createBitmap(wid, hgt, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(viewBmp);
        if(isToMakeTransperant) canvas.drawColor(Color.TRANSPARENT);
        myView.draw(canvas);
</code>```

I have already tried setting PorterDuff.Mode.CLEAR in drawColor() method. It didn't work.

edit : yes, the isToMakeTransperant boolean is always true. I have hard coded it to true for testing.

答:
you can create transition bitmap</p>

```<code>Bipmap bimap = Bitmap.createBitmap(BitmaoFactory.decodeResource(context.getResources(), R.color.transtion), 0, 0, width, height);
</code>```

Body:
I have an ImageView whose src is being set to a transparent square png with rounded corners.

I am calling View.draw(canvas) on the ImageView to take a screenshot. It leaves a gray border around the rounded corners like the image in the link

What can I do to remove the gray border?

Here is what I have tried..

        Bitmap viewBmp = Bitmap.createBitmap(wid, hgt, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(viewBmp);
        if(isToMakeTransperant) canvas.drawColor(Color.TRANSPARENT);
        myView.draw(canvas);

I have already tried setting PorterDuff.Mode.CLEAR in drawColor() method. It didn't work.

edit : yes, the isToMakeTransperant boolean is always true. I have hard coded it to true for testing.

Body:
you can create transition bitmap

Bipmap bimap = Bitmap.createBitmap(BitmaoFactory.decodeResource(context.getResources(), R.color.transtion), 0, 0, width, height);


问:
Set Drive VolumeLabel
I am working on a small utility where I would like to change the volume label on flash drives that are connected to the computer. I know that DriveInfo is capable of doing it but I am at a loss as for how to accomplish it. If anyone has a code sample I would really appreciate it.

Here is what i currently have:

```<code>DriveInfo[] allDrives = DriveInfo.GetDrives();
foreach (DriveInfo d in allDrives)
{
    if (d.IsReady && d.DriveType == DriveType.Removable)
    {
        //set volume label here
    }
}
</code>```

答:
Thanks James! I don't know why I had so many issues with this but you got me going down the right path.

Here is the final code to set the drive label. For anyone else that uses this, it will change the name of ANY removable drive that is attached to the system. If you need to only change the names of specific drive models you can use WMI's Win32_DiskDrive to narrow it down.

```<code>public void SetVolumeLabel(string newLabel)
{
    DriveInfo[] allDrives = DriveInfo.GetDrives();
    foreach (DriveInfo d in allDrives)
    {
        if (d.IsReady && d.DriveType == DriveType.Removable)
        {
            d.VolumeLabel = newLabel;
        }
    }
}

public string VolumeLabel { get; set; }

// Setting the drive name
private void button1_Click(object sender, EventArgs e)
{
    SetVolumeLabel("FlashDrive");
}
</code>```

Title: Set Drive VolumeLabel

Body:
I am working on a small utility where I would like to change the volume label on flash drives that are connected to the computer. I know that DriveInfo is capable of doing it but I am at a loss as for how to accomplish it. If anyone has a code sample I would really appreciate it.

Here is what i currently have:

DriveInfo[] allDrives = DriveInfo.GetDrives();
foreach (DriveInfo d in allDrives)
{
    if (d.IsReady && d.DriveType == DriveType.Removable)
    {
        //set volume label here
    }
}

Body:
Thanks James! I don't know why I had so many issues with this but you got me going down the right path.

Here is the final code to set the drive label. For anyone else that uses this, it will change the name of ANY removable drive that is attached to the system. If you need to only change the names of specific drive models you can use WMI's Win32_DiskDrive to narrow it down.

public void SetVolumeLabel(string newLabel)
{
    DriveInfo[] allDrives = DriveInfo.GetDrives();
    foreach (DriveInfo d in allDrives)
    {
        if (d.IsReady && d.DriveType == DriveType.Removable)
        {
            d.VolumeLabel = newLabel;
        }
    }
}

public string VolumeLabel { get; set; }

// Setting the drive name
private void button1_Click(object sender, EventArgs e)
{
    SetVolumeLabel("FlashDrive");
}


问:
Full image html in website
I want to ask. How can i make full image for the header like the image in html? could someone please give me some reference about creating that thing? Thanks.

答:
```<code>.class{
background-image: url('img/background.jpg') no-repeat;
background-attachment: fixed;
background-size:cover;
height: 100vh;
}
</code>```

Title: Full image html in website


问:
React Native: Exporting a function from a functional component
Issue:

I'm trying to figure out how to export a function that is called "addPostCode" from the functional component "ContractHandler".

I want to use "addPostCode" in an other functional component called "RentalDetailScreen" so that when I navigate to the next page it will trigger the "addPostCode" and store the state of "postCode" in "ContractHandler".

This is the "ContractHandler.js":

```<code>import React, { useState } from 'react';

const ContractHandler = () => {

  const [postCode, setPostCode] = useState();

  const addPostCode = (data) => {
    setPostCode(data)
    console.log(postCode)
  };

  return(
    <View>
      <Text></Text>
    </View>
  )

}

export default ContractHandler;
</code>```

These are parts of the RentalDetailScreen.js where I navigate to the next page and want to trigger the "addPostCode"-function and send the "postCode"-value to the "ContractHandler.js".

This is the import:

```<code>import { addPostCode } from '../../database/ContractHandler';
</code>```

This is the navigation with the "addPostCode"-function.

```<code><TouchableOpacity onPress={() => { navigation.navigate('SecurityDetail'); addPostCode(postCode); }}>
  <View style={slider.buttonStyle}>
    <Text style={slider.textStyle}>Neste</Text>
    <Ionicons name='ios-arrow-forward'style={slider.iconStyle} />
  </View>
</TouchableOpacity>
</code>```

"postCode" is just a variable that is given a value from a TextInput.

If I'm not being clear enough please let me know and I will try to explain better :)

答: The components' own state cannot be set from outside (technically you can solve it but this is not the right way). If you wanna share state between components, use global state manager (redux) or Context or if the components are siblings, just use their common parent to store the state.

Body:
Issue:

I'm trying to figure out how to export a function that is called "addPostCode" from the functional component "ContractHandler".

I want to use "addPostCode" in an other functional component called "RentalDetailScreen" so that when I navigate to the next page it will trigger the "addPostCode" and store the state of "postCode" in "ContractHandler".

This is the "ContractHandler.js":

import React, { useState } from 'react';

const ContractHandler = () => {

  const [postCode, setPostCode] = useState();

  const addPostCode = (data) => {
    setPostCode(data)
    console.log(postCode)
  };

  return(
    <View>
      <Text></Text>
    </View>
  )

}

export default ContractHandler;

These are parts of the RentalDetailScreen.js where I navigate to the next page and want to trigger the "addPostCode"-function and send the "postCode"-value to the "ContractHandler.js".

This is the import:

import { addPostCode } from '../../database/ContractHandler';

This is the navigation with the "addPostCode"-function.

<TouchableOpacity onPress={() => { navigation.navigate('SecurityDetail'); addPostCode(postCode); }}>
  <View style={slider.buttonStyle}>
    <Text style={slider.textStyle}>Neste</Text>
    <Ionicons name='ios-arrow-forward'style={slider.iconStyle} />
  </View>
</TouchableOpacity>

"postCode" is just a variable that is given a value from a TextInput.

If I'm not being clear enough please let me know and I will try to explain better :)


答:
You can use a variable line width and the transparency parameter, alpha as following. Start with some initial values and then increase the line thickness by 20% (for example) and decrease the alpha by 10%

P.S: I read the comment of IOBE and added it to my for loop for readers. Don't call the iterator variable and the array by the same name i. I have now used ii in the for loop

```<code>wid = 0.8
alpha=0.9

for ii in range(0,len(i)):
    rv1 = norm(loc = 0., scale = 1.0*ii)
    plt.plot(x,rv1.pdf(x),  color ='b', lw=wid, alpha=alpha)
    wid *= 1.2
    alpha *= 0.9
</code>```

Title: Plot getting bolder after each iteration

Body:
You can use a variable line width and the transparency parameter, alpha as following. Start with some initial values and then increase the line thickness by 20% (for example) and decrease the alpha by 10%

P.S: I read the comment of IOBE and added it to my for loop for readers. Don't call the iterator variable and the array by the same name i. I have now used ii in the for loop

wid = 0.8
alpha=0.9

for ii in range(0,len(i)):
    rv1 = norm(loc = 0., scale = 1.0*ii)
    plt.plot(x,rv1.pdf(x),  color ='b', lw=wid, alpha=alpha)
    wid *= 1.2
    alpha *= 0.9