问:
NoNodeAvailableException: No node was available to execute the query
I am not using Elasticssearch. I am trying to perform some database operations in cassandra using CQL. I am using threads. While running the code I am always getting the exception in thread after a while : com.datastax.oss.driver.api.core.NoNodeAvailableException: No node was available to execute the query.

I have tested with even one thread. The error is still there. Here is my code :

```<code>InetAddress addrOne = InetAddress.getByName("52.15.195.41");
InetSocketAddress addrSocOne = new InetSocketAddress(addrOne,9042);
CqlSession sessionOne = CqlSession.builder().addContactPoint(addrSocOne).withLocalDatacenter("us-east-2").withKeyspace("test").build();

while(counter <= 100)
{
    String query = "select max(id) FROM samplequeue";
    ResultSet rs = session.execute(query);
    for (Row row : rs)
    {
        int exS = row.getInt("system.max(id)");
    }
    counter++;
    Thread.sleep(50);
}
</code>```

This is a very simple, modified example just to demonstrate the problem. I am unable to resolve it. All the threads are exiting giving the same exception. I am running cassandra 3.11.4 on AWS. All my nodes are up and running and I can perform operations finely in the backend.

答:
You can execute nodetool status in cassandra and you will obtain the name of the Datacenter. That is the value that you must put in withLocalDatacenter method:

```<code>/opt/apache-cassandra-3.11.2/bin$ ./nodetool status
Datacenter: **dc1**
===============
Status=Up/Down
|/ State=Normal/Leaving/Joining/Moving
--  Address         Load       Tokens       Owns (effective)  Host ID    Rack
</code>```

Body:
I am not using Elasticssearch. I am trying to perform some database operations in cassandra using CQL. I am using threads. While running the code I am always getting the exception in thread after a while : com.datastax.oss.driver.api.core.NoNodeAvailableException: No node was available to execute the query.

I have tested with even one thread. The error is still there. Here is my code :

InetAddress addrOne = InetAddress.getByName("52.15.195.41");
InetSocketAddress addrSocOne = new InetSocketAddress(addrOne,9042);
CqlSession sessionOne = CqlSession.builder().addContactPoint(addrSocOne).withLocalDatacenter("us-east-2").withKeyspace("test").build();

while(counter <= 100)
{
    String query = "select max(id) FROM samplequeue";
    ResultSet rs = session.execute(query);
    for (Row row : rs)
    {
        int exS = row.getInt("system.max(id)");
    }
    counter++;
    Thread.sleep(50);
}

This is a very simple, modified example just to demonstrate the problem. I am unable to resolve it. All the threads are exiting giving the same exception. I am running cassandra 3.11.4 on AWS. All my nodes are up and running and I can perform operations finely in the backend.

Body:
You can execute nodetool status in cassandra and you will obtain the name of the Datacenter. That is the value that you must put in withLocalDatacenter method:

/opt/apache-cassandra-3.11.2/bin$ ./nodetool status
Datacenter: **dc1**
===============
Status=Up/Down
|/ State=Normal/Leaving/Joining/Moving
--  Address         Load       Tokens       Owns (effective)  Host ID    Rack


来源: stackexchange

问:
Kotlin - Scroll Detection issue in Recyclerview
Using below code to check that whether RecyclerView reached to bottom or not..

Means Checking that last item of the Recyclerview is visible or not..

For that I have googled and added Scroll listener in Recyclerview.

Using below code:

```<code>MyRecyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
       override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
           super.onScrollStateChanged(recyclerView, newState)
       }

       override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
           super.onScrolled(recyclerView, dx, dy)
           if (!MyRecyclerView.canScrollVertically(1)) {
               Toast.makeText(mContext, "Last", Toast.LENGTH_LONG).show();
           }
       }
   })
</code>```

Here, I am trying to check that Recyclerview reached to bottom or not.

Toast is not displaying when I scroll recyclerview to the bottom.

But, Toast displayed suddenly when items in the recyclerview binds first time. It should toast only when user scroll up to the bottom of the Recyclerview.

What might be the issue ?
Please guide. Thanks.

答:
I think, using RecyclerView.LayoutManager api will better suit your needs.
You can check LinearLayoutManager::findLastCompletelyVisibleItemPosition or findLastVisibleItemPosition method in your RecyclerView.OnScrollListener

ContentLicense: CC BY-SA 4.0

Body:
Using below code to check that whether RecyclerView reached to bottom or not..

Means Checking that last item of the Recyclerview is visible or not..

For that I have googled and added Scroll listener in Recyclerview.

Using below code:

MyRecyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
       override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
           super.onScrollStateChanged(recyclerView, newState)
       }

       override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
           super.onScrolled(recyclerView, dx, dy)
           if (!MyRecyclerView.canScrollVertically(1)) {
               Toast.makeText(mContext, "Last", Toast.LENGTH_LONG).show();
           }
       }
   })

Here, I am trying to check that Recyclerview reached to bottom or not.

Toast is not displaying when I scroll recyclerview to the bottom.

But, Toast displayed suddenly when items in the recyclerview binds first time. It should toast only when user scroll up to the bottom of the Recyclerview.

What might be the issue ?
Please guide. Thanks.


问:
Kubernates cluster instance
I have created a Kubernetes cluster and one of instance in the cluster is inactive
I want to review the configured Kubernetes Engine cluster of an inactive configuration by which command should I check?
Should I use this "kubectl config get-contexts"?
or
kubectl config use-context and kubectl config view?

Am beginner to cloud please anyone explains?

答:
You can use the below command to get list of all the nodes in GKE cluster:

kubectl get nodes -o wide

Once you have the list of nodes, you can describe the node to get the events"

kubectl describe node <Node-Name>

Based on the events you can debug the node.

Title: Kubernates cluster instance


问:
Assign AWK result to variable
This should be pretty straightfoward and I don't know why I am struggling with it.

I am running the following psql command from within a shell script in order to find out whether all indexes have been dropped before inserting data.

```<code>INDEXCOUNT=$(psql -p $dbPort -U enterprisedb -d main_db -c "select Count(*) from all_indexes where index_schema = 'enterprisedb';")
</code>```

At this point, INDEXCOUNT is equal to “COUNT ------- 0”

Now if I echo the following line I get the result I want -

```<code>echo $INDEXCOUNT | awk '{print $3}'
</code>```

How do I assign the value of $INDEXCOUNT | awk ‘{print $3}’ to a variable to check it in an “IF” statement?

For example:

```<code>RETURNCOUNT=$INDEXCOUNT | awk '{print $3}'
</code>```

答:
You can try this:

```<code>RETURNCOUNT=`echo $INDEXCOUNT | awk '{print $3}'`
</code>```

The idea is to include any shell command between backticks to get the result into a variable.

ContentLicense: CC BY-SA 3.0

Title: Assign AWK result to variable

Body:
This should be pretty straightfoward and I don't know why I am struggling with it.

I am running the following psql command from within a shell script in order to find out whether all indexes have been dropped before inserting data.

INDEXCOUNT=$(psql -p $dbPort -U enterprisedb -d main_db -c "select Count(*) from all_indexes where index_schema = 'enterprisedb';")

At this point, INDEXCOUNT is equal to “COUNT ------- 0”

Now if I echo the following line I get the result I want -

echo $INDEXCOUNT | awk '{print $3}'

How do I assign the value of $INDEXCOUNT | awk ‘{print $3}’ to a variable to check it in an “IF” statement?

For example:

RETURNCOUNT=$INDEXCOUNT | awk '{print $3}'

Body:
You can try this:

RETURNCOUNT=`echo $INDEXCOUNT | awk '{print $3}'`

The idea is to include any shell command between backticks to get the result into a variable.


问:
pyttsx3 initialization error, can't use pyttsx3
I was having some problems when using the .getproperty('voices') attribute in pyttsx3. So I decided to uninstall it and then re-install it using PIP to see if that may fix the problem.

Previous link to when I had the .getproperty('voices') error: Why do I get an error with pyttsx3 when I try to access the properties of the voice?

Now, when I installed it again using PIP, I can't even initialize it

```<code>import pyttsx3
engine = pyttsx3.init()
</code>```

It gives this error:

```<code>Traceback (most recent call last):
  File "C:\Users\saife\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pyttsx3\__init__.py", line 20, in init
    eng = _activeEngines[driverName]
  File "C:\Users\saife\AppData\Local\Programs\Python\Python38-32\lib\weakref.py", line 131, in __getitem__
    o = self.data[key]()
KeyError: None

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\saife\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pyttsx3\drivers\sapi5.py", line 3, in <module>
    from comtypes.gen import SpeechLib  # comtypes
ImportError: cannot import name 'SpeechLib' from 'comtypes.gen' (C:\Users\saife\AppData\Local\Programs\Python\Python38-32\lib\site-packages\comtypes\gen\__init__.py)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\saife\AppData\Local\Programs\Python\Python38-32\lib\ctypes\__init__.py", line 123, in WINFUNCTYPE
    return _win_functype_cache[(restype, argtypes, flags)]
KeyError: (<class 'ctypes.HRESULT'>, (<class 'comtypes.automation.tagVARIANT'>, <class 'comtypes.LP_POINTER(ISpeechRecoGrammar)'>), 0)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    engine = pyttsx3.init()
  File "C:\Users\saife\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pyttsx3\__init__.py", line 22, in init
    eng = Engine(driverName, debug)
  File "C:\Users\saife\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pyttsx3\engine.py", line 30, in __init__
    self.proxy = driver.DriverProxy(weakref.proxy(self), driverName, debug)
  File "C:\Users\saife\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pyttsx3\driver.py", line 50, in __init__
    self._module = importlib.import_module(name)
  File "C:\Users\saife\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 783, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "C:\Users\saife\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pyttsx3\drivers\sapi5.py", line 6, in <module>
    engine = comtypes.client.CreateObject("SAPI.SpVoice")
  File "C:\Users\saife\AppData\Local\Programs\Python\Python38-32\lib\site-packages\comtypes\client\__init__.py", line 250, in CreateObject
    return _manage(obj, clsid, interface=interface)
  File "C:\Users\saife\AppData\Local\Programs\Python\Python38-32\lib\site-packages\comtypes\client\__init__.py", line 188, in _manage
    obj = GetBestInterface(obj)
  File "C:\Users\saife\AppData\Local\Programs\Python\Python38-32\lib\site-packages\comtypes\client\__init__.py", line 110, in GetBestInterface
    mod = GetModule(tlib)
  File "C:\Users\saife\AppData\Local\Programs\Python\Python38-32\lib\site-packages\comtypes\client\_generate.py", line 110, in GetModule
    mod = _CreateWrapper(tlib, pathname)
  File "C:\Users\saife\AppData\Local\Programs\Python\Python38-32\lib\site-packages\comtypes\client\_generate.py", line 184, in _CreateWrapper
    mod = _my_import(fullname)
  File "C:\Users\saife\AppData\Local\Programs\Python\Python38-32\lib\site-packages\comtypes\client\_generate.py", line 24, in _my_import
    return __import__(fullname, globals(), locals(), ['DUMMY'])
  File "C:\Users\saife\AppData\Local\Programs\Python\Python38-32\lib\site-packages\comtypes\gen\_C866CA3A_32F7_11D2_9602_00C04F8EE628_0_5_4.py", line 455, in <module>
    ISpeechRecoContext._methods_ = [
  File "C:\Users\saife\AppData\Local\Programs\Python\Python38-32\lib\site-packages\comtypes\__init__.py", line 329, in __setattr__
    self._make_methods(value)
  File "C:\Users\saife\AppData\Local\Programs\Python\Python38-32\lib\site-packages\comtypes\__init__.py", line 698, in _make_methods
    prototype = WINFUNCTYPE(restype, *argtypes)
  File "C:\Users\saife\AppData\Local\Programs\Python\Python38-32\lib\ctypes\__init__.py", line 125, in WINFUNCTYPE
    class WinFunctionType(_CFuncPtr):
TypeError: item 1 in _argtypes_ passes a union by value, which is unsupported.
</code>```

答:
I hope you are trying to install pyttsx3 from https://pypi.org/project/pyttsx3/.

were you able to execute pip install pyttsx3 with out any issues?
Are you trying to run the above code from jupyter?
if yes then, please don't run the complete code at a time i.e the below code

```<code>import pyttsx3
engine = pyttsx3.init()
engine.say("I will speak this text")
engine.runAndWait()
</code>```

first run import pyttsx3 alone and thern try to put up your code one by one.
I have faced similar issue earlier many times while running it on diferent systems.
I don't know why this issue shows up but the above steps will surely do resolve the issue.

Body:
I was having some problems when using the .getproperty('voices') attribute in pyttsx3. So I decided to uninstall it and then re-install it using PIP to see if that may fix the problem.

Previous link to when I had the .getproperty('voices') error: Why do I get an error with pyttsx3 when I try to access the properties of the voice?

Now, when I installed it again using PIP, I can't even initialize it

import pyttsx3
engine = pyttsx3.init()

It gives this error:

Traceback (most recent call last):
  File "C:\Users\saife\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pyttsx3\__init__.py", line 20, in init
    eng = _activeEngines[driverName]
  File "C:\Users\saife\AppData\Local\Programs\Python\Python38-32\lib\weakref.py", line 131, in __getitem__
    o = self.data[key]()
KeyError: None

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\saife\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pyttsx3\drivers\sapi5.py", line 3, in <module>
    from comtypes.gen import SpeechLib  # comtypes
ImportError: cannot import name 'SpeechLib' from 'comtypes.gen' (C:\Users\saife\AppData\Local\Programs\Python\Python38-32\lib\site-packages\comtypes\gen\__init__.py)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\saife\AppData\Local\Programs\Python\Python38-32\lib\ctypes\__init__.py", line 123, in WINFUNCTYPE
    return _win_functype_cache[(restype, argtypes, flags)]
KeyError: (<class 'ctypes.HRESULT'>, (<class 'comtypes.automation.tagVARIANT'>, <class 'comtypes.LP_POINTER(ISpeechRecoGrammar)'>), 0)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    engine = pyttsx3.init()
  File "C:\Users\saife\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pyttsx3\__init__.py", line 22, in init
    eng = Engine(driverName, debug)
  File "C:\Users\saife\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pyttsx3\engine.py", line 30, in __init__
    self.proxy = driver.DriverProxy(weakref.proxy(self), driverName, debug)
  File "C:\Users\saife\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pyttsx3\driver.py", line 50, in __init__
    self._module = importlib.import_module(name)
  File "C:\Users\saife\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 783, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "C:\Users\saife\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pyttsx3\drivers\sapi5.py", line 6, in <module>
    engine = comtypes.client.CreateObject("SAPI.SpVoice")
  File "C:\Users\saife\AppData\Local\Programs\Python\Python38-32\lib\site-packages\comtypes\client\__init__.py", line 250, in CreateObject
    return _manage(obj, clsid, interface=interface)
  File "C:\Users\saife\AppData\Local\Programs\Python\Python38-32\lib\site-packages\comtypes\client\__init__.py", line 188, in _manage
    obj = GetBestInterface(obj)
  File "C:\Users\saife\AppData\Local\Programs\Python\Python38-32\lib\site-packages\comtypes\client\__init__.py", line 110, in GetBestInterface
    mod = GetModule(tlib)
  File "C:\Users\saife\AppData\Local\Programs\Python\Python38-32\lib\site-packages\comtypes\client\_generate.py", line 110, in GetModule
    mod = _CreateWrapper(tlib, pathname)
  File "C:\Users\saife\AppData\Local\Programs\Python\Python38-32\lib\site-packages\comtypes\client\_generate.py", line 184, in _CreateWrapper
    mod = _my_import(fullname)
  File "C:\Users\saife\AppData\Local\Programs\Python\Python38-32\lib\site-packages\comtypes\client\_generate.py", line 24, in _my_import
    return __import__(fullname, globals(), locals(), ['DUMMY'])
  File "C:\Users\saife\AppData\Local\Programs\Python\Python38-32\lib\site-packages\comtypes\gen\_C866CA3A_32F7_11D2_9602_00C04F8EE628_0_5_4.py", line 455, in <module>
    ISpeechRecoContext._methods_ = [
  File "C:\Users\saife\AppData\Local\Programs\Python\Python38-32\lib\site-packages\comtypes\__init__.py", line 329, in __setattr__
    self._make_methods(value)
  File "C:\Users\saife\AppData\Local\Programs\Python\Python38-32\lib\site-packages\comtypes\__init__.py", line 698, in _make_methods
    prototype = WINFUNCTYPE(restype, *argtypes)
  File "C:\Users\saife\AppData\Local\Programs\Python\Python38-32\lib\ctypes\__init__.py", line 125, in WINFUNCTYPE
    class WinFunctionType(_CFuncPtr):
TypeError: item 1 in _argtypes_ passes a union by value, which is unsupported.

Body:
I hope you are trying to install pyttsx3 from https://pypi.org/project/pyttsx3/.

were you able to execute pip install pyttsx3 with out any issues?
Are you trying to run the above code from jupyter?
if yes then, please don't run the complete code at a time i.e the below code

import pyttsx3
engine = pyttsx3.init()
engine.say("I will speak this text")
engine.runAndWait()

first run import pyttsx3 alone and thern try to put up your code one by one.
I have faced similar issue earlier many times while running it on diferent systems.
I don't know why this issue shows up but the above steps will surely do resolve the issue.


问:
How do i add values to a string array from a class?
I am trying to create a simple object-oriented program for a fictional movie theatre.
Therefore I am making a kind of list with all the movies. My issue is that I can not add genres to my genre array in the child classes to the Movies class.

Here is what I have made so far.

```<code>using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BentesBio
{
    class Program
    {
        static void Main(string[] args)
        {
            Movie[] moviesArray = new Movie[6];

            moviesArray[0] = new FeatureFilm { Director = "", Country = "", Budget = 0.0, BudgetCurrency = "", BudgetDKK = 0.0, Year = 0000, Score = "", Length = 00, Genre = { "", "" }, Cast = {} };
            moviesArray[1] = new FeatureFilm { Director = "", Country = "", Budget = 0.0, BudgetCurrency = "", BudgetDKK = 0.0, Year = 0000, Score = "", Length = 00 };
            moviesArray[2] = new FeatureFilm { Director = "", Country = "", Budget = 0.0, BudgetCurrency = "", BudgetDKK = 0.0, Year = 0000, Score = "", Length = 00 };
            moviesArray[3] = new FeatureFilm { Director = "", Country = "", Budget = 0.0, BudgetCurrency = "", BudgetDKK = 0.0, Year = 0000, Score = "", Length = 00 };
            moviesArray[4] = new Documentary { Director = "", Country = "", Budget = 0.0, BudgetCurrency = "", BudgetDKK = 0.0, Year = 0000, Score = "", Length = 00, Theme = { "", "" } };
            moviesArray[5] = new Documentary { Director = "", Country = "", Budget = 0.0, BudgetCurrency = "", BudgetDKK = 0.0, Year = 0000, Score = "", Length = 00 };

            Console.ReadKey();
        }
    }

    class Movie
    {
        public string Director { get; set; }
        public string Country { get; set; }
        public double Budget { get; set; }
        public string BudgetCurrency { get; set; }
        public double BudgetDKK { get; set; }
        public int Year { get; set; }
        public string Score { get; set; }
        public int Length { get; set; }
    }

    class FeatureFilm : Movie
    {
        public string[] Genre { get; set; }
        public string[] Cast { get; set; }
    }

    class Documentary : Movie
    {
        public string[] Theme { get; set; }
    }
}

</code>```

Any suggestions would be much appreciated.

答:
In programming languages, arrays normally are fixed size. If you don't like the size, you have to create a new one with a different size. If you want a container with a variable size, where you can add and remove elements at will, this is commonly called a list.

In C# for your purpose, that would be a List<string> instead of a string[].

Body:
I am trying to create a simple object-oriented program for a fictional movie theatre.
Therefore I am making a kind of list with all the movies. My issue is that I can not add genres to my genre array in the child classes to the Movies class.

Here is what I have made so far.

using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BentesBio
{
    class Program
    {
        static void Main(string[] args)
        {
            Movie[] moviesArray = new Movie[6];

            moviesArray[0] = new FeatureFilm { Director = "", Country = "", Budget = 0.0, BudgetCurrency = "", BudgetDKK = 0.0, Year = 0000, Score = "", Length = 00, Genre = { "", "" }, Cast = {} };
            moviesArray[1] = new FeatureFilm { Director = "", Country = "", Budget = 0.0, BudgetCurrency = "", BudgetDKK = 0.0, Year = 0000, Score = "", Length = 00 };
            moviesArray[2] = new FeatureFilm { Director = "", Country = "", Budget = 0.0, BudgetCurrency = "", BudgetDKK = 0.0, Year = 0000, Score = "", Length = 00 };
            moviesArray[3] = new FeatureFilm { Director = "", Country = "", Budget = 0.0, BudgetCurrency = "", BudgetDKK = 0.0, Year = 0000, Score = "", Length = 00 };
            moviesArray[4] = new Documentary { Director = "", Country = "", Budget = 0.0, BudgetCurrency = "", BudgetDKK = 0.0, Year = 0000, Score = "", Length = 00, Theme = { "", "" } };
            moviesArray[5] = new Documentary { Director = "", Country = "", Budget = 0.0, BudgetCurrency = "", BudgetDKK = 0.0, Year = 0000, Score = "", Length = 00 };

            Console.ReadKey();
        }
    }

    class Movie
    {
        public string Director { get; set; }
        public string Country { get; set; }
        public double Budget { get; set; }
        public string BudgetCurrency { get; set; }
        public double BudgetDKK { get; set; }
        public int Year { get; set; }
        public string Score { get; set; }
        public int Length { get; set; }
    }

    class FeatureFilm : Movie
    {
        public string[] Genre { get; set; }
        public string[] Cast { get; set; }
    }

    class Documentary : Movie
    {
        public string[] Theme { get; set; }
    }
}

Any suggestions would be much appreciated.


问:
Android: Clear old activity instance from history stack
I have the following simple scenario:

One Activity called ListCarsActivity.kt where list of cars are displayed. When the user click on the FloatingActionButton, it opens another activity called AddCarActivity.kt

When the user click on the Add Car button, I start a new intent to go to the initial activity ListCarsActivity.kt where the added car is now displayed.

Problem: From now, when I click on the Back button, the ListCarsActivity is displayed a second time.

How to clear the old entry of ListCarsActivity from the History stack?

答:
Your approach is valid and will work as you want. However, I would like to a bit more information here.

In your ListCarsActivity, on clicking the floatingButton, you are starting a new activity AddCarActivity. Once done, on clicking the button "Add Car", you can rather do your save/post logic and close (finish()) this (AddCarActivity).

Doing this will prevent you from relaunching the same activity (ListCarsActivity) again. Also, If you close (finish()) the ListCarsActivity and if the user presses back from the AddCarActivity, the app will close (considering there are only two activities). This is definitely what you don't want.

Rather, you can implement onResume method in your ListCarsActivity to refresh the list with new and updated data. This same function will be called once the user clicks on "Add Car" and the AddCarActivity is closed. Hence, there would be no need to startActivity again.


问:
setLocale not working properly, setting a new language does not change anything
I implemented the setLocale earlier in my app, and haven't checked it until yesterday. The changing of language was working properly, but now setting a new language does not change the language in my app. The way it works, is as follows: I added a spinner in my Profile activity in the toolbar. I use an adapter to create the spinner's look to show the name and a flag. It used to work, when I was changing the spinner, with a onItemSelectedListener I managed to change the language, but now it's not working anymore.

EDIT: Following @Hardik Talaviya's answer I added the LocaleManager class and changed the code, but the app behaves the same. It does not change the language according to the spinner selection.

LocaleManager.class:

```<code>public class LocaleManager {

private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language";

public static Context onAttach(Context context) {
    String lang = getPersistedData(context, Locale.getDefault().getLanguage());
    return setLocale(context, lang);
}

public static Context onAttach(Context context, String defaultLanguage) {
    String lang = getPersistedData(context, defaultLanguage);
    return setLocale(context, lang);
}

public static String getLanguage(Context context) {
    return getPersistedData(context, Locale.getDefault().getLanguage());
}

public static Context setLocale(Context context, String language) {
    persist(context, language);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        return updateResources(context, language);
    }
    return updateResourcesLegacy(context, language);
}

private static String getPersistedData(Context context, String defaultLanguage) {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    return preferences.getString(SELECTED_LANGUAGE, defaultLanguage);
}

private static void persist(Context context, String language) {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    SharedPreferences.Editor editor = preferences.edit();
    editor.putString(SELECTED_LANGUAGE, language);
    editor.apply();
}

@TargetApi(Build.VERSION_CODES.N)
private static Context updateResources(Context context, String language) {
    Locale locale = new Locale(language);
    Configuration configuration = context.getResources().getConfiguration();
    LocaleList localeList = new LocaleList(locale);
    localeList.setDefault(localeList);
    configuration.setLocales(localeList);
    return context.createConfigurationContext(configuration);
}

@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
@SuppressWarnings("deprecation")
private static Context updateResourcesLegacy(Context context, String language) {
    Locale locale = new Locale(language);
    Locale.setDefault(locale);
    Resources resources = context.getResources();
    Configuration configuration = resources.getConfiguration();
    configuration.locale = locale;
    configuration.setLayoutDirection(locale);
    resources.updateConfiguration(configuration, resources.getDisplayMetrics());
    return context;
}
</code>```

Added this method on all activities that uses strings:

```<code>@Override
protected void attachBaseContext(Context newBase) {
    super.attachBaseContext(LocaleManager.onAttach(newBase));
}
</code>```

OnItemSelectedListener :

```<code>@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    TaraITEM clickedItem = (TaraITEM) parent.getItemAtPosition(position);
    String clickedCountryName = clickedItem.getCountryName();
    pozitie = parent.getSelectedItemPosition();

    if (!clickedCountryName.equals(lastCountryName)) {
        lastCountryName = clickedCountryName;
        if (clickedCountryName.equals("FR")) {
            Context context= getBaseContext();
            LocaleManager.setLocale(context, "fr");
            Intent intent = new Intent(Profil.this, Profil.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            finish();
        } else if (clickedCountryName.equals("RO")) {
            LocaleManager.setLocale(this, "ro");
            Intent intent = new Intent(Profil.this, Profil.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            finish();
        } else if (clickedCountryName.equals("EN")) {
            LocaleManager.setLocale(this, "en");
            Intent intent = new Intent(Profil.this, Profil.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            finish();
        }

    }
}
</code>```

答:
Try to add below class

LocaleManager.java

```<code>public class LocaleManager {

    private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language";

    public static Context onAttach(Context context) {
        String lang = getPersistedData(context, Locale.getDefault().getLanguage());
        return setLocale(context, lang);
    }

    public static Context onAttach(Context context, String defaultLanguage) {
        String lang = getPersistedData(context, defaultLanguage);
        return setLocale(context, lang);
    }

    public static String getLanguage(Context context) {
        return getPersistedData(context, Locale.getDefault().getLanguage());
    }

    public static Context setLocale(Context context, String language) {
        persist(context, language);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return updateResources(context, language);
        }
        return updateResourcesLegacy(context, language);
    }

    private static String getPersistedData(Context context, String defaultLanguage) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        return preferences.getString(SELECTED_LANGUAGE, defaultLanguage);
    }

    private static void persist(Context context, String language) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString(SELECTED_LANGUAGE, language);
        editor.apply();
    }

    @TargetApi(Build.VERSION_CODES.N)
    private static Context updateResources(Context context, String language) {
        Locale locale = new Locale(language);
        Configuration configuration = context.getResources().getConfiguration();
        LocaleList localeList = new LocaleList(locale);
        localeList.setDefault(localeList);
        configuration.setLocales(localeList);
        return context.createConfigurationContext(configuration);
    }

    @SuppressWarnings("deprecation")
    private static Context updateResourcesLegacy(Context context, String language) {
        Locale locale = new Locale(language);
        Locale.setDefault(locale);
        Resources resources = context.getResources();
        Configuration configuration = resources.getConfiguration();
        configuration.locale = locale;
        configuration.setLayoutDirection(locale);
        resources.updateConfiguration(configuration, resources.getDisplayMetrics());
        return context;
    }
}
</code>```

Add attachBaseContex override method in all activity

```<code>@Override
protected void attachBaseContext(Context newBase) {
    super.attachBaseContext(LocaleManager.onAttach(newBase));
}
</code>```

Now,change language using this code

```<code>@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    TaraITEM clickedItem = (TaraITEM) parent.getItemAtPosition(position);
    String clickedCountryName = clickedItem.getCountryName();
    pozitie = parent.getSelectedItemPosition();

    if (!clickedCountryName.equals(lastCountryName)) {
        lastCountryName = clickedCountryName;
        if (clickedCountryName.equals("FR")) {
            LocaleManager.setLocale(context, "fr");
            Intent intent = new Intent(YourActivity.this, SplashScreenActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            finish();
        } else if (clickedCountryName.equals("RO")) {
            LocaleManager.setLocale(context, "ro");
            Intent intent = new Intent(YourActivity.this, SplashScreenActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            finish();
        } else if (clickedCountryName.equals("EN")) {
            LocaleManager.setLocale(context, "en");
            Intent intent = new Intent(YourActivity.this, SplashScreenActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            finish();
        }

    }
}
</code>```

I hope this can help you!

Body:
I implemented the setLocale earlier in my app, and haven't checked it until yesterday. The changing of language was working properly, but now setting a new language does not change the language in my app. The way it works, is as follows: I added a spinner in my Profile activity in the toolbar. I use an adapter to create the spinner's look to show the name and a flag. It used to work, when I was changing the spinner, with a onItemSelectedListener I managed to change the language, but now it's not working anymore.

EDIT: Following @Hardik Talaviya's answer I added the LocaleManager class and changed the code, but the app behaves the same. It does not change the language according to the spinner selection.

LocaleManager.class:

public class LocaleManager {

private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language";

public static Context onAttach(Context context) {
    String lang = getPersistedData(context, Locale.getDefault().getLanguage());
    return setLocale(context, lang);
}

public static Context onAttach(Context context, String defaultLanguage) {
    String lang = getPersistedData(context, defaultLanguage);
    return setLocale(context, lang);
}

public static String getLanguage(Context context) {
    return getPersistedData(context, Locale.getDefault().getLanguage());
}

public static Context setLocale(Context context, String language) {
    persist(context, language);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        return updateResources(context, language);
    }
    return updateResourcesLegacy(context, language);
}

private static String getPersistedData(Context context, String defaultLanguage) {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    return preferences.getString(SELECTED_LANGUAGE, defaultLanguage);
}

private static void persist(Context context, String language) {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    SharedPreferences.Editor editor = preferences.edit();
    editor.putString(SELECTED_LANGUAGE, language);
    editor.apply();
}

@TargetApi(Build.VERSION_CODES.N)
private static Context updateResources(Context context, String language) {
    Locale locale = new Locale(language);
    Configuration configuration = context.getResources().getConfiguration();
    LocaleList localeList = new LocaleList(locale);
    localeList.setDefault(localeList);
    configuration.setLocales(localeList);
    return context.createConfigurationContext(configuration);
}

@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
@SuppressWarnings("deprecation")
private static Context updateResourcesLegacy(Context context, String language) {
    Locale locale = new Locale(language);
    Locale.setDefault(locale);
    Resources resources = context.getResources();
    Configuration configuration = resources.getConfiguration();
    configuration.locale = locale;
    configuration.setLayoutDirection(locale);
    resources.updateConfiguration(configuration, resources.getDisplayMetrics());
    return context;
}

Added this method on all activities that uses strings:

@Override
protected void attachBaseContext(Context newBase) {
    super.attachBaseContext(LocaleManager.onAttach(newBase));
}

OnItemSelectedListener :

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    TaraITEM clickedItem = (TaraITEM) parent.getItemAtPosition(position);
    String clickedCountryName = clickedItem.getCountryName();
    pozitie = parent.getSelectedItemPosition();

    if (!clickedCountryName.equals(lastCountryName)) {
        lastCountryName = clickedCountryName;
        if (clickedCountryName.equals("FR")) {
            Context context= getBaseContext();
            LocaleManager.setLocale(context, "fr");
            Intent intent = new Intent(Profil.this, Profil.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            finish();
        } else if (clickedCountryName.equals("RO")) {
            LocaleManager.setLocale(this, "ro");
            Intent intent = new Intent(Profil.this, Profil.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            finish();
        } else if (clickedCountryName.equals("EN")) {
            LocaleManager.setLocale(this, "en");
            Intent intent = new Intent(Profil.this, Profil.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            finish();
        }

    }
}

Body:
Try to add below class

LocaleManager.java

public class LocaleManager {

    private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language";

    public static Context onAttach(Context context) {
        String lang = getPersistedData(context, Locale.getDefault().getLanguage());
        return setLocale(context, lang);
    }

    public static Context onAttach(Context context, String defaultLanguage) {
        String lang = getPersistedData(context, defaultLanguage);
        return setLocale(context, lang);
    }

    public static String getLanguage(Context context) {
        return getPersistedData(context, Locale.getDefault().getLanguage());
    }

    public static Context setLocale(Context context, String language) {
        persist(context, language);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return updateResources(context, language);
        }
        return updateResourcesLegacy(context, language);
    }

    private static String getPersistedData(Context context, String defaultLanguage) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        return preferences.getString(SELECTED_LANGUAGE, defaultLanguage);
    }

    private static void persist(Context context, String language) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString(SELECTED_LANGUAGE, language);
        editor.apply();
    }

    @TargetApi(Build.VERSION_CODES.N)
    private static Context updateResources(Context context, String language) {
        Locale locale = new Locale(language);
        Configuration configuration = context.getResources().getConfiguration();
        LocaleList localeList = new LocaleList(locale);
        localeList.setDefault(localeList);
        configuration.setLocales(localeList);
        return context.createConfigurationContext(configuration);
    }

    @SuppressWarnings("deprecation")
    private static Context updateResourcesLegacy(Context context, String language) {
        Locale locale = new Locale(language);
        Locale.setDefault(locale);
        Resources resources = context.getResources();
        Configuration configuration = resources.getConfiguration();
        configuration.locale = locale;
        configuration.setLayoutDirection(locale);
        resources.updateConfiguration(configuration, resources.getDisplayMetrics());
        return context;
    }
}

Add attachBaseContex override method in all activity

@Override
protected void attachBaseContext(Context newBase) {
    super.attachBaseContext(LocaleManager.onAttach(newBase));
}

Now,change language using this code

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    TaraITEM clickedItem = (TaraITEM) parent.getItemAtPosition(position);
    String clickedCountryName = clickedItem.getCountryName();
    pozitie = parent.getSelectedItemPosition();

    if (!clickedCountryName.equals(lastCountryName)) {
        lastCountryName = clickedCountryName;
        if (clickedCountryName.equals("FR")) {
            LocaleManager.setLocale(context, "fr");
            Intent intent = new Intent(YourActivity.this, SplashScreenActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            finish();
        } else if (clickedCountryName.equals("RO")) {
            LocaleManager.setLocale(context, "ro");
            Intent intent = new Intent(YourActivity.this, SplashScreenActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            finish();
        } else if (clickedCountryName.equals("EN")) {
            LocaleManager.setLocale(context, "en");
            Intent intent = new Intent(YourActivity.this, SplashScreenActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            finish();
        }

    }
}

I hope this can help you!


问:
Count all values from Column A but only certain values from Column B
(1) Table (SQL Fiddle):

```<code>CREATE TABLE Sales (
    Product Text,
    Sales_Monetary VARCHAR(255),
    Returns_Monetary VARCHAR(255)
);

INSERT INTO Sales
(Product, Sales_Monetary, Returns_Monetary)
VALUES
("Product A", "500", "300"),
("Product A", "200", "130"),
("Product A", "600", "0"),
("Product A", "900", "540"),
("Product B", "150", "70"),
("Product B", "480", "0"),
("Product B", "220", "0"),
("Product B", "300", "0"),
("Product B", "890", "670"),
("Product C", "360", "0"),
("Product C", "740", "530");
</code>```

(2) Desired Result:

```<code>            Sold_Items   Returned_Items    Return_Rate_Items
Product A      4            3                  0.75
Product B      5            2                  0.4
Product C      2            1                  0.5
</code>```

I want to get the Return Rate based on items from the example table above.

Therefore, I want to use a count on Sales_Monetary and Returns_Monetary.

However, when I do this the Products with 0 returns are counted as well.

In order to solve this issue I put WHERE Returns_Monetary > 0.

Unfortunately, with this condition the Sales_Monetary are also not counted.

```<code>Select
Product,
count(Sales_Monetary) AS Sold_Items
count(Returns_Monetary) AS Returned_Items,
count(Returns_Monetary) / count(Sales_Monetary) AS Return_Rate_Items
FROM Sales
WHERE Returns_Monetary > 0
GROUP BY 1;
</code>```

What do I need to change in my query to make it work?

答:
However, when I do this the Products with 0 returns are counted as well.

Here is one way to only count in Returns_Monetary that are greater than 0:

```<code>select
    Product,
    count(Sales_Monetary) AS Sold_Items
    sum(Returns_Monetary > 0) AS Returned_Items,
    sum(Returns_Monetary > 0) / count(Sales_Monetary) AS Return_Rate_Items
from Sales
group by 1;
</code>```

sum(Returns_Monetary > 0) increases by 1 for every Returns_Monetary that is greater than 0.

Body:
(1) Table (SQL Fiddle):

CREATE TABLE Sales (
    Product Text,
    Sales_Monetary VARCHAR(255),
    Returns_Monetary VARCHAR(255)
);

INSERT INTO Sales
(Product, Sales_Monetary, Returns_Monetary)
VALUES
("Product A", "500", "300"),
("Product A", "200", "130"),
("Product A", "600", "0"),
("Product A", "900", "540"),
("Product B", "150", "70"),
("Product B", "480", "0"),
("Product B", "220", "0"),
("Product B", "300", "0"),
("Product B", "890", "670"),
("Product C", "360", "0"),
("Product C", "740", "530");

(2) Desired Result:

            Sold_Items   Returned_Items    Return_Rate_Items
Product A      4            3                  0.75
Product B      5            2                  0.4
Product C      2            1                  0.5

I want to get the Return Rate based on items from the example table above.

Therefore, I want to use a count on Sales_Monetary and Returns_Monetary.

However, when I do this the Products with 0 returns are counted as well.

In order to solve this issue I put WHERE Returns_Monetary > 0.

Unfortunately, with this condition the Sales_Monetary are also not counted.

Select
Product,
count(Sales_Monetary) AS Sold_Items
count(Returns_Monetary) AS Returned_Items,
count(Returns_Monetary) / count(Sales_Monetary) AS Return_Rate_Items
FROM Sales
WHERE Returns_Monetary > 0
GROUP BY 1;

What do I need to change in my query to make it work?

Body:
However, when I do this the Products with 0 returns are counted as well.

Here is one way to only count in Returns_Monetary that are greater than 0:

select
    Product,
    count(Sales_Monetary) AS Sold_Items
    sum(Returns_Monetary > 0) AS Returned_Items,
    sum(Returns_Monetary > 0) / count(Sales_Monetary) AS Return_Rate_Items
from Sales
group by 1;

sum(Returns_Monetary > 0) increases by 1 for every Returns_Monetary that is greater than 0.


问:
Read console output of a shell script in Perl
Let's say I've got a shell script called print_error.sh looking like this:

```<code>#!/usr/bin/bash

echo "ERROR: Bla bla, yada yada."
exit 1
</code>```

Now I'm in a Perl script, calling this shell script with

```<code>system("print_error.sh")
</code>```

I now want to read the console output of print_error.sh and write it to a Log4perl logger.

How can I achieve this?

答:
Here's the solution I've found:

```<code>#!/usr/bin/perl

use Log::Log4perl;

my $logfile = "log.txt";
$ENV{"LOGFILE"} = $logfile;

Log::Log4perl->init("log4perl.properties");
$logger = Log::Log4perl->get_logger();

$logger->info("pos 1");
system("./print_error.sh 0 2>&1 >> $logfile") == 0
        or die "perl error";
$logger->info("pos 2");

exit 0
</code>```

See also here.

Body:
Let's say I've got a shell script called print_error.sh looking like this:

#!/usr/bin/bash

echo "ERROR: Bla bla, yada yada."
exit 1

Now I'm in a Perl script, calling this shell script with

system("print_error.sh")

I now want to read the console output of print_error.sh and write it to a Log4perl logger.

How can I achieve this?

Body:
Here's the solution I've found:

#!/usr/bin/perl

use Log::Log4perl;

my $logfile = "log.txt";
$ENV{"LOGFILE"} = $logfile;

Log::Log4perl->init("log4perl.properties");
$logger = Log::Log4perl->get_logger();

$logger->info("pos 1");
system("./print_error.sh 0 2>&1 >> $logfile") == 0
        or die "perl error";
$logger->info("pos 2");

exit 0

See also here.


问:
Persistant Checkbox Position
i wanted to make checkbox position persistant when refresh page, see the picture below.

Here's the UI

and here's my code :

```<code>    <div className='checkboxTransaction ml-2'>
      <input
        id='radio1'
        name='radio'
        type='radio'
        defaultChecked={true}
        value='waiting'
       />
      <label htmlFor='radio1'>Menunggu Pembayaran</label>
    </div>
    <div className='checkboxTransaction ml-2'>
      <input
        id='radio2'
        name='radio'
        type='radio'
        value='waiting'
       />
      <label htmlFor='radio1'>Pesanan Dikirm</label>
    </div>
</code>```

答:
If I understand you correctly, you want the state of the radio buttons to remain even after a refresh. For that purpose, you need to store the state of the radio buttons, for example, in the localStorage, and when rendering use the saved data to set the defaultChecked properly.

Here is a small sketch of the code that will probably show you what I mean.

const fakeLocalStorage = {};

class TestComponent extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      testValue: fakeLocalStorage.test || 1
    };
  }

  onRadioChange = ({ target: { value } }) => {
    this.setState({ testValue: value }, () => {
      fakeLocalStorage.test = value;

      console.log(fakeLocalStorage);
    });
  }

  renderInput(val) {
    return <input type='radio' name="test" onChange={this.onRadioChange} value={val} defaultChecked={this.state.testValue === val}  />;
  }

  render() {
    return (

      Test
      {this.renderInput(1)}
      {this.renderInput(2)}
      {this.renderInput(3)}

);
  }
}

ReactDOM.render(<TestComponent />, document.getElementById('root'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div></code>```

Title: Persistant Checkbox Position

Body:
i wanted to make checkbox position persistant when refresh page, see the picture below.

Here's the UI

and here's my code :

      <input
        id='radio1'
        name='radio'
        type='radio'
        defaultChecked={true}
        value='waiting'
       />
      Menunggu Pembayaran

      <input
        id='radio2'
        name='radio'
        type='radio'
        value='waiting'
       />
      Pesanan Dikirm

Body:
If I understand you correctly, you want the state of the radio buttons to remain even after a refresh. For that purpose, you need to store the state of the radio buttons, for example, in the localStorage, and when rendering use the saved data to set the defaultChecked properly.

Here is a small sketch of the code that will probably show you what I mean.

const fakeLocalStorage = {};

class TestComponent extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      testValue: fakeLocalStorage.test || 1
    };
  }

  onRadioChange = ({ target: { value } }) => {
    this.setState({ testValue: value }, () => {
      fakeLocalStorage.test = value;

      console.log(fakeLocalStorage);
    });
  }

  renderInput(val) {
    return <input type='radio' name="test" onChange={this.onRadioChange} value={val} defaultChecked={this.state.testValue === val}  />;
  }

  render() {
    return (<div>
      <label for="test">Test</label>
      {this.renderInput(1)}
      {this.renderInput(2)}
      {this.renderInput(3)}
    </div>);
  }
}

ReactDOM.render(<TestComponent />, document.getElementById('root'));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>


问:
In TensorFlow, what is the difference between Session.run() and Tensor.eval()?
TensorFlow has two ways to evaluate part of graph: Session.run on a list of variables and Tensor.eval.  Is there a difference between these two?

答:
Tensorflow 2.x Compatible Answer: Converting mrry's code to Tensorflow 2.x (>= 2.0) for the benefit of the community.

```<code>!pip install tensorflow==2.1
import tensorflow as tf

tf.compat.v1.disable_eager_execution()

t = tf.constant(42.0)
sess = tf.compat.v1.Session()
with sess.as_default():   # or `with sess:` to close on exit
    assert sess is tf.compat.v1.get_default_session()
    assert t.eval() == sess.run(t)

#The most important difference is that you can use sess.run() to fetch the values of many tensors in the same step:

t = tf.constant(42.0)
u = tf.constant(37.0)
tu = tf.multiply(t, u)
ut = tf.multiply(u, t)
with sess.as_default():
   tu.eval()  # runs one step
   ut.eval()  # runs one step
   sess.run([tu, ut])  # evaluates both tensors in a single step
</code>```

Body:
Tensorflow 2.x Compatible Answer: Converting mrry's code to Tensorflow 2.x (>= 2.0) for the benefit of the community.

!pip install tensorflow==2.1
import tensorflow as tf

tf.compat.v1.disable_eager_execution()

t = tf.constant(42.0)
sess = tf.compat.v1.Session()
with sess.as_default():   # or `with sess:` to close on exit
    assert sess is tf.compat.v1.get_default_session()
    assert t.eval() == sess.run(t)

#The most important difference is that you can use sess.run() to fetch the values of many tensors in the same step:

t = tf.constant(42.0)
u = tf.constant(37.0)
tu = tf.multiply(t, u)
ut = tf.multiply(u, t)
with sess.as_default():
   tu.eval()  # runs one step
   ut.eval()  # runs one step
   sess.run([tu, ut])  # evaluates both tensors in a single step


问:
Babel typescript unexpected token '?' in statement
Babel can't transform '?' in statement in typescript.</p>

```<code>let t= getObject()?.fieldName;//Module build failed (from ./node_modules/babel-loader/lib/index.js): Unexpected token

let t= getObject() && getObejct().fieldName;
</code>```

答:
Maybe you can use optional-chaining

```<code>npm install --save-dev @babel/plugin-proposal-optional-chaining
</code>```

add this in your babel file

```<code>{
  "plugins": ["@babel/plugin-proposal-optional-chaining"]
}
</code>```

Body:
Babel can't transform '?' in statement in typescript.

let t= getObject()?.fieldName;//Module build failed (from ./node_modules/babel-loader/lib/index.js): Unexpected token

let t= getObject() && getObejct().fieldName;

Body:
Maybe you can use optional-chaining

npm install --save-dev @babel/plugin-proposal-optional-chaining

add this in your babel file

{
  "plugins": ["@babel/plugin-proposal-optional-chaining"]
}


问:
Is Perl a good option for heavy text-processing?
I have this web application which needs to do several heavy text processing tasks: removing certain characters, parsing XML files, among others. Some of them involve regular expressions.

The web application has some implementations in Java and others in PHP. Is it worth using Perl or other specific text processing language for such tasks, or is there really no difference with using PHP?

I even thought of using Sed, Awk maybe even some compiled C scripts for processing texts. There's a lot of text to be processed...

答: Yes, Perl is a good option. As a language, it's definitely more suitable for those kinds of tasks than Java or PHP. If you have the Perl knowledge, I would recommend it for this kind of task.</p>

OwnerDisplayName: Fernando

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: brian d foy

OwnerDisplayName: Leon Timmermans


问:
jquery prevent default does not work
I want to change image when user click on a thumb image, and prevent it to jump to the top of page.

the first code I wrote:

```<code>$('#photos-list img').click(function(e) {
    e.preventDefault();

    var imgObj = new Image();
    var targetObj = $('#main_image img');
    imgObj.onload = function() {
        targetObj.attr('src',this.src);

    }
    imgObj.src = $(this).attr('rel');
});
</code>```

the preventDefault() works fine. ok, I want to add some effects to the image changing, like fade in, I add some jquery effects in

```<code>$('#photos-list img').click(function(e) {
    e.preventDefault();

    var imgObj = new Image();
    var targetObj = $('#main_image img');
    imgObj.onload = function() {
        targetObj.hide();
        targetObj.attr('src',this.src);
        targetObj.fadeIn('normal');

    }
    imgObj.src = $(this).attr('rel');
});
</code>```

and this time , the preventDefault does not work, even I gave fadeIn() a preventdefault like:

```<code>targetObj.fadeIn('normal', function(e1){e1.preventDefault();});
</code>```

any methods to solve this problem?

答:
It's work:</p>

```<code>if(event.preventDefault){
    event.preventDefault();
}else{
    event.returnValue = false;
};
</code>```

Title: jquery prevent default does not work

Body:
I want to change image when user click on a thumb image, and prevent it to jump to the top of page.

the first code I wrote:

$('#photos-list img').click(function(e) {
    e.preventDefault();

    var imgObj = new Image();
    var targetObj = $('#main_image img');
    imgObj.onload = function() {
        targetObj.attr('src',this.src);

    }
    imgObj.src = $(this).attr('rel');
});

the preventDefault() works fine. ok, I want to add some effects to the image changing, like fade in, I add some jquery effects in

$('#photos-list img').click(function(e) {
    e.preventDefault();

    var imgObj = new Image();
    var targetObj = $('#main_image img');
    imgObj.onload = function() {
        targetObj.hide();
        targetObj.attr('src',this.src);
        targetObj.fadeIn('normal');

    }
    imgObj.src = $(this).attr('rel');
});

and this time , the preventDefault does not work, even I gave fadeIn() a preventdefault like:

targetObj.fadeIn('normal', function(e1){e1.preventDefault();});

any methods to solve this problem?

Body:
It's work:

if(event.preventDefault){
    event.preventDefault();
}else{
    event.returnValue = false;
};


问:
Accessing OAuth secured API from Spring Batch
My company has a OAuth 2 secured API that I need to access from a Spring Batch or Scheduled process. I can access this API from our web applications using the following code:

First I created a WebClient bean

```<code>@Configuration
public class ScimOAuthConfiguration
{

    /**
     * This class creates and returns a WebClient
     * that has been built to authenticate with
     * SCIM using OAuth2
     *
     * @param clientRegistrationRepository
     * @param authorizedClientRepository
     * @return WebClient
     */

    @Bean
    WebClient scimWebClient(ClientRegistrationRepository clientRegistrationRepository,
            OAuth2AuthorizedClientRepository authorizedClientRepository)
    {
        //Creates a Servlet OAuth2 Authorized Client Exchange Filter
        ServletOAuth2AuthorizedClientExchangeFilterFunction oauth =
                new ServletOAuth2AuthorizedClientExchangeFilterFunction(
                        clientRegistrationRepository, authorizedClientRepository);

        //Returns WebClient with OAuth2 filter applied to it
        return WebClient.builder().apply(oauth.oauth2Configuration()).build();
    }
}
</code>```

The userSearch() method below just makes a request to an end point, and converts the results into some classes that I have created.

```<code>@Component
@Slf4j
public class UserSearchService {

    private final UserUtil userUtil;

    private final WebClient webClient;

    public UserSearchService(UserUtil userUtil, WebClient webClient) {
        this.userUtil = userUtil;
        this.webClient = webClient;
    }

    /**
     * This method will query the SCIM API and return the results.
     */
    public Schema<User> userSearch(UserSearchForm form) {

        if (form.getCwsId().isEmpty() && form.getLastName().isEmpty() && form.getFirstName().isEmpty() && form.getEmail().isEmpty()) {
            return null;
        }

        //generate the request URI
        String uri = userUtil.generateSearchURL(form);

        //Creates a User Schema object to contain the results of the web request
        Schema<User> users = null;

        try {
            users = this.webClient.get()
                    .uri(uri)
                    .attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.clientRegistrationId("scim"))
                    .retrieve()
                    .bodyToMono(new ParameterizedTypeReference<Schema<User>>() {
                    })
                    .block();

        } catch (WebClientResponseException ex) {
            log.error(ex.getMessage(), ex);
        }

        return users;

    }
}
</code>```

When I call this function in a controller or rest endpoint everything works just fine. Example:

```<code>@RestController
@Slf4j
public class UserSearchController {

    @Autowired
    UserSearchService service;

    @PostMapping(value="/userSearch")
    public Schema<User> userSearch(@RequestBody UserSearchForm form) {
        return service.userSearch(form);
    }

}
</code>```

No problems so far...

I have been given a task that requires me to create a Spring Batch job that will run at midnight every night. Part of this batch job will require me to gather user information via the secured API. I would prefer to put this batch job inside of my web application project. The goal is to have this web application running on a server, and every night at midnight start this batch job that simply sends out some automated reminder emails. It would be nice to have everything be self-contained and in one repository. Here is my simplified example of the batch job that tries to access the secured API:

```<code>@Configuration
@Slf4j
public class ReminderEmailJob {

    @Autowired
    JobBuilderFactory jobBuilderFactory;

    @Autowired
    StepBuilderFactory stepBuilderFactory;

    @Autowired
    UserSearchService userSearchService;

    @Bean
    public Job job() {
        return this.jobBuilderFactory.get("basicJob")
                .start(step1())
                .build();
    }

    @Bean
    public Step step1() {
        return this.stepBuilderFactory.get("step1").tasklet((contribution, chunkContext) -> {
            UserSearchForm form = new UserSearchForm("", "", "userNameHere", "");
            Schema<User> user = userSearchService.userSearch(form);
            System.out.println(user);

            log.info("Hello, world!");
            return RepeatStatus.FINISHED;
        }).build();
    }
}

</code>```

Here is a @Scheduled method that will run this batch job every night at midnight:

```<code>@Service
@Configuration
@EnableScheduling
@Slf4j
public class EmailScheduler {

    @Autowired
    ReminderEmailJob job;

    @Autowired
    JobLauncher jobLauncher;

    @Scheduled(cron = "0 0 0 * * *")
    public void runAutomatedEmailBatchJob() throws JobParametersInvalidException, JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException {
        jobLauncher.run(job.job(), new JobParametersBuilder().addDate("launchDate", new Date()).toJobParameters());
    }
}
</code>```

When I try running the batch job I get the following error:

```<code>2020-02-19 10:21:38,347 ERROR [scheduling-1] org.springframework.batch.core.step.AbstractStep: Encountered an error executing step step1 in job basicJob
java.lang.IllegalArgumentException: request cannot be null
    at org.springframework.util.Assert.notNull(Assert.java:198)
    at org.springframework.security.oauth2.client.web.HttpSessionOAuth2AuthorizedClientRepository.loadAuthorizedClient(HttpSessionOAuth2AuthorizedClientRepository.java:47)
    at org.springframework.security.oauth2.client.web.AuthenticatedPrincipalOAuth2AuthorizedClientRepository.loadAuthorizedClient(AuthenticatedPrincipalOAuth2AuthorizedClientRepository.java:75)
    at org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction.populateDefaultOAuth2AuthorizedClient(ServletOAuth2AuthorizedClientExchangeFilterFunction.java:321)
    at org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction.lambda$null$1(ServletOAuth2AuthorizedClientExchangeFilterFunction.java:187)
    at org.springframework.web.reactive.function.client.DefaultWebClient$DefaultRequestBodyUriSpec.attributes(DefaultWebClient.java:234)
    at org.springframework.web.reactive.function.client.DefaultWebClient$DefaultRequestBodyUriSpec.attributes(DefaultWebClient.java:153)
    at org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction.lambda$defaultRequest$2(ServletOAuth2AuthorizedClientExchangeFilterFunction.java:184)
    at org.springframework.web.reactive.function.client.DefaultWebClient$DefaultRequestBodyUriSpec.initRequestBuilder(DefaultWebClient.java:324)
    at org.springframework.web.reactive.function.client.DefaultWebClient$DefaultRequestBodyUriSpec.exchange(DefaultWebClient.java:318)
    at org.springframework.web.reactive.function.client.DefaultWebClient$DefaultRequestBodyUriSpec.retrieve(DefaultWebClient.java:368)
    at com.cat.reman.springbootvuejs.dao.service.cgds.UserSearchService.userSearch(UserSearchService.java:53)
    at com.cat.reman.springbootvuejs.batch.ReminderEmailJob.lambda$step1$0(ReminderEmailJob.java:47)
    at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:407)
    at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:331)
    at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:140)
    at org.springframework.batch.core.step.tasklet.TaskletStep$2.doInChunkContext(TaskletStep.java:273)
    at org.springframework.batch.core.scope.context.StepContextRepeatCallback.doInIteration(StepContextRepeatCallback.java:82)
    at org.springframework.batch.repeat.support.RepeatTemplate.getNextResult(RepeatTemplate.java:375)
    at org.springframework.batch.repeat.support.RepeatTemplate.executeInternal(RepeatTemplate.java:215)
    at org.springframework.batch.repeat.support.RepeatTemplate.iterate(RepeatTemplate.java:145)
    at org.springframework.batch.core.step.tasklet.TaskletStep.doExecute(TaskletStep.java:258)
    at org.springframework.batch.core.step.AbstractStep.execute(AbstractStep.java:203)
    at org.springframework.batch.core.job.SimpleStepHandler.handleStep(SimpleStepHandler.java:148)
    at org.springframework.batch.core.job.AbstractJob.handleStep(AbstractJob.java:399)
    at org.springframework.batch.core.job.SimpleJob.doExecute(SimpleJob.java:135)
    at org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:313)
    at org.springframework.batch.core.launch.support.SimpleJobLauncher$1.run(SimpleJobLauncher.java:144)
    at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:50)
    at org.springframework.batch.core.launch.support.SimpleJobLauncher.run(SimpleJobLauncher.java:137)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:343)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:198)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
    at org.springframework.batch.core.configuration.annotation.SimpleBatchConfiguration$PassthruAdvice.invoke(SimpleBatchConfiguration.java:127)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
    at com.sun.proxy.$Proxy131.run(Unknown Source)
    at com.cat.reman.springbootvuejs.dao.service.emailService.EmailScheduler.jakeTest(EmailScheduler.java:162)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:84)
    at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54)
    at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:514)
    at java.base/java.util.concurrent.FutureTask.runAndReset(FutureTask.java:305)
    at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:300)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
    at java.base/java.lang.Thread.run(Thread.java:844)
</code>```

Which leads me to believe that in the context of the web application we can access the WebClient bean that was created just fine. When it comes to the batch job it's a different story. I have found that these two instances will be run on different threads, and will not share the same information or context.

My question is how do I access a secured API in a similar fashion using Spring Batch? I have the OAuth token client id, client secret, etc. available. Thank you.

答:
My question is how do I access a secured API in a similar fashion using Spring Batch? I have the OAuth token client id, client secret, etc. available

You can create a custom ItemReader based on a OAuth2RestTemplate to access the secured API. I found this example to be useful. Just make sure to read data in a paginated fashion to avoid loading all items in memory at once.

That said, I don't see the need to run this job in a web application. Running your EmailScheduler as a standalone spring boot app is enough IMO.

Body:
My company has a OAuth 2 secured API that I need to access from a Spring Batch or Scheduled process. I can access this API from our web applications using the following code:

First I created a WebClient bean

@Configuration
public class ScimOAuthConfiguration
{

    /**
     * This class creates and returns a WebClient
     * that has been built to authenticate with
     * SCIM using OAuth2
     *
     * @param clientRegistrationRepository
     * @param authorizedClientRepository
     * @return WebClient
     */

    @Bean
    WebClient scimWebClient(ClientRegistrationRepository clientRegistrationRepository,
            OAuth2AuthorizedClientRepository authorizedClientRepository)
    {
        //Creates a Servlet OAuth2 Authorized Client Exchange Filter
        ServletOAuth2AuthorizedClientExchangeFilterFunction oauth =
                new ServletOAuth2AuthorizedClientExchangeFilterFunction(
                        clientRegistrationRepository, authorizedClientRepository);

        //Returns WebClient with OAuth2 filter applied to it
        return WebClient.builder().apply(oauth.oauth2Configuration()).build();
    }
}

The userSearch() method below just makes a request to an end point, and converts the results into some classes that I have created.

@Component
@Slf4j
public class UserSearchService {

    private final UserUtil userUtil;

    private final WebClient webClient;

    public UserSearchService(UserUtil userUtil, WebClient webClient) {
        this.userUtil = userUtil;
        this.webClient = webClient;
    }

    /**
     * This method will query the SCIM API and return the results.
     */
    public Schema<User> userSearch(UserSearchForm form) {

        if (form.getCwsId().isEmpty() && form.getLastName().isEmpty() && form.getFirstName().isEmpty() && form.getEmail().isEmpty()) {
            return null;
        }

        //generate the request URI
        String uri = userUtil.generateSearchURL(form);

        //Creates a User Schema object to contain the results of the web request
        Schema<User> users = null;

        try {
            users = this.webClient.get()
                    .uri(uri)
                    .attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.clientRegistrationId("scim"))
                    .retrieve()
                    .bodyToMono(new ParameterizedTypeReference<Schema<User>>() {
                    })
                    .block();

        } catch (WebClientResponseException ex) {
            log.error(ex.getMessage(), ex);
        }

        return users;

    }
}

When I call this function in a controller or rest endpoint everything works just fine. Example:

@RestController
@Slf4j
public class UserSearchController {

    @Autowired
    UserSearchService service;

    @PostMapping(value="/userSearch")
    public Schema<User> userSearch(@RequestBody UserSearchForm form) {
        return service.userSearch(form);
    }

}

No problems so far...

I have been given a task that requires me to create a Spring Batch job that will run at midnight every night. Part of this batch job will require me to gather user information via the secured API. I would prefer to put this batch job inside of my web application project. The goal is to have this web application running on a server, and every night at midnight start this batch job that simply sends out some automated reminder emails. It would be nice to have everything be self-contained and in one repository. Here is my simplified example of the batch job that tries to access the secured API:

@Configuration
@Slf4j
public class ReminderEmailJob {

    @Autowired
    JobBuilderFactory jobBuilderFactory;

    @Autowired
    StepBuilderFactory stepBuilderFactory;

    @Autowired
    UserSearchService userSearchService;

    @Bean
    public Job job() {
        return this.jobBuilderFactory.get("basicJob")
                .start(step1())
                .build();
    }

    @Bean
    public Step step1() {
        return this.stepBuilderFactory.get("step1").tasklet((contribution, chunkContext) -> {
            UserSearchForm form = new UserSearchForm("", "", "userNameHere", "");
            Schema<User> user = userSearchService.userSearch(form);
            System.out.println(user);

            log.info("Hello, world!");
            return RepeatStatus.FINISHED;
        }).build();
    }
}

Here is a @Scheduled method that will run this batch job every night at midnight:

@Service
@Configuration
@EnableScheduling
@Slf4j
public class EmailScheduler {

    @Autowired
    ReminderEmailJob job;

    @Autowired
    JobLauncher jobLauncher;

    @Scheduled(cron = "0 0 0 * * *")
    public void runAutomatedEmailBatchJob() throws JobParametersInvalidException, JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException {
        jobLauncher.run(job.job(), new JobParametersBuilder().addDate("launchDate", new Date()).toJobParameters());
    }
}

When I try running the batch job I get the following error:

2020-02-19 10:21:38,347 ERROR [scheduling-1] org.springframework.batch.core.step.AbstractStep: Encountered an error executing step step1 in job basicJob
java.lang.IllegalArgumentException: request cannot be null
    at org.springframework.util.Assert.notNull(Assert.java:198)
    at org.springframework.security.oauth2.client.web.HttpSessionOAuth2AuthorizedClientRepository.loadAuthorizedClient(HttpSessionOAuth2AuthorizedClientRepository.java:47)
    at org.springframework.security.oauth2.client.web.AuthenticatedPrincipalOAuth2AuthorizedClientRepository.loadAuthorizedClient(AuthenticatedPrincipalOAuth2AuthorizedClientRepository.java:75)
    at org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction.populateDefaultOAuth2AuthorizedClient(ServletOAuth2AuthorizedClientExchangeFilterFunction.java:321)
    at org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction.lambda$null$1(ServletOAuth2AuthorizedClientExchangeFilterFunction.java:187)
    at org.springframework.web.reactive.function.client.DefaultWebClient$DefaultRequestBodyUriSpec.attributes(DefaultWebClient.java:234)
    at org.springframework.web.reactive.function.client.DefaultWebClient$DefaultRequestBodyUriSpec.attributes(DefaultWebClient.java:153)
    at org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction.lambda$defaultRequest$2(ServletOAuth2AuthorizedClientExchangeFilterFunction.java:184)
    at org.springframework.web.reactive.function.client.DefaultWebClient$DefaultRequestBodyUriSpec.initRequestBuilder(DefaultWebClient.java:324)
    at org.springframework.web.reactive.function.client.DefaultWebClient$DefaultRequestBodyUriSpec.exchange(DefaultWebClient.java:318)
    at org.springframework.web.reactive.function.client.DefaultWebClient$DefaultRequestBodyUriSpec.retrieve(DefaultWebClient.java:368)
    at com.cat.reman.springbootvuejs.dao.service.cgds.UserSearchService.userSearch(UserSearchService.java:53)
    at com.cat.reman.springbootvuejs.batch.ReminderEmailJob.lambda$step1$0(ReminderEmailJob.java:47)
    at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:407)
    at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:331)
    at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:140)
    at org.springframework.batch.core.step.tasklet.TaskletStep$2.doInChunkContext(TaskletStep.java:273)
    at org.springframework.batch.core.scope.context.StepContextRepeatCallback.doInIteration(StepContextRepeatCallback.java:82)
    at org.springframework.batch.repeat.support.RepeatTemplate.getNextResult(RepeatTemplate.java:375)
    at org.springframework.batch.repeat.support.RepeatTemplate.executeInternal(RepeatTemplate.java:215)
    at org.springframework.batch.repeat.support.RepeatTemplate.iterate(RepeatTemplate.java:145)
    at org.springframework.batch.core.step.tasklet.TaskletStep.doExecute(TaskletStep.java:258)
    at org.springframework.batch.core.step.AbstractStep.execute(AbstractStep.java:203)
    at org.springframework.batch.core.job.SimpleStepHandler.handleStep(SimpleStepHandler.java:148)
    at org.springframework.batch.core.job.AbstractJob.handleStep(AbstractJob.java:399)
    at org.springframework.batch.core.job.SimpleJob.doExecute(SimpleJob.java:135)
    at org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:313)
    at org.springframework.batch.core.launch.support.SimpleJobLauncher$1.run(SimpleJobLauncher.java:144)
    at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:50)
    at org.springframework.batch.core.launch.support.SimpleJobLauncher.run(SimpleJobLauncher.java:137)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:343)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:198)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
    at org.springframework.batch.core.configuration.annotation.SimpleBatchConfiguration$PassthruAdvice.invoke(SimpleBatchConfiguration.java:127)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
    at com.sun.proxy.$Proxy131.run(Unknown Source)
    at com.cat.reman.springbootvuejs.dao.service.emailService.EmailScheduler.jakeTest(EmailScheduler.java:162)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:84)
    at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54)
    at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:514)
    at java.base/java.util.concurrent.FutureTask.runAndReset(FutureTask.java:305)
    at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:300)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
    at java.base/java.lang.Thread.run(Thread.java:844)

Which leads me to believe that in the context of the web application we can access the WebClient bean that was created just fine. When it comes to the batch job it's a different story. I have found that these two instances will be run on different threads, and will not share the same information or context.

My question is how do I access a secured API in a similar fashion using Spring Batch? I have the OAuth token client id, client secret, etc. available. Thank you.


问:
Get WooCommerce product categories from WordPress
I am trying to get the product categories from WooCommerce through a function in  my WordPress theme

```<code>    function get_me_list_of($atts, $content = null)
    {
        $args = array( 'post_type' => 'product', 'posts_per_page' => 10, 'product_cat' => $atts[0]);

        $loop = new WP_Query( $args );

        echo '<h1 class="upp">Style '.$atts[0].'</h1>';
        echo "<ul class='mylisting'>";
        while ( $loop->have_posts() ) : $loop->the_post();
        global $product;

        echo '<li><a href="'.get_permalink().'">'.get_the_post_thumbnail($loop->post->ID, 'thumbnail').'</a></li>';
     echo '<li><a href="'.get_permalink().'">'.$loop->post->post_title.'</a></li>';

echo '<li><a href="">'.get_categories().'</a></li>';
        endwhile;

        echo "</ul>";

        wp_reset_query();

    }

    ?>
</code>```

The above code returns some products, but the product categories.

When I included echo '
'.get_categories().'
'; in the code above it returns as an array. How do I fix this?

How do i change this to get the product categories from WooCommerce?

答:
In my opinion this is the simplest solution</p>

```<code>$orderby = 'name';
                $order = 'asc';
                $hide_empty = false ;
                $cat_args = array(
                    'orderby'    => $orderby,
                    'order'      => $order,
                    'hide_empty' => $hide_empty,
                );

                $product_categories = get_terms( 'product_cat', $cat_args );

                if( !empty($product_categories) ){
                    echo '

                <ul>';
                    foreach ($product_categories as $key => $category) {
                        echo '

                <li>';
                        echo '<a href="'.get_term_link($category).'" >';
                        echo $category->name;
                        echo '</a>';
                        echo '</li>';
                    }
                    echo '</ul>

                ';
                }
</code>```

Body:
I am trying to get the product categories from WooCommerce through a function in  my WordPress theme

    function get_me_list_of($atts, $content = null)
    {
        $args = array( 'post_type' => 'product', 'posts_per_page' => 10, 'product_cat' => $atts[0]);

        $loop = new WP_Query( $args );

        echo '
Style '.$atts[0].'
';
        echo "
";
        while ( $loop->have_posts() ) : $loop->the_post();
        global $product;

        echo '
'.get_the_post_thumbnail($loop->post->ID, 'thumbnail').'
';
     echo '
'.$loop->post->post_title.'
';

echo '
'.get_categories().'
';
        endwhile;

        echo "
";

        wp_reset_query();

    }

    ?>

The above code returns some products, but the product categories.

When I included echo '
'.get_categories().'
'; in the code above it returns as an array. How do I fix this?

How do i change this to get the product categories from WooCommerce?

Body:
In my opinion this is the simplest solution

$orderby = 'name';
                $order = 'asc';
                $hide_empty = false ;
                $cat_args = array(
                    'orderby'    => $orderby,
                    'order'      => $order,
                    'hide_empty' => $hide_empty,
                );

                $product_categories = get_terms( 'product_cat', $cat_args );

                if( !empty($product_categories) ){
                    echo '

                <ul>';
                    foreach ($product_categories as $key => $category) {
                        echo '

                <li>';
                        echo '<a href="'.get_term_link($category).'" >';
                        echo $category->name;
                        echo '</a>';
                        echo '</li>';
                    }
                    echo '</ul>

                ';
                }


问:
DocumentFormat.OpenXml Adding an Image to a word doc
I am creating a simple word doc, using the openXml SDK.
It is working so far.
Now how can I add an image from my file system to this doc? I don't care where it is in the doc just so it is there.
Thanks!
Here is what I have so far.</p>

```<code> string fileName = "proposal"+dealerId +Guid.NewGuid().ToString()+".doc";
       string filePath = @"C:\DWSApplicationFiles\Word\" + fileName;
       using (WordprocessingDocument wordDoc = WordprocessingDocument.Create(filePath, WordprocessingDocumentType.Document, true))
       {
           MainDocumentPart mainPart = wordDoc.AddMainDocumentPart();

           mainPart.Document = new Document();
           //create the body
           Body body = new Body();
           DocumentFormat.OpenXml.Wordprocessing.Paragraph p = new DocumentFormat.OpenXml.Wordprocessing.Paragraph();
           DocumentFormat.OpenXml.Wordprocessing.Run runParagraph = new DocumentFormat.OpenXml.Wordprocessing.Run();

           DocumentFormat.OpenXml.Wordprocessing.Text text_paragraph = new DocumentFormat.OpenXml.Wordprocessing.Text("This is a test");
           runParagraph.Append(text_paragraph);
           p.Append(runParagraph);
           body.Append(p);
           mainPart.Document.Append(body);
           mainPart.Document.Save();
       }
</code>```

答:
This code worked for me:  http://msdn.microsoft.com/en-us/library/bb497430.aspx

Your code adds image to your docx package, but in order to see it in the document you have to declare it in your document.xml i.e. link it to your physical image. That's why you have to write that long function listed in the msdn link.

My problem is how to add effects to pictures (editing, croping, background removal).
If you know how to do this I'd appreciate your help :)

Body:
I am creating a simple word doc, using the openXml SDK.
It is working so far.
Now how can I add an image from my file system to this doc? I don't care where it is in the doc just so it is there.
Thanks!
Here is what I have so far.

 string fileName = "proposal"+dealerId +Guid.NewGuid().ToString()+".doc";
       string filePath = @"C:\DWSApplicationFiles\Word\" + fileName;
       using (WordprocessingDocument wordDoc = WordprocessingDocument.Create(filePath, WordprocessingDocumentType.Document, true))
       {
           MainDocumentPart mainPart = wordDoc.AddMainDocumentPart();

           mainPart.Document = new Document();
           //create the body
           Body body = new Body();
           DocumentFormat.OpenXml.Wordprocessing.Paragraph p = new DocumentFormat.OpenXml.Wordprocessing.Paragraph();
           DocumentFormat.OpenXml.Wordprocessing.Run runParagraph = new DocumentFormat.OpenXml.Wordprocessing.Run();

           DocumentFormat.OpenXml.Wordprocessing.Text text_paragraph = new DocumentFormat.OpenXml.Wordprocessing.Text("This is a test");
           runParagraph.Append(text_paragraph);
           p.Append(runParagraph);
           body.Append(p);
           mainPart.Document.Append(body);
           mainPart.Document.Save();
       }


问:
How to have a KTable emits only the latest updates?
My KTable is emitting on each update, instead of the latest updates only.

Please see code below (in Scala):

object SimpleTable extends App {
  val topic = "simple-table"

  val prodProps = new Properties()
  prodProps.put("bootstrap.servers", "localhost:9092")
  prodProps.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer")
  prodProps.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer")
  prodProps.put("acks", "1")
  prodProps.put("retries", "3")

  val producer = new KafkaProducer[String, String](prodProps)

  producer.send(new ProducerRecord[String, String](topic, "key1", "value1"))
  producer.send(new ProducerRecord[String, String](topic, "key2", "value2"))
  producer.send(new ProducerRecord[String, String](topic, "key3", "value3"))
  producer.send(new ProducerRecord[String, String](topic, "key1", "value11"))
  producer.send(new ProducerRecord[String, String](topic, "key2", "value22"))
  producer.send(new ProducerRecord[String, String](topic, "key3", "value33"))

  producer.close()

  val streamProps = new Properties()
  streamProps.put(StreamsConfig.APPLICATION_ID_CONFIG, "simple-table-app1")
  streamProps.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092")
  //streamProps.put(ConsumerConfig.GROUP_ID_CONFIG, "group11")
  //streamProps.put(ConsumerConfig.CLIENT_ID_CONFIG, "client11")
  //streamProps.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest")
  //streamProps.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "18000")
  //streamProps.put(StreamsConfig.COMMIT_INTERVAL_MS_CONFIG, "18000")
  //streamProps.put(StreamsConfig.CACHE_MAX_BYTES_BUFFERING_CONFIG, "10485760")
  //streamProps.put(StreamsConfig.NUM_STREAM_THREADS_CONFIG, "1")
  //streamProps.put(ConsumerConfig.METADATA_MAX_AGE_CONFIG, "10000")
  //streamProps.put(StreamsConfig.REPLICATION_FACTOR_CONFIG, 1)
  //streamProps.put(StreamsConfig.DEFAULT_TIMESTAMP_EXTRACTOR_CLASS_CONFIG, classOf[WallclockTimestampExtractor])

  import org.apache.kafka.streams.scala.Serdes._
  implicit val consumeSerdes: Consumed[String, String] = Consumed.`with`[String, String]
  val builder = new StreamsBuilder()

  val simpleTable: KTable[String, String] = builder.table[String, String](topic)
  simpleTable.toStream.print(Printed.toSysOut[String, String].withLabel("simple-table"))

  val streams = new KafkaStreams(builder.build(), streamProps)
  streams.start()
  Thread.sleep(10000)
  streams.close()
}
```

<p>This App is displaying this:</p>

```[simple-table]: key1, value1
[simple-table]: key2, value2
[simple-table]: key3, value3
[simple-table]: key1, value11
[simple-table]: key2, value22
[simple-table]: key3, value33
```

<p>I am supposed to have only the latest 3 lines. Please help. </p>

<p><strong>UPDATE</strong></p>

<p>As per the solution below, everything works well when I create the KTable like this:</p>

```val simpleTable: KTable[String, String] =
    builder.table[String, String](topic, Materialized.as[String, String, KeyValueStore[Bytes, Array[Byte]]]("simple-table-store"))
```

答:
I got an answer from this Question.

The code used to work with older version of kafka-streams, older than 2.2.

CopyPasted

In Kafka 2.2, an optimization was introduced to reduce the resource footprint of Kafka Streams. A KTable is not necessarily materialized if it's not required for the computation. This holds for your case, because mapValues() can be computed on-the-fly. Because the KTable is not materialized, there is no cache and thus each input record produces one output record.

Compare: https://issues.apache.org/jira/browse/KAFKA-6036

If you want to enforce KTable materialization, you can pass in Materilized.as("someStoreName") into StreamsBuilder#table() method.

Body:
My KTable is emitting on each update, instead of the latest updates only.

Please see code below (in Scala):

object SimpleTable extends App {
  val topic = "simple-table"

  val prodProps = new Properties()
  prodProps.put("bootstrap.servers", "localhost:9092")
  prodProps.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer")
  prodProps.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer")
  prodProps.put("acks", "1")
  prodProps.put("retries", "3")

  val producer = new KafkaProducer[String, String](prodProps)

  producer.send(new ProducerRecord[String, String](topic, "key1", "value1"))
  producer.send(new ProducerRecord[String, String](topic, "key2", "value2"))
  producer.send(new ProducerRecord[String, String](topic, "key3", "value3"))
  producer.send(new ProducerRecord[String, String](topic, "key1", "value11"))
  producer.send(new ProducerRecord[String, String](topic, "key2", "value22"))
  producer.send(new ProducerRecord[String, String](topic, "key3", "value33"))

  producer.close()

  val streamProps = new Properties()
  streamProps.put(StreamsConfig.APPLICATION_ID_CONFIG, "simple-table-app1")
  streamProps.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092")
  //streamProps.put(ConsumerConfig.GROUP_ID_CONFIG, "group11")
  //streamProps.put(ConsumerConfig.CLIENT_ID_CONFIG, "client11")
  //streamProps.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest")
  //streamProps.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "18000")
  //streamProps.put(StreamsConfig.COMMIT_INTERVAL_MS_CONFIG, "18000")
  //streamProps.put(StreamsConfig.CACHE_MAX_BYTES_BUFFERING_CONFIG, "10485760")
  //streamProps.put(StreamsConfig.NUM_STREAM_THREADS_CONFIG, "1")
  //streamProps.put(ConsumerConfig.METADATA_MAX_AGE_CONFIG, "10000")
  //streamProps.put(StreamsConfig.REPLICATION_FACTOR_CONFIG, 1)
  //streamProps.put(StreamsConfig.DEFAULT_TIMESTAMP_EXTRACTOR_CLASS_CONFIG, classOf[WallclockTimestampExtractor])

  import org.apache.kafka.streams.scala.Serdes._
  implicit val consumeSerdes: Consumed[String, String] = Consumed.`with`[String, String]
  val builder = new StreamsBuilder()

  val simpleTable: KTable[String, String] = builder.table[String, String](topic)
  simpleTable.toStream.print(Printed.toSysOut[String, String].withLabel("simple-table"))

  val streams = new KafkaStreams(builder.build(), streamProps)
  streams.start()
  Thread.sleep(10000)
  streams.close()
}

This App is displaying this:

[simple-table]: key1, value1
[simple-table]: key2, value2
[simple-table]: key3, value3
[simple-table]: key1, value11
[simple-table]: key2, value22
[simple-table]: key3, value33

I am supposed to have only the latest 3 lines. Please help.

UPDATE

As per the solution below, everything works well when I create the KTable like this:

val simpleTable: KTable[String, String] =
    builder.table[String, String](topic, Materialized.as[String, String, KeyValueStore[Bytes, Array[Byte]]]("simple-table-store"))