问:
Behaviour of threads with combination of synchronized methods in a class

Case 1

I have 2 synchronized methods as shown below:

```<code>class A {
    public void synchronized methodA() {}
    public void synchronized methodB() {}
}
</code>```

A: I have threads T1 and T2. Can the threads simultaneously executemethodA and methodB (respectively) belonging to the same instance of class A?

My analysis: The answer is no because only one method will be executed by thread T1 and thread T2 will be blocked until T1 finishes execution.

B: I have threads T1 and T2. Can the threads simultaneously execute methodA and methodB (respectively) belonging to different instances of class A?

My analysis: The answer is yes because T1 and T2 can execute methodA and methodB belonging to different instances of class A and they will not be blocked.

Is my understanding correct as per my analysis for case 1?

Update: Case 2

I have 2 synchronized methods, one is non static and the other is static.

```<code>class A {
    public void synchronized methodA() {}
    public void static synchronized methodB() {}
}
</code>```

A: I have threads T1 and T2.  Can the threads simultaneously execute methodA and  methodB (respectively) belonging to the same instance of class A?

My analysis: The answer is no because only one method will be executed by T1 and T2 will be blocked until T1 finishes execution.

B: I have threads T1 and T2. Can the threads simultaneously execute methodA and methodB (respectively) belonging to different instances of class A?

My analysis: The answer is yes because T1 and T2 can execute methodA and methodB belonging to different instances and they will not be blocked.

Is my understanding correct as per my analysis for case 2?

答:
Case 1: You are correct.

Every Java object has (among other things) an associated mutual exclusion lock (mutex). When synchronized is applied to a non-static method, it is the instance's mutex that is locked. Thus synchronized methods work on a per-object basis.

Static synchronized methods use the lock of the Class object, so operate on a per-class basis (modulo ClassLoader) and independently of non-static methods. You can also use synchronized() in method bodies to use the lock of any object you wish.

Case 2: You are not correct, as methodA() and methodB() use different mutexes, as described above.

Body:
Case 1

I have 2 synchronized methods as shown below:

class A {
    public void synchronized methodA() {}
    public void synchronized methodB() {}
}

A: I have threads T1 and T2. Can the threads simultaneously executemethodA and methodB (respectively) belonging to the same instance of class A?

My analysis: The answer is no because only one method will be executed by thread T1 and thread T2 will be blocked until T1 finishes execution.

B: I have threads T1 and T2. Can the threads simultaneously execute methodA and methodB (respectively) belonging to different instances of class A?

My analysis: The answer is yes because T1 and T2 can execute methodA and methodB belonging to different instances of class A and they will not be blocked.

Is my understanding correct as per my analysis for case 1?

Update: Case 2

I have 2 synchronized methods, one is non static and the other is static.

class A {
    public void synchronized methodA() {}
    public void static synchronized methodB() {}
}

A: I have threads T1 and T2.  Can the threads simultaneously execute methodA and  methodB (respectively) belonging to the same instance of class A?

My analysis: The answer is no because only one method will be executed by T1 and T2 will be blocked until T1 finishes execution.

B: I have threads T1 and T2. Can the threads simultaneously execute methodA and methodB (respectively) belonging to different instances of class A?

My analysis: The answer is yes because T1 and T2 can execute methodA and methodB belonging to different instances and they will not be blocked.

Is my understanding correct as per my analysis for case 2?


来源: stackexchange

问:
isset is not working on submit
This is a 5-star rating form and I am trying to make it work.

```<code><div class="stars">
  <form>
    <input class="star star-5" id="star-5" type="radio" name="star" value="5"/>
    <label class="star star-5" for="star-5"></label>
    <input class="star star-4" id="star-4" type="radio" name="star" value="4"/>
    <label class="star star-4" for="star-4"></label>
    <input class="star star-3" id="star-3" type="radio" name="star" value="3"/>
    <label class="star star-3" for="star-3"></label>
    <input class="star star-2" id="star-2" type="radio" name="star" value="2"/>
    <label class="star star-2" for="star-2"></label>
    <input class="star star-1" id="star-1" type="radio" name="star" value="1"/>
    <label class="star star-1" for="star-1"></label>
    <button class="button" type="submit" name="submit" value="submit">Submit</button>

  </form>
</div>
</code>```

When I press the submit button nothing happens. The code does not move into the if statement, though it should since submit is not longer null.

```<code><?php
if(isset($_POST['submit'])){
    $rating = $_POST['star'];
    echo "hello";
    echo $rating;
}
?>
</code>```

答:
isset() checks if a variable has a value including ( False , 0 , or empty string) , but not NULL. Returns TRUE if variable exists otherwise returns FALSE.

On the other hand the empty() function checks if the variable has an empty value, empty string , 0, NULL ,or False. Returns FALSE if variable has a non-empty and non-zero value.

Example

```<code>if(!empty($_POST['star'])){
     ....
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: isset is not working on submit

Body:
This is a 5-star rating form and I am trying to make it work.

  <form>
    <input class="star star-5" id="star-5" type="radio" name="star" value="5"/>

    <input class="star star-4" id="star-4" type="radio" name="star" value="4"/>

    <input class="star star-3" id="star-3" type="radio" name="star" value="3"/>

    <input class="star star-2" id="star-2" type="radio" name="star" value="2"/>

    <input class="star star-1" id="star-1" type="radio" name="star" value="1"/>

    <button class="button" type="submit" name="submit" value="submit">Submit</button>

  </form>

When I press the submit button nothing happens. The code does not move into the if statement, though it should since submit is not longer null.

<?php
if(isset($_POST['submit'])){
    $rating = $_POST['star'];
    echo "hello";
    echo $rating;
}
?>

Body:
isset() checks if a variable has a value including ( False , 0 , or empty string) , but not NULL. Returns TRUE if variable exists otherwise returns FALSE.

On the other hand the empty() function checks if the variable has an empty value, empty string , 0, NULL ,or False. Returns FALSE if variable has a non-empty and non-zero value.

Example

if(!empty($_POST['star'])){
     ....
}


问:
Scraping json response using scrapy
JSON RESPONSE FROM WEBSITE I am new to python scrapy and json . I am trying to scrape json response from 78751 . But it is showing error . The code i used is

```<code>import scrapy
import json
class BlackSpider(scrapy.Spider):
    name = 'black'
    start_urls = ['https://appworld.blackberry.com/cas/content/2360/reviews/2.17.2?page=1&pagesize=100&sortby=newest&callback=_content_2360_reviews_2_17_2&_=1499161778751']

    def parse(self, response):
         data = re.findall('(\{.+\})\);', response.body_as_unicode())
         a=json.loads(data[0])

         item = MyItem()
         item["Reviews"] = a["reviews"][4]["review"]

         return item
</code>```

The error it is showing is
 ValueError("No JSON object could be decoded")ERROR

答:
The response you are getting is javascript function with some json in it:

_content_2360_reviews_2_17_2(\r\n{"some":"json"}]});\r\n

To extract the data from this you can use simple regex solution:

```<code>import re
import json
data = re.findall('(\{.+\})\);', response.body_as_unicode())
json.loads(data[0])
</code>```

It trasnslates to: select everything between {} that ends with );

edit: results I'm getting with this:

```<code>{'platform': None,
 'reviews': [{'createdDate': '2017-07-04',
   'model': 'London',
   'nickname': 'aravind14-92362',
   'rating': 6,
   'review': 'Very bad ',
   'title': 'My WhatsApp no update '}],
 'totalReviews': 569909,
 'version': '2.17.2'}
</code>```

Title: Scraping json response using scrapy

Body:
JSON RESPONSE FROM WEBSITE I am new to python scrapy and json . I am trying to scrape json response from 78751 . But it is showing error . The code i used is

import scrapy
import json
class BlackSpider(scrapy.Spider):
    name = 'black'
    start_urls = ['https://appworld.blackberry.com/cas/content/2360/reviews/2.17.2?page=1&pagesize=100&sortby=newest&callback=_content_2360_reviews_2_17_2&_=1499161778751']

    def parse(self, response):
         data = re.findall('(\{.+\})\);', response.body_as_unicode())
         a=json.loads(data[0])

         item = MyItem()
         item["Reviews"] = a["reviews"][4]["review"]

         return item

The error it is showing is
 ValueError("No JSON object could be decoded")ERROR

Body:
The response you are getting is javascript function with some json in it:

_content_2360_reviews_2_17_2(\r\n{"some":"json"}]});\r\n

To extract the data from this you can use simple regex solution:

import re
import json
data = re.findall('(\{.+\})\);', response.body_as_unicode())
json.loads(data[0])

It trasnslates to: select everything between {} that ends with );

edit: results I'm getting with this:

{'platform': None,
 'reviews': [{'createdDate': '2017-07-04',
   'model': 'London',
   'nickname': 'aravind14-92362',
   'rating': 6,
   'review': 'Very bad ',
   'title': 'My WhatsApp no update '}],
 'totalReviews': 569909,
 'version': '2.17.2'}


问:
Java collection aggregate using lambdas
I am new to java 8 lamdas. I need help on the below collection aggregation and sorted list.
I have Arraylist of object which has List

```<code>[
[parentName1,parentkey1, child1Name1, childKey1],
[parentName1,parentkey1, child1Name2, childKey2],
[parentName3,parentkey3, child1Name3, childKey3],
[parentName3,parentkey3, child1Name4, childKey4],
[parentName5,parentkey5, child1Name5, childKey5],
[parentName5,parentkey5, child1Name6, childKey6]
]
</code>```

I would like aggregate above collections using java 8 lambdas in to sorted list.

```<code>List(Parent(parentName1,parentkey1,  List(  Child(child1Name1,childKey1),Child(child1Name2, childKey2)  ),
     Parent(parentName3,parentkey3,  List(  Child(child1Name3,childKey3),Child(child1Name4, childKey4)  ),
     Parent(parentName5,parentkey5,  List(  Child(child1Name5,childKey5),Child(child1Name5, childKey6)  )
     );
</code>```

Any help would appreciated.

答:
I did not understand sorting criteria using which you wanted to sort the list but here is generic example but with little modification it ll work for your case also.

```<code>  employeeList.stream()
            .sorted((e1, e2) -> Integer.compare(e1.getEmployeeNumber(), e2.getEmployeeNumber()))
            .forEach(e -> System.out.println(e));
</code>```

Above example shows examplyee object can be sorted based employee number, but you can change the logic to fit your case.

Title: Java collection aggregate using lambdas

Body:
I am new to java 8 lamdas. I need help on the below collection aggregation and sorted list.
I have Arraylist of object which has List

[
[parentName1,parentkey1, child1Name1, childKey1],
[parentName1,parentkey1, child1Name2, childKey2],
[parentName3,parentkey3, child1Name3, childKey3],
[parentName3,parentkey3, child1Name4, childKey4],
[parentName5,parentkey5, child1Name5, childKey5],
[parentName5,parentkey5, child1Name6, childKey6]
]

I would like aggregate above collections using java 8 lambdas in to sorted list.

List(Parent(parentName1,parentkey1,  List(  Child(child1Name1,childKey1),Child(child1Name2, childKey2)  ),
     Parent(parentName3,parentkey3,  List(  Child(child1Name3,childKey3),Child(child1Name4, childKey4)  ),
     Parent(parentName5,parentkey5,  List(  Child(child1Name5,childKey5),Child(child1Name5, childKey6)  )
     );

Any help would appreciated.

Body:
I did not understand sorting criteria using which you wanted to sort the list but here is generic example but with little modification it ll work for your case also.

  employeeList.stream()
            .sorted((e1, e2) -> Integer.compare(e1.getEmployeeNumber(), e2.getEmployeeNumber()))
            .forEach(e -> System.out.println(e));

Above example shows examplyee object can be sorted based employee number, but you can change the logic to fit your case.


问:
Disable time in bootstrap date time picker
I am using bootstrap date time picker in my web application, made in PHP/HTML5 and JavaScript. I am currently using one from here:
http://tarruda.github.io/bootstrap-datetimepicker/

When I am using the control without time, it doesn't work. It just shows a blank text box.

I just want to remove time from date time picker. Is there any solution for this?

```<code><div class="well">
    <div id="datetimepicker4" class="input-append">
        <input data-format="yyyy-MM-dd" type="text"></input>
        <span class="add-on">
            <i data-time-icon="icon-time" data-date-icon="icon-calendar"> </i>
        </span>
    </div>
</div>
<script type="text/javascript">
    $(function() {
        $('#datetimepicker4').datetimepicker({ pickTime: false });
    });
</script>
</code>```

答:
This allows to show time in input field but hides time picker button, which is second li element in accordion</p>

```<code>.bootstrap-datetimepicker-widget .list-unstyled li:nth-child(2){
    display: none;
}
</code>```

Body:
I am using bootstrap date time picker in my web application, made in PHP/HTML5 and JavaScript. I am currently using one from here:
http://tarruda.github.io/bootstrap-datetimepicker/

When I am using the control without time, it doesn't work. It just shows a blank text box.

I just want to remove time from date time picker. Is there any solution for this?

        <input data-format="yyyy-MM-dd" type="text"></input>

Body:
This allows to show time in input field but hides time picker button, which is second li element in accordion

.bootstrap-datetimepicker-widget .list-unstyled li:nth-child(2){
    display: none;
}


问:
'UserLoginForm' object has no attribute 'cleanned_data' Django
Hello i have some trouble with authentification in Django so that's what i have in view.py

```<code>    from django.shortcuts import render, redirect
    from django.contrib.auth import authenticate, login, logout, get_user_model
    from django.shortcuts import render
    from django.views import generic
    from FS import forms

    from .forms import UserLoginForm, UserRegisterForm

def login_view(request):
    form= UserLoginForm(request.POST or None)
    title = "Connexion"
    if form.is_valid():
        username = form.cleanned_data.get("username")
        password = form.cleanned_data.get("password")
        user = authenticate(username=username, password=password)
        login(request.user.is_authenticated())

    return render(request,"forms.html",{"form":form, "title": title})

def register_view(request):
    print(request.user.is_authenticated())
    title= "Inscription"
    print(request.user.is_authenticated())
    form = UserRegisterForm(request.POST or None)
    if form.is_valid():
        user = form.save(commit=False)
        password = form.cleanned_data.get('password')
        user.set_password(password)
        user.save()
        login(request, user)
        print(request.user.is_authenticated())
        #redirect

    context = {
    "form":form,
    "title":title
    }
    return render(request,"forms.html", context)

def logout_view(request):
         logout(request)
         return render(request, "forms.html")
</code>```

and that's in forms.py

```<code>from django.contrib.auth.models import User
from django import forms
from django.contrib.auth import authenticate, login, logout, get_user_model

from django.forms import ModelForm

User = get_user_model()

class UserLoginForm(forms.Form):
    username = forms.CharField()
    password= forms.CharField(widget=forms.PasswordInput)

    def clean(self, *args, **kwargs):

        username = self.cleanned_data.get('username')
        passworrd = self.cleanned_data.get('password')

        if username and password:
            user = authenticate(username=username, password=password)
            if not user:
                raise forms.ValidationError('This user does not exist')
            if not user.check_password(password):
                raise forms.ValidationError('Mot de passe incorrecte')
            if not user.is_active:
                raise forms.ValidationError('plus valide')
        return super(UserLoginForm, forms).clean(*args, **kwargs)

class UserRegisterForm(forms.ModelForm):

    class Meta:
        model = User
        fields = ['username', 'password']
</code>```

and there is always this error "'UserLoginForm' object has no attribute 'cleanned_data'"

I don't understand, i don't know how to make a form.is_valid() before. I can't see how to change my code to have the same thing

答: You may need to change form.cleanned_data to form.cleaned_data.

Body:
Hello i have some trouble with authentification in Django so that's what i have in view.py

    from django.shortcuts import render, redirect
    from django.contrib.auth import authenticate, login, logout, get_user_model
    from django.shortcuts import render
    from django.views import generic
    from FS import forms

    from .forms import UserLoginForm, UserRegisterForm

def login_view(request):
    form= UserLoginForm(request.POST or None)
    title = "Connexion"
    if form.is_valid():
        username = form.cleanned_data.get("username")
        password = form.cleanned_data.get("password")
        user = authenticate(username=username, password=password)
        login(request.user.is_authenticated())

    return render(request,"forms.html",{"form":form, "title": title})

def register_view(request):
    print(request.user.is_authenticated())
    title= "Inscription"
    print(request.user.is_authenticated())
    form = UserRegisterForm(request.POST or None)
    if form.is_valid():
        user = form.save(commit=False)
        password = form.cleanned_data.get('password')
        user.set_password(password)
        user.save()
        login(request, user)
        print(request.user.is_authenticated())
        #redirect

    context = {
    "form":form,
    "title":title
    }
    return render(request,"forms.html", context)

def logout_view(request):
         logout(request)
         return render(request, "forms.html")

and that's in forms.py

from django.contrib.auth.models import User
from django import forms
from django.contrib.auth import authenticate, login, logout, get_user_model

from django.forms import ModelForm

User = get_user_model()

class UserLoginForm(forms.Form):
    username = forms.CharField()
    password= forms.CharField(widget=forms.PasswordInput)

    def clean(self, *args, **kwargs):

        username = self.cleanned_data.get('username')
        passworrd = self.cleanned_data.get('password')

        if username and password:
            user = authenticate(username=username, password=password)
            if not user:
                raise forms.ValidationError('This user does not exist')
            if not user.check_password(password):
                raise forms.ValidationError('Mot de passe incorrecte')
            if not user.is_active:
                raise forms.ValidationError('plus valide')
        return super(UserLoginForm, forms).clean(*args, **kwargs)

class UserRegisterForm(forms.ModelForm):

    class Meta:
        model = User
        fields = ['username', 'password']

and there is always this error "'UserLoginForm' object has no attribute 'cleanned_data'"

I don't understand, i don't know how to make a form.is_valid() before. I can't see how to change my code to have the same thing


问:
Xcode iOS 8 Keyboard types not supported
I have a UITextField Ctrl-dragged as an @Outlet in my .swift class.
Now in viewDidLoad i'm using this code

```<code>self.myTextField.keyboardType = UIKeyboardType.DecimalPad
</code>```

When i launch my app on simulator and click on the UITextField i got this log

```<code>    Can't find keyplane that supports type 8 for keyboard
    iPhone-Portrait-DecimalPad;
    using 2617181025_Portrait_iPhone-Simple-Pad_Default
</code>```

I have no crash or something but the keyboard is not displayed. I also tried to set it from Storyboard but it's the same.

I also noticed that whenever i click on any UITextField the keyboard is never displayed (but no log is shown for the default keyboard)

I'm using Xcode-Beta 3 anyone faced this issue?

答: This error had come when your keyboard input type is Number Pad.I got same error than I change my Textfield keyboard input type to Default fix my issue.</p>

Body:
I have a UITextField Ctrl-dragged as an @Outlet in my .swift class.
Now in viewDidLoad i'm using this code

self.myTextField.keyboardType = UIKeyboardType.DecimalPad

When i launch my app on simulator and click on the UITextField i got this log

    Can't find keyplane that supports type 8 for keyboard
    iPhone-Portrait-DecimalPad;
    using 2617181025_Portrait_iPhone-Simple-Pad_Default

I have no crash or something but the keyboard is not displayed. I also tried to set it from Storyboard but it's the same.

I also noticed that whenever i click on any UITextField the keyboard is never displayed (but no log is shown for the default keyboard)

I'm using Xcode-Beta 3 anyone faced this issue?


问:
DB2 Sql order - SQL0104N
I have a problem with the following SQL code based on the database TERRA. The code should return all the organizations which only have European countries as members.

```<code>SELECT DISTINCT O.Name FROM Organisation O, ist_Mitglied iM, Land L,
umfasst U WHERE O.Abkuerzung = iM.Organisation AND iM.Land = L.L_ID
AND L.L_ID = U.land AND Kontinent LIKE 'Europa%' AND EXCEPT (SELECT
DISTINCT O.Name FROM Organisation O, ist_Mitglied iM, Land L, umfasst
U WHERE O.Abkuerzung = iM.Organisation AND iM.Land = L.L_ID AND L.L_ID
= U.land AND Kontinent NOT LIKE 'Europa%');
</code>```

The error message is the following:

SQL0104N  An unexpected token "DISTINCT" was found following "' AND EXCEPT
  (SELECT".  Expected tokens may include:  "(".  SQLSTATE=42601

Do you have any idea? thanks!

答:
Never use commas in the FROM clause.  Always use proper, explicit JOIN syntax.

EXCEPT is a set-based operator.  It should not be preceded with AND.  And, DISTINCT is unnecessary.  Try this:

```<code>SELECT O.Name
FROM Organisation O JOIN
     ist_Mitglied iM
     ON O.Abkuerzung = iM.Organisation JOIN
     Land L JOIN
     ON iM.Land = L.L_ID
     umfasst U
     ON L.L_ID = U.land WHERE  Kontinent LIKE 'Europa%'
EXCEPT
SELECT O.Name
FROM Organisation O JOIN
     ist_Mitglied iM
     ON O.Abkuerzung = iM.Organisation JOIN
     Land L JOIN
     ON iM.Land = L.L_ID
     umfasst U
     ON L.L_ID = U.land
 WHERE Kontinent NOT LIKE 'Europa%';
</code>```

There are other ways to write the query.  This seems closest to the way you are attempting to write the query in your question.

Title: DB2 Sql order - SQL0104N

Body:
I have a problem with the following SQL code based on the database TERRA. The code should return all the organizations which only have European countries as members.

SELECT DISTINCT O.Name FROM Organisation O, ist_Mitglied iM, Land L,
umfasst U WHERE O.Abkuerzung = iM.Organisation AND iM.Land = L.L_ID
AND L.L_ID = U.land AND Kontinent LIKE 'Europa%' AND EXCEPT (SELECT
DISTINCT O.Name FROM Organisation O, ist_Mitglied iM, Land L, umfasst
U WHERE O.Abkuerzung = iM.Organisation AND iM.Land = L.L_ID AND L.L_ID
= U.land AND Kontinent NOT LIKE 'Europa%');

The error message is the following:

SQL0104N  An unexpected token "DISTINCT" was found following "' AND EXCEPT
  (SELECT".  Expected tokens may include:  "(".  SQLSTATE=42601

Do you have any idea? thanks!

Body:
Never use commas in the FROM clause.  Always use proper, explicit JOIN syntax.

EXCEPT is a set-based operator.  It should not be preceded with AND.  And, DISTINCT is unnecessary.  Try this:

SELECT O.Name
FROM Organisation O JOIN
     ist_Mitglied iM
     ON O.Abkuerzung = iM.Organisation JOIN
     Land L JOIN
     ON iM.Land = L.L_ID
     umfasst U
     ON L.L_ID = U.land WHERE  Kontinent LIKE 'Europa%'
EXCEPT
SELECT O.Name
FROM Organisation O JOIN
     ist_Mitglied iM
     ON O.Abkuerzung = iM.Organisation JOIN
     Land L JOIN
     ON iM.Land = L.L_ID
     umfasst U
     ON L.L_ID = U.land
 WHERE Kontinent NOT LIKE 'Europa%';

There are other ways to write the query.  This seems closest to the way you are attempting to write the query in your question.


问:
Add css to 1 page using scss and ReactJS and redux
I am using ReactJS with redux.
I using scss.
lets say my path is:
http://localhost:3000/login
I need to add to this page:
html:{ overflow:hidden}

and on other pages i want to remove this attribute.

Anyone have a clue?

答:
You can change the style attribute of the html tag:</p>

```<code>class MyPage extends React.Component {

  componentWillMount() {
    this.htmlTag = document.getElementsByTagName('html')[0];
    this.htmlTag.setAttribute('style', 'overflow: hidden');
  }

  componentWillUnmount() {
    this.htmlTag.setAttribute('style', '');
  }

  ...
}
</code>```

Body:
You can change the style attribute of the html tag:

class MyPage extends React.Component {

  componentWillMount() {
    this.htmlTag = document.getElementsByTagName('html')[0];
    this.htmlTag.setAttribute('style', 'overflow: hidden');
  }

  componentWillUnmount() {
    this.htmlTag.setAttribute('style', '');
  }

  ...
}


问:
Styling HTML Dropdown List
I am trying to change the appearance of a dropdown for phone number extensions on my website.
Instead of all the text being unevenly spaced, it is spaced between the extension.

For example:

```<code>(+43) Austria
(+353) Ireland
(+1) United States
</code>```

Would become:

```<code>(+43)  Austria
(+353) Ireland
(+1)   United States
</code>```

I have tried simple whitespaces (as  ) and trying to separate the (+XX) and country name apart in separate  tags but to no avail.

The whitespaces have no effect and the   and spans just show up as their written code instead. Is there any way to format the dropdown to make this work? A sample of the HTML is below (the list of countries is extensive):

```<code>    <select class="countryCodeForMobile valid" id="countryCodeForMobile" name="countryCode">
    <option value="+61">(+61) Australia</option>
    <option value="+43">(+43) Austria</option>
    <option value="+32">(+32) Belgium</option>
    <option value="+55">(+55) Brazil</option>
    <option value="+1">(+1) Canada</option>
    <option value="+33">(+33) France</option>
    <option value="+49">(+49) Germany</option>
    <option value="+353">(+353) Ireland</option>
    <option value="+39">(+39) Italy</option>
    <option value="+31">(+31) Netherlands </option>
    <option value="+64">(+64) New Zealand</option>
    <option value="+48">(+48) Poland</option>
    <option value="+351">(+351) Portugal</option>
    <option value="+27">(+27) South Africa</option>
    <option value="+34">(+34) Spain</option>
    <option value="+41">(+41) Switzerland</option>
    <option selected="selected" value="+44">(+44) United Kingdom</option>
    <option value="+1">(+1) United States</option>
    </select>
</code>```

答:
Since you used a JQuery tag in your question I assume it is used.
Here is a function that dynamically inserts  s so that a format is maintained. You can take the output and hard code it into your webpage if you wish, so that the same calculation needn't be run every time. But this way if you update the information, it automatically adjusts.

var number_of_spaces = 7;

$("#countryCodeForMobile option").each(function(){

  var codelength = $(this).attr("value").length + 2; //2 Added for brackets.
  var value = $(this).html();
  var code = value.slice(0,codelength)
  var country = value.slice(codelength+1);
  var number_of_nbsps = number_of_spaces - code.length;
  var final = code;
  for (var i=0; i<number_of_nbsps; i ++)
  {
  final = final + "  "
  }
  final = final + country;
  $(this).html(final);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="countryCodeForMobile valid" id="countryCodeForMobile" name="countryCode">
    <option value="+61">(+61) Australia</option>
    <option value="+43">(+43) Austria</option>
    <option value="+32">(+32) Belgium</option>
    <option value="+55">(+55) Brazil</option>
    <option value="+1">(+1) Canada</option>
    <option value="+33">(+33) France</option>
    <option value="+49">(+49) Germany</option>
    <option value="+353">(+353) Ireland</option>
    <option value="+39">(+39) Italy</option>
    <option value="+31">(+31) Netherlands </option>
    <option value="+64">(+64) New Zealand</option>
    <option value="+48">(+48) Poland</option>
    <option value="+351">(+351) Portugal</option>
    <option value="+27">(+27) South Africa</option>
    <option value="+34">(+34) Spain</option>
    <option value="+41">(+41) Switzerland</option>
    <option selected="selected" value="+44">(+44) United Kingdom</option>
    <option value="+1">(+1) United States</option>
    </select></code>```

Title: Styling HTML Dropdown List

Body:
I am trying to change the appearance of a dropdown for phone number extensions on my website.
Instead of all the text being unevenly spaced, it is spaced between the extension.

For example:

(+43) Austria
(+353) Ireland
(+1) United States

Would become:

(+43)  Austria
(+353) Ireland
(+1)   United States

I have tried simple whitespaces (as  ) and trying to separate the (+XX) and country name apart in separate  tags but to no avail.

The whitespaces have no effect and the   and spans just show up as their written code instead. Is there any way to format the dropdown to make this work? A sample of the HTML is below (the list of countries is extensive):

    <select class="countryCodeForMobile valid" id="countryCodeForMobile" name="countryCode">
    <option value="+61">(+61) Australia</option>
    <option value="+43">(+43) Austria</option>
    <option value="+32">(+32) Belgium</option>
    <option value="+55">(+55) Brazil</option>
    <option value="+1">(+1) Canada</option>
    <option value="+33">(+33) France</option>
    <option value="+49">(+49) Germany</option>
    <option value="+353">(+353) Ireland</option>
    <option value="+39">(+39) Italy</option>
    <option value="+31">(+31) Netherlands </option>
    <option value="+64">(+64) New Zealand</option>
    <option value="+48">(+48) Poland</option>
    <option value="+351">(+351) Portugal</option>
    <option value="+27">(+27) South Africa</option>
    <option value="+34">(+34) Spain</option>
    <option value="+41">(+41) Switzerland</option>
    <option selected="selected" value="+44">(+44) United Kingdom</option>
    <option value="+1">(+1) United States</option>
    </select>

Body:
Since you used a JQuery tag in your question I assume it is used.
Here is a function that dynamically inserts &nbsp;s so that a format is maintained. You can take the output and hard code it into your webpage if you wish, so that the same calculation needn't be run every time. But this way if you update the information, it automatically adjusts.

var number_of_spaces = 7;

$("#countryCodeForMobile option").each(function(){

  var codelength = $(this).attr("value").length + 2; //2 Added for brackets.
  var value = $(this).html();
  var code = value.slice(0,codelength)
  var country = value.slice(codelength+1);
  var number_of_nbsps = number_of_spaces - code.length;
  var final = code;
  for (var i=0; i<number_of_nbsps; i ++)
  {
  final = final + "&nbsp;&nbsp;"
  }
  final = final + country;
  $(this).html(final);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="countryCodeForMobile valid" id="countryCodeForMobile" name="countryCode">
    <option value="+61">(+61) Australia</option>
    <option value="+43">(+43) Austria</option>
    <option value="+32">(+32) Belgium</option>
    <option value="+55">(+55) Brazil</option>
    <option value="+1">(+1) Canada</option>
    <option value="+33">(+33) France</option>
    <option value="+49">(+49) Germany</option>
    <option value="+353">(+353) Ireland</option>
    <option value="+39">(+39) Italy</option>
    <option value="+31">(+31) Netherlands </option>
    <option value="+64">(+64) New Zealand</option>
    <option value="+48">(+48) Poland</option>
    <option value="+351">(+351) Portugal</option>
    <option value="+27">(+27) South Africa</option>
    <option value="+34">(+34) Spain</option>
    <option value="+41">(+41) Switzerland</option>
    <option selected="selected" value="+44">(+44) United Kingdom</option>
    <option value="+1">(+1) United States</option>
    </select>


问:
Link in input text field
HI All,

I know this is bit strange question, but please suggest.

I want to create a link on website url content in input type"text" field not any other html tag,Is it possible and if yes how.

Regards & Thanks
Amit

答:
Half the people here missunderstood it. The OP would like to have the content/value of the input fields to be hyperlinks instantly and NOT the fields themselves.

It is doable... although it's not an input field but the appearance acts like such one.

Use the following: contenteditable=true

HTML

```<code><div contenteditable=true>
  <a id=lnk style=-moz-appearance:textfield href=http://www.google.com>http://www.google.com</a>
</div>
</code>```

or optionally -webkit-appearance ..depends

JavaScript

```<code>var lnk=document.getElementById('lnk');
lnk.addEventListener('click',()=>{
    window.location.href = lnk.getAttribute('href');
});
</code>```

http://jsfiddle.net/Dezain/jm9mzrzp/

ContentLicense: CC BY-SA 2.5

Title: Link in input text field

Body:
Half the people here missunderstood it. The OP would like to have the content/value of the input fields to be hyperlinks instantly and NOT the fields themselves.

It is doable... although it's not an input field but the appearance acts like such one.

Use the following: contenteditable=true

HTML

<div contenteditable=true>
  <a id=lnk style=-moz-appearance:textfield href=http://www.google.com>http://www.google.com</a>
</div>

or optionally -webkit-appearance ..depends

JavaScript

var lnk=document.getElementById('lnk');
lnk.addEventListener('click',()=>{
    window.location.href = lnk.getAttribute('href');
});

http://jsfiddle.net/Dezain/jm9mzrzp/

ContentLicense: CC BY-SA 4.0


问:
Expression with parameter (LINQ, SQL,C#)
i struggling to find the correct way to query for a specific entity in my database. I have a table TeamMember which looks as follows:

```<code>public class TeamMember
{
    public Guid TeamId { get; set; }
    public Guid ManagerUserId  { get; set; }
    ...
}
</code>```

At several positions i want to query for a "TeamManager" in my teams.

```<code>public TeamMember GetTeamManager(Guid teamId, List<TeamMember> teamMembers)
{
    return teamMembers.FirstOrDefault(member => member.TeamId == teamId && member.ManagerUserId == null);
}
</code>```

If i want to use a method in an expression e.g (not real code),

```<code>...
// IQueryable<TeamMember>
teamMembers.Where(member => member.team.GetTeamManager(teamId, teamMembers))
</code>```

it works fine for in memory objects, but this does not work in combination with the entity framework, so real db objects.

Therefore i was experimenting with static expressions, but i did not find any solution which uses a static expression in combination with a variable e.g.:

```<code>// this should be an ideal solution
Expression<Func<TeamMember, bool>> exp = teammember => teamMember.TeamId == **CUSTOM_VARIABLE** && teamMember.ManagerUserId == null;

teamMembers.Where(exp)
</code>```

I want to reuse the expression, but i also want to be able to modify the variable. My goal is to avoid the creation of an object in between because the following would work, but is less efficient (correct me if i'm wrong)

```<code>teamMembers.ToList().Where(member => member.team.GetTeamManager(teamId, teamMembers))
</code>```

So please help me with my problem :).
Thank you in advance!

答:
You can create a function that operates on IQueryable.</p>

```<code>public TeamMember GetTeamManager(IQueryable<TeamMember> baseQuery,Guid teamId)
{
    return baseQuery.FirstOrDefault(member => member.TeamId == teamId && member.ManagerUserId == null);
}
</code>```

Body:
i struggling to find the correct way to query for a specific entity in my database. I have a table TeamMember which looks as follows:

public class TeamMember
{
    public Guid TeamId { get; set; }
    public Guid ManagerUserId  { get; set; }
    ...
}

At several positions i want to query for a "TeamManager" in my teams.

public TeamMember GetTeamManager(Guid teamId, List<TeamMember> teamMembers)
{
    return teamMembers.FirstOrDefault(member => member.TeamId == teamId && member.ManagerUserId == null);
}

If i want to use a method in an expression e.g (not real code),

...
// IQueryable<TeamMember>
teamMembers.Where(member => member.team.GetTeamManager(teamId, teamMembers))

it works fine for in memory objects, but this does not work in combination with the entity framework, so real db objects.

Therefore i was experimenting with static expressions, but i did not find any solution which uses a static expression in combination with a variable e.g.:

// this should be an ideal solution
Expression<Func<TeamMember, bool>> exp = teammember => teamMember.TeamId == **CUSTOM_VARIABLE** && teamMember.ManagerUserId == null;

teamMembers.Where(exp)

I want to reuse the expression, but i also want to be able to modify the variable. My goal is to avoid the creation of an object in between because the following would work, but is less efficient (correct me if i'm wrong)

teamMembers.ToList().Where(member => member.team.GetTeamManager(teamId, teamMembers))

So please help me with my problem :).
Thank you in advance!

Body:
You can create a function that operates on IQueryable.

public TeamMember GetTeamManager(IQueryable<TeamMember> baseQuery,Guid teamId)
{
    return baseQuery.FirstOrDefault(member => member.TeamId == teamId && member.ManagerUserId == null);
}


问:
CassandraPojoSink no error, however data is not getting written into the cassandra
I am trying to write Flink's Cassandra SINK connector using CassandraPojoSink class. I am not getting any error/exception, but No records committed into the Cassandra table.

I am using following code.

========= Sink connector code snapshot ==================

```<code>DataStream<Event> stream = eventStream.flatMap(new EventTransformation());

    try {
        stream.addSink(new CassandraPojoSink<>(Event.class, new ClusterBuilder() {

          private static final long serialVersionUID = -2485105213096858846L;

          @Override
          public Cluster buildCluster(Cluster.Builder builder) {
            return builder.addContactPoint("localhost").withPort(9042).build();
         }
        }));
    } catch (Exception e) {
        e.printStackTrace();
    }
</code>```

====== POJO CLASS ================

```<code>@Table(keyspace= "cloud", name = "event")
public class Event implements Serializable {

    private static final long serialVersionUID = 3284839826384795926L;

    @Column(name = "name")
    private String name;

    @Column(name = "msg")
        private String msg;

    public Event(){

    }

    //......

}
</code>```

答:
There are many reasons why a Flink job might fail to produce any output. Some common reasons include:

the app doesn't call env.execute()

the app is set to use event time, but there's no watermark generator

the watermarking logic is confused somehow, and no watermarks are being generated (e.g., the app is generating watermarks based on the CPU clock rather than event timestamps, causing every event to be late)

Body:
I am trying to write Flink's Cassandra SINK connector using CassandraPojoSink class. I am not getting any error/exception, but No records committed into the Cassandra table.

I am using following code.

========= Sink connector code snapshot ==================

DataStream<Event> stream = eventStream.flatMap(new EventTransformation());

    try {
        stream.addSink(new CassandraPojoSink<>(Event.class, new ClusterBuilder() {

          private static final long serialVersionUID = -2485105213096858846L;

          @Override
          public Cluster buildCluster(Cluster.Builder builder) {
            return builder.addContactPoint("localhost").withPort(9042).build();
         }
        }));
    } catch (Exception e) {
        e.printStackTrace();
    }

====== POJO CLASS ================

@Table(keyspace= "cloud", name = "event")
public class Event implements Serializable {

    private static final long serialVersionUID = 3284839826384795926L;

    @Column(name = "name")
    private String name;

    @Column(name = "msg")
        private String msg;

    public Event(){

    }

    //......

}


问:
Discard curl downloads below a minimum file size
I regularly need to iterate through some image downloads via curl and want to discard those downloads that are below a certain file size, because they obviously don't exist, i. e. the returned "image" is a 404 page. curl has a --max-filesize option, but not one for minimum file sizes.

I was thinking of something where I would pass the URL image location and the minimum file size to the script curlmin, such as

curlmin url minfilesize

I believe that since I'm using sequences of alphanumeric series using [ ] to iterate through days, I need to be able to delete those files below a certain file size "on the fly". My attempt below is anything but complete, because I'm stuck on how to reference the "current" file in the 'if' statement and how to actually delete the file. But it might as well be that my one liner wouldn't work in first place either.

```<code>#!/bin/bash
curl -O $1 | if [ $(wc -c <"$1") -le $2 ]; then delete_file_here; fi
                            ^^                  ^^^^^^^^^^^^^^^^
</code>```

Any idea? Thanks.

答:
If you just want curl to avoid creating a local file when the remote one doesn't exist or there was an error in requesting/downloading it just use the -f flag:

```<code>curl -fO "$1"
</code>```

If, however, you want to remove files below a certain size, here are a couple of options:

You can get the filename by using parameter expansion to get rid of everything up to the last / like ${1##*/}

so you could do

```<code>curl -O "$1"
if [[ $(wc -c < "${1##*/}") -le $2 ]]; then
    rm -f "${1##*/}"
fi
</code>```

or we could check using find:

```<code>curl -O "$1"
find . -type f -name "${1##*/}" -size -"$2"c -delete
</code>```

assuming your find supports -delete.  Otherwise you could replace that with -exec rm -f {} +

and if your curl command might download multiple files you can easily adapt the find command to find all files in a directory structure smaller than the given size.

The safest path is to use find since it won't be tripped up by strange filenames.  Failing that, you could try using another language that is better able to support these operations.  If you are confident that you have only safe names you could try the following:

```<code>curl -O "$1" 2>&1 | awk -v min_size="$2" '/-->/ {"stat -c%s " $NF | getline s; if(s < min_size) {system("rm " $NF);}}'
</code>```

which will pass $2 into awk as the variable min_size.  Then we'll look at each line of curl output that contains -->.  The last field of those lines (assuming safe names again) is the local filename, so we'll call stat on that to get the size (-c %s) and then check if that size is below our min_size.  If it is, call rm on it, once again trusting that we have safe names and not ones that will contain IFS or globbing characters or the like.

Body:
I regularly need to iterate through some image downloads via curl and want to discard those downloads that are below a certain file size, because they obviously don't exist, i. e. the returned "image" is a 404 page. curl has a --max-filesize option, but not one for minimum file sizes.

I was thinking of something where I would pass the URL image location and the minimum file size to the script curlmin, such as

curlmin url minfilesize

I believe that since I'm using sequences of alphanumeric series using [ ] to iterate through days, I need to be able to delete those files below a certain file size "on the fly". My attempt below is anything but complete, because I'm stuck on how to reference the "current" file in the 'if' statement and how to actually delete the file. But it might as well be that my one liner wouldn't work in first place either.

#!/bin/bash
curl -O $1 | if [ $(wc -c <"$1") -le $2 ]; then delete_file_here; fi
                            ^^                  ^^^^^^^^^^^^^^^^

Any idea? Thanks.

Body:
If you just want curl to avoid creating a local file when the remote one doesn't exist or there was an error in requesting/downloading it just use the -f flag:

curl -fO "$1"

If, however, you want to remove files below a certain size, here are a couple of options:

You can get the filename by using parameter expansion to get rid of everything up to the last / like ${1##*/}

so you could do

curl -O "$1"
if [[ $(wc -c < "${1##*/}") -le $2 ]]; then
    rm -f "${1##*/}"
fi

or we could check using find:

curl -O "$1"
find . -type f -name "${1##*/}" -size -"$2"c -delete

assuming your find supports -delete.  Otherwise you could replace that with -exec rm -f {} +

and if your curl command might download multiple files you can easily adapt the find command to find all files in a directory structure smaller than the given size.

The safest path is to use find since it won't be tripped up by strange filenames.  Failing that, you could try using another language that is better able to support these operations.  If you are confident that you have only safe names you could try the following:

curl -O "$1" 2>&1 | awk -v min_size="$2" '/-->/ {"stat -c%s " $NF | getline s; if(s < min_size) {system("rm " $NF);}}'

which will pass $2 into awk as the variable min_size.  Then we'll look at each line of curl output that contains -->.  The last field of those lines (assuming safe names again) is the local filename, so we'll call stat on that to get the size (-c %s) and then check if that size is below our min_size.  If it is, call rm on it, once again trusting that we have safe names and not ones that will contain IFS or globbing characters or the like.


问:
Why isn't Python fexlibe when it comes data-types of function arguments?
This is probably a bad title but what I mean by it is the following:

Since Python is dynamically-typed, why do certain functions insist on being used with certain data types only and do not handle the conversion themselves internally if necessary? What problems could that lead to?

Examples:

startswith(): Takes both strings and tuples as arguments.

Why not lists
too? And if there is a good reason for that (which is probably the
case), why does it not simply convert them internally?

join(): Only accepts containers of string items.

Why does it not simply do a [str(x) for x in whatever]?

From the design of the language, I have the impression so far that it values flexibility more than purity and therefore the above behavior seems kind of non-typical..

Another example comes from @VPfB

"IPv4 address (host, port) must be tuple - not a list - in socket library.".

Can it be that tuples are prefered due to their immutability? Is there a case where a tuple is denied and only a list accepted? Preferably part from the standard Python distribution and its modules.

答:
Python is strongly dynamically typed which means that objects have definite types and conversions must be performed explicitly. For the why, consider the Zen of Python:

Explicit is better than implicit.


问:
SQL data retrieve - C#
how do i retrieve data from a table within a loop or something. That means I want to retrieve row by row at a time. but the sequence of rows may differ.
For example, 1st time i want 5rd row,then 2nd, then 9...so on.

I searched it through the internet. I got only two answers.

Use several SqlConnection objects.

reader= sqlCommand.ExecuteReader();
While(reader.Read()){
    reader["Column Name"].ToString();
}

If you got my problem, please help me
Thank you.

答:
Sounds like you should correct your data layer to return the values in the order you are going to process them. It would be easiest and fastest! :)

As an alternative I'd suggest that you load your result into a DataTable:

```<code>    DataTable table = new DataTable();
    using ( SqlCommand command = new SqlCommand() )
    {
           // TODO: Set up your command here
        using (SqlDataAdapter adapter = new SqlDataAdapter(command))
        {
            adapter.Fill(table);
        }
    }

    // Use your DataTable like this...

    if ( table.Rows.Count >= 5 ) {
        DataRow firstRow = table.Rows[0]; // #1 row
        DataRow fifthRow = table.Rows[4]; // #5 row
        DataRow secondRow = table.Rows[1]; // #2 row
    }
</code>```

/Alex

Title: SQL data retrieve - C#

Body:
Sounds like you should correct your data layer to return the values in the order you are going to process them. It would be easiest and fastest! :)

As an alternative I'd suggest that you load your result into a DataTable:

    DataTable table = new DataTable();
    using ( SqlCommand command = new SqlCommand() )
    {
           // TODO: Set up your command here
        using (SqlDataAdapter adapter = new SqlDataAdapter(command))
        {
            adapter.Fill(table);
        }
    }

    // Use your DataTable like this...

    if ( table.Rows.Count >= 5 ) {
        DataRow firstRow = table.Rows[0]; // #1 row
        DataRow fifthRow = table.Rows[4]; // #5 row
        DataRow secondRow = table.Rows[1]; // #2 row
    }

/Alex


问:
Postgresql with Hibernate: could not determine LocalDate type in jpql query
I migrated from hibernate-core:4.3.11.Final to
hibernate-core:5.2.10.Final because I want to use LocalDate from java 8 Date/Time APi in jpql for parameters, like this:

```<code>@Query("SELECT t FROM TransactionHistory t WHERE (t.account.id=:account)" + "AND (:dateFrom IS NULL OR t.date >= :dateFrom) AND (:dateTo IS NULL OR t.date <= :dateTo) order by t.date asc")
List<TransactionHistory> findByAccountIdAndDate(@Param("account") Long id,
                                                @Param("dateFrom") LocalDate from,
                                                @Param("dateTo") LocalDate to);
</code>```

In build.gradle file I have next necessary dependencies:

```<code>compile group: 'org.hibernate', name: 'hibernate-core', version: '5.2.10.Final'
compile group: 'org.postgresql', name: 'postgresql', version: '42.1.1'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: '1.4.0.RELEASE'
</code>```

When I run server I get the next stack trace:

```<code>    org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
        at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:261)
        at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:244)
        at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:491)
        at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)
        at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
        at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
        at com.sun.proxy.$Proxy218.findByAccountIdAndDate(Unknown Source)
        at sun.reflect.GeneratedMethodAccessor378.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
        at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:85)
        at com.my_company.aop.logging.LoggingAspect.logAround(LoggingAspect.java:74)
        at sun.reflect.GeneratedMethodAccessor317.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:629)
        at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:618)
        at org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroundAdvice.java:70)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
        at com.sun.proxy.$Proxy218.findByAccountIdAndDate(Unknown Source)
        at com.my_company.ibank.account.AccountService.doTestIntegrationTask(AccountService.java:830)
        at com.my_company.ibank.account.AccountService$$FastClassBySpringCGLIB$$dc3e5dc0.invoke(<generated>)
        at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
        at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:720)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
        at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:85)
        at com.my_company.ibank.aop.logging.LoggingAspect.logAround(LoggingAspect.java:74)
        at sun.reflect.GeneratedMethodAccessor317.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:629)
        at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:618)
        at org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroundAdvice.java:70)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
        at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:280)
        at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655)
        at com.my_company.ibank.account.AccountService$$EnhancerBySpringCGLIB$$d97ec4f4.doTestIntegrationTask(<generated>)
        at sun.reflect.GeneratedMethodAccessor371.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:65)
        at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:748)
Caused by: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
        at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:106)
        at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
        at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
        at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
        at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:80)
        at org.hibernate.loader.Loader.getResultSet(Loader.java:2123)
        at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1911)
        at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1887)
        at org.hibernate.loader.Loader.doQuery(Loader.java:932)
        at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:349)
        at org.hibernate.loader.Loader.doList(Loader.java:2615)
        at org.hibernate.loader.Loader.doList(Loader.java:2598)
        at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2430)
        at org.hibernate.loader.Loader.list(Loader.java:2425)
        at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:502)
        at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:379)
        at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:216)
        at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1488)
        at org.hibernate.query.internal.AbstractProducedQuery.doList(AbstractProducedQuery.java:1445)
        at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1414)
        at org.hibernate.query.Query.getResultList(Query.java:146)
        at org.springframework.data.jpa.repository.query.JpaQueryExecution$CollectionExecution.doExecute(JpaQueryExecution.java:118)
        at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:82)
        at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:116)
        at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:106)
        at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:482)
        at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:460)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
        at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:280)
        at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
        ... 60 common frames omitted
Caused by: org.postgresql.util.PSQLException: ERROR: could not determine data type of parameter $2
        at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2476)
        at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2189)
        at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:300)
        at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:428)
        at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:354)
        at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:169)
        at org.postgresql.jdbc.PgPreparedStatement.executeQuery(PgPreparedStatement.java:117)
        at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeQuery(ProxyPreparedStatement.java:52)
        at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeQuery(HikariProxyPreparedStatement.java)
        at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:71)
        ... 90 common frames omitted
</code>```

So postgres can not determine data type of parameter $2, which is must be LocalDate as described in query above, please help to solve this problem, thanks.

答:
try to add

```<code>@Convert(converter = LocalDateConverter.class)
</code>```

Example:

```<code>@Column
  @Convert(converter = LocalDateConverter.class)
  private LocalDate valueDate;
</code>```

Hope this will help you.

Body:
I migrated from hibernate-core:4.3.11.Final to
hibernate-core:5.2.10.Final because I want to use LocalDate from java 8 Date/Time APi in jpql for parameters, like this:

@Query("SELECT t FROM TransactionHistory t WHERE (t.account.id=:account)" + "AND (:dateFrom IS NULL OR t.date >= :dateFrom) AND (:dateTo IS NULL OR t.date <= :dateTo) order by t.date asc")
List<TransactionHistory> findByAccountIdAndDate(@Param("account") Long id,
                                                @Param("dateFrom") LocalDate from,
                                                @Param("dateTo") LocalDate to);

In build.gradle file I have next necessary dependencies:

compile group: 'org.hibernate', name: 'hibernate-core', version: '5.2.10.Final'
compile group: 'org.postgresql', name: 'postgresql', version: '42.1.1'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: '1.4.0.RELEASE'

When I run server I get the next stack trace:

    org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
        at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:261)
        at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:244)
        at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:491)
        at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)
        at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
        at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
        at com.sun.proxy.$Proxy218.findByAccountIdAndDate(Unknown Source)
        at sun.reflect.GeneratedMethodAccessor378.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
        at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:85)
        at com.my_company.aop.logging.LoggingAspect.logAround(LoggingAspect.java:74)
        at sun.reflect.GeneratedMethodAccessor317.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:629)
        at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:618)
        at org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroundAdvice.java:70)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
        at com.sun.proxy.$Proxy218.findByAccountIdAndDate(Unknown Source)
        at com.my_company.ibank.account.AccountService.doTestIntegrationTask(AccountService.java:830)
        at com.my_company.ibank.account.AccountService$$FastClassBySpringCGLIB$$dc3e5dc0.invoke(<generated>)
        at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
        at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:720)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
        at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:85)
        at com.my_company.ibank.aop.logging.LoggingAspect.logAround(LoggingAspect.java:74)
        at sun.reflect.GeneratedMethodAccessor317.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:629)
        at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:618)
        at org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroundAdvice.java:70)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
        at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:280)
        at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655)
        at com.my_company.ibank.account.AccountService$$EnhancerBySpringCGLIB$$d97ec4f4.doTestIntegrationTask(<generated>)
        at sun.reflect.GeneratedMethodAccessor371.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:65)
        at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:748)
Caused by: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
        at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:106)
        at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
        at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
        at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
        at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:80)
        at org.hibernate.loader.Loader.getResultSet(Loader.java:2123)
        at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1911)
        at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1887)
        at org.hibernate.loader.Loader.doQuery(Loader.java:932)
        at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:349)
        at org.hibernate.loader.Loader.doList(Loader.java:2615)
        at org.hibernate.loader.Loader.doList(Loader.java:2598)
        at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2430)
        at org.hibernate.loader.Loader.list(Loader.java:2425)
        at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:502)
        at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:379)
        at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:216)
        at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1488)
        at org.hibernate.query.internal.AbstractProducedQuery.doList(AbstractProducedQuery.java:1445)
        at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1414)
        at org.hibernate.query.Query.getResultList(Query.java:146)
        at org.springframework.data.jpa.repository.query.JpaQueryExecution$CollectionExecution.doExecute(JpaQueryExecution.java:118)
        at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:82)
        at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:116)
        at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:106)
        at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:482)
        at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:460)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
        at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:280)
        at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
        ... 60 common frames omitted
Caused by: org.postgresql.util.PSQLException: ERROR: could not determine data type of parameter $2
        at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2476)
        at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2189)
        at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:300)
        at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:428)
        at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:354)
        at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:169)
        at org.postgresql.jdbc.PgPreparedStatement.executeQuery(PgPreparedStatement.java:117)
        at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeQuery(ProxyPreparedStatement.java:52)
        at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeQuery(HikariProxyPreparedStatement.java)
        at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:71)
        ... 90 common frames omitted

So postgres can not determine data type of parameter $2, which is must be LocalDate as described in query above, please help to solve this problem, thanks.

Body:
try to add

@Convert(converter = LocalDateConverter.class)

Example:

@Column
  @Convert(converter = LocalDateConverter.class)
  private LocalDate valueDate;

Hope this will help you.


问:
UITextView text not starting from top
I have a UITextView. I want its text to start from top but I it is not coming from top. Please have a look at my code :

```<code>UITextView *myTextView = [[UITextView alloc] init];
myTextView.frame = rect;
myTextView.editable = NO;
myTextView.font = [UIFont fontWithName:@"Helvetica" size:MAIN_FONT_SIZE];
myTextView.backgroundColor = [UIColor clearColor];
myTextView.text = sourceNode.label;
myTextView.dataDetectorTypes = UIDataDetectorTypeAll;
[cell.contentView addSubview:myTextView];
[myTextView sizeToFit];
[self alignTextToTopTextView:myTextView];
</code>```

alignTextToTopTextView:

```<code>-(void)alignTextToTopTextView :(UITextView*)textView{

    CGRect frame = textView.frame;
    frame.size.height = textView.contentSize.height;
    textView.frame = frame;
}
</code>```

Please see the below screenshot.

UITextView is on the right side.

答:
```<code>self.yourTextView.scrollEnabled = NO;

self.yourTextView.textContainerInset = UIEdgeInsetsMake(0, 0, 0, 0);
</code>```

Title: UITextView text not starting from top

Body:
I have a UITextView. I want its text to start from top but I it is not coming from top. Please have a look at my code :

UITextView *myTextView = [[UITextView alloc] init];
myTextView.frame = rect;
myTextView.editable = NO;
myTextView.font = [UIFont fontWithName:@"Helvetica" size:MAIN_FONT_SIZE];
myTextView.backgroundColor = [UIColor clearColor];
myTextView.text = sourceNode.label;
myTextView.dataDetectorTypes = UIDataDetectorTypeAll;
[cell.contentView addSubview:myTextView];
[myTextView sizeToFit];
[self alignTextToTopTextView:myTextView];

alignTextToTopTextView:

-(void)alignTextToTopTextView :(UITextView*)textView{

    CGRect frame = textView.frame;
    frame.size.height = textView.contentSize.height;
    textView.frame = frame;
}

Please see the below screenshot.

UITextView is on the right side.


问:
Get n-th element from all dictionary values - Python
Is there any out of the box syntax/func that would return n-th value of all dictionary keys. For example n=2 for the following dic

```<code>dic = {'a': [1, 2, 3, 4],
       'b': [5, 6, 7, 8],
       'c': [9, 10, 11, 12]}
</code>```

would return:

```<code>newdic = {'a': 3,
          'b': 7,
          'c': 11}
</code>```

For now I defined the following function which works fine, but I find it kind of ugly.

```<code>def nth_value(n, **kwargs):
    dic = {}
    for key, value in kwargs.items():
        dic[key] = value[n]
    return dic
</code>```

P.S. I know for sure that all lists are of same length.

答:
Improvement to avoid IndexError: list index out of range:

```<code>>>> dic = {'a': [1, 2, 3, 4],
           'b': [5, 6, 7, 8],
           'c': [9, 10, 11, 12]}

>>> n = 3
>>> {k:v[n] if n < len(v) else None for k, v in dic.items()}
{'a': 4, 'b': 8, 'c': 12}

>>> del dic['b'][-1]
>>> {k:v[n] if n < len(v) else None for k, v in dic.items()}
{'a': 4, 'b': None, 'c': 12}
</code>```

Body:
Is there any out of the box syntax/func that would return n-th value of all dictionary keys. For example n=2 for the following dic

dic = {'a': [1, 2, 3, 4],
       'b': [5, 6, 7, 8],
       'c': [9, 10, 11, 12]}

would return:

newdic = {'a': 3,
          'b': 7,
          'c': 11}

For now I defined the following function which works fine, but I find it kind of ugly.

def nth_value(n, **kwargs):
    dic = {}
    for key, value in kwargs.items():
        dic[key] = value[n]
    return dic

P.S. I know for sure that all lists are of same length.

Body:
Improvement to avoid IndexError: list index out of range:

>>> dic = {'a': [1, 2, 3, 4],
           'b': [5, 6, 7, 8],
           'c': [9, 10, 11, 12]}

>>> n = 3
>>> {k:v[n] if n < len(v) else None for k, v in dic.items()}
{'a': 4, 'b': 8, 'c': 12}

>>> del dic['b'][-1]
>>> {k:v[n] if n < len(v) else None for k, v in dic.items()}
{'a': 4, 'b': None, 'c': 12}


问:
MPI create MPI_Datatype from struct containing structs with structs and typedef
I have a quite complex program which I have to parallel with MPI. I use MPICH3 for this.

I know the way to make a new MPI_Datatype as:

```<code>  typedef struct{
    float x;
    float y;
    int centroid;
} point;
typedef struct{
    int csize;//the current size
    int tsize;//the total size
    point * data;//the data carried
} ArrayList;

const int nfields=3;
MPI_Aint disps[nfields];
int blocklens[] = {1,1,1};
MPI_Datatype types[] = {MPI_FLOAT, MPI_FLOAT, MPI_INT};

disps[0] = offsetof( point, x );
disps[1] = offsetof( point, y );
disps[2] = offsetof( point, centroid );

MPI_Datatype istruct, pstruct;
MPI_Type_create_struct(nfields, blocklens, disps, types, &istruct );
MPI_Type_create_resized( istruct, 0, (char *)&(points[1]) - (char *)(&points[0]), &pstruct );
MPI_Type_commit(&pstruct);
</code>```

But I have to do a MPI_Datatype of the following struct BigInteger:

```<code>struct mylimb
{
  int x;
};
typedef struct mylimb limb;
typedef enum eBoolean
{
  FALSE = 0,
  TRUE,
} boolean;

enum eSign
{
  SIGN_POSITIVE = 0,
  SIGN_NEGATIVE,
};

typedef struct BigInteger
{
  limb limbs[1000];
  int nbrLimbs;
  enum eSign sign;
} BigInteger;
</code>```

The struct is widely used in the code so I can not simply change it to a easier way. So can anybody tell my how I can do a MPI_Datatype from the BigInteger?
My main problem is the limb which is a mylimb  how can I concat this into my MPI_Datatype

Thanks in advance!
chrigi

答:
an other way to rewrite BigInteger is

```<code>typedef struct BigInteger
{
  int limbs[1000];
  int nbrLimbs;
  enum eSign sign;
} BigInteger;
</code>```

so you can use MPI_Type_create_struct() with blocklens={1000,1,1}

my main concern is the size of enum eSign. if you do not mix big and little endian, you can declare it as MPI_BYTE and sizeof(enum eSign)

Body:
I have a quite complex program which I have to parallel with MPI. I use MPICH3 for this.

I know the way to make a new MPI_Datatype as:

  typedef struct{
    float x;
    float y;
    int centroid;
} point;
typedef struct{
    int csize;//the current size
    int tsize;//the total size
    point * data;//the data carried
} ArrayList;

const int nfields=3;
MPI_Aint disps[nfields];
int blocklens[] = {1,1,1};
MPI_Datatype types[] = {MPI_FLOAT, MPI_FLOAT, MPI_INT};

disps[0] = offsetof( point, x );
disps[1] = offsetof( point, y );
disps[2] = offsetof( point, centroid );

MPI_Datatype istruct, pstruct;
MPI_Type_create_struct(nfields, blocklens, disps, types, &istruct );
MPI_Type_create_resized( istruct, 0, (char *)&(points[1]) - (char *)(&points[0]), &pstruct );
MPI_Type_commit(&pstruct);

But I have to do a MPI_Datatype of the following struct BigInteger:

struct mylimb
{
  int x;
};
typedef struct mylimb limb;
typedef enum eBoolean
{
  FALSE = 0,
  TRUE,
} boolean;

enum eSign
{
  SIGN_POSITIVE = 0,
  SIGN_NEGATIVE,
};

typedef struct BigInteger
{
  limb limbs[1000];
  int nbrLimbs;
  enum eSign sign;
} BigInteger;

The struct is widely used in the code so I can not simply change it to a easier way. So can anybody tell my how I can do a MPI_Datatype from the BigInteger?
My main problem is the limb which is a mylimb  how can I concat this into my MPI_Datatype

Thanks in advance!
chrigi

Body:
an other way to rewrite BigInteger is

typedef struct BigInteger
{
  int limbs[1000];
  int nbrLimbs;
  enum eSign sign;
} BigInteger;

so you can use MPI_Type_create_struct() with blocklens={1000,1,1}

my main concern is the size of enum eSign. if you do not mix big and little endian, you can declare it as MPI_BYTE and sizeof(enum eSign)


问:
Writing a git post-commit file in node.js
I'm trying to write a git post-commit file in node.js and I'm having trouble.

The file seems to have to be named post-commit in the .git/hooks directory. Since that file can't have an extension, my vim editor won't persistently give it javascript syntax highlighting, and thus none of my snippets work, and a variety of other challenges present themselves.

What can I do? Tell git to run post-commit.js or tell vim to consider this file javascript, but that doesn't persist.

Thoughts?

答:
Use :set filetype=javascript command in vim to set file type.
You may also want to enable modeline in vim and include the aforementioned command in a comment at the top of your file like this:

```<code>/* vim: set filetype=javascript : */
your_Javascript_code_goes_here()
</code>```

To enable modeline in vim, add this to your ~/.vimrc file:

```<code>set modelines=2
set modeline
</code>```

That will enable searching for vim modelines in the first two lines of the file.

Body:
Use :set filetype=javascript command in vim to set file type.
You may also want to enable modeline in vim and include the aforementioned command in a comment at the top of your file like this:

/* vim: set filetype=javascript : */
your_Javascript_code_goes_here()

To enable modeline in vim, add this to your ~/.vimrc file:

set modelines=2
set modeline

That will enable searching for vim modelines in the first two lines of the file.


问:
Firebase Cloud System sending recurring messages?
Is there any possibility in Firebase Cloud System to configure messages to be sended for example in a 10 minutes basis without using an external server?</p>

答:
Cron jobs are possible with Firebase Cloud Functions. But you'll have to integrate it with Google App Engine ( at least for now, anyway ).

Check out this blog post by Abe Haskins of the Firebase team.

This should help you too.


问:
How to update an observable array inside a component from the main ViewModel?
I need to set from the main viewmodel a property inside an observable array.

I'm using the classic pre to debug and display the content of my observable array.
By using types.valueHasMutated() I can see the applied changes - just only to vm.types (which wouldn't be the case otherwise).

However, I need to see this changes reflected inside my component.

In my example, when I ckick "Apples", the corresponding input shall be disabled like the one below. Sadly, this is actually not the case.

What I'm doing wrong?

ko.components.register("available-items", {
  viewModel: function(params) {
    function AvailableItems(params) {
      var self = this;
      self.params = params;
      self.location = "A";
      self.types = ko.computed(function() {
        var types = self.params.types();
        return ko.utils.arrayFilter(types, function(item) {
          return item.location == self.location;
        });
      });
      self.addItem = function(data, event) {
        self.params.items.addItem(self.location, data.type);
      };
    }
    return new AvailableItems(params);
  },
  template: '
' +
    '
Add item
' +
    '
' +
    '
' +
    '<input type="text" data-bind="value: type, enable:available, event: {click: $parent.addItem}" readonly/>' +
    '
' +
    '
' +
    '
',
  synchronous: true
});

var types = [{
  type: "Apples",
  location: "A",
  available: true
}, {
  type: "Bananas",
  location: "A",
  available: false
}];

function Vm(data) {
  var self = this;
  self.items = ko.observableArray();
  self.types = ko.observableArray(ko.utils.arrayMap(data, function(item) {
    return item;
  }));
  self.items.addItem = function(location, type) {
    self.items.push({
      location: location,
      type: type
    });
    if (location == "A" && type == "Apples") {
      self.types()[0].available = false;
      self.types.valueHasMutated();
    }
  };
}

ko.options.deferUpdates = true;
var vm = new Vm(types);
ko.applyBindings(vm);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>pre {
  position: absolute;
  width: 300px;
  right: 0;
  top: 0;
}</code>```

<!DOCTYPE html>

 -

```
  </body>
</html></code>```

答:
I've found the problem. It's in your html: "params: vm" should be "params: $data"</p>

```<code> <div data-bind="component:{name:'available-items',params:$data}"></div>
</code>```

Body:
I need to set from the main viewmodel a property inside an observable array.

I'm using the classic pre to debug and display the content of my observable array.
By using types.valueHasMutated() I can see the applied changes - just only to vm.types (which wouldn't be the case otherwise).

However, I need to see this changes reflected inside my component.

In my example, when I ckick "Apples", the corresponding input shall be disabled like the one below. Sadly, this is actually not the case.

What I'm doing wrong?

ko.components.register("available-items", {
  viewModel: function(params) {
    function AvailableItems(params) {
      var self = this;
      self.params = params;
      self.location = "A";
      self.types = ko.computed(function() {
        var types = self.params.types();
        return ko.utils.arrayFilter(types, function(item) {
          return item.location == self.location;
        });
      });
      self.addItem = function(data, event) {
        self.params.items.addItem(self.location, data.type);
      };
    }
    return new AvailableItems(params);
  },
  template: '
' +
    '
Add item
' +
    '
' +
    '
' +
    '<input type="text" data-bind="value: type, enable:available, event: {click: $parent.addItem}" readonly/>' +
    '
' +
    '
' +
    '
',
  synchronous: true
});

var types = [{
  type: "Apples",
  location: "A",
  available: true
}, {
  type: "Bananas",
  location: "A",
  available: false
}];

function Vm(data) {
  var self = this;
  self.items = ko.observableArray();
  self.types = ko.observableArray(ko.utils.arrayMap(data, function(item) {
    return item;
  }));
  self.items.addItem = function(location, type) {
    self.items.push({
      location: location,
      type: type
    });
    if (location == "A" && type == "Apples") {
      self.types()[0].available = false;
      self.types.valueHasMutated();
    }
  };
}

ko.options.deferUpdates = true;
var vm = new Vm(types);
ko.applyBindings(vm);

pre {
  position: absolute;
  width: 300px;
  right: 0;
  top: 0;
}

<!DOCTYPE html>

 -

Body:
I've found the problem. It's in your html: "params: vm" should be "params: $data"

 <div data-bind="component:{name:'available-items',params:$data}"></div>


问:
Prompt doesn't appear in Application.InputBox on Excel for Mac 15
Here's my code:

```<code>Sub demo1()
    Dim Rng1 As Range
    Set Rng1 = Application.InputBox("The Prompt", "The Dialog Title", Type:=8)
End Sub
</code>```

Here's the result on Excel for Windows (I've also clicked on a cell to add the reference):

Here's the result on Excel for Mac (I've clicked on a cell, as above):

I'm using version 15. Simply, I don't see The Prompt on Excel for Mac. Some research shows that people have been able to use the plain InputBox (instead of Application.InputBox) as a workaround, but I need the souped-up version because the user needs to click a cell range, and the set variable must be a range object. A plain vb InputBox can't do this. Thanks in advance for any suggestions.

答:
I've looked high and low for a solution here but can't find one. It seems the Mac dialog simply doesn't contain two distinct sections (title+prompt). I've created a workaround which I'll post, it might be useful if anyone has the same problem. But if anyone can come up with a better solution I will remark the answer.

Firstly we check if we're on PC or Mac with this:

```<code>On Error Resume Next
If Val(Application.Version) = Int(Val(Application.Version)) Then
    theOs = 0 'whole version number = PC
Else
    theOs = 1 'version number with decimal = Mac
End If
If Err.Number <> 0 Then
    Err.Clear
    theOs = 0
End If
On Error GoTo 0
</code>```

Then I use the prompt if we're on PC, or the title if we're on Mac, like this:

```<code>theQ1 = "This is my prompt"
theQ2 = ""
If theOs = 1 Then
    theQ2 = theQ1
    theQ1 = ""
End If
Set Rng1 = Application.InputBox(theQ1, theQ2, Type:=8)
</code>```

For PC, it works like normal... for Mac, the prompt is in place of the title, so the user can still understand what is being requested. One important downside is that the title line is more limited in space and we can't use line breaks.

Body:
Here's my code:

Sub demo1()
    Dim Rng1 As Range
    Set Rng1 = Application.InputBox("The Prompt", "The Dialog Title", Type:=8)
End Sub

Here's the result on Excel for Windows (I've also clicked on a cell to add the reference):

Here's the result on Excel for Mac (I've clicked on a cell, as above):

I'm using version 15. Simply, I don't see The Prompt on Excel for Mac. Some research shows that people have been able to use the plain InputBox (instead of Application.InputBox) as a workaround, but I need the souped-up version because the user needs to click a cell range, and the set variable must be a range object. A plain vb InputBox can't do this. Thanks in advance for any suggestions.

Body:
I've looked high and low for a solution here but can't find one. It seems the Mac dialog simply doesn't contain two distinct sections (title+prompt). I've created a workaround which I'll post, it might be useful if anyone has the same problem. But if anyone can come up with a better solution I will remark the answer.

Firstly we check if we're on PC or Mac with this:

On Error Resume Next
If Val(Application.Version) = Int(Val(Application.Version)) Then
    theOs = 0 'whole version number = PC
Else
    theOs = 1 'version number with decimal = Mac
End If
If Err.Number <> 0 Then
    Err.Clear
    theOs = 0
End If
On Error GoTo 0

Then I use the prompt if we're on PC, or the title if we're on Mac, like this:

theQ1 = "This is my prompt"
theQ2 = ""
If theOs = 1 Then
    theQ2 = theQ1
    theQ1 = ""
End If
Set Rng1 = Application.InputBox(theQ1, theQ2, Type:=8)

For PC, it works like normal... for Mac, the prompt is in place of the title, so the user can still understand what is being requested. One important downside is that the title line is more limited in space and we can't use line breaks.


问:
How to retrieve html code as preview among text in sql php
I submitted some text to an SQL database like this:

"You can check my photo below (img src=..myimg.jpg..)and please also comment."

Now i want to retrieve it in PHP and containing image preview. The image code is HTML.

答: You need to escape data from DB before presenting it in page in order to what is stored doesn't mess with your page. But if you want also show the image, then you have to extract the img src part and put it back inside escaped output in proper html tag.</p>


答:
You can't make exp a property because of the need to capture a variable, but you can make it a function returning Expression<Func<TeamMember,bool>>:

```<code>Expression<Func<TeamMember,bool>> MakeMemberExpression(Guid teamId) {
    return teammember => teamMember.TeamId == teamId && teamMember.ManagerUserId == null;
}
</code>```

or even

```<code>Expression<Func<TeamMember,bool>> MakeMemberExpression(Guid teamId) =>
    teammember => teamMember.TeamId == teamId && teamMember.ManagerUserId == null;
</code>```

You can use it as follows:

```<code>var members = teamMembers.Where(MakeMemberExpression(teamId));
</code>```

Title: Expression with parameter (LINQ, SQL,C#)

Body:
i struggling to find the correct way to query for a specific entity in my database. I have a table TeamMember which looks as follows:

public class TeamMember
{
    public Guid TeamId { get; set; }
    public Guid ManagerUserId  { get; set; }
    ...
}

At several positions i want to query for a "TeamManager" in my teams.

public TeamMember GetTeamManager(Guid teamId, List<TeamMember> teamMembers)
{
    return teamMembers.FirstOrDefault(member => member.TeamId == teamId && member.ManagerUserId == null);
}

If i want to use a method in an expression e.g (not real code),

...
// IQueryable<TeamMember>
teamMembers.Where(member => member.team.GetTeamManager(teamId, teamMembers))

it works fine for in memory objects, but this does not work in combination with the entity framework, so real db objects.

Therefore i was experimenting with static expressions, but i did not find any solution which uses a static expression in combination with a variable e.g.:

// this should be an ideal solution
Expression<Func<TeamMember, bool>> exp = teammember => teamMember.TeamId == **CUSTOM_VARIABLE** && teamMember.ManagerUserId == null;

teamMembers.Where(exp)

I want to reuse the expression, but i also want to be able to modify the variable. My goal is to avoid the creation of an object in between because the following would work, but is less efficient (correct me if i'm wrong)

teamMembers.ToList().Where(member => member.team.GetTeamManager(teamId, teamMembers))

So please help me with my problem :).
Thank you in advance!

Body:
You can't make exp a property because of the need to capture a variable, but you can make it a function returning Expression<Func<TeamMember,bool>>:

Expression<Func<TeamMember,bool>> MakeMemberExpression(Guid teamId) {
    return teammember => teamMember.TeamId == teamId && teamMember.ManagerUserId == null;
}

or even

Expression<Func<TeamMember,bool>> MakeMemberExpression(Guid teamId) =>
    teammember => teamMember.TeamId == teamId && teamMember.ManagerUserId == null;

You can use it as follows:

var members = teamMembers.Where(MakeMemberExpression(teamId));