问:
Trying to convert this VB.Net ThreadStart WCF code to C#
I have the following code in VB.Net.  It compiles and works as desired.

In my efforts to move to C#, whenever I work on a new project, I endeavour to use C#, however in this case, I'm clearly missing something.

```<code>Private m_Service As ServiceHost = Nothing

Public Function Start(ByVal AddressToConnect As String) As Thread
    Dim ServerProcess As New Thread(AddressOf WebService)

    ServerProcess.Start(AddressToConnect)

    Return ServerProcess
End Function

Private Sub WebService(ByVal AddressToListen As String) ' Address should be in the form: "http://localhost:8000/IHello"
    ' Define where to listen
    Dim Address As Uri = New Uri(AddressToListen)
    ' Define how to exchange messages
    Dim Binding As BasicHttpBinding = New BasicHttpBinding()

    ' When the connection is established, define what object is created
    m_Service = New ServiceHost(GetType(Worker), Address)

    ' Add an endpoint, passing the address, binding and contract
    m_Service.AddServiceEndpoint(GetType([Interface].IContract), Binding, Address)

    ' YOU MUST PERFORM THE FOLLOWING BEFORE YOU ATTEMPT TO OPEN THE CONNECTION
    ' netsh http add urlacl url=http://+:80/MyUri user=DOMAIN\user

    ' Begin listening for connections
    m_Service.Open()
    Console.WriteLine("WCF Service started")
End Sub

Public Sub [Stop]()
    m_Service.Close()
    m_Service = Nothing
End Sub
</code>```

The same in C# from one of those VB to C# conversion sites says the following should work:

```<code>private ServiceHost _Service = null;

public Thread Start(string AddressToConnect)
{

    Thread ServerProcess = new Thread(new EventHandler(WebService));
    ServerProcess.Start(AddressToConnect);
    return ServerProcess;
}

private void WebService(string AddressToListen)
{
    //  Address should be in the form: "http://localhost:8000/IHello"
    //  Define where to listen
    Uri Address = new Uri(AddressToListen);
    //  Define how to exchange messages

    BasicHttpBinding Binding = new BasicHttpBinding();

    //  When the connection is established, define what object is created
    _Service = new ServiceHost(typeof(Worker), Address);

    //  Add an endpoint, passing the address, binding and contract
    _Service.AddServiceEndpoint(typeof(Interface.IContract), Binding, Address);

    //  YOU MUST PERFORM THE FOLLOWING BEFORE YOU ATTEMPT TO OPEN THE CONNECTION
    //  netsh http add urlacl url=http://+:80/MyUri user=DOMAIN\user

    //  Begin listening for connections
    _Service.Open();
    Console.WriteLine("WCF Service started");
}

public void Stop()
{
    _Service.Close();
    _Service = null;
}
</code>```

The problem is that the compiler complains about:
    Thread ServerProcess = new Thread(new EventHandler(WebService));

"No overload for WebService matches delegate EventHandler"

What am I doing wrong?  What should the C# code be?

Apologies for what should be an easy question, but I've always struggled with delegates.

--EDIT--

Thanks to Markus, this is what I have now:

```<code>public Thread Start(string AddressToConnect)
    {
        Thread ServerProcess = new Thread(WebService);

        ServerProcess.Start(AddressToConnect);

        return ServerProcess;
    }
</code>```

And the WebService method is now:

```<code>private void WebService(object AddressToListen)
    {
        //  Address should be in the form: "http://localhost:8000/IHello"
        //  Define where to listen
        Uri Address = new Uri((string)AddressToListen);
        //  Define how to exchange messages
...
</code>```

答:
You can remove the AddressOf operator. It is not required in C#:

```<code>Thread ServerProcess = new Thread(WebService);
</code>```

One thing to note though is that the method provided needs to match the signature of ParameterizedThreadStart. This takes an object as parameter  so you need to change the signature of your WebService method:

```<code>private void WebService(object AddressToListen)
</code>```

In the method, you have to convert the object to a string.

Body:
I have the following code in VB.Net.  It compiles and works as desired.

In my efforts to move to C#, whenever I work on a new project, I endeavour to use C#, however in this case, I'm clearly missing something.

Private m_Service As ServiceHost = Nothing

Public Function Start(ByVal AddressToConnect As String) As Thread
    Dim ServerProcess As New Thread(AddressOf WebService)

    ServerProcess.Start(AddressToConnect)

    Return ServerProcess
End Function

Private Sub WebService(ByVal AddressToListen As String) ' Address should be in the form: "http://localhost:8000/IHello"
    ' Define where to listen
    Dim Address As Uri = New Uri(AddressToListen)
    ' Define how to exchange messages
    Dim Binding As BasicHttpBinding = New BasicHttpBinding()

    ' When the connection is established, define what object is created
    m_Service = New ServiceHost(GetType(Worker), Address)

    ' Add an endpoint, passing the address, binding and contract
    m_Service.AddServiceEndpoint(GetType([Interface].IContract), Binding, Address)

    ' YOU MUST PERFORM THE FOLLOWING BEFORE YOU ATTEMPT TO OPEN THE CONNECTION
    ' netsh http add urlacl url=http://+:80/MyUri user=DOMAIN\user

    ' Begin listening for connections
    m_Service.Open()
    Console.WriteLine("WCF Service started")
End Sub

Public Sub [Stop]()
    m_Service.Close()
    m_Service = Nothing
End Sub

The same in C# from one of those VB to C# conversion sites says the following should work:

private ServiceHost _Service = null;

public Thread Start(string AddressToConnect)
{

    Thread ServerProcess = new Thread(new EventHandler(WebService));
    ServerProcess.Start(AddressToConnect);
    return ServerProcess;
}

private void WebService(string AddressToListen)
{
    //  Address should be in the form: "http://localhost:8000/IHello"
    //  Define where to listen
    Uri Address = new Uri(AddressToListen);
    //  Define how to exchange messages

    BasicHttpBinding Binding = new BasicHttpBinding();

    //  When the connection is established, define what object is created
    _Service = new ServiceHost(typeof(Worker), Address);

    //  Add an endpoint, passing the address, binding and contract
    _Service.AddServiceEndpoint(typeof(Interface.IContract), Binding, Address);

    //  YOU MUST PERFORM THE FOLLOWING BEFORE YOU ATTEMPT TO OPEN THE CONNECTION
    //  netsh http add urlacl url=http://+:80/MyUri user=DOMAIN\user

    //  Begin listening for connections
    _Service.Open();
    Console.WriteLine("WCF Service started");
}

public void Stop()
{
    _Service.Close();
    _Service = null;
}

The problem is that the compiler complains about:
    Thread ServerProcess = new Thread(new EventHandler(WebService));

"No overload for WebService matches delegate EventHandler"

What am I doing wrong?  What should the C# code be?

Apologies for what should be an easy question, but I've always struggled with delegates.

--EDIT--

Thanks to Markus, this is what I have now:

public Thread Start(string AddressToConnect)
    {
        Thread ServerProcess = new Thread(WebService);

        ServerProcess.Start(AddressToConnect);

        return ServerProcess;
    }

And the WebService method is now:

private void WebService(object AddressToListen)
    {
        //  Address should be in the form: "http://localhost:8000/IHello"
        //  Define where to listen
        Uri Address = new Uri((string)AddressToListen);
        //  Define how to exchange messages
...

Body:
You can remove the AddressOf operator. It is not required in C#:

Thread ServerProcess = new Thread(WebService);

One thing to note though is that the method provided needs to match the signature of ParameterizedThreadStart. This takes an object as parameter  so you need to change the signature of your WebService method:

private void WebService(object AddressToListen)

In the method, you have to convert the object to a string.


来源: stackexchange

问:
Is MySQL SSL really safe to use?
I was searching the web for an entire answer, but didn't really find any. My question: Is it safe to allow access to MySQL on my server directly from the internet, when I use the implemented SSL of MySQL?

My point is: MySQL SSL encrypts all communication and one can restrict the access to the database by forcing SSL (GRANT ALL PRIVILEGES ON <database> TO '<external_user>'@'%' IDENTIFIED BY 'pass' REQUIRE SSL), to allow access to the database only for users with a public key. All good.

However, I have to allow access to MySQL from any IP address (removing bind-address 127.0.0.1) and I have to open port 3306 in my firewall (in my case I use ufw as a front-end for iptables). These two steps seem very insecure for me (especially when i count the attempts to attack my port 22 in the fail2ban log).

Does anyone have a reason why I am wrong, an alternative idea or a set of settings to make this secure?

Note: I don't want to use an SSH Tunnel. It is certainly very secure, but to my knowledge reduces performance quite a lot.

Note II: I want to connect to the database with PHPs PDO class.

答:
SSL as used in your setup secures the transport against sniffing and modifications - nothing more and nothing less. Your setting of require SSL only requires the client to use SSL (contrary to your claim of "allow access to the database only for users with a public key"). It does not enforce the use of specific client certificates or even client certificates at all. This means anybody knowing the password can connect.

Thus, proper access control of your database still depends only on all passwords staying secret. And while SSL helps against sniffing the password from the connection and against modifying traffic (i.e. changing statements) it does not help against an attacker already knowing the password.

TLS does not help either to protect against problems at your client, like the attacker being able to inject his own SQL statements using SQL injection. And, exposing the database directly to the internet makes it vulnerable to denial of service attacks and also to brute-forcing passwords, no matter if SSL is used or not.

ContentLicense: CC BY-SA 3.0

Title: Is MySQL SSL really safe to use?


问:
Dynamically loading a SWF into ShadowBox
FYI, ShadowBox is a javscript media viewer/lightbox.  http://www.shadowbox-js.com/

Running into an issue when trying to dynamically load SWFs into my ShadowBox.

My script outputs the following HTML:

```<code><div id="LightBoxItemList">
<a href="Images/large01.jpg" rel="shadowbox[Mixed];" class="First" />
<a href="Images/Hydro_Sample.swf" rel="shadowbox[Mixed];width: 800;height: 600;" />
<a href="Images/large01.jpg" rel="shadowbox[Mixed];" />
</div>
</code>```

After this HTML is created and inserted into my page, I run the following script:

```<code>Shadowbox.clearCache();
Shadowbox.setup("#LightBoxItemList a");
</code>```

Everything loads correct except the SWF.  The SWF loads with a width and height of 300x300.  I'm not sure what I'm doing wrong, but any advice would be awesome.  Also, I'm running init() with skipSetup.

I would also note that if I put in the HTML into the sample statically (not through an AJAX call), it works correctly after my Shadowbox.Init() (with skipSetup taken out).

So it looks like setup() isn't doing what it should be doing.  Or I'm doing it wrong.

Any suggestions would be greatly appreciated!

答:
You need to use = after width and height. Not :.

```<code>shadowbox[Mixed];width=600;height=200;
</code>```

ContentLicense: CC BY-SA 2.5

Body:
FYI, ShadowBox is a javscript media viewer/lightbox.  http://www.shadowbox-js.com/

Running into an issue when trying to dynamically load SWFs into my ShadowBox.

My script outputs the following HTML:

After this HTML is created and inserted into my page, I run the following script:

Shadowbox.clearCache();
Shadowbox.setup("#LightBoxItemList a");

Everything loads correct except the SWF.  The SWF loads with a width and height of 300x300.  I'm not sure what I'm doing wrong, but any advice would be awesome.  Also, I'm running init() with skipSetup.

I would also note that if I put in the HTML into the sample statically (not through an AJAX call), it works correctly after my Shadowbox.Init() (with skipSetup taken out).

So it looks like setup() isn't doing what it should be doing.  Or I'm doing it wrong.

Any suggestions would be greatly appreciated!

Body:
You need to use = after width and height. Not :.

shadowbox[Mixed];width=600;height=200;


问:
How to Move IBM Rational ClearCase Solaris VOB Server VOBs to a new domain
Our Clearcase Environment details as follows,

```<code>Server Operating System: SunOS 5.10 Generic.
Clearcase Server Version: ClearCase 7.0.0.2-IFIX02.
Storage Type: NAS (Network-attached storage).
Client Side clearcase used on: Windows, Linux and Ubuntu operating systems.
</code>```

Requirement Description:-

We have Sun Solaris clearcase VOB server, we need to move our VOB server to new domain, Therefore could you share the best ways to migrate our VOBs to new domain.

答:
It was only Windows user PCs moved to new domain.

Then it is described by Domain user and group accounts

That does require a new service Albd Account, in order to net start the albd service.

But also:

setting the domain accounts for the Rational ClearCase administrators group and Rational ClearCase server process user

setting the Rational ClearCase primary group

ContentLicense: CC BY-SA 4.0

Body:
Our Clearcase Environment details as follows,

Server Operating System: SunOS 5.10 Generic.
Clearcase Server Version: ClearCase 7.0.0.2-IFIX02.
Storage Type: NAS (Network-attached storage).
Client Side clearcase used on: Windows, Linux and Ubuntu operating systems.

Requirement Description:-

We have Sun Solaris clearcase VOB server, we need to move our VOB server to new domain, Therefore could you share the best ways to migrate our VOBs to new domain.


问:
Clear text field on pressing enter
(Solved. Sorry for wasting your guys' time.)

In a web-based app I'm developing for personal use (online community), users have the option of using a "command line" at the top, versus navigating through numerous pages. This saves time, sanity, and executes the code once.

The command line works. As of right now, when you hit enter (there is no submit button), it opens a new tab, runs "cmdline.php" with the relevant $_POST information, and then closes that tab when it's finished executing.

The problem comes in when the tab closes, the old text is still there, "NEW;1283;JSMITH". To avoid people having to highlight and delete it for another entry, I'm trying to figure out how to have it self-clear when you hit enter.

Here is what I have found so far. Note that I'm brand new to javascript/jquery.

```<code>    <script src="java/jquery.js"></script>
    <script type="text/javascript">
    $('#cmdline').bind('keyup', function(e) {
        if (e.keyCode === 13) {
        $('#cmdline').find('input:text').val('');
        }
    });
    </script>
</code>```

(later in the same file)

```<code>    <form   target="_blank"
            action="cmdline.php"
            method="POST"
            id="cmdline"
    >
        <input type="text" placeholder="Ready for Command" autocomplete="off" name="cmdline">
    </form>
</code>```

答:
Just fixed it. I knew as soon as I posted a question I would figure it out...</p>

```<code>    <script src="java/jquery.js"></script>
    <script type="text/javascript">

    function emptyText() {
        $('#cmdline').find('input:text').val('')
    }

    </script>

    <form   target="_blank"
            action="cmdline.php"
            method="POST"
            id="cmdline"
            onsubmit="emptyText()"
    >
        <input type="text" placeholder="Ready for Command" autocomplete="off" name="cmdline">
    </form>
</code>```

Title: Clear text field on pressing enter

Body:
(Solved. Sorry for wasting your guys' time.)

In a web-based app I'm developing for personal use (online community), users have the option of using a "command line" at the top, versus navigating through numerous pages. This saves time, sanity, and executes the code once.

The command line works. As of right now, when you hit enter (there is no submit button), it opens a new tab, runs "cmdline.php" with the relevant $_POST information, and then closes that tab when it's finished executing.

The problem comes in when the tab closes, the old text is still there, "NEW;1283;JSMITH". To avoid people having to highlight and delete it for another entry, I'm trying to figure out how to have it self-clear when you hit enter.

Here is what I have found so far. Note that I'm brand new to javascript/jquery.

(later in the same file)

    <form   target="_blank"
            action="cmdline.php"
            method="POST"
            id="cmdline"
    >
        <input type="text" placeholder="Ready for Command" autocomplete="off" name="cmdline">
    </form>

Body:
Just fixed it. I knew as soon as I posted a question I would figure it out...

    <script src="java/jquery.js"></script>
    <script type="text/javascript">

    function emptyText() {
        $('#cmdline').find('input:text').val('')
    }

    </script>

    <form   target="_blank"
            action="cmdline.php"
            method="POST"
            id="cmdline"
            onsubmit="emptyText()"
    >
        <input type="text" placeholder="Ready for Command" autocomplete="off" name="cmdline">
    </form>


问:
disable xampp redirect http to https
I created VirtualHost at my xampp in localhost for wordpress and add this code in httpd-vhosts.conf :

```<code><VirtualHost *:80>
ServerAdmin webmaster@mysitefolder
DocumentRoot "E:/xampp/htdocs/mysitefolder"
ServerName mysitefolder
ErrorLog "logs/mysitefolder-error.log"
CustomLog "logs/mysitefolder-access.log" common
</VirtualHost>
</code>```

but when enter http://mysitefolder in browser it's aout redirect to https://mysitefolder and not load my site. how can disable https and only using http ?thank you

答:
In your wp-config.php file.

```<code>define('WP_HOME','http://yourwordpressurl.com');
define('WP_SITEURL','http://yourwordpressurl.com');
</code>```

This will force your site to use http:// instead of https

Title: disable xampp redirect http to https

Body:
I created VirtualHost at my xampp in localhost for wordpress and add this code in httpd-vhosts.conf :

<VirtualHost *:80>
ServerAdmin webmaster@mysitefolder
DocumentRoot "E:/xampp/htdocs/mysitefolder"
ServerName mysitefolder
ErrorLog "logs/mysitefolder-error.log"
CustomLog "logs/mysitefolder-access.log" common
</VirtualHost>

but when enter http://mysitefolder in browser it's aout redirect to https://mysitefolder and not load my site. how can disable https and only using http ?thank you

Body:
In your wp-config.php file.

define('WP_HOME','http://yourwordpressurl.com');
define('WP_SITEURL','http://yourwordpressurl.com');

This will force your site to use http:// instead of https


问:
How to change action link as per drop-down list?
```<code><form action="result.php" method="POST">
<select name="strm">
  <option disabled="disabled" selected="selected" value="">Select Your Stream</option>
  <option value="ARTS">Arts</option>
  <option value="COMMERCE">Commerce</option>
  <option value="SCIENCE">Science</option>
</select>

<input maxlength="4" minlength="4" name="rollcode" oninput="setCustomValidity('')" oninvalid="this.setCustomValidity('Enter your Center Code')" placeholder="Center Code" required="" type="text" />

<input maxlength="5" minlength="5" name="rollno" oninput="setCustomValidity('')" oninvalid="this.setCustomValidity('Enter your Roll No')" placeholder="Roll No" required="" type="text" />

<input type="submit" value="Get Result" />
</code>```

Above mentioned a form where I want to change my action link as per selection of Arts, Commrence or Science. In other words Now the default php link contains all 3 stream's information in one but I want to create separate database for each and searchable from one form. Is there any way to do this?

答:
You can add this.form.action of JavaScript with all options like below:

```<code><form action="result.php" method="POST">
<select name="strm">
  <option selected="selected" value="">Select Your Stream</option>
  <option onclick="javaScript: this.form.action='arts.php';" value="ARTS">Arts</option>
  <option onclick="javaScript: this.form.action='commerce.php';" value="COMMERCE">Commerce</option>
  <option onclick="javaScript: this.form.action='science.php';" value="SCIENCE">Science</option>
</select>
</code>```

When you submit the form, there form action will be replace with the one you add in select option.

You can also send to common action like result.php with parameter like below:

```<code><form action="result.php" method="POST">
<select name="strm">
  <option selected="selected" value="">Select Your Stream</option>
  <option onclick="javaScript: this.form.action='result.php?title=arts';" value="ARTS">Arts</option>
  <option onclick="javaScript: this.form.action='result.php?title=commerce';" value="COMMERCE">Commerce</option>
  <option onclick="javaScript: this.form.action='result.php?title=science';" value="SCIENCE">Science</option>
</select>
</code>```

You can also do it with JQuery in the below way:

```<code><form action="result.php" method="POST" name="streamForm" id="streamForm">
<select name="strm" id="strm">
  <option selected="selected" value="">Select Your Stream</option>
  <option value="ARTS">Arts</option>
  <option value="COMMERCE">Commerce</option>
  <option value="SCIENCE">Science</option>
</select>
</code>```

Jquery Code:

```<code><script type="text/JavaScript">
$("#strm").change(function() {
  var action = $(this).val() == "ARTS";
  $("#streamForm").attr("action", "arts.php");
});
</script>
</code>```

Body:
<form action="result.php" method="POST">
<select name="strm">
  <option disabled="disabled" selected="selected" value="">Select Your Stream</option>
  <option value="ARTS">Arts</option>
  <option value="COMMERCE">Commerce</option>
  <option value="SCIENCE">Science</option>
</select>

<input maxlength="4" minlength="4" name="rollcode" oninput="setCustomValidity('')" oninvalid="this.setCustomValidity('Enter your Center Code')" placeholder="Center Code" required="" type="text" />

<input maxlength="5" minlength="5" name="rollno" oninput="setCustomValidity('')" oninvalid="this.setCustomValidity('Enter your Roll No')" placeholder="Roll No" required="" type="text" />

<input type="submit" value="Get Result" />

Above mentioned a form where I want to change my action link as per selection of Arts, Commrence or Science. In other words Now the default php link contains all 3 stream's information in one but I want to create separate database for each and searchable from one form. Is there any way to do this?

Body:
You can add this.form.action of JavaScript with all options like below:

<form action="result.php" method="POST">
<select name="strm">
  <option selected="selected" value="">Select Your Stream</option>
  <option onclick="javaScript: this.form.action='arts.php';" value="ARTS">Arts</option>
  <option onclick="javaScript: this.form.action='commerce.php';" value="COMMERCE">Commerce</option>
  <option onclick="javaScript: this.form.action='science.php';" value="SCIENCE">Science</option>
</select>

When you submit the form, there form action will be replace with the one you add in select option.

You can also send to common action like result.php with parameter like below:

<form action="result.php" method="POST">
<select name="strm">
  <option selected="selected" value="">Select Your Stream</option>
  <option onclick="javaScript: this.form.action='result.php?title=arts';" value="ARTS">Arts</option>
  <option onclick="javaScript: this.form.action='result.php?title=commerce';" value="COMMERCE">Commerce</option>
  <option onclick="javaScript: this.form.action='result.php?title=science';" value="SCIENCE">Science</option>
</select>

You can also do it with JQuery in the below way:

<form action="result.php" method="POST" name="streamForm" id="streamForm">
<select name="strm" id="strm">
  <option selected="selected" value="">Select Your Stream</option>
  <option value="ARTS">Arts</option>
  <option value="COMMERCE">Commerce</option>
  <option value="SCIENCE">Science</option>
</select>

Jquery Code:

<script type="text/JavaScript">
$("#strm").change(function() {
  var action = $(this).val() == "ARTS";
  $("#streamForm").attr("action", "arts.php");
});
</script>


问:
How to stop execution of piece of code in android until data is retrieved from Firebase?
I am trying to perform some task based on the data retrieved from Firebase.

```<code>for (inti=0;i<dateList.size();i++)
{
    attendanceDateRef= attendanceRef.child(dateList.get(i));
    attendanceClassRef= attendanceDateRef.child(ViewAttendanceSelectClassActivity.selectedClass);
    attendanceClassRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshotdataSnapshot) {
            for (DataSnapshotdsp : dataSnapshot.getChildren())
            {
                attendanceList.add(dsp.getValue(String.class));
                Log.e("attendanceListValues",dsp.getValue(String.class));
            }
        }

        @Override
        public void onCancelled(DatabaseErrordatabaseError) {

        }
    });
}

intindex=1;

for (inti=1;i<=attendanceList.size();i++)
{
    if(i%4==0)
    {
        fullDateRangeList.add(dateList.get(index));
        index++;
    }
    else
    {
        fullDateRangeList.add(dateList.get(index));
    }

}

Log.e("fullDateRangeList",String.valueOf(fullDateRangeList.size()));
Log.e("attendanceList",String.valueOf(attendanceList.size()));
</code>```

above code is written on the OnClick event of a Button , when I click on the Button following output is generated on logcat:

```<code>fullDateRangeList:0
attendanceList:0
attendanceListValues:Value1
attendanceListValues:Value2
attendanceListValues:Value3
attendanceListValues:Value4
.
.
.
attendanceListValues:ValueN
</code>```

from the above output it looks like second loop is executing before data is retrieved from Firebase and that is why size of fullDateRange and attendanceList is 0.

is there any way i can prevent second loop from executing until data is stored in attendanceList?

答:
You cannot stop that method or make it wait until you get the all the data from your database. This is the behaviour of an asynchronous method. You need to change the logic of your code a little bit by declaring and using that data only inside the onDataChange() method, otherwise it will be always empty.

Also there is another approach. If you want, you can dive into the asynchronous world and use my answer from this post.

Body:
I am trying to perform some task based on the data retrieved from Firebase.

for (inti=0;i<dateList.size();i++)
{
    attendanceDateRef= attendanceRef.child(dateList.get(i));
    attendanceClassRef= attendanceDateRef.child(ViewAttendanceSelectClassActivity.selectedClass);
    attendanceClassRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshotdataSnapshot) {
            for (DataSnapshotdsp : dataSnapshot.getChildren())
            {
                attendanceList.add(dsp.getValue(String.class));
                Log.e("attendanceListValues",dsp.getValue(String.class));
            }
        }

        @Override
        public void onCancelled(DatabaseErrordatabaseError) {

        }
    });
}

intindex=1;

for (inti=1;i<=attendanceList.size();i++)
{
    if(i%4==0)
    {
        fullDateRangeList.add(dateList.get(index));
        index++;
    }
    else
    {
        fullDateRangeList.add(dateList.get(index));
    }

}

Log.e("fullDateRangeList",String.valueOf(fullDateRangeList.size()));
Log.e("attendanceList",String.valueOf(attendanceList.size()));

above code is written on the OnClick event of a Button , when I click on the Button following output is generated on logcat:

fullDateRangeList:0
attendanceList:0
attendanceListValues:Value1
attendanceListValues:Value2
attendanceListValues:Value3
attendanceListValues:Value4
.
.
.
attendanceListValues:ValueN

from the above output it looks like second loop is executing before data is retrieved from Firebase and that is why size of fullDateRange and attendanceList is 0.

is there any way i can prevent second loop from executing until data is stored in attendanceList?


问:
How do you determine how far to normalize a database?
When creating a database structure, what are good guidelines to follow or good ways to determine how far a database should be normalized? Should you create an un-normalized database and split it apart as the project progresses? Should you create it fully normalized and combine tables as needed for performance?</p>

答:
Database normizational I feel is an art form.

You don't want to over normalize your database because you will have too many tables and it will cause your queries of even simple objects take longer than they should.

A good rule of thumb I follow is to normalize the same information repeated over and over again.

For example if you are creating a contact management application it would make sense to have Address (Street, City, State, Zip, etc. . ) as its own table.

However if you have only 2 types of contacts, Business or personal, do you need a contact type table if you know you are only going to have 2?  For me no.

I would start by first figuring out the datatypes you need.  Use a modeling program to help like Visio.  You don't want to start with a non-normalized database because you will eventually normalize.  Start by putting objects in there logical groupings, as you see data repeated take that data into a new table.  I would keep up with that process until you feel you have the database designed.

Let testing tell you if you need to combine tables.  A well written query can cover any over normalization.


问:
Data Analytics Approach
I have a dataset of fresh graduate employees with their GPA scores and whether they were hired or fired after Probation period. I was asked by the boss to analyse whether the university GPA has any significant effect on being hired or fired. Sometimes additional features can also be included like university ranking and etc. Boss is now a days interested in data science and machine learning. But I haven't had any prior experience in data analytics  So just give me a heads up into how i can approach this problem and what i should learn to do this? I have programming background (know python) so technical jargons are welcome.</p>

答:
In these , you are basically trying to predict whether the university GPA,university ranking and etc has any significant effect on being hired or fired after Probation period. Basically it is Binary classification problem (for complete tutorial on these Binary Classification Best Tutorial).
The approach given by @janu777 is correct , i wanted to add some additional information in that.
The steps for solving these problem is ,

```<code>Data Exploration(include variable identifications)
Data Cleaning
Feature Engineering(Watching correlations kind of property among features)
Model Building and Training
Doing Predictions
</code>```

Basically from python side you will use these libraries

```<code>Pandas
Scikit Learn
Matplotlib
numpy
Sklearn
Statsmodelapi
</code>```

Data Exploration:
Firstly you should have previous years data(whether previous employee was hired or fired) as train set .

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

df = pd.read_csv("../trainset.csv") #Reading the dataset in a dataframe
df.describe()
</code>```

Data Cleaning

Now in these stage you should have to see missing values and all in your data and you can do treatment according to your choice , most famous is to drop all missing values , so for that you can use these ,

```<code>df.dropna(axis=0, how='all')
</code>```

I am assuming that your train set have 3 variable in which university GPA and university ranking is feature variable . and your target variable is hired/fired(1 or 0) . you should use correlation among your predictor and target variable and also visualization will be helpful.

```<code>trainingdata['GPA'].astype('float64').corr(trainingdata['target'].astype('float64'))
</code>```

or

```<code># importing the required module
import matplotlib.pyplot as plt

# x axis values
x = [1,2,3] # your feature variable
# corresponding y axis values
y = [2,4,1] # your target variable

# plotting the points
plt.plot(x, y)

# naming the x axis
plt.xlabel('x - axis')
# naming the y axis
plt.ylabel('y - axis')

# giving a title to my graph
plt.title('My first graph!')

# function to show the plot
plt.show()
</code>```

Model Building and predictions and fitting
That is very important stage , now you need to create model for your problem and you can use these algorithms Sklearn algo(you should apply vaious algorithms as Randomforest,lineardiscriminate,decisiontree,knn,svm etc and choose only that algorithm which gives good score)
sample code for these is ,

```<code>from sklearn.ensemble import RandomForestClassifier
#Building random forest classifier model
def random_forest_classifier(features, target):
    """
    To train the random forest classifier with features and target data
    :param features:
    :param target:
    :return: trained random forest classifier
    """
    clf = RandomForestClassifier()
    clf.fit(features, target)
    return clf
</code>```

Doing Predictions
Now you can do prediction on your test data , sample code for the same is ,

```<code>   predictions = randomforestmodelis.predict(test_x)
    for i in range(0, 5):
        print("Actual outcome :: {} and Predicted outcome :: {}".format(list(test_y)[i], predictions[i]))
        #print("Train Accuracy :: ", accuracy_score(train_y, randomforestmodelis.predict(train_x)))
    print("Test Accuracy  :: ", accuracy_score(test_y, predictions))
</code>```

That should solve your problem .

Title: Data Analytics Approach

Body:
In these , you are basically trying to predict whether the university GPA,university ranking and etc has any significant effect on being hired or fired after Probation period. Basically it is Binary classification problem (for complete tutorial on these Binary Classification Best Tutorial).
The approach given by @janu777 is correct , i wanted to add some additional information in that.
The steps for solving these problem is ,

Data Exploration(include variable identifications)
Data Cleaning
Feature Engineering(Watching correlations kind of property among features)
Model Building and Training
Doing Predictions

Basically from python side you will use these libraries

Pandas
Scikit Learn
Matplotlib
numpy
Sklearn
Statsmodelapi

Data Exploration:
Firstly you should have previous years data(whether previous employee was hired or fired) as train set .

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

df = pd.read_csv("../trainset.csv") #Reading the dataset in a dataframe
df.describe()

Data Cleaning

Now in these stage you should have to see missing values and all in your data and you can do treatment according to your choice , most famous is to drop all missing values , so for that you can use these ,

df.dropna(axis=0, how='all')

I am assuming that your train set have 3 variable in which university GPA and university ranking is feature variable . and your target variable is hired/fired(1 or 0) . you should use correlation among your predictor and target variable and also visualization will be helpful.

trainingdata['GPA'].astype('float64').corr(trainingdata['target'].astype('float64'))

or

# importing the required module
import matplotlib.pyplot as plt

# x axis values
x = [1,2,3] # your feature variable
# corresponding y axis values
y = [2,4,1] # your target variable

# plotting the points
plt.plot(x, y)

# naming the x axis
plt.xlabel('x - axis')
# naming the y axis
plt.ylabel('y - axis')

# giving a title to my graph
plt.title('My first graph!')

# function to show the plot
plt.show()

Model Building and predictions and fitting
That is very important stage , now you need to create model for your problem and you can use these algorithms Sklearn algo(you should apply vaious algorithms as Randomforest,lineardiscriminate,decisiontree,knn,svm etc and choose only that algorithm which gives good score)
sample code for these is ,

from sklearn.ensemble import RandomForestClassifier
#Building random forest classifier model
def random_forest_classifier(features, target):
    """
    To train the random forest classifier with features and target data
    :param features:
    :param target:
    :return: trained random forest classifier
    """
    clf = RandomForestClassifier()
    clf.fit(features, target)
    return clf

Doing Predictions
Now you can do prediction on your test data , sample code for the same is ,

   predictions = randomforestmodelis.predict(test_x)
    for i in range(0, 5):
        print("Actual outcome :: {} and Predicted outcome :: {}".format(list(test_y)[i], predictions[i]))
        #print("Train Accuracy :: ", accuracy_score(train_y, randomforestmodelis.predict(train_x)))
    print("Test Accuracy  :: ", accuracy_score(test_y, predictions))

That should solve your problem .


问:
Exception While Running SpringWS JUnit Test : java.lang.IllegalStateException: Failed to load ApplicationContext

I am getting an exception when I try to run the Spring Web Service JUnit Test Using the Spring WebService ServerSide Integration Test using MockWebServiceClient. When I run the WebService (Not Test), it is running fine but when I run the Junit Test, I'm getting many exceptions.

java.lang.IllegalStateException: Failed to load ApplicationContext

and

Error creating bean with name 'spring_WS_ServletConfig': Unsatisfied dependency expressed through field 'dataSource';

Can anybody please tell me what's going on these codes?

Spring_WS_ServletConfig

```<code>@Configuration
@EnableWs
@EnableTransactionManagement
@ComponentScan({ "com.springws.endpoint", "com.mybatis.", "com.mapstruct" })
@ImportResource({ "classpath:/SpringConfig/spring-database-config.xml" })
public class Spring_WS_ServletConfig extends WsConfigurerAdapter {
    @Autowired
    DataSource dataSource;

    @Bean("StudentServiceWsdl")
    public DefaultWsdl11Definition orders() throws SQLException {
        DefaultWsdl11Definition definition = new DefaultWsdl11Definition();
        definition.setPortTypeName("StudentService_SpringWS_PortType");
        definition.setLocationUri("http://localhost:8080/MvnSpringMcc/StudentService_SpringWS/");
        definition.setTargetNamespace("com.springws.student/LearnSpringWs");
        definition.setServiceName("SpringWSService");
        definition.setSchema(studentsSchema());

        return definition;
    }

    @Bean
    public XsdSchema studentsSchema() {
        Resource resource = new ClassPathResource("/wsdl/StudentTask.xsd");
        return new SimpleXsdSchema(new ClassPathResource("/Schema_Wsdl/StudentTask.xsd"));
    }

    @Override
    public void addInterceptors(List<EndpointInterceptor> interceptors) {
        PayloadValidatingInterceptor validator = new PayloadValidatingInterceptor();
        validator.setValidateRequest(true);
        validator.setValidateResponse(true);
        validator.setSchema(new ClassPathResource("/Schema_Wsdl/StudentTask.xsd"));
    }
}
</code>```

CourseServiceEndPointServerSideIntegrationTest

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { Spring_WS_ServletConfig.class })
public class CourseServiceEndPointServerSideIntegrationTest {
    @Autowired
    ResourceLoader resourceLoader;

    @Autowired
    private ApplicationContext applicationContext;

    private MockWebServiceClient mockClient;

    @Before
    public void createClient() {
        mockClient = MockWebServiceClient.createClient(applicationContext);
    }

    @Test
    public void customerEndpoint() throws Exception {
        Resource requestPayLoad = resourceLoader.getResource("classpath:xmlTestFiles/RequestPayLoad.xml");
        Resource responsePayLoad = resourceLoader.getResource("classpath:xmlTestFiles/ResponsePayLoad.xml");

        mockClient.sendRequest(withPayload(requestPayLoad)).andExpect(payload(responsePayLoad));
    }
}
</code>```

RequestPayLoad.xml File

```<code><?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:lear="com.springws.student/LearnSpringWs" xmlns:stud="com.springws.student/StudentSchema">
    <soapenv:Header />
    <soapenv:Body>
        <lear:GetCourseRequest>
            <lear:Course>
                <stud:courseID>100</stud:courseID>
            </lear:Course>
        </lear:GetCourseRequest>
    </soapenv:Body>
</soapenv:Envelope>
</code>```

```<code>customerEndpoint(com.springws.test.CourseServiceEndPointServerSideIntegrationTest)  Time elapsed: 0.009 sec  <<< ERROR!
java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
    at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
    at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.ws.config.annotation.DelegatingWsConfiguration': Unsatisfied dependency expressed through method 'setConfigurers' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'spring_WS_ServletConfig': Unsatisfied dependency expressed through field 'dataSource'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'javax.sql.DataSource' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
Related cause: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [SpringConfig/spring-database-config.xml]: Invocation of init method failed; nested exception is javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial
Related cause: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'courseMapper' defined in class path resource [SpringConfig/spring-database-config.xml]: Cannot resolve reference to bean 'sqlSessionFactory' while setting bean property 'sqlSessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [SpringConfig/spring-database-config.xml]: Cannot resolve reference to bean 'dataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [SpringConfig/spring-database-config.xml]: Invocation of init method failed; nested exception is javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial
Related cause: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'studentMapper' defined in class path resource [SpringConfig/spring-database-config.xml]: Cannot resolve reference to bean 'sqlSessionFactory' while setting bean property 'sqlSessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [SpringConfig/spring-database-config.xml]: Cannot resolve reference to bean 'dataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [SpringConfig/spring-database-config.xml]: Invocation of init method failed; nested exception is javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial
Related cause: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [SpringConfig/spring-database-config.xml]: Invocation of init method failed; nested exception is javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial
Related cause: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'courseMapper' defined in class path resource [SpringConfig/spring-database-config.xml]: Cannot resolve reference to bean 'sqlSessionFactory' while setting bean property 'sqlSessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [SpringConfig/spring-database-config.xml]: Cannot resolve reference to bean 'dataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [SpringConfig/spring-database-config.xml]: Invocation of init method failed; nested exception is javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial
Related cause: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'studentMapper' defined in class path resource [SpringConfig/spring-database-config.xml]: Cannot resolve reference to bean 'sqlSessionFactory' while setting bean property 'sqlSessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [SpringConfig/spring-database-config.xml]: Cannot resolve reference to bean 'dataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [SpringConfig/spring-database-config.xml]: Invocation of init method failed; nested exception is javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:667)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:372)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.context.support.PostProcessorRegistrationDelegate.registerBeanPostProcessors(PostProcessorRegistrationDelegate.java:225)
    at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:703)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:528)
    at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:128)
    at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60)
    at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:108)
    at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:251)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
    ... 31 more
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'spring_WS_ServletConfig': Unsatisfied dependency expressed through field 'dataSource'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'javax.sql.DataSource' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.addCandidateEntry(DefaultListableBeanFactory.java:1316)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1282)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveMultipleBeans(DefaultListableBeanFactory.java:1180)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1096)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:659)
    ... 58 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'javax.sql.DataSource' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1493)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
    ... 74 more

Results :

Tests in error:
  customerEndpoint(com.springws.test.CourseServiceEndPointServerSideIntegrationTest): Failed to load ApplicationContext
</code>```

答:
As it clearly stated in Exception message - no bean of DataSource class was found within Application Context of the test run. You can either

1) remove injection of DataSource into Spring_WS_ServletConfig since it seems to be not used in that class

2) provide DataSource bean (real or mock, depending on your needs), for example like:

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { Spring_WS_ServletConfig.class, CourseServiceEndPointServerSideIntegrationTest.class })
@Configuration // << in order to use this class as "bean provider"
public class CourseServiceEndPointServerSideIntegrationTest {

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(environment.getProperty("test.database.driver"));
        dataSource.setUrl(environment.getProperty("test.database.url"));
        dataSource.setUsername(environment.getProperty("test.database.username"));
        dataSource.setPassword(environment.getProperty("test.database.password"));
        return dataSource;
    }

// or it can be just mocked using Mockito or similar framework

    @Bean
    public DataSource datasource() {
         return Mockito.mock(DataSource.class)
    }
// ...

}
</code>```

Body:
I am getting an exception when I try to run the Spring Web Service JUnit Test Using the Spring WebService ServerSide Integration Test using MockWebServiceClient. When I run the WebService (Not Test), it is running fine but when I run the Junit Test, I'm getting many exceptions.

java.lang.IllegalStateException: Failed to load ApplicationContext

and

Error creating bean with name 'spring_WS_ServletConfig': Unsatisfied dependency expressed through field 'dataSource';

Can anybody please tell me what's going on these codes?

Spring_WS_ServletConfig

@Configuration
@EnableWs
@EnableTransactionManagement
@ComponentScan({ "com.springws.endpoint", "com.mybatis.", "com.mapstruct" })
@ImportResource({ "classpath:/SpringConfig/spring-database-config.xml" })
public class Spring_WS_ServletConfig extends WsConfigurerAdapter {
    @Autowired
    DataSource dataSource;

    @Bean("StudentServiceWsdl")
    public DefaultWsdl11Definition orders() throws SQLException {
        DefaultWsdl11Definition definition = new DefaultWsdl11Definition();
        definition.setPortTypeName("StudentService_SpringWS_PortType");
        definition.setLocationUri("http://localhost:8080/MvnSpringMcc/StudentService_SpringWS/");
        definition.setTargetNamespace("com.springws.student/LearnSpringWs");
        definition.setServiceName("SpringWSService");
        definition.setSchema(studentsSchema());

        return definition;
    }

    @Bean
    public XsdSchema studentsSchema() {
        Resource resource = new ClassPathResource("/wsdl/StudentTask.xsd");
        return new SimpleXsdSchema(new ClassPathResource("/Schema_Wsdl/StudentTask.xsd"));
    }

    @Override
    public void addInterceptors(List<EndpointInterceptor> interceptors) {
        PayloadValidatingInterceptor validator = new PayloadValidatingInterceptor();
        validator.setValidateRequest(true);
        validator.setValidateResponse(true);
        validator.setSchema(new ClassPathResource("/Schema_Wsdl/StudentTask.xsd"));
    }
}

CourseServiceEndPointServerSideIntegrationTest

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { Spring_WS_ServletConfig.class })
public class CourseServiceEndPointServerSideIntegrationTest {
    @Autowired
    ResourceLoader resourceLoader;

    @Autowired
    private ApplicationContext applicationContext;

    private MockWebServiceClient mockClient;

    @Before
    public void createClient() {
        mockClient = MockWebServiceClient.createClient(applicationContext);
    }

    @Test
    public void customerEndpoint() throws Exception {
        Resource requestPayLoad = resourceLoader.getResource("classpath:xmlTestFiles/RequestPayLoad.xml");
        Resource responsePayLoad = resourceLoader.getResource("classpath:xmlTestFiles/ResponsePayLoad.xml");

        mockClient.sendRequest(withPayload(requestPayLoad)).andExpect(payload(responsePayLoad));
    }
}

RequestPayLoad.xml File

<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:lear="com.springws.student/LearnSpringWs" xmlns:stud="com.springws.student/StudentSchema">
    <soapenv:Header />
    <soapenv:Body>
        <lear:GetCourseRequest>
            <lear:Course>
                <stud:courseID>100</stud:courseID>
            </lear:Course>
        </lear:GetCourseRequest>
    </soapenv:Body>
</soapenv:Envelope>

customerEndpoint(com.springws.test.CourseServiceEndPointServerSideIntegrationTest)  Time elapsed: 0.009 sec  <<< ERROR!
java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
    at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
    at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.ws.config.annotation.DelegatingWsConfiguration': Unsatisfied dependency expressed through method 'setConfigurers' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'spring_WS_ServletConfig': Unsatisfied dependency expressed through field 'dataSource'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'javax.sql.DataSource' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
Related cause: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [SpringConfig/spring-database-config.xml]: Invocation of init method failed; nested exception is javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial
Related cause: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'courseMapper' defined in class path resource [SpringConfig/spring-database-config.xml]: Cannot resolve reference to bean 'sqlSessionFactory' while setting bean property 'sqlSessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [SpringConfig/spring-database-config.xml]: Cannot resolve reference to bean 'dataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [SpringConfig/spring-database-config.xml]: Invocation of init method failed; nested exception is javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial
Related cause: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'studentMapper' defined in class path resource [SpringConfig/spring-database-config.xml]: Cannot resolve reference to bean 'sqlSessionFactory' while setting bean property 'sqlSessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [SpringConfig/spring-database-config.xml]: Cannot resolve reference to bean 'dataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [SpringConfig/spring-database-config.xml]: Invocation of init method failed; nested exception is javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial
Related cause: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [SpringConfig/spring-database-config.xml]: Invocation of init method failed; nested exception is javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial
Related cause: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'courseMapper' defined in class path resource [SpringConfig/spring-database-config.xml]: Cannot resolve reference to bean 'sqlSessionFactory' while setting bean property 'sqlSessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [SpringConfig/spring-database-config.xml]: Cannot resolve reference to bean 'dataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [SpringConfig/spring-database-config.xml]: Invocation of init method failed; nested exception is javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial
Related cause: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'studentMapper' defined in class path resource [SpringConfig/spring-database-config.xml]: Cannot resolve reference to bean 'sqlSessionFactory' while setting bean property 'sqlSessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [SpringConfig/spring-database-config.xml]: Cannot resolve reference to bean 'dataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [SpringConfig/spring-database-config.xml]: Invocation of init method failed; nested exception is javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:667)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:372)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.context.support.PostProcessorRegistrationDelegate.registerBeanPostProcessors(PostProcessorRegistrationDelegate.java:225)
    at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:703)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:528)
    at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:128)
    at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60)
    at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:108)
    at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:251)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
    ... 31 more
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'spring_WS_ServletConfig': Unsatisfied dependency expressed through field 'dataSource'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'javax.sql.DataSource' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.addCandidateEntry(DefaultListableBeanFactory.java:1316)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1282)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveMultipleBeans(DefaultListableBeanFactory.java:1180)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1096)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:659)
    ... 58 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'javax.sql.DataSource' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1493)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
    ... 74 more

Results :

Tests in error:
  customerEndpoint(com.springws.test.CourseServiceEndPointServerSideIntegrationTest): Failed to load ApplicationContext

Body:
As it clearly stated in Exception message - no bean of DataSource class was found within Application Context of the test run. You can either

1) remove injection of DataSource into Spring_WS_ServletConfig since it seems to be not used in that class

2) provide DataSource bean (real or mock, depending on your needs), for example like:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { Spring_WS_ServletConfig.class, CourseServiceEndPointServerSideIntegrationTest.class })
@Configuration // << in order to use this class as "bean provider"
public class CourseServiceEndPointServerSideIntegrationTest {

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(environment.getProperty("test.database.driver"));
        dataSource.setUrl(environment.getProperty("test.database.url"));
        dataSource.setUsername(environment.getProperty("test.database.username"));
        dataSource.setPassword(environment.getProperty("test.database.password"));
        return dataSource;
    }

// or it can be just mocked using Mockito or similar framework

    @Bean
    public DataSource datasource() {
         return Mockito.mock(DataSource.class)
    }
// ...

}


问:
Deploying a socket.io app in on multiple-nodes
I have an app on heroku that uses socket.io for server-client communication.  Everything is working just fine.  However, once I scale my app to more than 1 dyno, I get several http request errors:

can't establish a connection to the server at wss://***/socket.io/?EIO=2&transport=websocket&sid=Hky6IHdckNADdU_tAACm. socket.io.js:4520
The connection to wss://***/socket.io/?EIO=2&transport=websocket&sid=Hky6IHdckNADdU_tAACm was interrupted while the page was loading. socket.io.js:4520
can't establish a connection to the server at wss://***/socket.io/?EIO=2&transport=websocket&sid=kWymv6ItJHBcUybZAAAA. socket.io.js:4520
The connection to wss://***/socket.io/?EIO=2&transport=websocket&sid=kWymv6ItJHBcUybZAAAA was interrupted while the page was loading. socket.io.js:4520

As well as a load of

HTTP status 400
{ code: 1, message: "Session ID unknown" }

My socket.io is using the redis adapter, so the state should be shared correctly.  I kind of verified this by connecting to redis and issuing the following command:

PSUBSCRIBE socket.io#*

Since I can see data traveling back and force on this channel, I am assuming my socket.io redis adapter is working fine.

Anyone know how to make socket.io work on heroku with more than 1 dyno?

答:
You need sticky load balancing. Socket.io has a great article on it, so I'll leave it to them to explain the topic:

https://socket.io/docs/using-multiple-nodes/


问:
Swift 3: how to change the button image in UITableView?
```<code> func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

   ...

 let doLikeBtn = detailCell.contentView.viewWithTag(106) as! UIButton
                doLikeBtn.setTitle(String(indexPath.row), for: UIControlState.normal)
                doLikeBtn.addTarget(self, action: #selector(doLike(sender:)), for: UIControlEvents.touchUpInside)

...

 }

...

 func doLike(sender: UIButton) {
        selectUserIndex = sender.title(for: UIControlState.normal)!

    if sender.image(for: UIControlState.normal) == UIImage(named: "btn_Like.png") {
        sender.setImage(UIImage(named: "btn_not_Like.png"), for: UIControlState.normal)
    }else {
        sender.setImage(UIImage(named: "btn_Like.png"), for: UIControlState.normal)
    }
 }
</code>```

If I click one button in table, and then change the image of button, but other some button's images also are changed repeatedly.
I can't understand this.
Please help me!
Best regards.

答:
Updated for Swift 3/4:

Use lines of code to change/set the UIButton Image in UITableView;

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "YourTableViewCellStoryboardIdentifier")! as! YourTableViewCellName

        if status == 1{
            cell.mStatusButtonOutlet.setImage(UIImage(named: "pending_icon"), for: .normal)
        }else if status == 2{
            cell.mStatusButtonOutlet.setImage(UIImage(named: "approval"), for: .normal)
        }else if status == 3{
            cell.mStatusButtonOutlet.setImage(UIImage(named: "reject_icon"), for: .normal)
        }else{
            cell.mStatusButtonOutlet.setImage(UIImage(named: "cancle"), for: .normal)
        }

    return cell
}
</code>```

Note: where mStatusButtonOutlet - is your UIButtonOutlet

Enjoy..!

Body:
 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

   ...

 let doLikeBtn = detailCell.contentView.viewWithTag(106) as! UIButton
                doLikeBtn.setTitle(String(indexPath.row), for: UIControlState.normal)
                doLikeBtn.addTarget(self, action: #selector(doLike(sender:)), for: UIControlEvents.touchUpInside)

...

 }

...

 func doLike(sender: UIButton) {
        selectUserIndex = sender.title(for: UIControlState.normal)!

    if sender.image(for: UIControlState.normal) == UIImage(named: "btn_Like.png") {
        sender.setImage(UIImage(named: "btn_not_Like.png"), for: UIControlState.normal)
    }else {
        sender.setImage(UIImage(named: "btn_Like.png"), for: UIControlState.normal)
    }
 }

If I click one button in table, and then change the image of button, but other some button's images also are changed repeatedly.
I can't understand this.
Please help me!
Best regards.

Body:
Updated for Swift 3/4:

Use lines of code to change/set the UIButton Image in UITableView;

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "YourTableViewCellStoryboardIdentifier")! as! YourTableViewCellName

        if status == 1{
            cell.mStatusButtonOutlet.setImage(UIImage(named: "pending_icon"), for: .normal)
        }else if status == 2{
            cell.mStatusButtonOutlet.setImage(UIImage(named: "approval"), for: .normal)
        }else if status == 3{
            cell.mStatusButtonOutlet.setImage(UIImage(named: "reject_icon"), for: .normal)
        }else{
            cell.mStatusButtonOutlet.setImage(UIImage(named: "cancle"), for: .normal)
        }

    return cell
}

Note: where mStatusButtonOutlet - is your UIButtonOutlet

Enjoy..!


问:
How do you display "%5d" in C?
How do you display the string "%5d" in C? I tried putting a backslash in front of the percent, but it won't print (and gave warnings). I tried Googling but to no avail. I guess this is too wide for me to find a specific answer.

```<code>#include <stdio.h>

int main(void)
{
    int test = 40;
    printf("\%5.1d %5.1d", test); //this is the one
    printf("%5.1d", test);
    return 0;
}
</code>```

Any help?

答:
To print % try printf("%%");

This works

```<code>printf("%%5.1d %5.1d", test);
</code>```

Title: How do you display "%5d" in C?

Body:
How do you display the string "%5d" in C? I tried putting a backslash in front of the percent, but it won't print (and gave warnings). I tried Googling but to no avail. I guess this is too wide for me to find a specific answer.

#include <stdio.h>

int main(void)
{
    int test = 40;
    printf("\%5.1d %5.1d", test); //this is the one
    printf("%5.1d", test);
    return 0;
}

Any help?

Body:
To print % try printf("%%");

This works

printf("%%5.1d %5.1d", test);


问:
Operator '==' cannot be applied to operands of type 'byte[]' and 'string' | EDITED
```<code>Encoding.ASCII.GetString(o.Username) == textBox1.Text
</code>```

this was the code I was previously given to fix this problem. I'm not sure where to put it in my code. Please help!!

This is the section with the error:

```<code>private void button1_Click(object sender, EventArgs e)
{
    if (string.IsNullOrEmpty(textBox1.Text))
    {
        MessageBox.Show("Please Enter your username.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        textBox1.Focus();
        return;
    }
    try
    {
        using (DataEntities test = new DataEntities())
        {
            var query = from o in test.Users
                        where o.Username == textBox1.Text && o.Password == textBox2.Text
                        select o;
            if(query.SingleOrDefault() != null)
            {
                MessageBox.Show("You have been successfully logged in.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //Add your code process login here
            }
            else
            {
                MessageBox.Show("Your username or password is incorrect.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}
</code>```

答:
You're getting this error when you try to compile, right?

I think your problem actually is that you don't have quotes around your query.

This:

```<code>var query = from o in test.Users
where o.Username == textBox1.Text && o.Password == textBox2.text
select o;
</code>```

Should be:

```<code>var query = "from o in test.Users" +
"where o.Username == textBox1.Text && o.Password == textBox2.text" +
"select o";
</code>```

query is a string, so you need to surround everything right of the = with quotes.  This tells the compiler that it's a string literal, not more code.

Body:
Encoding.ASCII.GetString(o.Username) == textBox1.Text

this was the code I was previously given to fix this problem. I'm not sure where to put it in my code. Please help!!

This is the section with the error:

private void button1_Click(object sender, EventArgs e)
{
    if (string.IsNullOrEmpty(textBox1.Text))
    {
        MessageBox.Show("Please Enter your username.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        textBox1.Focus();
        return;
    }
    try
    {
        using (DataEntities test = new DataEntities())
        {
            var query = from o in test.Users
                        where o.Username == textBox1.Text && o.Password == textBox2.Text
                        select o;
            if(query.SingleOrDefault() != null)
            {
                MessageBox.Show("You have been successfully logged in.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //Add your code process login here
            }
            else
            {
                MessageBox.Show("Your username or password is incorrect.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

Body:
You're getting this error when you try to compile, right?

I think your problem actually is that you don't have quotes around your query.

This:

var query = from o in test.Users
where o.Username == textBox1.Text && o.Password == textBox2.text
select o;

Should be:

var query = "from o in test.Users" +
"where o.Username == textBox1.Text && o.Password == textBox2.text" +
"select o";

query is a string, so you need to surround everything right of the = with quotes.  This tells the compiler that it's a string literal, not more code.


问:
How to Select an item from Dropdown Menu using while Loop in Php Mysql
How do I select a particular item from the following drop-down code using while loop in php ?

I am able to populate the drop-down,but unable to select a particular item from the drop-down. Please Help, if you can. Thanks.

```<code><div class="form-group">
    <select name="submit" for="no_id">
    <?php
        $query = "SELECT * FROM crap";
        $select_dropdown = mysqli_query($conn, $query);
        #function confirm stores in functions.php
        confirm($select_dropdown);
        while($row=mysqli_fetch_assoc($select_dropdown)){
            $keyas_id= $row['keyas_id'];
            $valueas_title =$row['valueas_title'];
            echo "<option value=$keyas_id>  $valueas_title </option>";
        }
    ?>
    </select>
</div>
</code>```

答:
```<code>$selectedId = 'Your selected ID';
$isSelected = '';

if ( $keyas_id === $selectedId) {
    $isSelected = "selected='selected'";
}
echo "<option value=$keyas_id $isSelected>  $valueas_title </option>";
</code>```

Body:
How do I select a particular item from the following drop-down code using while loop in php ?

I am able to populate the drop-down,but unable to select a particular item from the drop-down. Please Help, if you can. Thanks.

    <select name="submit" for="no_id">
    <?php
        $query = "SELECT * FROM crap";
        $select_dropdown = mysqli_query($conn, $query);
        #function confirm stores in functions.php
        confirm($select_dropdown);
        while($row=mysqli_fetch_assoc($select_dropdown)){
            $keyas_id= $row['keyas_id'];
            $valueas_title =$row['valueas_title'];
            echo "<option value=$keyas_id>  $valueas_title </option>";
        }
    ?>
    </select>


问:
Boost::Log Safety of using the same backend with multiple sinks
Mine is not a real problem but more a correct usage question.

Foreword: I am using boost::log as logging facility and I am working on some libraries that will be shared among different applications and all may need different levels of logging.
I came up with a setup where I have (or may have) specific channels and severity levels for each library, and a kind of factory that enables the library-using application to create the proper/desired sink(s) for the library, without the need of knowing the details of the library's channels and severity levels.

Now the real question: wanting to collect all the application's logs in some specific "places" (e.g. stdout, or some severity related files) I was planning to feed all the relevant sinks with the same backend; is this approach correct? I didn't find anything against it in the docs, but neither an example showing this usage...

An example would be:

```<code>namespace bl = boost::log;
namespace bl_snk = boost::log::sinks;
.
.
.
boost::shared_ptr< bl_snk::text_file_backend > text_backend = boost::make_shared< bl_snk::text_file_backend >(
                bl::keywords::file_name = "/tmp/file_%5N.log",
                bl::keywords::rotation_size = 5 * 1024 * 1024,
                bl::keywords::time_based_rotation = bl_snk::file::rotation_at_time_point(12, 0, 0)
            );
text_backend->auto_flush(true);

log_factory_libA.CreateSink< bl_snk::text_file_backend >(text_backend);
log_factory_libB.CreateSink< bl_snk::text_file_backend >(text_backend);
</code>```

Where, under the hood, CreateSink does basically:

```<code>using sink_t = bl_snk::synchronous_sink< bl_snk::text_file_backend >;
boost::shared_ptr<sink_t> lib_sink = boost::make_shared<sink_t>(text_backend);
</code>```

答:
I was planning to feed all the relevant sinks with the same backend; is this approach correct?

No, this is not correct. Sink frontends implement thread synchronization, so if multiple frontends share a backend the backend becomes unprotected.

There is generally no reason to use multiple frontends for a single backend. If you want to direct multiple channels to a single file or console, you don't need to create multiple sinks. A single sink should be created per file/console; you can control which channels are routed to the sink by updating its filter.

Body:
Mine is not a real problem but more a correct usage question.

Foreword: I am using boost::log as logging facility and I am working on some libraries that will be shared among different applications and all may need different levels of logging.
I came up with a setup where I have (or may have) specific channels and severity levels for each library, and a kind of factory that enables the library-using application to create the proper/desired sink(s) for the library, without the need of knowing the details of the library's channels and severity levels.

Now the real question: wanting to collect all the application's logs in some specific "places" (e.g. stdout, or some severity related files) I was planning to feed all the relevant sinks with the same backend; is this approach correct? I didn't find anything against it in the docs, but neither an example showing this usage...

An example would be:

namespace bl = boost::log;
namespace bl_snk = boost::log::sinks;
.
.
.
boost::shared_ptr< bl_snk::text_file_backend > text_backend = boost::make_shared< bl_snk::text_file_backend >(
                bl::keywords::file_name = "/tmp/file_%5N.log",
                bl::keywords::rotation_size = 5 * 1024 * 1024,
                bl::keywords::time_based_rotation = bl_snk::file::rotation_at_time_point(12, 0, 0)
            );
text_backend->auto_flush(true);

log_factory_libA.CreateSink< bl_snk::text_file_backend >(text_backend);
log_factory_libB.CreateSink< bl_snk::text_file_backend >(text_backend);

Where, under the hood, CreateSink does basically:

using sink_t = bl_snk::synchronous_sink< bl_snk::text_file_backend >;
boost::shared_ptr<sink_t> lib_sink = boost::make_shared<sink_t>(text_backend);