问:
Blogger Notable Template - Post Pagination Fix or Replacement?
The Blogger "Notable" template's post pagination link on the bottom of the main page only shows a "More Posts" link. It's missing a "Previous Posts". It's also missing the traditional "Home" link. The "More Posts" link correctly disappears on the last page of posts.

I am looking to enable at least a "Previous Posts" link.

This appears to be intentional on the part of Google as the code includes this:

```<code><div class='blog-pager container' id='blog-pager'> <b:include cond='data:newerPageUrl' name='previousPageLink'/> <b:include cond='data:olderPageUrl' name='nextPageLink'/> <b:include cond='data:view.url != data:blog.homepageUrl' name='homePageLink'/></div>
</code>```

But in two locations each the code includes:

```<code><b:includable id='previousPageLink'><!-- Don't show --></b:includable>

<b:includable id='homePageLink'><!-- Don't show --></b:includable>
</code>```

I attempted to fix this by first altering this line:

```<code><a expr:href='data:blog.homepageUrl'>Home</a>
</code>```

The only thing that did was the "Home" link to appear on the last page of posts where the "More Posts" previous was placed. Several other examples found online could not be tried as they refer to code that no longer exists within templates.

I've also tried at least a dozen 3rd party numbered pagination coding schemes which overwrite Blogger's existing code, but those do not work correctly.

Any idea of how to fix the template to enable the links or 3rd party code that might work?

答:
Thanks Prayag Verma! That Worked Great!

The "More Posts" link code was:

```<code><b:includable id='nextPageLink'>
<a class='blog-pager-older-link flat-button ripple' expr:href='data:olderPageUrl' expr:title='data:messages.morePosts'>
<data:messages.morePosts/>
</a>
</b:includable>
</code>```

I decided to replace the default text for both the older and newer links. Thus I replaced <data:messages.newerPosts/> with ← Previous and I replaced <data:messages.morePosts/> with Next →.

I also added a border to make them stand out more. As this button class has a -8 margin the margin needed to be reset to 0 otherwise the two buttons next to each other would overlap. A 8px margin was then added to the Next button so they would not touch.

As this template uses a sticky menu at the top the Home button at the button was unnecessary so I hid it. The default top margin on the blog-pager was too much and was thus reduced.

The following code needed to be inserted just above the  tag:

```<code><style>
.blog-pager a{
margin: 0px;
border: 1px solid #25a186;
}

.blog-pager a.blog-pager-older-link.flat-button.ripple{
margin-left: 8px;
}

.blog-pager a.home-link.flat-button.ripple{
display:none;
}

.blog-pager{
margin-top: 14px;
</style>
</code>```

Body:
The Blogger "Notable" template's post pagination link on the bottom of the main page only shows a "More Posts" link. It's missing a "Previous Posts". It's also missing the traditional "Home" link. The "More Posts" link correctly disappears on the last page of posts.

I am looking to enable at least a "Previous Posts" link.

This appears to be intentional on the part of Google as the code includes this:

But in two locations each the code includes:

I attempted to fix this by first altering this line:

Home

The only thing that did was the "Home" link to appear on the last page of posts where the "More Posts" previous was placed. Several other examples found online could not be tried as they refer to code that no longer exists within templates.

I've also tried at least a dozen 3rd party numbered pagination coding schemes which overwrite Blogger's existing code, but those do not work correctly.

Any idea of how to fix the template to enable the links or 3rd party code that might work?

Body:
Thanks Prayag Verma! That Worked Great!

The "More Posts" link code was:

<b:includable id='nextPageLink'>
<a class='blog-pager-older-link flat-button ripple' expr:href='data:olderPageUrl' expr:title='data:messages.morePosts'>
<data:messages.morePosts/>
</a>
</b:includable>

I decided to replace the default text for both the older and newer links. Thus I replaced <data:messages.newerPosts/> with &#8592; Previous and I replaced <data:messages.morePosts/> with Next &#8594;.

I also added a border to make them stand out more. As this button class has a -8 margin the margin needed to be reset to 0 otherwise the two buttons next to each other would overlap. A 8px margin was then added to the Next button so they would not touch.

As this template uses a sticky menu at the top the Home button at the button was unnecessary so I hid it. The default top margin on the blog-pager was too much and was thus reduced.

The following code needed to be inserted just above the </body> tag:

<style>
.blog-pager a{
margin: 0px;
border: 1px solid #25a186;
}

.blog-pager a.blog-pager-older-link.flat-button.ripple{
margin-left: 8px;
}

.blog-pager a.home-link.flat-button.ripple{
display:none;
}

.blog-pager{
margin-top: 14px;
</style>


来源: stackexchange

问:
ASP.NET MVC: how to prevent unauthenticated user to directly GET images?
I have confidential images that I only want to show to authenticated users. On the  razor view, which is only accessible to authenticated users, I have

How do I prevent an unauthenticated user to bypass my razor view and directly request this photo through a HTTP GET?

答: You need to develop an http handler that checks for image extensions. See this article for how to https://www.codeproject.com/Articles/39158/Protect-Files-and-Folders-Using-HttpHandlers-in-AS</p>

ContentLicense: CC BY-SA 3.0


问:
How to trigger event on dynamically generated elements (in mootools)
Example to demonstrate the issue can be found here:

http://jsfiddle.net/Byyu2/

As you can see only the first "Add" button triggers an event. The dynamically generated button does not. This is understandable as on page load these elements have not been created.

So what do I need to change to enable dynamically generated elements to also be registered to an event?

Thanks for looking.

答:
What about using Element.cloneEvents?

Check this sample:
http://jsfiddle.net/Byyu2/5/

It looks kind of ugly, because you can't call cloneEvents() directly on the new row (cloneEvents() does not work recursivly), but it works :-)

ContentLicense: CC BY-SA 2.5


问:
Codility MinAbsSum
I tried this Codility test: MinAbsSum.
https://codility.com/programmers/lessons/17-dynamic_programming/min_abs_sum/

I solved the problem by searching the whole tree of possibilities. The results were OK, however, my solution failed due to timeout for large input. In other words the time complexity was not as good as expected. My solution is O(nlogn), something normal with trees. But this coding test was in the section "Dynamic Programming", and there must be some way to improve it. I tried with summing the whole set first and then using this information, but always there is something missing in my solution. Does anybody have an idea on how to improve my solution using DP?

```<code>#include <vector>
using namespace std;

int sum(vector<int>& A, size_t i, int s)
{
   if (i == A.size())
      return s;

   int tmpl = s + A[i];
   int tmpr = s - A[i];
   return min (abs(sum(A, i+1, tmpl)), abs(sum(A, i+1, tmpr)));
}

int solution(vector<int> &A) {
   return sum(A, 0, 0);
}
</code>```

答:
You are almost 90% to the actual solution. It seems you understand recursion very well. Now, You should apply dynamic programming here with your program.

 Dynamic Programming is nothing but memoization to the recursion so that we will not calculate same sub problems again and again. If same sub problems encounter , we return the previously calculated and memorized value. Memorization can be done with the help of a 2D array , say dp[][], where first state represent current index of array and second state represent summation.

For this problem specific, instead of giving calls to both states from each state, you sometimes can greedily take decision to skip one call.

Title: Codility MinAbsSum

Body:
I tried this Codility test: MinAbsSum.
https://codility.com/programmers/lessons/17-dynamic_programming/min_abs_sum/

I solved the problem by searching the whole tree of possibilities. The results were OK, however, my solution failed due to timeout for large input. In other words the time complexity was not as good as expected. My solution is O(nlogn), something normal with trees. But this coding test was in the section "Dynamic Programming", and there must be some way to improve it. I tried with summing the whole set first and then using this information, but always there is something missing in my solution. Does anybody have an idea on how to improve my solution using DP?

#include <vector>
using namespace std;

int sum(vector<int>& A, size_t i, int s)
{
   if (i == A.size())
      return s;

   int tmpl = s + A[i];
   int tmpr = s - A[i];
   return min (abs(sum(A, i+1, tmpl)), abs(sum(A, i+1, tmpr)));
}

int solution(vector<int> &A) {
   return sum(A, 0, 0);
}

ContentLicense: CC BY-SA 4.0


问:
No output of type SPLIT_LIST after update gradle to 3.0.0-alpha5
After update gradle to 3.0.0-alpha5 my project can't sync gradle.

I received this message:

Gradle sync failed: No output of type: SPLIT_LIST

and in idea.log something about my release variant:

Variant 'release' has no output with type 'SPLIT_LIST'

```<code>buildTypes {
    release {
        minifyEnabled true
        shrinkResources true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
</code>```

答: The problem is with shrinkResources config. Removing it is temporary solution for now. Unfortunately I didn't find any info about deprecation of that so I think it's a bug.

Body:
After update gradle to 3.0.0-alpha5 my project can't sync gradle.

I received this message:

Gradle sync failed: No output of type: SPLIT_LIST

and in idea.log something about my release variant:

Variant 'release' has no output with type 'SPLIT_LIST'

buildTypes {
    release {
        minifyEnabled true
        shrinkResources true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}


问:
WCF Service Reference Error in WIndows Service
I have a windows service with a base namespace of XXXX. I have a number of WCF services with a base namespace of WebServices. These are hosted in IIS.

When I add one of the WCF services (DataManagement) as a service reference to my windows service, I get the following errors when I build the service:

```<code>Error   162 The type name 'WebServices' does not exist in the type 'XXXX.XXXX'
Reference.cs    Line 200    Col 61

Error   163 The type name 'WebServices' does not exist in the type 'XXXX.XXXX'
Reference.cs    Line 205    Col 94

Error   164 The type name 'WebServices' does not exist in the type 'XXXX.XXXX'
Reference.cs    Line 205    Col 134
</code>```

Reference.cs is an automatically generated file, The lines of code created are:

Error 1:

```<code>[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
public interface IDataManagementChannel : XXXX.WebServices.IDataManagement, System.ServiceModel.IClientChannel {
}
</code>```

Errors 2 & 3:

```<code>[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
public partial class DataManagementClient : System.ServiceModel.ClientBase<XXXX.WebServices.IDataManagement>, XXXX.WebServices.IDataManagement {
</code>```

I have been struggling to resolve these without much success. None of the suggestions I have found that appear to be related to this issue work for me. There was one issue with the same problem, but there were no answers. Any ideas?

答:
A bit late, but in case someone stumbles upon this...

Steps to reproduce:

Create a windows service project "TestService".
Rename the Service1 class to TestService.

Compile - it works.

Add reference to a WCF service.

Compile - it no longer works.

error CS0426: The type name 'SomeWCFService' does not exist in the type 'TestService'

Solution: Change the name of the TestService class to something else, as it conflicts with the TestService namespace.

Body:
I have a windows service with a base namespace of XXXX. I have a number of WCF services with a base namespace of WebServices. These are hosted in IIS.

When I add one of the WCF services (DataManagement) as a service reference to my windows service, I get the following errors when I build the service:

Error   162 The type name 'WebServices' does not exist in the type 'XXXX.XXXX'
Reference.cs    Line 200    Col 61

Error   163 The type name 'WebServices' does not exist in the type 'XXXX.XXXX'
Reference.cs    Line 205    Col 94

Error   164 The type name 'WebServices' does not exist in the type 'XXXX.XXXX'
Reference.cs    Line 205    Col 134

Reference.cs is an automatically generated file, The lines of code created are:

Error 1:

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
public interface IDataManagementChannel : XXXX.WebServices.IDataManagement, System.ServiceModel.IClientChannel {
}

Errors 2 & 3:

[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
public partial class DataManagementClient : System.ServiceModel.ClientBase<XXXX.WebServices.IDataManagement>, XXXX.WebServices.IDataManagement {

I have been struggling to resolve these without much success. None of the suggestions I have found that appear to be related to this issue work for me. There was one issue with the same problem, but there were no answers. Any ideas?


问:
Phoenix: value is not retrieved in view
I would like to get teams value in template.
I can't get teams values. QUERY is OK.
Error message is blow.

ArgumentError at GET /members/new
assign @teams not available in eex template.
Please make sure all proper assigns have been set. If this
is a child template, ensure assigns are given explicitly by
the parent template as they are not automatically forwarded.

Is anything wrong?

member_controller.ex

```<code>  def new(conn, _params) do
    changeset = Member.changeset(%Member{})
    teams = Repo.all(Team)
    assign(conn, :teams, teams)
    render(conn, "new.html", changeset: changeset)
  end
</code>```

form.html.eex

```<code><%= @teams %>
</code>```

答:
I think the above code can modified as</p>

```<code>def new(conn, _params) do
  changeset = Member.changeset(%Member{})
  teams = Repo.all(Team)
  render("new.html", changeset: changeset, teams: teams)
end
</code>```

Title: Phoenix: value is not retrieved in view

Body:
I would like to get teams value in template.
I can't get teams values. QUERY is OK.
Error message is blow.

ArgumentError at GET /members/new
assign @teams not available in eex template.
Please make sure all proper assigns have been set. If this
is a child template, ensure assigns are given explicitly by
the parent template as they are not automatically forwarded.

Is anything wrong?

member_controller.ex

  def new(conn, _params) do
    changeset = Member.changeset(%Member{})
    teams = Repo.all(Team)
    assign(conn, :teams, teams)
    render(conn, "new.html", changeset: changeset)
  end

form.html.eex

<%= @teams %>

Body:
I think the above code can modified as

def new(conn, _params) do
  changeset = Member.changeset(%Member{})
  teams = Repo.all(Team)
  render("new.html", changeset: changeset, teams: teams)
end


问:
How to create catalog in indexing service using c#
I want to automate Windows Indexing Service.

This has to be done in c#.

Concept is :-
I have a folder.
Client uploads docs in that folder
Client will search docs using Window Indexing Service.

Above steps are there in application.

I am making an installer and want to automate window indexing service on client machine.

Please help!! Any ideas are welcome.
I have been googling, didn't found solution.

答:
I haven't used Windows Indexing, but these look like promising places to start:

MSDN: Querying the Index
Programmatically

MSDN: Windows Search Overview

Searching Indexing Service

Using the Windows Indexing
Service


问:
The requested resource does not support http method 'GET" while making a POST call in WebAPI
I am trying to call an API written by me. However when I am trying to call a POST method via $.ajax it returns an error:

The requested resource does not support http method 'GET"

When I try to call via Postman, I get the desired results. On top of this, the $.ajax for the same method works for all calls. Here is my API method

```<code>[HttpPost]
[Route("api/Ticket/GetTicketsAssignedToTechnician/")]
public List<Ticket> GetTicketsAssignedToTechnician([FromBody]string technicianEmail)
{
    return dbManager.GetTicketsByAssignedTechnician(technicianEmail);
}
</code>```

```<code>postData: function (serviceURL, parameterValue, success, failure, error) {
    $.ajax({
        url: serviceURL,
        method: "POST",
        data: JSON.stringify(parameterValue),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: success,
        failure: failure,
        error: error
    });
}
</code>```

Here is call to $.ajax:

```<code>Utility.postData(Dashboard.hostURL + "Ticket/GetTicketsAssignedToTechnician/", email, function(data) {
  console.log(data);
}, function(data) {
  console.log("failure." + data.responseText);
}, function(data) {
  console.log("Error." + data.responseText);
});
</code>```

答:
try to do as below</p>

```<code>       $http({

            method: "POST",
            url: serviceURL,
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(parameterValue),
            dataType: 'JSON'
        })
</code>```

Body:
I am trying to call an API written by me. However when I am trying to call a POST method via $.ajax it returns an error:

The requested resource does not support http method 'GET"

When I try to call via Postman, I get the desired results. On top of this, the $.ajax for the same method works for all calls. Here is my API method

[HttpPost]
[Route("api/Ticket/GetTicketsAssignedToTechnician/")]
public List<Ticket> GetTicketsAssignedToTechnician([FromBody]string technicianEmail)
{
    return dbManager.GetTicketsByAssignedTechnician(technicianEmail);
}

postData: function (serviceURL, parameterValue, success, failure, error) {
    $.ajax({
        url: serviceURL,
        method: "POST",
        data: JSON.stringify(parameterValue),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: success,
        failure: failure,
        error: error
    });
}

Here is call to $.ajax:

Utility.postData(Dashboard.hostURL + "Ticket/GetTicketsAssignedToTechnician/", email, function(data) {
  console.log(data);
}, function(data) {
  console.log("failure." + data.responseText);
}, function(data) {
  console.log("Error." + data.responseText);
});

Body:
try to do as below

       $http({

            method: "POST",
            url: serviceURL,
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(parameterValue),
            dataType: 'JSON'
        })


问:
Disable form but keep each of its elements look like enabled
I would like to disable the whole Form but still, keep each of this Form elements like TextBox, Buttons etc to look like enabled.

So, I want to block user interactions on those elements, but preserve it's standard look, not grayed out etc.

Can that be done in kind of automatic way or one just need to manually handle EnabledChanged events for each of affected controls?

答:
The easiest solution would be to have a transparent image on top of all controls and you just show it when you want to disable the controls.

This image will catch all mouse inputs but it is possible that the controls can still be selected by keyboard.


问:
Getting the left-center or right-center point on a Google Maps map
Currently I can retrieve the center point of the map using

```<code>new google.maps.LatLng(map.getCenter().lat(), map.getCenter().lng());
</code>```

What I am now trying to do, is get the left-center OR the right-center point of the map. For example:
Link to example image

As far as I know, there is no built in Google Maps API function to retrieve either of these points.

答:
You can get the bound

```<code>var bounds = map.getBounds();

var ne = bounds.getNorthEast();
var sw = bounds.getSouthWest();
</code>```

then get the middle of the lats and lngs

```<code>eg in Nothern - Western area (otherwise check for min and max lat and lng):

middleLat = sw.lat() + ( ne.lat() - sw.lat())/2;
</code>```

your left center is in

```<code>(middleLat, sw.lng() )
</code>```

you right center is in

```<code> (middleLat, ne.lng() )
</code>```

Body:
Currently I can retrieve the center point of the map using

new google.maps.LatLng(map.getCenter().lat(), map.getCenter().lng());

What I am now trying to do, is get the left-center OR the right-center point of the map. For example:
Link to example image

As far as I know, there is no built in Google Maps API function to retrieve either of these points.

Body:
You can get the bound

var bounds = map.getBounds();

var ne = bounds.getNorthEast();
var sw = bounds.getSouthWest();

then get the middle of the lats and lngs

eg in Nothern - Western area (otherwise check for min and max lat and lng):

middleLat = sw.lat() + ( ne.lat() - sw.lat())/2;

your left center is in

(middleLat, sw.lng() )

you right center is in

 (middleLat, ne.lng() )


问:
How can I write sequential execution in foreach loop of nodejs?
I am new to nodejs. please help me how to save the data in foreach loop and send response back to controller.it returns false not return object. Thanks in advance

Here is my code like

```<code>var rideStatus = require('../models/ridestatus');
module.exports = {
  invite_ride: function* (body) {
    var saved = false;
    var receivers = body.uids;
    receivers = receivers.split(',').filter(function(n) { return n != 'null'; });
    receivers.forEach(function* (n) {
      yield rideStatus.findOne(
        {$and: [{ride_id: body.rideid}, {receiver_id: receivers}]},
        function(err, doc) {
          if (doc === null) {
            new rideStatus({
              ride_id: body.rideid,
              invited_id: body.userId,
              receiver_id: receivers,
            }).save(function(err1, ridestatus) {
              if (!err1) {
                rideStatus.findOne({_id: ridestatus._id}).
                  populate('ride_id').
                  populate('invited_id').
                  populate('receiver_id').
                  exec(function(err2, user) {
                    // console.log(user);
                    if (user != null) {
                      saved = user;

                    }
                  });
              }
            });
          }
        });
    });
    return saved;
  },
};
</code>```

答: Look at library on the link: async</p>

Body:
I am new to nodejs. please help me how to save the data in foreach loop and send response back to controller.it returns false not return object. Thanks in advance

Here is my code like

var rideStatus = require('../models/ridestatus');
module.exports = {
  invite_ride: function* (body) {
    var saved = false;
    var receivers = body.uids;
    receivers = receivers.split(',').filter(function(n) { return n != 'null'; });
    receivers.forEach(function* (n) {
      yield rideStatus.findOne(
        {$and: [{ride_id: body.rideid}, {receiver_id: receivers}]},
        function(err, doc) {
          if (doc === null) {
            new rideStatus({
              ride_id: body.rideid,
              invited_id: body.userId,
              receiver_id: receivers,
            }).save(function(err1, ridestatus) {
              if (!err1) {
                rideStatus.findOne({_id: ridestatus._id}).
                  populate('ride_id').
                  populate('invited_id').
                  populate('receiver_id').
                  exec(function(err2, user) {
                    // console.log(user);
                    if (user != null) {
                      saved = user;

                    }
                  });
              }
            });
          }
        });
    });
    return saved;
  },
};

Body: Look at library on the link: async


问:
Compile error using C# automatically implemented properties
A C# Noob, I am trying to use SharpDevelop utility to convert my VB.NET application a C#.

I am noticing that my automatically implemented properties are generating a lot of errors. For example, take the following property:

public SqlDateTime DateOfBirth { get; set; }

Whenever I try to access the implied underlying module level variable, _DateOfBirth, I get the error.

Error   699 The name '_DateOfBirth' does not exist in the current context   D:\Users\Chad\Desktop\BESI CSharp\BESI\BESI.BusinessObjects.ConvertedToC#\ChinaVisa.cs  240 13  Besi.BusinessObjects.Converted

I could expand the properties declarations out to full-fledged properties, but this should n't be necessary and I'd like to understand why I am getting this error.

答:
You cannot access the compiler-created backing variable - you must use the property.  The compiler-generated backing field is specifically named in such a way to prevent you from accessing it (it is not named _DateOfBirth, it is named something like <DateOfBirth>k__BackingField).

Access the property directly - if you need to manipulate the backing field directly then don't use an automatically implemented property.

Just a side note - it doesn't matter what the property name is (it is an implementation detail and could change on different versions of the compiler or with different compiler implementations altogether).  The field is given an identifier that is specifically designed to meet the naming restrictions of the CLR but fail the naming restrictions of C# making it impossible to ever write straight C# code that accesses that variable directly.

Also remember that automatically implemented properties are not public fields.  They are a shorthand that the compiler expands for you (sort of like a macro).

So this class:

```<code>class Bar
{
    public object Foo { get; set; }
}
</code>```

Gets expanded to this:

```<code>class Bar
{
    [CompilerGenerated]
    private object <Foo>k__BackingField;

    public object Foo
    {
        [CompilerGenerated]
        get
        {
            return this.<Foo>k__BackingField;
        }
        [CompilerGenerated]
        set
        {
            this.<Foo>k__BackingField = value;
        }
    }
}
</code>```

It is still a full property - you are simply allowing the compiler to write the getters and setters for you.

Body:
You cannot access the compiler-created backing variable - you must use the property.  The compiler-generated backing field is specifically named in such a way to prevent you from accessing it (it is not named _DateOfBirth, it is named something like <DateOfBirth>k__BackingField).

Access the property directly - if you need to manipulate the backing field directly then don't use an automatically implemented property.

Just a side note - it doesn't matter what the property name is (it is an implementation detail and could change on different versions of the compiler or with different compiler implementations altogether).  The field is given an identifier that is specifically designed to meet the naming restrictions of the CLR but fail the naming restrictions of C# making it impossible to ever write straight C# code that accesses that variable directly.

Also remember that automatically implemented properties are not public fields.  They are a shorthand that the compiler expands for you (sort of like a macro).

So this class:

class Bar
{
    public object Foo { get; set; }
}

Gets expanded to this:

class Bar
{
    [CompilerGenerated]
    private object <Foo>k__BackingField;

    public object Foo
    {
        [CompilerGenerated]
        get
        {
            return this.<Foo>k__BackingField;
        }
        [CompilerGenerated]
        set
        {
            this.<Foo>k__BackingField = value;
        }
    }
}

It is still a full property - you are simply allowing the compiler to write the getters and setters for you.


问:
Why Angular UI Router does not load my template?
I am really struggling with Angular since it is very fragile i think and I have a very simple case (probably the simplest case ever) which does not work yet.

Here is my module (so i do inject the library):

```<code>  angular.module(
          'module', ['ui.router']
</code>```

My index.html:

```<code><html data-ng-app="module">

<head>
    ... several libraries and my js files including ui-router library js + my app.js where the state definitions are located.
</head>

<body>
    <div ui-view></div>
</body>
</code>```

And why is not my template injected in ui-view?

EDIT: Sorry, i was in a hurry, forgot to add some details.. I have updated the app.js section like this:

```<code>    .state('default',
      {
        url: '/',
        template: '<h1>default</h1>'
      })
    .state('x',
      {
        url: '/x',
        template: '<h1>X</h1>'
      });
</code>```

Now default state works as expected. But i call the url "host/x" i get a "Cannot GET /x".. when i call the url like "host/#x", it works.

But i have also this section for html5 mode in my app.js:

```<code>  $locationProvider.html5Mode({
    enabled: true,
    requireBase: true
  });
</code>```

I have also this in the head section of my index.html:

```<code><base href="/">
</code>```

I thought, html5 should already handle the hash(#) part of the url? How can i get rid of that # in URL, so i can call directly "host/x"?

答:
You need to specify the url property and go to this url to see this page. State should be something like:

```<code>.state("yourStateName", {
    template: "<h1>My Contacts</h1>",
    url: "/stateURL"
})
</code>```

This is working example of url provider form my project:

```<code> angular.module("app")

  .config(function ($urlRouterProvider, $locationProvider, $stateProvider) {

  $locationProvider
    .html5Mode(true);
  $urlRouterProvider.when('/', '/url1');
  $urlRouterProvider.when('', '/url2');
  $urlRouterProvider.when('/url3', 'url4');
  $urlRouterProvider.otherwise('/url5');
});
</code>```

Body:
I am really struggling with Angular since it is very fragile i think and I have a very simple case (probably the simplest case ever) which does not work yet.

Here is my module (so i do inject the library):

  angular.module(
          'module', ['ui.router']

My index.html:

    ... several libraries and my js files including ui-router library js + my app.js where the state definitions are located.

And why is not my template injected in ui-view?

EDIT: Sorry, i was in a hurry, forgot to add some details.. I have updated the app.js section like this:

    .state('default',
      {
        url: '/',
        template: '
default
'
      })
    .state('x',
      {
        url: '/x',
        template: '
X
'
      });

Now default state works as expected. But i call the url "host/x" i get a "Cannot GET /x".. when i call the url like "host/#x", it works.

But i have also this section for html5 mode in my app.js:

  $locationProvider.html5Mode({
    enabled: true,
    requireBase: true
  });

I have also this in the head section of my index.html:

<base href="/">

I thought, html5 should already handle the hash(#) part of the url? How can i get rid of that # in URL, so i can call directly "host/x"?

Body:
You need to specify the url property and go to this url to see this page. State should be something like:

.state("yourStateName", {
    template: "<h1>My Contacts</h1>",
    url: "/stateURL"
})

This is working example of url provider form my project:

 angular.module("app")

  .config(function ($urlRouterProvider, $locationProvider, $stateProvider) {

  $locationProvider
    .html5Mode(true);
  $urlRouterProvider.when('/', '/url1');
  $urlRouterProvider.when('', '/url2');
  $urlRouterProvider.when('/url3', 'url4');
  $urlRouterProvider.otherwise('/url5');
});


问:
error No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined: expected single matching bean but found 2
MySQL, postgresql
I want to put the same data in the same name table.

Both databases have the same table.

error

```<code>WARN  2017-07-04 14:53:03 o.s.c.s.GenericApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tempMasterServiceImpl': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined: expected single matching bean but found 2: entityManagerFactoryBean,entityManagerFactoryBean2
INFO  2017-07-04 14:53:03 o.s.o.j.LocalContainerEntityManagerFactoryBean - Closing JPA EntityManagerFactory for persistence unit 'default'
INFO  2017-07-04 14:53:03 o.s.o.j.LocalContainerEntityManagerFactoryBean - Closing JPA EntityManagerFactory for persistence unit 'default'
ERROR 2017-07-04 14:53:03 o.s.t.context.TestContextManager - Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@7af44dd0] to prepare test instance [jp.co.ui2.dev.server.c_one.tempServiceTest@26d8c9da]
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124) ~[spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83) ~[spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117) ~[spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83) ~[spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230) ~[spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) [junit-4.12.jar:4.12]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) [junit-4.12.jar:4.12]
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.junit.runners.ParentRunner.run(ParentRunner.java:363) [junit-4.12.jar:4.12]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) [.cp/:na]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'courseMasterServiceImpl': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined: expected single matching bean but found 2: entityManagerFactoryBean,entityManagerFactoryBean2
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessPropertyValues(PersistenceAnnotationBeanPostProcessor.java:357) ~[spring-orm-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:776) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861) ~[spring-context-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541) ~[spring-context-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:128) ~[spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60) ~[spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98) ~[spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116) ~[spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
... 25 common frames omitted
Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined: expected single matching bean but found 2: entityManagerFactoryBean,entityManagerFactoryBean2
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findDefaultEntityManagerFactory(PersistenceAnnotationBeanPostProcessor.java:587) ~[spring-orm-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findEntityManagerFactory(PersistenceAnnotationBeanPostProcessor.java:546) ~[spring-orm-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.resolveEntityManager(PersistenceAnnotationBeanPostProcessor.java:712) ~[spring-orm-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.getResourceToInject(PersistenceAnnotationBeanPostProcessor.java:685) ~[spring-orm-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:169) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessPropertyValues(PersistenceAnnotationBeanPostProcessor.java:354) ~[spring-orm-4.3.2.RELEASE.jar:4.3.2.RELEASE]
... 39 common frames omitted
</code>```

test.properties

```<code>//mysql
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:8888/testdb

jdbc.username=test
jdbc.password=test

//postgresql
jdbc.driverClassName2=org.postgresql.Driver
jdbc.url2=jdbc:postgresql://localhost:5432/postgres

jdbc.username2=postgres
jdbc.password2=postgres
</code>```

TestConfig.java

```<code>@Configuration
@Import({ testServerConfig.class })
public class TestConfig
{

@Bean
public PropertiesFactoryBean prop() {
    PropertiesFactoryBean f = new PropertiesFactoryBean();
    f.setLocations(new Resource[] {
            new FileSystemResource("src/main/webapp/WEB-INF/config.properties"),
            new ClassPathResource("test.properties", getClass())
    });
    return f;
}
</code>```

}

tempServiceTest.java

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestConfig.class, loader =AnnotationConfigContextLoader.class)
public class ShopInfoServiceTest extends AbstractServiceTest
{

@Autowired
private tempMasterService tempService;

@Test
public void testCustomCode()
{
    // insert
    doInTransaction(new Runnable() {
        @Override
        public void run() {

            tempMaster info = createTemp( );
            tempService.insertTempMaster(info);

        }
    });

}

private tempMaster createTemp () {

    tempMaster xxx = new tempMaster ();

    xxx.setTempId(1);
    xxx.setTempName("chaco1234");
    xxx.setDescription("tttttt2232");
    xxx.setUserId("admin");
    return xxx;
}
</code>```

}

testServerConfig.java

```<code>@Configuration
@ComponentScan(basePackages = { "com.co.test.dev" }, excludeFilters = {
    @Filter(type = FilterType.ANNOTATION, value = Controller.class),
    @Filter(type = FilterType.ANNOTATION, value = Configuration.class) })
@EnableTransactionManagement
@EnableScheduling
@EnableCaching
@ImportResource("classpath:job-context.xml")
public class testServerConfig
{
@Autowired
private ApplicationContext ctx;

@Autowired
private ResourceLoader resourceLoader;

@Value("#{prop['jdbc.driverClassName'] ?: ''}")
private String jdbcDriverClassName;

@Value("#{prop['jdbc.url'] ?: ''}")
private String jdbcUrl;

@Value("#{prop['jdbc.username'] ?: ''}")
private String jdbcUsername;

@Value("#{prop['jdbc.password'] ?: ''}")
private String jdbcPassword;

@Value("#{prop['jdbc.driverClassName2'] ?: ''}")
private String jdbcDriverClassName2;

@Value("#{prop['jdbc.url2'] ?: ''}")
private String jdbcUrl2;

@Value("#{prop['jdbc.username2'] ?: ''}")
private String jdbcUsername2;

@Value("#{prop['jdbc.password2'] ?: ''}")
private String jdbcPassword2;

@Value("#{prop['hibernate.dialect2'] ?: ''}")
private String hibernateDialect2;

@Value("#{prop['jdbc.initialSize'] ?: '0'}")
private int jdbcInitialSize;

@Value("#{prop['jdbc.maxActive'] ?: '50'}")
private int jdbcMaxActive;

@Value("#{prop['jdbc.maxIdle'] ?: '5'}")
private int jdbcMaxIdle;

@Value("#{prop['jdbc.maxWait'] ?: '5000'}")
private int jdbcMaxWait;

@Value("#{prop['jdbc.minIdle'] ?: '0'}")
private int jdbcMinIdle;

@Value("#{prop['jdbc.testWhileIdle'] ?: 'false'}")
private boolean jdbcTestWhileIdle;

@Value("#{prop['jdbc.testOnBorrow'] ?: 'false'}")
private boolean jdbcTestOnBorrow;

@Value("#{prop['jdbc.validationQuery'] ?: ''}")
private String jdbcValidationQuery;

@Value("#{prop['hibernate.hbm2ddl.auto'] ?: 'update'}")
private String hibernateDDLAuto;

@Value("#{prop['hibernate.dialect'] ?: ''}")
private String hibernateDialect;

@Value("#{prop['hibernate.search.indexBase'] ?: ''}")
private String searchIndexBase;

@Value("#{prop['hibernate.packages.to.scan'] ?: ''}")
private String packagesToScan;

protected String getRealPath(String path)
{
    if ((ctx != null) && (ctx instanceof WebApplicationContext)
            && (((WebApplicationContext) ctx).getServletContext() != null)) return ((WebApplicationContext) ctx)
            .getServletContext().getRealPath(path);
    else return "src/main/webapp/" + path;
}

@Bean
public PropertiesFactoryBean prop()
{
    String path = getRealPath("/WEB-INF/config.properties");
    PropertiesFactoryBean f = new PropertiesFactoryBean();
    f.setLocation(new FileSystemResource(path));
    return f;
}

@Bean(name="dataSource")
public DataSource dataSource()
{
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(jdbcDriverClassName);
    ds.setUrl(jdbcUrl);
    ds.setUsername(jdbcUsername);
    ds.setPassword(jdbcPassword);
    ds.setInitialSize(jdbcInitialSize);
    ds.setMaxActive(jdbcMaxActive);
    ds.setMaxIdle(jdbcMaxIdle);
    ds.setMaxWait(jdbcMaxWait);
    ds.setMinIdle(jdbcMinIdle);
    ds.setTestWhileIdle(jdbcTestWhileIdle);
    ds.setValidationQuery(jdbcValidationQuery);
    return ds;
}

@Bean(name="dataSource2")
public DataSource dataSource2()
{
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(jdbcDriverClassName2);
    ds.setUrl(jdbcUrl2);
    ds.setUsername(jdbcUsername2);
    ds.setPassword(jdbcPassword2);
    ds.setInitialSize(jdbcInitialSize);
    ds.setMaxActive(jdbcMaxActive);
    ds.setMaxIdle(jdbcMaxIdle);
    ds.setMaxWait(jdbcMaxWait);
    ds.setMinIdle(jdbcMinIdle);
    ds.setTestWhileIdle(jdbcTestWhileIdle);
    ds.setValidationQuery(jdbcValidationQuery);
    return ds;
}

@Bean(name="entityManagerFactoryBean")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean()
{
    LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
    emf.setDataSource(dataSource());
    if (packagesToScan != null) {
        String[] pts = packagesToScan.split(",");
        emf.setPackagesToScan(pts);
    }
    emf.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
    Properties p = new Properties();
    p.setProperty("hibernate.archive.autodetection", "class");
    p.setProperty("hibernate.dialect", hibernateDialect);
    p.setProperty("hibernate.show_sql", "false");
    p.setProperty("hibernate.format_sql", "true");
    p.setProperty("hibernate.hbm2ddl.auto", hibernateDDLAuto);
    //naming-strategy
    p.setProperty("hibernate.ejb.naming_strategy", "org.hibernate.cfg.ImprovedNamingStrategy");
    emf.setJpaProperties(p);
    return emf;
}
@Bean(name="entityManagerFactoryBean2")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean2()
{
    LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
    emf.setDataSource(dataSource());
    if (packagesToScan != null) {
        String[] pts = packagesToScan.split(",");
        emf.setPackagesToScan(pts);
    }
    emf.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
    Properties p = new Properties();
    p.setProperty("hibernate.archive.autodetection", "class");
    p.setProperty("hibernate.dialect2", hibernateDialect2);
    p.setProperty("hibernate.show_sql", "false");
    p.setProperty("hibernate.format_sql", "true");
    p.setProperty("hibernate.hbm2ddl.auto", hibernateDDLAuto);
    //naming-strategy
    p.setProperty("hibernate.ejb.naming_strategy", "org.hibernate.cfg.ImprovedNamingStrategy");
    emf.setJpaProperties(p);
    return emf;
}

@Bean(name="transactionManager")
public PlatformTransactionManager transactionManager()
{
    JpaTransactionManager tm = new JpaTransactionManager();
    tm.setEntityManagerFactory(entityManagerFactoryBean().getObject());
    return tm;
}
@Bean(name="transactionManager2")
public PlatformTransactionManager transactionManager2()
{
    JpaTransactionManager tm = new JpaTransactionManager();
    tm.setEntityManagerFactory(entityManagerFactoryBean2().getObject());
    return tm;
}

@Bean
public EhCacheCacheManager cacheManager()
{
    EhCacheCacheManager cm = new EhCacheCacheManager();
    cm.setCacheManager(ehcache().getObject());
    return cm;
}

@Bean
public EhCacheManagerFactoryBean ehcache()
{
    EhCacheManagerFactoryBean factory = new EhCacheManagerFactoryBean();
    factory.setConfigLocation(resourceLoader.getResource("classpath:ehcache.xml"));
    return factory;
}

@Bean(name = "configSftpSessionfactoryId")
public DefaultSftpSessionFactory sftpSessionFactory() {
    DefaultSftpSessionFactory sftp = new DefaultSftpSessionFactory();
    sftp.setHost(sftpHost);
    sftp.setPort(sftpPort);
    sftp.setUser(sftpUser);
    sftp.setPassword(sftpPassword);
    if (sftpPrivateKey != null && !"".equals(sftpPrivateKey)) {
        sftp.setPrivateKey(resourceLoader.getResource(sftpPrivateKey));
        sftp.setPrivateKeyPassphrase(sftpPrivateKeyPassphrase);
    }
    sftp.setAllowUnknownKeys(true);
    return sftp;
}
</code>```

}

tempMasterServiceImpl

```<code>@Service
@Transactional
@SwabAdminAuthCheck
public class tempMasterImpl implements tempMasterService{
private Logger logger = LoggerFactory.getLogger(getClass());

@PersistenceContext
private EntityManager em;

@Override
public void insertTempMaster(tempMaster obj) throws SwabException {

    Query keyq = em.createQuery("select tempId from tempMaster where userId = :userId");

    keyq.setParameter("userId", obj.getUserId());

    Integer tmepId = null;
    try{
        tempId = (Integer)keyq.getSingleResult();
        obj.setTempId( tempId );
    } catch (NoResultException  nre){

    }

    tempMaster searchData = em.find(tempMaster.class, obj);

    if (searchData == null) {
        logger.debug("insert");
        em.persist(obj);
    } else {
        logger.debug("update");
        em.merge(obj);
    }
}
</code>```

}

答:
Will this source help?

datasourse-config.xml

```<code><bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${jdbc.driverClassName}" />
    <property name="url" value="${jdbc.url}" />
    <property name="username" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
</bean>

<bean id="dataSource2"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${jdbc.driverClassName2}" />
    <property name="url" value="${jdbc.url2}" />
    <property name="username" value="${jdbc.username2}" />
    <property name="password" value="${jdbc.password2}" />
</bean>

<context:property-placeholder location="classpath:config.properties" />

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <constructor-arg ref="entityManagerFactoryBean" />
</bean>
<bean id="transactionManager2" class="org.springframework.orm.jpa.JpaTransactionManager">
    <constructor-arg ref="entityManagerFactoryBean2" />
</bean>

<bean id="entityManagerFactoryBean"
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="dataSource" />

    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
            <property name="showSql" value="true" />
        </bean>
    </property>
    <property name="jpaDialect">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
    </property>
    <property name="jpaProperties">
        <props>
            <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
            <prop key="hibernate.dialect">${hibernate.dialect}</prop>

        </props>
    </property>
</bean>

<bean id="entityManagerFactoryBean2"
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="dataSource2" />

    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
            <property name="showSql" value="true" />
        </bean>
    </property>
    <property name="jpaDialect">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
    </property>
    <property name="jpaProperties">
        <props>
            <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
            <prop key="hibernate.dialect">${hibernate.dialect2}</prop>

        </props>
    </property>
</bean>
</code>```

persistence.xml

```<code><?xml version="1.0" encoding="UTF-8" standalone="no"?>
<persistence version="2.0"
  xmlns="http://java.sun.com/xml/ns/persistence"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
  http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">

  <persistence-unit name="persistenceUnit" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <properties>
      <property name="hibernate.dialect" value="org.hibernate.dialect.DerbyTenSevenDialect" />
      <property name="hibernate.hbm2ddl.auto" value="create"/>
      <property name="hibernate.connection.driver_class" value="org.apache.derby.jdbc.EmbeddedDriver" />
    </properties>
  </persistence-unit>
</persistence>
</code>```

spring-config.xml

```<code><beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.2.xsd">

    <bean id="jobRepository" class="org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean">
      <property name="transactionManager" ref="transactionManager" />
    </bean>

    <bean id="jobLauncher" class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
      <property name="jobRepository" ref="jobRepository" />
    </bean>

    <!-- 非同期処理タスクExecutor -->
    <bean id="asyncTaskExecutor" class="org.springframework.core.task.SimpleAsyncTaskExecutor" />

    <!-- バリデーションプロセッサ -->
    <bean id="validatingItemProcessor" class="org.springframework.batch.item.validator.ValidatingItemProcessor">
      <property name="validator">
        <bean class="org.springframework.batch.item.validator.SpringValidator">
          <property name="validator">
            <!-- Hibernate バリデータ -->
            <bean name="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
          </property>
        </bean>
       </property>
    </bean>

    <!-- property config file -->
    <bean id="propertyFilebean" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
      <property name="location" value="config.properties"/>
    </bean>

    <bean id="dummyTasklet" class="jp.co.ui2.sms.batch.tasklet.DummyTasklet">
      <property name="batchStatus">
        <value type="org.springframework.batch.core.BatchStatus">FAILED</value>
      </property>
    </bean>
</beans>
</code>```

Body:
MySQL, postgresql
I want to put the same data in the same name table.

Both databases have the same table.

error

WARN  2017-07-04 14:53:03 o.s.c.s.GenericApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tempMasterServiceImpl': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined: expected single matching bean but found 2: entityManagerFactoryBean,entityManagerFactoryBean2
INFO  2017-07-04 14:53:03 o.s.o.j.LocalContainerEntityManagerFactoryBean - Closing JPA EntityManagerFactory for persistence unit 'default'
INFO  2017-07-04 14:53:03 o.s.o.j.LocalContainerEntityManagerFactoryBean - Closing JPA EntityManagerFactory for persistence unit 'default'
ERROR 2017-07-04 14:53:03 o.s.t.context.TestContextManager - Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@7af44dd0] to prepare test instance [jp.co.ui2.dev.server.c_one.tempServiceTest@26d8c9da]
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124) ~[spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83) ~[spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117) ~[spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83) ~[spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230) ~[spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) [junit-4.12.jar:4.12]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) [junit-4.12.jar:4.12]
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.junit.runners.ParentRunner.run(ParentRunner.java:363) [junit-4.12.jar:4.12]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) [.cp/:na]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'courseMasterServiceImpl': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined: expected single matching bean but found 2: entityManagerFactoryBean,entityManagerFactoryBean2
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessPropertyValues(PersistenceAnnotationBeanPostProcessor.java:357) ~[spring-orm-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:776) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861) ~[spring-context-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541) ~[spring-context-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:128) ~[spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60) ~[spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98) ~[spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116) ~[spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
... 25 common frames omitted
Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined: expected single matching bean but found 2: entityManagerFactoryBean,entityManagerFactoryBean2
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findDefaultEntityManagerFactory(PersistenceAnnotationBeanPostProcessor.java:587) ~[spring-orm-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findEntityManagerFactory(PersistenceAnnotationBeanPostProcessor.java:546) ~[spring-orm-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.resolveEntityManager(PersistenceAnnotationBeanPostProcessor.java:712) ~[spring-orm-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.getResourceToInject(PersistenceAnnotationBeanPostProcessor.java:685) ~[spring-orm-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:169) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessPropertyValues(PersistenceAnnotationBeanPostProcessor.java:354) ~[spring-orm-4.3.2.RELEASE.jar:4.3.2.RELEASE]
... 39 common frames omitted

test.properties

//mysql
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:8888/testdb

jdbc.username=test
jdbc.password=test

//postgresql
jdbc.driverClassName2=org.postgresql.Driver
jdbc.url2=jdbc:postgresql://localhost:5432/postgres

jdbc.username2=postgres
jdbc.password2=postgres

TestConfig.java

@Configuration
@Import({ testServerConfig.class })
public class TestConfig
{

@Bean
public PropertiesFactoryBean prop() {
    PropertiesFactoryBean f = new PropertiesFactoryBean();
    f.setLocations(new Resource[] {
            new FileSystemResource("src/main/webapp/WEB-INF/config.properties"),
            new ClassPathResource("test.properties", getClass())
    });
    return f;
}

}

tempServiceTest.java

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestConfig.class, loader =AnnotationConfigContextLoader.class)
public class ShopInfoServiceTest extends AbstractServiceTest
{

@Autowired
private tempMasterService tempService;

@Test
public void testCustomCode()
{
    // insert
    doInTransaction(new Runnable() {
        @Override
        public void run() {

            tempMaster info = createTemp( );
            tempService.insertTempMaster(info);

        }
    });

}

private tempMaster createTemp () {

    tempMaster xxx = new tempMaster ();

    xxx.setTempId(1);
    xxx.setTempName("chaco1234");
    xxx.setDescription("tttttt2232");
    xxx.setUserId("admin");
    return xxx;
}

}

testServerConfig.java

@Configuration
@ComponentScan(basePackages = { "com.co.test.dev" }, excludeFilters = {
    @Filter(type = FilterType.ANNOTATION, value = Controller.class),
    @Filter(type = FilterType.ANNOTATION, value = Configuration.class) })
@EnableTransactionManagement
@EnableScheduling
@EnableCaching
@ImportResource("classpath:job-context.xml")
public class testServerConfig
{
@Autowired
private ApplicationContext ctx;

@Autowired
private ResourceLoader resourceLoader;

@Value("#{prop['jdbc.driverClassName'] ?: ''}")
private String jdbcDriverClassName;

@Value("#{prop['jdbc.url'] ?: ''}")
private String jdbcUrl;

@Value("#{prop['jdbc.username'] ?: ''}")
private String jdbcUsername;

@Value("#{prop['jdbc.password'] ?: ''}")
private String jdbcPassword;

@Value("#{prop['jdbc.driverClassName2'] ?: ''}")
private String jdbcDriverClassName2;

@Value("#{prop['jdbc.url2'] ?: ''}")
private String jdbcUrl2;

@Value("#{prop['jdbc.username2'] ?: ''}")
private String jdbcUsername2;

@Value("#{prop['jdbc.password2'] ?: ''}")
private String jdbcPassword2;

@Value("#{prop['hibernate.dialect2'] ?: ''}")
private String hibernateDialect2;

@Value("#{prop['jdbc.initialSize'] ?: '0'}")
private int jdbcInitialSize;

@Value("#{prop['jdbc.maxActive'] ?: '50'}")
private int jdbcMaxActive;

@Value("#{prop['jdbc.maxIdle'] ?: '5'}")
private int jdbcMaxIdle;

@Value("#{prop['jdbc.maxWait'] ?: '5000'}")
private int jdbcMaxWait;

@Value("#{prop['jdbc.minIdle'] ?: '0'}")
private int jdbcMinIdle;

@Value("#{prop['jdbc.testWhileIdle'] ?: 'false'}")
private boolean jdbcTestWhileIdle;

@Value("#{prop['jdbc.testOnBorrow'] ?: 'false'}")
private boolean jdbcTestOnBorrow;

@Value("#{prop['jdbc.validationQuery'] ?: ''}")
private String jdbcValidationQuery;

@Value("#{prop['hibernate.hbm2ddl.auto'] ?: 'update'}")
private String hibernateDDLAuto;

@Value("#{prop['hibernate.dialect'] ?: ''}")
private String hibernateDialect;

@Value("#{prop['hibernate.search.indexBase'] ?: ''}")
private String searchIndexBase;

@Value("#{prop['hibernate.packages.to.scan'] ?: ''}")
private String packagesToScan;

protected String getRealPath(String path)
{
    if ((ctx != null) && (ctx instanceof WebApplicationContext)
            && (((WebApplicationContext) ctx).getServletContext() != null)) return ((WebApplicationContext) ctx)
            .getServletContext().getRealPath(path);
    else return "src/main/webapp/" + path;
}

@Bean
public PropertiesFactoryBean prop()
{
    String path = getRealPath("/WEB-INF/config.properties");
    PropertiesFactoryBean f = new PropertiesFactoryBean();
    f.setLocation(new FileSystemResource(path));
    return f;
}

@Bean(name="dataSource")
public DataSource dataSource()
{
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(jdbcDriverClassName);
    ds.setUrl(jdbcUrl);
    ds.setUsername(jdbcUsername);
    ds.setPassword(jdbcPassword);
    ds.setInitialSize(jdbcInitialSize);
    ds.setMaxActive(jdbcMaxActive);
    ds.setMaxIdle(jdbcMaxIdle);
    ds.setMaxWait(jdbcMaxWait);
    ds.setMinIdle(jdbcMinIdle);
    ds.setTestWhileIdle(jdbcTestWhileIdle);
    ds.setValidationQuery(jdbcValidationQuery);
    return ds;
}

@Bean(name="dataSource2")
public DataSource dataSource2()
{
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(jdbcDriverClassName2);
    ds.setUrl(jdbcUrl2);
    ds.setUsername(jdbcUsername2);
    ds.setPassword(jdbcPassword2);
    ds.setInitialSize(jdbcInitialSize);
    ds.setMaxActive(jdbcMaxActive);
    ds.setMaxIdle(jdbcMaxIdle);
    ds.setMaxWait(jdbcMaxWait);
    ds.setMinIdle(jdbcMinIdle);
    ds.setTestWhileIdle(jdbcTestWhileIdle);
    ds.setValidationQuery(jdbcValidationQuery);
    return ds;
}

@Bean(name="entityManagerFactoryBean")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean()
{
    LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
    emf.setDataSource(dataSource());
    if (packagesToScan != null) {
        String[] pts = packagesToScan.split(",");
        emf.setPackagesToScan(pts);
    }
    emf.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
    Properties p = new Properties();
    p.setProperty("hibernate.archive.autodetection", "class");
    p.setProperty("hibernate.dialect", hibernateDialect);
    p.setProperty("hibernate.show_sql", "false");
    p.setProperty("hibernate.format_sql", "true");
    p.setProperty("hibernate.hbm2ddl.auto", hibernateDDLAuto);
    //naming-strategy
    p.setProperty("hibernate.ejb.naming_strategy", "org.hibernate.cfg.ImprovedNamingStrategy");
    emf.setJpaProperties(p);
    return emf;
}
@Bean(name="entityManagerFactoryBean2")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean2()
{
    LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
    emf.setDataSource(dataSource());
    if (packagesToScan != null) {
        String[] pts = packagesToScan.split(",");
        emf.setPackagesToScan(pts);
    }
    emf.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
    Properties p = new Properties();
    p.setProperty("hibernate.archive.autodetection", "class");
    p.setProperty("hibernate.dialect2", hibernateDialect2);
    p.setProperty("hibernate.show_sql", "false");
    p.setProperty("hibernate.format_sql", "true");
    p.setProperty("hibernate.hbm2ddl.auto", hibernateDDLAuto);
    //naming-strategy
    p.setProperty("hibernate.ejb.naming_strategy", "org.hibernate.cfg.ImprovedNamingStrategy");
    emf.setJpaProperties(p);
    return emf;
}

@Bean(name="transactionManager")
public PlatformTransactionManager transactionManager()
{
    JpaTransactionManager tm = new JpaTransactionManager();
    tm.setEntityManagerFactory(entityManagerFactoryBean().getObject());
    return tm;
}
@Bean(name="transactionManager2")
public PlatformTransactionManager transactionManager2()
{
    JpaTransactionManager tm = new JpaTransactionManager();
    tm.setEntityManagerFactory(entityManagerFactoryBean2().getObject());
    return tm;
}

@Bean
public EhCacheCacheManager cacheManager()
{
    EhCacheCacheManager cm = new EhCacheCacheManager();
    cm.setCacheManager(ehcache().getObject());
    return cm;
}

@Bean
public EhCacheManagerFactoryBean ehcache()
{
    EhCacheManagerFactoryBean factory = new EhCacheManagerFactoryBean();
    factory.setConfigLocation(resourceLoader.getResource("classpath:ehcache.xml"));
    return factory;
}

@Bean(name = "configSftpSessionfactoryId")
public DefaultSftpSessionFactory sftpSessionFactory() {
    DefaultSftpSessionFactory sftp = new DefaultSftpSessionFactory();
    sftp.setHost(sftpHost);
    sftp.setPort(sftpPort);
    sftp.setUser(sftpUser);
    sftp.setPassword(sftpPassword);
    if (sftpPrivateKey != null && !"".equals(sftpPrivateKey)) {
        sftp.setPrivateKey(resourceLoader.getResource(sftpPrivateKey));
        sftp.setPrivateKeyPassphrase(sftpPrivateKeyPassphrase);
    }
    sftp.setAllowUnknownKeys(true);
    return sftp;
}

}

tempMasterServiceImpl

@Service
@Transactional
@SwabAdminAuthCheck
public class tempMasterImpl implements tempMasterService{
private Logger logger = LoggerFactory.getLogger(getClass());

@PersistenceContext
private EntityManager em;

@Override
public void insertTempMaster(tempMaster obj) throws SwabException {

    Query keyq = em.createQuery("select tempId from tempMaster where userId = :userId");

    keyq.setParameter("userId", obj.getUserId());

    Integer tmepId = null;
    try{
        tempId = (Integer)keyq.getSingleResult();
        obj.setTempId( tempId );
    } catch (NoResultException  nre){

    }

    tempMaster searchData = em.find(tempMaster.class, obj);

    if (searchData == null) {
        logger.debug("insert");
        em.persist(obj);
    } else {
        logger.debug("update");
        em.merge(obj);
    }
}

}

Body:
Will this source help?

datasourse-config.xml

<bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${jdbc.driverClassName}" />
    <property name="url" value="${jdbc.url}" />
    <property name="username" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
</bean>

<bean id="dataSource2"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${jdbc.driverClassName2}" />
    <property name="url" value="${jdbc.url2}" />
    <property name="username" value="${jdbc.username2}" />
    <property name="password" value="${jdbc.password2}" />
</bean>

<context:property-placeholder location="classpath:config.properties" />

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <constructor-arg ref="entityManagerFactoryBean" />
</bean>
<bean id="transactionManager2" class="org.springframework.orm.jpa.JpaTransactionManager">
    <constructor-arg ref="entityManagerFactoryBean2" />
</bean>

<bean id="entityManagerFactoryBean"
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="dataSource" />

    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
            <property name="showSql" value="true" />
        </bean>
    </property>
    <property name="jpaDialect">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
    </property>
    <property name="jpaProperties">
        <props>
            <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
            <prop key="hibernate.dialect">${hibernate.dialect}</prop>

        </props>
    </property>
</bean>

<bean id="entityManagerFactoryBean2"
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="dataSource2" />

    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
            <property name="showSql" value="true" />
        </bean>
    </property>
    <property name="jpaDialect">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
    </property>
    <property name="jpaProperties">
        <props>
            <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
            <prop key="hibernate.dialect">${hibernate.dialect2}</prop>

        </props>
    </property>
</bean>

persistence.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<persistence version="2.0"
  xmlns="http://java.sun.com/xml/ns/persistence"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
  http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">

  <persistence-unit name="persistenceUnit" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <properties>
      <property name="hibernate.dialect" value="org.hibernate.dialect.DerbyTenSevenDialect" />
      <property name="hibernate.hbm2ddl.auto" value="create"/>
      <property name="hibernate.connection.driver_class" value="org.apache.derby.jdbc.EmbeddedDriver" />
    </properties>
  </persistence-unit>
</persistence>

spring-config.xml

<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.2.xsd">

    <bean id="jobRepository" class="org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean">
      <property name="transactionManager" ref="transactionManager" />
    </bean>

    <bean id="jobLauncher" class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
      <property name="jobRepository" ref="jobRepository" />
    </bean>

    <!-- 非同期処理タスクExecutor -->
    <bean id="asyncTaskExecutor" class="org.springframework.core.task.SimpleAsyncTaskExecutor" />

    <!-- バリデーションプロセッサ -->
    <bean id="validatingItemProcessor" class="org.springframework.batch.item.validator.ValidatingItemProcessor">
      <property name="validator">
        <bean class="org.springframework.batch.item.validator.SpringValidator">
          <property name="validator">
            <!-- Hibernate バリデータ -->
            <bean name="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
          </property>
        </bean>
       </property>
    </bean>

    <!-- property config file -->
    <bean id="propertyFilebean" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
      <property name="location" value="config.properties"/>
    </bean>

    <bean id="dummyTasklet" class="jp.co.ui2.sms.batch.tasklet.DummyTasklet">
      <property name="batchStatus">
        <value type="org.springframework.batch.core.BatchStatus">FAILED</value>
      </property>
    </bean>
</beans>


问:
Gradle + Sonar host URL and basic auth
Have a Sonar instance running behind basic auth (not Sonar auth).

Using the Sonar Gradle plugin and specifying the Sonar host URL in gradle.properties via:

```<code>systemProp.sonar.host.url=https://admin:password@sonarqube.host.com
</code>```

However this does not seem to authenticate as in Gradle logs I see:

SonarQube server [https://admin:password@sonarqube.host.com] can not
  be reached

If I curl the same URL I get a 200 response as expected.

Not sure why the sonar.host.url isn't playing nicely?

答:
Two things:

proxy authentication between SonarQube Scanner and Server is only
supported since SonarQube 6.1
( SONAR-8084 )

with the above, http.proxyUser and http.proxyPassword are leveraged for basic proxy authentication (and you can leave sonar.host.url to the actual HTTP URL)

Title: Gradle + Sonar host URL and basic auth

Body:
Have a Sonar instance running behind basic auth (not Sonar auth).

Using the Sonar Gradle plugin and specifying the Sonar host URL in gradle.properties via:

systemProp.sonar.host.url=https://admin:password@sonarqube.host.com

However this does not seem to authenticate as in Gradle logs I see:

SonarQube server [https://admin:password@sonarqube.host.com] can not
  be reached

If I curl the same URL I get a 200 response as expected.

Not sure why the sonar.host.url isn't playing nicely?


问:
How to validate a name in C without using isalpha?
I'm a beginner in C programming, and I want to validate the name the user has input without using isalpha. Is that possible?</p>

```<code>char name[51];

puts("Please enter your name");
scanf("%[^\n]s", name);
</code>```

答:
Although there is already an accepted answer, I think that you may still need clarification about how to go about solving a problem like this (without copying someone's solution).

A string is an array of characters ending with a null terminator ('\0' character). Knowing this, after you get the user input string, you can just loop over the string until you reach the '\0' character, and test each character for valid letters.

You can use cascading if-statements to test for the presence of a letter, or you could use a switch-statement which would be far more efficient (this is a good opportunity to learn about how switch statements differ from cascading if-statements, hint: switch is really just computed goto), or use an alphabet string that you loop over (I still prefer the switch-statement because of efficiency). If anything other than a letter (as specified in your switch-statement) is present, then just print an error message and return from the function with an error code.

If you are testing for multiple words that are separated by whitespace like spaces, tabs, or newlines, then just include that in the switch statement as special conditions.

Body:
I'm a beginner in C programming, and I want to validate the name the user has input without using isalpha. Is that possible?

char name[51];

puts("Please enter your name");
scanf("%[^\n]s", name);


问:
How to iterate over Mysql database query using Python?
I want to run a query on MySql Database by iterating over it. I get the output from ML classifier which I need to store in my database. Here pred is the result from the classifier. I am trying to iterate like this-

```<code>for i in range(len(pred)):
    cursor.execute("UPDATE my_table SET status = %s WHERE status is null;", pred[i])
</code>```

But it gives me this error-

```<code>TypeError: 'numpy.int64' object is not iterable
</code>```

And the same error on other attempts as well, like-

```<code>for num in pred:
    cursor.execute("UPDATE cc_jobboard_job_application SET status = %s WHERE status is null;", num)
</code>```

Similarly, I have tried saving this pred into dataframe then iterating over it and also used enums for the purpose.
This code is doing well for single values as I do not have to get it into any loop. How can I appropriately iterate over this update query?

答:
execute's second argument needs to be a tuple even if the query has a single parameter.

Your loop is not very pythonic and can be simplified. Instead of iterating over the range of the indexes, directly iterate over the elements.

```<code>for num in pred:
    cursor.execute("UPDATE my_table SET status = %s WHERE status is null;", (num,))
</code>```

Body:
I want to run a query on MySql Database by iterating over it. I get the output from ML classifier which I need to store in my database. Here pred is the result from the classifier. I am trying to iterate like this-

for i in range(len(pred)):
    cursor.execute("UPDATE my_table SET status = %s WHERE status is null;", pred[i])

But it gives me this error-

TypeError: 'numpy.int64' object is not iterable

And the same error on other attempts as well, like-

for num in pred:
    cursor.execute("UPDATE cc_jobboard_job_application SET status = %s WHERE status is null;", num)

Similarly, I have tried saving this pred into dataframe then iterating over it and also used enums for the purpose.
This code is doing well for single values as I do not have to get it into any loop. How can I appropriately iterate over this update query?

Body:
execute's second argument needs to be a tuple even if the query has a single parameter.

Your loop is not very pythonic and can be simplified. Instead of iterating over the range of the indexes, directly iterate over the elements.

for num in pred:
    cursor.execute("UPDATE my_table SET status = %s WHERE status is null;", (num,))


问:
Reconciliation tool [comparing two large data set of records]
I have been asked to build a reconciliation tool which could compare two large datasets (We may assume input source as two excels).

Each row in excel contains 40-50 columns and record to be compared at each column level. Each file contains close to 3 million of records or roughly 4-5 GB of data.[data may not be in sorted format]

I would appreciate if i could get some hint.
Can following technologies be a good fit

Apache Spark

Apache Spark + Ignite [assuming real time reconciliation in between time frames]

Apache Ignite + Apache Hadoop

Any suggestion to build out in-house tool.

答:
I have also been working on the same-

You can load the csv files to temporary tables using Pyspark/Scala and query on top of the temp tables created.


问:
Match two strings in one line with grep
I am trying to use grep to match lines that contain two different strings. I have tried the following but this matches lines that contain either string1 or string2 which not what I want.

```<code>grep 'string1\|string2' filename
</code>```

So how do I match with grep only the lines that contain both strings?

答:
If you have a grep with a -P option for a limited perl regex, you can use

```<code>grep -P '(?=.*string1)(?=.*string2)'
</code>```

which has the advantage of working with overlapping strings.  It's somewhat more straightforward using perl as grep, because you can specify the and logic more directly:

```<code>perl -ne 'print if /string1/ && /string2/'
</code>```

Title: Match two strings in one line with grep

Body:
I am trying to use grep to match lines that contain two different strings. I have tried the following but this matches lines that contain either string1 or string2 which not what I want.

grep 'string1\|string2' filename

So how do I match with grep only the lines that contain both strings?

Body:
If you have a grep with a -P option for a limited perl regex, you can use

grep -P '(?=.*string1)(?=.*string2)'

which has the advantage of working with overlapping strings.  It's somewhat more straightforward using perl as grep, because you can specify the and logic more directly:

perl -ne 'print if /string1/ && /string2/'


问:
Populate a column in SQL Server by weekday or weekend depending on the datetime
I am working on SQL Server, wherein I cannot update any existing column nor can I add any more data/ column to the data.

I have a column of dttime (yyyy-mm-dd hh:mm:ss) which consists of the date time value against each entry.
I want to select the existing columns , and a new column as wd which will be populated as 'weekend' when the day of the week is either Saturday or Sunday and 'weekday' in case of other days

I am using the below query:

```<code>SELECT id, total,
case when dayofweek(dttime) in (1,7) then 'Weekend' else 'Weekday' end as wd
from table_name
</code>```

Please suggest where is the mistake here, or is there any alternative to this, in case I have more than two different things to populate in a similar way, based on another column.

答:
Please try below query</p>

```<code>SELECT id, total,
case when DATEPART(dw,dttime) in (1,7) then 'Weekend' else 'Weekday' end as wd
from table_name
</code>```

Body:
I am working on SQL Server, wherein I cannot update any existing column nor can I add any more data/ column to the data.

I have a column of dttime (yyyy-mm-dd hh:mm:ss) which consists of the date time value against each entry.
I want to select the existing columns , and a new column as wd which will be populated as 'weekend' when the day of the week is either Saturday or Sunday and 'weekday' in case of other days

I am using the below query:

SELECT id, total,
case when dayofweek(dttime) in (1,7) then 'Weekend' else 'Weekday' end as wd
from table_name

Please suggest where is the mistake here, or is there any alternative to this, in case I have more than two different things to populate in a similar way, based on another column.

Body:
Please try below query

SELECT id, total,
case when DATEPART(dw,dttime) in (1,7) then 'Weekend' else 'Weekday' end as wd
from table_name


问:
Linker Command failed with exit code 1 (use -v to see invocation)?
while Running i face this issue.

Linker Command failed with exit code 1 (use -v to see invocation)? in xcode 8.3.2.

I am not using COCOAPODS in my project

while clicking issue navigator item.For this particular error its not opening.

Error Screen shot
 https://i.stack.imgur.com/usJFW.png

答:
Possible solutions.

Go to Compile sources in Build Phases, make sure there is no
duplicate files and all .m files of your project is there.

Go to your build settings and switch the target's settings to
    ENABLE_BITCODE = YES.

Try luck with Product -> Clean


问:
how to handle login-error in flask?
I am new to flask and python. I have a website to which users can log in. I need to improve the security.

what i want to do is: when a user try many wrong passwords, I ban him further trying, ask him email and ask the user to reset password in the case the user forget the password.

I reviewed documentations about flask-admin, flask-secure. Since I am new to this, don't know where to start.

does flask-secure provide features to do what I want? or should I look into something also?

答:
I'm not sure if I approve of this feature. But it could be achieved by either a field in the user table of your database or a runtime dictionary. Choose whichever gives you the level of persistence you want.

When a user attempts to log in and fails you simply increment this field. And if the field reaches a certain value you lock the user or do whatever you want.

Sending an email in python can be found at the docs.

As for a password reset system.
When a user needs to reset their password you generate a key. This can be a base64-encoded string of random bytes. This key can be stored in the user table with en expiry datetime.

Now you can create a route in flask that takes this key as path- or query-parameter.
So when a user needs to reset their password you can send them a unique link with this key as a path- or query-param (whichever you choose).

Title: how to handle login-error in flask?


问:
Prevent Button from inheriting BackColor of Parent
When I have a parent control which has a BackColor other than SystemColors.Control, but I have buttons on that parent control that I want to be drawn in the system them. However, when I do not change the BackColor of the buttons, it's drawn in the color of the parent. When I change the BackColor of the button to SystemColors.Control, it isn't drawn in the Windows theme anymore.

The left version is with SystemColors.Control and the right is without changing the BackColor.

Blown up, it looks like this. Here you can see that the buttons have a solid background.

Any suggestions how I can fix this?

The effect in the image can be accomplished by creating a new .NET 2.0 WinForms project and changing the constructor of Form1 to the following:

```<code>public Form1()
{
    InitializeComponent();

    var textBox = new TextBox();
    Controls.Add(textBox);

    var button = new Button { Text = "L", Width = 23, Height = 18, Left = -1, Top = -1 };
    textBox.Controls.Add(button);

    // Disable the line below to get the default behavior
    button.BackColor = SystemColors.Control;
}
</code>```

答:
I unforuantely only have access to Windows 7 at the moment so I can't test on XP etc. but are you calling Application.EnableVisualStyles in the Main entry point of your WinForms application?

On Windows 7 with Aero enabled the buttons do not assume the parent color if Application.EnableVisualStyles is called.

NB: You should set button.UseVisualStyleBackColor = true; and do not explicitly set the BackColor property of the button.

Body:
When I have a parent control which has a BackColor other than SystemColors.Control, but I have buttons on that parent control that I want to be drawn in the system them. However, when I do not change the BackColor of the buttons, it's drawn in the color of the parent. When I change the BackColor of the button to SystemColors.Control, it isn't drawn in the Windows theme anymore.

The left version is with SystemColors.Control and the right is without changing the BackColor.

Blown up, it looks like this. Here you can see that the buttons have a solid background.

Any suggestions how I can fix this?

The effect in the image can be accomplished by creating a new .NET 2.0 WinForms project and changing the constructor of Form1 to the following:

public Form1()
{
    InitializeComponent();

    var textBox = new TextBox();
    Controls.Add(textBox);

    var button = new Button { Text = "L", Width = 23, Height = 18, Left = -1, Top = -1 };
    textBox.Controls.Add(button);

    // Disable the line below to get the default behavior
    button.BackColor = SystemColors.Control;
}


问:
Proper way of defining functions in ES6?
I'm just wondering how to write ES6 functions properly. I know that it depends on personal preference but what are the pros and cons?

```<code>function foo() {
  ...
}
</code>```

vs.

```<code>const foo = () => {
  ...
};
</code>```

vs.

```<code>const foo = function () {
  ...
};
</code>```

vs.

```<code>const foo = function bar() {
  ...
};
</code>```

The airbnb style guide recommends the latter. But it makes no sense to me to define two names for one function.

答:
The first one has an advantage of avoiding errors related do hoisting, so you can use the function before its declaration.

With the other options, you can use them only after the declaration, because before that point, they are variables with undefined value (due to hoisting). So I would say the first option is the safest one.

Body:
I'm just wondering how to write ES6 functions properly. I know that it depends on personal preference but what are the pros and cons?

function foo() {
  ...
}

vs.

const foo = () => {
  ...
};

vs.

const foo = function () {
  ...
};

vs.

const foo = function bar() {
  ...
};

The airbnb style guide recommends the latter. But it makes no sense to me to define two names for one function.


问:
Changing Drawer left and right button image dynamically?
react-native-router-flux v3.37.0
react-native v0.42.0

I'm trying to update drawer navigation bar right image dynamically where I have used leftButtonImage, rightButtonImage, where once user read all the notification I want to change the button image.

I could not manage to re-render or update this button image, Is this feature not supported or is there something that I'm missing?

答:
You can re-render using props or states naturally.

Check the states you want, and apply image resource following the states.(or props)

```<code>let NotiImage = {
    normal: require('../assets/image/notinormal.png');
    new: require('../assets/image/new.png');
}

render() {
    ...

    <Image source={ this.state.newNoti ? NotiImage.new : NotiImage.normal } />

    ...
}
</code>```

Body:
You can re-render using props or states naturally.

Check the states you want, and apply image resource following the states.(or props)

let NotiImage = {
    normal: require('../assets/image/notinormal.png');
    new: require('../assets/image/new.png');
}

render() {
    ...

    <Image source={ this.state.newNoti ? NotiImage.new : NotiImage.normal } />

    ...
}


问:
How to check if the user had already like the comment
I am designing a 'http api' for client app, it about comment,the situation is that if the app user logged in, he could likes some comments and unlike them,but they can not like twice or more times, so every time when the app get the comments data from my 'http api', the data should be able to tell the client app if the comment had already be liked by the user.
Well, I have implement the api recently,but I found it works not well, my design is:

Insert:
I created a table 'Comment' for saving comment(content, created time and so on) a table'User' for app user, and a table 'Like' for recording the info of which user liked which comment
When user like a comment:
1, increase the the record 'like_counts' in table 'comment'
2, insert into table Like set user='the user' and comment='the comment'

Query:

Query the comment list from mysql (about 20 records every page)

Foreach very comment and query from table Like where comment=='the comment' and user='the user'

if the query result is exist in step 2, that means the user had liked the comment before.

The matter is when the client get the comments for one page,that mean I have to execute 20 queries with table 'Like' to check if the user had liked it before, that will be very bad design, I think. I know that I could use some cache, like Redis, It's the next step, I want to know what's the good way for mysql way?

答:
I suppose the comments are stored in a table and as such will have a comment_id.

Same for user with a user_id.

The likes are stored in a table named Likes and has 2 columns: user_id and comment_id.  both as a foreign key to the comments-table and the user-table.

Together they form the primary key in the table Likes. Thus preventing duplicates.

Should user 123 want to like comment 1000 again, it will result in a duplicate key error for 123-1000 combination.
So your application will not need to check before inserting: the insert will simply fail. To your application the task to recognize that error message and give the error message