问:
Why do I get TypeError: unhashable type when using NLTK lemmatizer on sentence?
I'm currently working on lemmantizing a sentence while also applying pos_tags. This is what I have so far

```<code>import nltk
from nltk.tokenize import word_tokenize
from nltk.corpus import wordnet
from nltk.stem import WordNetLemmatizer
from nltk import pos_tag

lem = WordNetLemmatizer()

def findTag(sentence):
    sentence = word_tokenize(sentence)
    sentence = [i.strip(" ") for i in sentence]
    pos_label = nltk.pos_tag(sentence)[0][1][0].lower()

    if pos_label == "j":
        pos_label == "a"

    if pos_label in ["a", "n", "v"]:
        print(lem.lemmatize(word, pos = pos_label))
    elif pos_label in ['r']:
        print(wordnet.synset(sentence+".r.1").lemmas()[0].pertainyms()[0].name())
    else:
        print(lem.lemmatize(sentence))

findTag("I love running angrily")
</code>```

However, when I input a sentence with this I get the error

```<code>Traceback (most recent call last):
  File "spoilerDetect.py", line 25, in <module>
    findTag("I love running angrily")
  File "spoilerDetect.py", line 22, in findTag
    print(lem.lemmatize(sentence))
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/nltk/stem/wordnet.py", line 41, in lemmatize
    lemmas = wordnet._morphy(word, pos)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/nltk/corpus/reader/wordnet.py", line 1905, in _morphy
    if form in exceptions:
TypeError: unhashable type: 'list'
</code>```

I understand that lists are unhashable but am unsure of how to fix this. Do I change lists to a tuple or is there something I'm not understanding?

答:
Lets walk through the code and see how to get your desired output.

First the imports, you have

```<code>import nltk
from nltk import pos_tag
</code>```

and then you were using

```<code>pos_label = nltk.pos_tag(...)
</code>```

Since you're already using from nltk import pos_tag, the pos_tag is already in the global namespace, just do:

```<code>pos_label = pos_tag(...)
</code>```

Idiomatically, the imports should be cleaned up a little to look like this:

```<code>from nltk import word_tokenize, pos_tag
from nltk.corpus import wordnet as wn
from nltk.stem import WordNetLemmatizer

wnl = WordNetLemmatizer()
</code>```

Next actually keeping the list of tokenized words and then the list of pos tags and then the list of lemmas separately sounds logical but since the function finally only returns the function, you should be able to chain up the pos_tag(word_tokenize(...)) function and iterate through it so that you can retrieve the POS tag and tokens, i.e.

```<code>sentence = "I love running angrily"
for word, pos in pos_tag(word_tokenize(sentence)):
    print(word, '|', pos)
</code>```

[out]:

```<code>I | PRP
love | VBP
running | VBG
angrily | RB
</code>```

Now, we know that there's a mismatch between the outputs of pos_tag and the POS that the WordNetLemmatizer is expecting. From https://github.com/alvations/pywsd/blob/master/pywsd/utils.py#L124, there is a function call penn2morphy that looks like this:

```<code>def penn2morphy(penntag, returnNone=False, default_to_noun=False) -> str:
    """
    Converts tags from Penn format (input: single string) to Morphy.
    """
    morphy_tag = {'NN':'n', 'JJ':'a', 'VB':'v', 'RB':'r'}
    try:
        return morphy_tag[penntag[:2]]
    except:
        if returnNone:
            return None
        elif default_to_noun:
            return 'n'
        else:
            return ''
</code>```

An example:

```<code>>>> penn2morphy('JJ')
'a'
>>> penn2morphy('PRP')
''
</code>```

And if we use these converted tags as inputs to the WordNetLemmatizer and reusing your if-else conditions:

```<code>sentence = "I love running angrily"
for token, pos in pos_tag(word_tokenize(sentence)):
    morphy_pos = penn2morphy(pos)
    if morphy_pos in ["a", "n", "v"]:
        print(wnl.lemmatize(token, pos=morphy_pos))
    elif morphy_pos in ['r']:
        print(wn.synset(token+".r.1").lemmas()[0].pertainyms()[0].name())
    else:
        print(wnl.lemmatize(token))
</code>```

[out]:

```<code>I
love
run
angry
</code>```

Hey, what did you do there? Your code works but mine doesn't!

Okay, now that we know how to get the desired output. Lets recap.

First, we clean up imports

Then, we clean up the preprocessing (without keeping intermediate variables)

Then, we "functionalized" the conversion of POS tags from Penn -> Morphy

Lastly, we applied the same if/else conditions and run the lemmatizer.

But how is it that my code doesn't work?!

Okay, lets work through your code to see why you're getting the error.

First lets check every output that you get within the findTag function, printing the type of the output and the output

```<code>pos_label = nltk.pos_tag(...)
</code>```0

[out]:

```<code>pos_label = nltk.pos_tag(...)
</code>```1

At sentence = word_tokenize(sentence), you have already overwritten your original variable to the function, usually that's a sign of error later on =)

Now lets look at the next line:

```<code>pos_label = nltk.pos_tag(...)
</code>```2

[out]:

```<code>pos_label = nltk.pos_tag(...)
</code>```3

Now we see that the sentence = [i.strip(" ") for i in sentence] is actually meaningless given the example sentence.

Q: But is it true that all tokens output by word_tokenize would have no trailing/heading spaces which i.strip(' ') is trying to do?

A: Yes, it seems like so. Then NLTK first performs the regex operations on strings, then call the str.split() function which would have removed heading/trailing spaces between tokens, see https://github.com/nltk/nltk/blob/develop/nltk/tokenize/destructive.py#L141

Lets continue:

```<code>pos_label = nltk.pos_tag(...)
</code>```4

[out]:

```<code>pos_label = nltk.pos_tag(...)
</code>```5

Q: Wait a minute, where is the pos_label only a single string?

Q: And what is POS tag p?

A: Lets look closer what's happening in nltk.pos_tag(sentence)[0][1][0].lower()

Usually, when you have to do such [0][1][0] nested index retrieval, its error prone. We need to ask what's [0][1][0]?

We know that sentence now after sentence = word_tokenize(sentence) has became a list of strings. And pos_tag(sentence) would return a list of tuples of strings where the first item in the tuple is the token and the second the POS tag, i.e.

```<code>pos_label = nltk.pos_tag(...)
</code>```6

[out]:

```<code>pos_label = nltk.pos_tag(...)
</code>```7

Now if we know thing = pos_tag(word_tokenize("I love running angrily")), outputs the above, lets work with that to see what [0][1][0] is accessing.

```<code>pos_label = nltk.pos_tag(...)
</code>```8

So thing[0] outputs the tuple of (token, pos) for the first token.

```<code>pos_label = nltk.pos_tag(...)
</code>```9

And thing[0][1] outputs the POS for the first token.

```<code>pos_label = pos_tag(...)
</code>```0

Achso, the [0][1][0] looks for the first character of the POS of the first token.

So the question is that the desired behavior? If so, why are you only looking at the POS of the first word?

Regardless of what I'm looking at. Your explanation still that doesn't tell me why the TypeError: unhashable type: 'list' occurs. Stop distracting me and tell me how to resolve the TypeError!!

Okay, we move on, now that we know thing = pos_tag(word_tokenize("I love running angrily")) and thing[0][1][0].lower() = 'p'

Given your if-else conditions,

```<code>pos_label = pos_tag(...)
</code>```1

we find that 'p' value would have gone to the else, i.e. print(lem.lemmatize(sentence)) but wait a minute remember what has sentence became after you've modified it with:

```<code>pos_label = pos_tag(...)
</code>```2

So what happens if we just ignore all the rest of the code and focus on this:

```<code>from nltk.stem import WordNetLemmatizer

lem = WordNetLemmatizer()
sentence = ['I', 'love', 'running', 'angrily']

lem.lemmatize(sentence)
</code>```

[out]:

```<code>-------------------------------------------------------------------------
TypeError                               Traceback (most recent call last)
<ipython-input-34-497ae98ecaa3> in <module>
      4 sentence = ['I', 'love', 'running', 'angrily']
      5
----> 6 lem.lemmatize(sentence)

~/Library/Python/3.6/lib/python/site-packages/nltk/stem/wordnet.py in lemmatize(self, word, pos)
     39
     40     def lemmatize(self, word, pos=NOUN):
---> 41         lemmas = wordnet._morphy(word, pos)
     42         return min(lemmas, key=len) if lemmas else word
     43

~/Library/Python/3.6/lib/python/site-packages/nltk/corpus/reader/wordnet.py in _morphy(self, form, pos, check_exceptions)
   1903         # 0. Check the exception lists
   1904         if check_exceptions:
-> 1905             if form in exceptions:
   1906                 return filter_forms([form] + exceptions[form])
   1907

TypeError: unhashable type: 'list'
</code>```

Ah ha!! That's where the error occurs!!!

It's because WordNetLemmatizer is expecting a single string input and you're putting a list of strings. Example usage:

```<code>from nltk.stem import WordNetLemmatizer

wnl = WordNetLemmatizer()
token = 'words'
wnl.lemmatize(token, pos='n')
</code>```

Q: Why didn't you just get to the point?!

A: Then you would miss out on how to debug your code and make it better =)

Body:
I'm currently working on lemmantizing a sentence while also applying pos_tags. This is what I have so far

import nltk
from nltk.tokenize import word_tokenize
from nltk.corpus import wordnet
from nltk.stem import WordNetLemmatizer
from nltk import pos_tag

lem = WordNetLemmatizer()

def findTag(sentence):
    sentence = word_tokenize(sentence)
    sentence = [i.strip(" ") for i in sentence]
    pos_label = nltk.pos_tag(sentence)[0][1][0].lower()

    if pos_label == "j":
        pos_label == "a"

    if pos_label in ["a", "n", "v"]:
        print(lem.lemmatize(word, pos = pos_label))
    elif pos_label in ['r']:
        print(wordnet.synset(sentence+".r.1").lemmas()[0].pertainyms()[0].name())
    else:
        print(lem.lemmatize(sentence))

findTag("I love running angrily")

However, when I input a sentence with this I get the error

Traceback (most recent call last):
  File "spoilerDetect.py", line 25, in <module>
    findTag("I love running angrily")
  File "spoilerDetect.py", line 22, in findTag
    print(lem.lemmatize(sentence))
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/nltk/stem/wordnet.py", line 41, in lemmatize
    lemmas = wordnet._morphy(word, pos)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/nltk/corpus/reader/wordnet.py", line 1905, in _morphy
    if form in exceptions:
TypeError: unhashable type: 'list'

I understand that lists are unhashable but am unsure of how to fix this. Do I change lists to a tuple or is there something I'm not understanding?

Body:
Lets walk through the code and see how to get your desired output.

First the imports, you have

import nltk
from nltk import pos_tag

and then you were using

pos_label = nltk.pos_tag(...)

Since you're already using from nltk import pos_tag, the pos_tag is already in the global namespace, just do:

pos_label = pos_tag(...)

Idiomatically, the imports should be cleaned up a little to look like this:

from nltk import word_tokenize, pos_tag
from nltk.corpus import wordnet as wn
from nltk.stem import WordNetLemmatizer

wnl = WordNetLemmatizer()

Next actually keeping the list of tokenized words and then the list of pos tags and then the list of lemmas separately sounds logical but since the function finally only returns the function, you should be able to chain up the pos_tag(word_tokenize(...)) function and iterate through it so that you can retrieve the POS tag and tokens, i.e.

sentence = "I love running angrily"
for word, pos in pos_tag(word_tokenize(sentence)):
    print(word, '|', pos)

[out]:

I | PRP
love | VBP
running | VBG
angrily | RB

Now, we know that there's a mismatch between the outputs of pos_tag and the POS that the WordNetLemmatizer is expecting. From https://github.com/alvations/pywsd/blob/master/pywsd/utils.py#L124, there is a function call penn2morphy that looks like this:

def penn2morphy(penntag, returnNone=False, default_to_noun=False) -> str:
    """
    Converts tags from Penn format (input: single string) to Morphy.
    """
    morphy_tag = {'NN':'n', 'JJ':'a', 'VB':'v', 'RB':'r'}
    try:
        return morphy_tag[penntag[:2]]
    except:
        if returnNone:
            return None
        elif default_to_noun:
            return 'n'
        else:
            return ''

An example:

>>> penn2morphy('JJ')
'a'
>>> penn2morphy('PRP')
''

And if we use these converted tags as inputs to the WordNetLemmatizer and reusing your if-else conditions:

sentence = "I love running angrily"
for token, pos in pos_tag(word_tokenize(sentence)):
    morphy_pos = penn2morphy(pos)
    if morphy_pos in ["a", "n", "v"]:
        print(wnl.lemmatize(token, pos=morphy_pos))
    elif morphy_pos in ['r']:
        print(wn.synset(token+".r.1").lemmas()[0].pertainyms()[0].name())
    else:
        print(wnl.lemmatize(token))

[out]:

I
love
run
angry

Hey, what did you do there? Your code works but mine doesn't!

Okay, now that we know how to get the desired output. Lets recap.

First, we clean up imports

Then, we clean up the preprocessing (without keeping intermediate variables)

Then, we "functionalized" the conversion of POS tags from Penn -> Morphy

Lastly, we applied the same if/else conditions and run the lemmatizer.

But how is it that my code doesn't work?!

Okay, lets work through your code to see why you're getting the error.

First lets check every output that you get within the findTag function, printing the type of the output and the output

sentence = "I love running angrily"
sentence = word_tokenize(sentence)
print(type(sentence))
print(sentence)

[out]:

<class 'list'>
['I', 'love', 'running', 'angrily']

At sentence = word_tokenize(sentence), you have already overwritten your original variable to the function, usually that's a sign of error later on =)

Now lets look at the next line:

sentence = "I love running angrily"
sentence = word_tokenize(sentence)
sentence = [i.strip(" ") for i in sentence]

print(type(sentence))
print(sentence)

[out]:

<class 'list'>
['I', 'love', 'running', 'angrily']

Now we see that the sentence = [i.strip(" ") for i in sentence] is actually meaningless given the example sentence.

Q: But is it true that all tokens output by word_tokenize would have no trailing/heading spaces which i.strip(' ') is trying to do?

A: Yes, it seems like so. Then NLTK first performs the regex operations on strings, then call the str.split() function which would have removed heading/trailing spaces between tokens, see https://github.com/nltk/nltk/blob/develop/nltk/tokenize/destructive.py#L141

Lets continue:

sentence = "I love running angrily"
sentence = word_tokenize(sentence)
sentence = [i.strip(" ") for i in sentence]
pos_label = nltk.pos_tag(sentence)[0][1][0].lower()

print(type(pos_label))
print(pos_label)

[out]:

<class 'str'>
p

Q: Wait a minute, where is the pos_label only a single string?

Q: And what is POS tag p?

A: Lets look closer what's happening in nltk.pos_tag(sentence)[0][1][0].lower()

Usually, when you have to do such [0][1][0] nested index retrieval, its error prone. We need to ask what's [0][1][0]?

We know that sentence now after sentence = word_tokenize(sentence) has became a list of strings. And pos_tag(sentence) would return a list of tuples of strings where the first item in the tuple is the token and the second the POS tag, i.e.

sentence = "I love running angrily"
sentence = word_tokenize(sentence)
sentence = [i.strip(" ") for i in sentence]
thing = pos_tag(sentence)

print(type(thing))
print(thing)

[out]:

<class 'list'>
[('I', 'PRP'), ('love', 'VBP'), ('running', 'VBG'), ('angrily', 'RB')]

Now if we know thing = pos_tag(word_tokenize("I love running angrily")), outputs the above, lets work with that to see what [0][1][0] is accessing.

>>> thing = [('I', 'PRP'), ('love', 'VBP'), ('running', 'VBG'), ('angrily', 'RB')]
>>> thing[0][1]
('I', 'PRP')

So thing[0] outputs the tuple of (token, pos) for the first token.

>>> thing = [('I', 'PRP'), ('love', 'VBP'), ('running', 'VBG'), ('angrily', 'RB')]
>>> thing[0][1]
'PRP'

And thing[0][1] outputs the POS for the first token.

>>> thing = [('I', 'PRP'), ('love', 'VBP'), ('running', 'VBG'), ('angrily', 'RB')]
>>> thing[0][1][0]
'P'

Achso, the [0][1][0] looks for the first character of the POS of the first token.

So the question is that the desired behavior? If so, why are you only looking at the POS of the first word?

Regardless of what I'm looking at. Your explanation still that doesn't tell me why the TypeError: unhashable type: 'list' occurs. Stop distracting me and tell me how to resolve the TypeError!!

Okay, we move on, now that we know thing = pos_tag(word_tokenize("I love running angrily")) and thing[0][1][0].lower() = 'p'

Given your if-else conditions,

if pos_label in ["a", "n", "v"]:
    print(lem.lemmatize(word, pos = pos_label))
elif pos_label in ['r']:
    print(wordnet.synset(sentence+".r.1").lemmas()[0].pertainyms()[0].name())
else:
    print(lem.lemmatize(sentence))

we find that 'p' value would have gone to the else, i.e. print(lem.lemmatize(sentence)) but wait a minute remember what has sentence became after you've modified it with:

>>> sentence = word_tokenize("I love running angrily")
>>> sentence = [i.strip(" ") for i in sentence]
>>> sentence
['I', 'love', 'running', 'angrily']

So what happens if we just ignore all the rest of the code and focus on this:

from nltk.stem import WordNetLemmatizer

lem = WordNetLemmatizer()
sentence = ['I', 'love', 'running', 'angrily']

lem.lemmatize(sentence)

[out]:

-------------------------------------------------------------------------
TypeError                               Traceback (most recent call last)
<ipython-input-34-497ae98ecaa3> in <module>
      4 sentence = ['I', 'love', 'running', 'angrily']
      5
----> 6 lem.lemmatize(sentence)

~/Library/Python/3.6/lib/python/site-packages/nltk/stem/wordnet.py in lemmatize(self, word, pos)
     39
     40     def lemmatize(self, word, pos=NOUN):
---> 41         lemmas = wordnet._morphy(word, pos)
     42         return min(lemmas, key=len) if lemmas else word
     43

~/Library/Python/3.6/lib/python/site-packages/nltk/corpus/reader/wordnet.py in _morphy(self, form, pos, check_exceptions)
   1903         # 0. Check the exception lists
   1904         if check_exceptions:
-> 1905             if form in exceptions:
   1906                 return filter_forms([form] + exceptions[form])
   1907

TypeError: unhashable type: 'list'

Ah ha!! That's where the error occurs!!!

It's because WordNetLemmatizer is expecting a single string input and you're putting a list of strings. Example usage:

from nltk.stem import WordNetLemmatizer

wnl = WordNetLemmatizer()
token = 'words'
wnl.lemmatize(token, pos='n')

Q: Why didn't you just get to the point?!

A: Then you would miss out on how to debug your code and make it better =)


来源: stackexchange

问:
How do i get the IP address of ORACLE 11 g DATABASE on windows 10 to remotely connect to it?
I have installed oracle 11g on windows 10 f drive of my laptop. I want know the IP address of the database in order to connect to it using python? How do i find the ip address?

I tried this command:
 select sys_context('USERENV','IP_ADDRESS') from dual;
however it gives me the local host address.

i also tried
SELECT UTL_INADDR.get_host_address from dual;
however this throws an error saying network access denied by access control list

how do i find out the IP address?

答:
You must have a TNSNAMES.ORA file in your Oracle Configuration. Find that file and open it. There should be ip adresses and needed ports in there.

From official docs:

By default, tnsnames.ora is located in the $ORACLE_HOME/network/admin
  directory on UNIX operating systems and in the
  %ORACLE_HOME%\network\admin directory on Windows operating systems.
  tnsnames.ora can also be stored the following locations:

The directory specified by the TNS_ADMIN environment variable or
  registry value

On UNIX operating systems, the global configuration directory. For
  example, on the Solaris Operating System, this directory is
  /var/opt/oracle.

Then you can connect db with python cx_Oracle library using syntax below for connection string.

connection_oracle_textfile.txt -> username/password@HOST:PORT/SERVICE_NAME(you can find all of them but username and password in tnsnames.ora file)

```<code>import cx_Oracle as cx_Oracle
def get_oracle_table_from_dbm(sql_text):
if 'connection_oracle' not in  globals():
    print('connection does not exist. Try to connect it...')
    f = open('connection_oracle_textfile.txt', "r")
    fx = f.read()
    ####
    global connection_oracle
    connection_oracle = cx_Oracle.connect(fx)
    ####
    print('connection established!!')

print('Already have connection. Just fetch data!!')
return pd.read_sql(sql_text, con=connection_oracle)
</code>```

Docs

ContentLicense: CC BY-SA 4.0

Body:
You must have a TNSNAMES.ORA file in your Oracle Configuration. Find that file and open it. There should be ip adresses and needed ports in there.

From official docs:

By default, tnsnames.ora is located in the $ORACLE_HOME/network/admin
  directory on UNIX operating systems and in the
  %ORACLE_HOME%\network\admin directory on Windows operating systems.
  tnsnames.ora can also be stored the following locations:

The directory specified by the TNS_ADMIN environment variable or
  registry value

On UNIX operating systems, the global configuration directory. For
  example, on the Solaris Operating System, this directory is
  /var/opt/oracle.

Then you can connect db with python cx_Oracle library using syntax below for connection string.

connection_oracle_textfile.txt -> username/password@HOST:PORT/SERVICE_NAME(you can find all of them but username and password in tnsnames.ora file)

import cx_Oracle as cx_Oracle
def get_oracle_table_from_dbm(sql_text):
if 'connection_oracle' not in  globals():
    print('connection does not exist. Try to connect it...')
    f = open('connection_oracle_textfile.txt', "r")
    fx = f.read()
    ####
    global connection_oracle
    connection_oracle = cx_Oracle.connect(fx)
    ####
    print('connection established!!')

print('Already have connection. Just fetch data!!')
return pd.read_sql(sql_text, con=connection_oracle)

Docs


问:
Adding custom CSS and JS to Shopify
I am working on getting vertical tabs for a page on Shopify, using the 'Atlantic' theme.
As this theme does not have vertical tabs by default, I have used the external JS and CSS "jquery-jvert-tabs".

My question is, if I upload the JS and CSS files as assets, how do I link them to the page on which I want to use these and how to make use of these on the page after that, if I have certain style elements available there too?

答:
Open theme.liquid and check how the css and js are included and add yours by following them.Add your custom file to assets.Css And Js Add
Image attached </p>

ContentLicense: CC BY-SA 3.0

Title: Adding custom CSS and JS to Shopify


问:
Plotting and extracting fft phase
Here is a code that compares fft phase plotting with 2 different methods :

```<code>import numpy as np
import matplotlib.pyplot as plt
import scipy.fftpack

phase = np.pi / 4
f = 1
fs = f*20
dur=10
t = np.linspace(0, dur, num=fs*dur, endpoint=False)
y = np.cos(2 * np.pi * t + phase)
Y = scipy.fftpack.fftshift(scipy.fftpack.fft(y))
f = scipy.fftpack.fftshift(scipy.fftpack.fftfreq(len(t)))

p = np.angle(Y)
p[np.abs(Y) < 1] = 0

fig, ax = plt.subplots(2, 1)
ax[0].plot(t, y)
ax[1].plot(f*fs, p, label='from fft')
ax[1].phase_spectrum(y, fs, window=None, label='from phase_spectrum')
plt.legend()
plt.show()
</code>```

here is the result :

Here is result when signal number of period is not an integer :

I have several questions :

why are phase plot with phase_spectrum or using fft and the angle so different? Using fft and then np.angle produces good results, but how can we explain magnitude_spectrum result?

Here we are in a very simple case where we have sine periodic signal with N periods For if I have a widepand signal and I want to extract phase at f how can I do? For example here with both methods presented in example, I'm not sure I can extract a precise phase. With phase_spectrum, at f = 1 I cannot find back pi/4. And with fft and then np.angle, in order to extract the good phase I need to be sure signal number of period is an integer.

答:
Before the answer, just a small note:

Remove the p[np.abs(Y) < 1] = 0 line. Most of your spectrum has magnitude below 1, which is why, with this line, your spectrum looks mostly like a flat line at zero.

Now to the answer:

phase_spectrum does three things different than you:

It applies phase unwrapping.

If you want to apply phase unwrapping in your code, just do np.unwrap(np.angle(Y)).

If you want matplotlib to plot the spectrum without unwrapping, use angle_spectrum instead.

It applies a windowing function to the data before computing the spectrum.

I know you passed a window=None, but, for some reason, matplotlib decided that window=None means "use a hanning window, please" (see the docs).

If you do not want matplotlib to apply the window, one solution is to pass window=lambda x: x.

The docs actually suggest passing window=matplotlib.mlab.window_none, but the source for it is just a def window_none(x): return x.

It computes the one-sided version of your spectrum. The docs say this is the default whenever the input is real, not complex.

To get the normal two-sided version, pass sides='twosided' to the phase_spectrum call.

Now, about getting the phase at a frequency f:

To do this, you must use the phase without unwrapping.

You are right that you can't directly extract the phase of the single tone signal if you do not have an integer number of cycles. That is because the singal's frequency does not fall exactly on top of any frequency bin in the FFT. You can get an approximation with the phase of the nearest bin, though. You could also do a sinc interpolation of the spectrum to get its value at the frequency you want.

If you only care about the phase of a single frequency f, then you shouldn't use FFT at all. The FFT computes the phase and amplitue at all frequencies. If you only care about a single frequency, just do Y_at_f = y @ np.exp(2j * np.pi * f * t) and get that phase by np.angle(Y_at_f).

Title: Plotting and extracting fft phase

Body:
Here is a code that compares fft phase plotting with 2 different methods :

import numpy as np
import matplotlib.pyplot as plt
import scipy.fftpack

phase = np.pi / 4
f = 1
fs = f*20
dur=10
t = np.linspace(0, dur, num=fs*dur, endpoint=False)
y = np.cos(2 * np.pi * t + phase)
Y = scipy.fftpack.fftshift(scipy.fftpack.fft(y))
f = scipy.fftpack.fftshift(scipy.fftpack.fftfreq(len(t)))

p = np.angle(Y)
p[np.abs(Y) < 1] = 0

fig, ax = plt.subplots(2, 1)
ax[0].plot(t, y)
ax[1].plot(f*fs, p, label='from fft')
ax[1].phase_spectrum(y, fs, window=None, label='from phase_spectrum')
plt.legend()
plt.show()

here is the result :

Here is result when signal number of period is not an integer :

I have several questions :

why are phase plot with phase_spectrum or using fft and the angle so different? Using fft and then np.angle produces good results, but how can we explain magnitude_spectrum result?

Here we are in a very simple case where we have sine periodic signal with N periods For if I have a widepand signal and I want to extract phase at f how can I do? For example here with both methods presented in example, I'm not sure I can extract a precise phase. With phase_spectrum, at f = 1 I cannot find back pi/4. And with fft and then np.angle, in order to extract the good phase I need to be sure signal number of period is an integer.


问:
Apache Camel Mail: How to send email when we have Mail Host only?
Following is my code:

```<code>from("file:input?noop=true")
                    .log(LoggingLevel.INFO, "Read from the input file")
                    .setHeader("to", simple("fz@digga.com"))
                    .to("smtps://scan.buzu.com")
</code>```

In earlier java codes, we just give to(any xyz) and from(any xyz) and host only scan.buzu.com. No other parameter we give i.e no username, or password or anything I am not sure if the above implementation is fine in camel to achieve using hostname only?

When i change it from smtps to smptp, It says fllowing

```<code>Caused by: com.sun.mail.smtp.SMTPAddressFailedException: 504 5.5.2 <camel@localhost>: Sender address rejected: need fully-qualified address
</code>```

but i do not have any user or anything to login.

答:
Fixed it by adding xyz Sender as well as smtp in place of smtps:</p>

```<code>from("file:input?noop=true")
                .log(LoggingLevel.INFO, "Read from the input file")
                .setHeader("to", simple("fz@digga.com"))
                .setHeader("from", simple("support@digga.com"))
                .to("smtp://scan.buzu.com")
</code>```

Body:
Following is my code:

from("file:input?noop=true")
                    .log(LoggingLevel.INFO, "Read from the input file")
                    .setHeader("to", simple("fz@digga.com"))
                    .to("smtps://scan.buzu.com")

In earlier java codes, we just give to(any xyz) and from(any xyz) and host only scan.buzu.com. No other parameter we give i.e no username, or password or anything I am not sure if the above implementation is fine in camel to achieve using hostname only?

When i change it from smtps to smptp, It says fllowing

Caused by: com.sun.mail.smtp.SMTPAddressFailedException: 504 5.5.2 <camel@localhost>: Sender address rejected: need fully-qualified address

but i do not have any user or anything to login.

Body:
Fixed it by adding xyz Sender as well as smtp in place of smtps:

from("file:input?noop=true")
                .log(LoggingLevel.INFO, "Read from the input file")
                .setHeader("to", simple("fz@digga.com"))
                .setHeader("from", simple("support@digga.com"))
                .to("smtp://scan.buzu.com")


问:
node.js npm error message - system cannot find the path specified
I have a strange error message I don't understand or can't get rid of.
Secondly when I try to create express app on webstorm it can't find express.
I'm using windows 7 64 bit.

PS C:\dv> npm -v

The system cannot find the path specified.

```<code>1.2.14
</code>```

PS C:\dv>

many thanks in advance

Jeremy

答:
For me , Deleting these two folder worked:

JUST Delete

```<code>C:\Users\yourUserName\AppData\Roaming\npm
</code>```

AND

```<code>C:\Users\yourUserName\AppData\Roaming\npm-cache
</code>```

Body:
I have a strange error message I don't understand or can't get rid of.
Secondly when I try to create express app on webstorm it can't find express.
I'm using windows 7 64 bit.

PS C:\dv> npm -v

The system cannot find the path specified.

1.2.14

PS C:\dv>

many thanks in advance

Jeremy

Body:
For me , Deleting these two folder worked:

JUST Delete

C:\Users\yourUserName\AppData\Roaming\npm

AND

C:\Users\yourUserName\AppData\Roaming\npm-cache


问:
How to implement usage of multiple strategies at runtime
I need to process a list of records returned from a service.

However the processing algorithm for a record changes completely based on a certain field on the record.

To implement this , I have defined an IProcessor interface which has just one method :

```<code>public interface IProcessor
{
    ICollection<OutputEntity> Process(ICollection<InputEntity>> entities);
}
</code>```

And I have two concrete implementations of IProcessor for the different types of processing.

The issue is that I need to use all implementations of IProcessor at the same time .. so how do I inject the IProcessor into my Engine class which drives the whole thing:

```<code>public class Engine
{
    public void ProcessRecords(IService service)
    {
        var records = service.GetRecords();
        var type1Records = records.Where(x => x.SomeField== "Type1").ToList();
        var type2Records = records.Where(x => x.SomeField== "Type2").ToList();

        IProcessor processor1 = new Type1Processor();
        processor.Process(type1Records);

        IProcessor processor2 = new Type2Processor();
        processor.Process(type2Records);
    }
}
</code>```

This is what I'm doing at present .. and it doesn't look nice and clean.

Any ideas as to how I could improve this design .. using IoC perhaps ?

答:
Change your IProcessor interface, and add a new function:

```<code>public interface IProcessor
{
    ICollection<OutputEntity> Process(InputEntity> entity);
    bool CanProcess (InputEntity entity);
}
</code>```

Then your code doesn't need to know anything about the implementation:

```<code>foreach (var entity in entities) {
    var processor = allOfMyProcessors.First(p=>p.CanProcess(entity));

    processor.Process(entity);
}
</code>```

Your processor would do the magic:

```<code>public class Processor1 : IProcessor {
    public bool CanProcess(InputEntity entity) {
        return entity.Field == "field1";
    }
}
</code>```

Benefit of this approach is that you can load new processors from assemblies etc. without your main code implementation having to know about any single implementation out there.

Body:
I need to process a list of records returned from a service.

However the processing algorithm for a record changes completely based on a certain field on the record.

To implement this , I have defined an IProcessor interface which has just one method :

public interface IProcessor
{
    ICollection<OutputEntity> Process(ICollection<InputEntity>> entities);
}

And I have two concrete implementations of IProcessor for the different types of processing.

The issue is that I need to use all implementations of IProcessor at the same time .. so how do I inject the IProcessor into my Engine class which drives the whole thing:

public class Engine
{
    public void ProcessRecords(IService service)
    {
        var records = service.GetRecords();
        var type1Records = records.Where(x => x.SomeField== "Type1").ToList();
        var type2Records = records.Where(x => x.SomeField== "Type2").ToList();

        IProcessor processor1 = new Type1Processor();
        processor.Process(type1Records);

        IProcessor processor2 = new Type2Processor();
        processor.Process(type2Records);
    }
}

This is what I'm doing at present .. and it doesn't look nice and clean.

Any ideas as to how I could improve this design .. using IoC perhaps ?

Body:
Change your IProcessor interface, and add a new function:

public interface IProcessor
{
    ICollection<OutputEntity> Process(InputEntity> entity);
    bool CanProcess (InputEntity entity);
}

Then your code doesn't need to know anything about the implementation:

foreach (var entity in entities) {
    var processor = allOfMyProcessors.First(p=>p.CanProcess(entity));

    processor.Process(entity);
}

Your processor would do the magic:

public class Processor1 : IProcessor {
    public bool CanProcess(InputEntity entity) {
        return entity.Field == "field1";
    }
}

Benefit of this approach is that you can load new processors from assemblies etc. without your main code implementation having to know about any single implementation out there.


问:
Adding dataset and column arguments into a function from a named vector -rlang question
I have a series of functions that make some ggplot2 charts.

I have a new dataset that I want to use these functions on, to make the charts.

This new dataset has its own unique names for the columns that the functions needs.

It is also likely that I will get additional new datasets (with their own different column names) in the future).

I was thinking of making a named vector where I specified the new dataset's column names to utilise (and also the name of the new dataset object itself), and I could give the values of this named vector to each of the functions.

Here is a minimally reproducible example for what I am talking about.

I know it is going to involve some combination of !!, enquo, sym... but I've tried heaps and it looks like it's got me beat.

Also, I would like to do this without altering the functions (i.e. I would still like to utilise the functions by entering in the dataset / column object names directly, as well).

```<code>library(tidyverse)
library(rlang)

# make a dataset
dif_data_name <- tibble(dif_col_name = 1:50)

# a function that only utilises a dataset
test_function_only_data <- function(dataset) {

  dataset %>%
    pull() %>%
    sum()
}

# a function that utilises the dataset and a specific column

test_function_with_col <- function(dataset, only_column) {

  only_column <- enquo(only_column)

  dataset %>%
    pull(!! only_column) %>%
    sum()
}

# If I specify the datset object, this works
test_function_only_data(dif_data_name)

# so does this (with the column name as well)
test_function_with_col(dif_data_name, dif_col_name)

# But I was hoping to use a named vector for the dataset and column arguments

function_arguments <- c("dataset" = "dif_data_name",
                         "only_column" = "dif_col_name")

# These (below) do not work. But I would like to figure out how to make them work.

# first function test

test_function_only_data(
  function_arguments[["dataset"]]
                        )

# second function test

test_function_with_col(function_arguments[["dataset"]],
                       function_arguments[["only_column"]])

</code>```

答:
Update  (per OP comments)

Here's a full example using the data posted in the gist in this comment thread.

```<code>set.seed(123)

new_table <- tibble(
  Date = seq.Date(as.Date("2016-01-01"), as.Date("2019-12-31"), 1)
  ) %>%
  mutate(total_sales = rnorm(n()))

new_yearly_lines_fn <- function(sales_table, date_col, money_col) {
  date_col <- sym(date_col)
  money_col <- sym(money_col)
  sales_table <- eval(sym(sales_table))

  sales_table %>%
    group_by(year_month = floor_date({{date_col}}, "months"),
             year = year({{date_col}})) %>%
    summarise(total_sales = sum({{money_col}})) %>%
    ungroup() %>%
    ggplot() +
    aes(year_month, total_sales, col = factor(year)) +
    geom_line(stat = "identity", size = 2) +
    geom_point(stat = "identity", size = 2, col = "black")

}

function_arguments <- c("the_dataset" = "new_table",
                        "the_date_col" = "Date",
                        "the_money_col" = "total_sales")

new_yearly_lines_fn(function_arguments[["the_dataset"]],
                    function_arguments[["the_date_col"]],
                    function_arguments[["the_money_col"]])
</code>```

FWIW, there are simpler ways to pass the information you want into a function with tidy evaluation.  But here's how you'd do it with your named vector:

```<code>f <- function(named) {
  df_str <- named[["dataset"]]
  col_str <- named[["only_column"]]

  dataset <- eval(sym(df_str))

  dataset %>%
    pull({{col_str}}) %>%
    sum()
}

f(function_arguments)
# 1275
</code>```

Variants which pass in individual components of function_arguments will also work:

```<code>f2 <- function(df_str, col_str) {
  col <- sym(col_str)
  dataset <- eval(sym(df_str))

  dataset %>%
    pull({{col_str}}) %>%
    sum()
}

f2(function_arguments[["dataset"]], function_arguments[["only_column"]])
# 1275
</code>```

Note that !! notation is now replaced by  {{ }} notation, as of rlang. 0.4.0.

Body:
I have a series of functions that make some ggplot2 charts.

I have a new dataset that I want to use these functions on, to make the charts.

This new dataset has its own unique names for the columns that the functions needs.

It is also likely that I will get additional new datasets (with their own different column names) in the future).

I was thinking of making a named vector where I specified the new dataset's column names to utilise (and also the name of the new dataset object itself), and I could give the values of this named vector to each of the functions.

Here is a minimally reproducible example for what I am talking about.

I know it is going to involve some combination of !!, enquo, sym... but I've tried heaps and it looks like it's got me beat.

Also, I would like to do this without altering the functions (i.e. I would still like to utilise the functions by entering in the dataset / column object names directly, as well).

library(tidyverse)
library(rlang)

# make a dataset
dif_data_name <- tibble(dif_col_name = 1:50)

# a function that only utilises a dataset
test_function_only_data <- function(dataset) {

  dataset %>%
    pull() %>%
    sum()
}

# a function that utilises the dataset and a specific column

test_function_with_col <- function(dataset, only_column) {

  only_column <- enquo(only_column)

  dataset %>%
    pull(!! only_column) %>%
    sum()
}

# If I specify the datset object, this works
test_function_only_data(dif_data_name)

# so does this (with the column name as well)
test_function_with_col(dif_data_name, dif_col_name)

# But I was hoping to use a named vector for the dataset and column arguments

function_arguments <- c("dataset" = "dif_data_name",
                         "only_column" = "dif_col_name")

# These (below) do not work. But I would like to figure out how to make them work.

# first function test

test_function_only_data(
  function_arguments[["dataset"]]
                        )

# second function test

test_function_with_col(function_arguments[["dataset"]],
                       function_arguments[["only_column"]])

Body:
Update  (per OP comments)

Here's a full example using the data posted in the gist in this comment thread.

set.seed(123)

new_table <- tibble(
  Date = seq.Date(as.Date("2016-01-01"), as.Date("2019-12-31"), 1)
  ) %>%
  mutate(total_sales = rnorm(n()))

new_yearly_lines_fn <- function(sales_table, date_col, money_col) {
  date_col <- sym(date_col)
  money_col <- sym(money_col)
  sales_table <- eval(sym(sales_table))

  sales_table %>%
    group_by(year_month = floor_date({{date_col}}, "months"),
             year = year({{date_col}})) %>%
    summarise(total_sales = sum({{money_col}})) %>%
    ungroup() %>%
    ggplot() +
    aes(year_month, total_sales, col = factor(year)) +
    geom_line(stat = "identity", size = 2) +
    geom_point(stat = "identity", size = 2, col = "black")

}

function_arguments <- c("the_dataset" = "new_table",
                        "the_date_col" = "Date",
                        "the_money_col" = "total_sales")

new_yearly_lines_fn(function_arguments[["the_dataset"]],
                    function_arguments[["the_date_col"]],
                    function_arguments[["the_money_col"]])

FWIW, there are simpler ways to pass the information you want into a function with tidy evaluation.  But here's how you'd do it with your named vector:

f <- function(named) {
  df_str <- named[["dataset"]]
  col_str <- named[["only_column"]]

  dataset <- eval(sym(df_str))

  dataset %>%
    pull({{col_str}}) %>%
    sum()
}

f(function_arguments)
# 1275

Variants which pass in individual components of function_arguments will also work:

f2 <- function(df_str, col_str) {
  col <- sym(col_str)
  dataset <- eval(sym(df_str))

  dataset %>%
    pull({{col_str}}) %>%
    sum()
}

f2(function_arguments[["dataset"]], function_arguments[["only_column"]])
# 1275

Note that !! notation is now replaced by  {{ }} notation, as of rlang. 0.4.0.


问:
Which Class is missing in the following program?
```<code>class Test
{
int unique_element(int arr[],int n)
{
    int result=0;
    for(int i=0;i<n;i++)
    {
        int sum=0;
        x=(1<<i);
        for(int j=0;j<n;j++)
        {
            if(arr[j]&x)
                sum++;
        }
        if(sum%3)
        {
            result |= x;
            System.out.println(x);
        }
    }
    return(result);
}
public static void main(String[] args){
    int arr[]={3,1,1,9,3,1,3,9,9,5};
    N=arr.length;
    System.out.println(unique_element(arr[],N));
    }
}
</code>```

Program for every element appears 3 times in a given arr except 1 element. Logic is correct but I'm getting error in print statement like .class is expected.

Test.java:28:error: '.class' expected

System.out.println(unique_element(arr[],N));

and i'm getting error in if statement --> if(arr[j] & x){ sum++;}

Test.java:298: error: incompatible types: int cannot be converted to boolean

```<code>      if(arr[j]&x)
</code>```

答:
You forget to declear the data type of N. Also either need to declare the method unique_element -> static or create a new instance of Test.

For example:

```<code>public static void main(String[] args){
    int arr[]={3,1,1,9,3,1,3,9,9,5};
    // declear N with data type
    int N=arr.length;
    System.out.println(new Test().unique_element(arr,N));
}
</code>```

Update:

i'm getting error in if statement --> if(arr[j] & x){ sum++;}

Actually if(arr[j] & x) is c style syntax in Java a boolean expression is expected inside if statement. You can change it:

```<code>if((arr[j] & x) !=0){ sum++;}
</code>```

The same thing is also true for: if(sum%3). This should be:

```<code>if(sum%3 !=0)
{
    result |= x;
    System.out.println(x);
}
</code>```

Body:
class Test
{
int unique_element(int arr[],int n)
{
    int result=0;
    for(int i=0;i<n;i++)
    {
        int sum=0;
        x=(1<<i);
        for(int j=0;j<n;j++)
        {
            if(arr[j]&x)
                sum++;
        }
        if(sum%3)
        {
            result |= x;
            System.out.println(x);
        }
    }
    return(result);
}
public static void main(String[] args){
    int arr[]={3,1,1,9,3,1,3,9,9,5};
    N=arr.length;
    System.out.println(unique_element(arr[],N));
    }
}

Program for every element appears 3 times in a given arr except 1 element. Logic is correct but I'm getting error in print statement like .class is expected.

Test.java:28:error: '.class' expected

System.out.println(unique_element(arr[],N));

and i'm getting error in if statement --> if(arr[j] & x){ sum++;}

Test.java:298: error: incompatible types: int cannot be converted to boolean

      if(arr[j]&x)

Body:
You forget to declear the data type of N. Also either need to declare the method unique_element -> static or create a new instance of Test.

For example:

public static void main(String[] args){
    int arr[]={3,1,1,9,3,1,3,9,9,5};
    // declear N with data type
    int N=arr.length;
    System.out.println(new Test().unique_element(arr,N));
}

Update:

i'm getting error in if statement --> if(arr[j] & x){ sum++;}

Actually if(arr[j] & x) is c style syntax in Java a boolean expression is expected inside if statement. You can change it:

if((arr[j] & x) !=0){ sum++;}

The same thing is also true for: if(sum%3). This should be:

if(sum%3 !=0)
{
    result |= x;
    System.out.println(x);
}


问:
`make` error when compiling vim with python3 support
I am trying to compile vim with python3 support.

I cloned vim: git clone https://github.com/vim/vim and ran:

```<code>./configure --enable-python3interp
</code>```

Output:

```<code>configure: loading cache auto/config.cache
checking whether make sets $(MAKE)... (cached) yes
checking for gcc... (cached) gcc
checking whether the C compiler works... yes
checking for C compiler default output file name... a.out
checking for suffix of executables...
checking whether we are cross compiling... no
checking for suffix of object files... (cached) o
checking whether we are using the GNU C compiler... (cached) yes
checking whether gcc accepts -g... (cached) yes
checking for gcc option to accept ISO C89... (cached) none needed
checking for gcc option to accept ISO C99... (cached) none needed
checking how to run the C preprocessor... (cached) gcc -E
checking for grep that handles long lines and -e... (cached) /bin/grep
checking for egrep... (cached) /bin/grep -E
checking for fgrep... (cached) /bin/grep -F
checking for library containing strerror... (cached) none required
checking for gawk... (cached) mawk
checking for strip... (cached) strip
checking for ANSI C header files... (cached) yes
checking for sys/wait.h that is POSIX.1 compatible... (cached) yes
checking for unsigned long long int... (cached) yes
checking for long long int... (cached) yes
checking if the compiler supports trailing commas... yes
checking if the compiler supports C++ comments... yes
checking --enable-fail-if-missing argument... no
checking for clang version... N/A
configure: checking for buggy tools...
checking for BeOS... no
checking for QNX... no
checking for Darwin (Mac OS X)... no
checking for AvailabilityMacros.h... (cached) no
checking --with-local-dir argument... Defaulting to /usr/local
checking --with-vim-name argument... Defaulting to vim
checking --with-ex-name argument... Defaulting to ex
checking --with-view-name argument... Defaulting to view
checking --with-global-runtime argument... no
checking --with-modified-by argument... no
checking if character set is EBCDIC... no
checking --disable-smack argument... no
checking for linux/xattr.h... (cached) yes
checking for attr/xattr.h... (cached) no
checking --disable-selinux argument... no
checking for is_selinux_enabled in -lselinux... (cached) no
checking --with-features argument... Defaulting to huge
checking --with-compiledby argument... no
checking --disable-xsmp argument... no
checking --disable-xsmp-interact argument... no
checking --enable-luainterp argument... no
checking --enable-mzschemeinterp argument... no
checking --enable-perlinterp argument... no
checking --enable-pythoninterp argument... no
checking --enable-python3interp argument... yes
checking --with-python3-command argument... no
checking Python version... (cached) 3.6
checking Python is 3.0 or better... yep
checking Python's abiflags... (cached) m
checking Python's install prefix... (cached) /home/user/venvs/fundreader
checking Python's execution prefix... (cached) /home/user/venvs/fundreader
(cached) checking Python's configuration directory... (cached) /home/user/anaconda3/lib/python3.6/config-3.6m-x86_64-linux-gnu
(cached) checking Python3's dll name... (cached) libpython3.6m.a
checking if -pthread should be used... yes
checking if compile and link flags for Python 3 are sane... yes
checking if -fPIE can be added for Python3... yes
checking --enable-tclinterp argument... no
checking --enable-rubyinterp argument... no
checking --enable-cscope argument... no
checking --disable-netbeans argument... no
checking --disable-channel argument... no
checking for socket in -lsocket... (cached) no
checking for gethostbyname in -lnsl... (cached) yes
checking whether compiling with process communication is possible... yes
checking --enable-terminal argument... defaulting to yes
checking --enable-autoservername argument... no
checking --enable-multibyte argument... yes
checking --disable-rightleft argument... no
checking --disable-arabic argument... no
checking --enable-xim argument... defaulting to auto
checking --enable-fontset argument... no
checking for xmkmf... no
checking for X... (cached) libraries , headers
checking for gethostbyname... (cached) yes
checking for connect... (cached) yes
checking for remove... (cached) yes
checking for shmat... (cached) yes
checking for IceConnectionNumber in -lICE... (cached) yes
checking if X11 header files can be found... yes
checking for _XdmcpAuthDoIt in -lXdmcp... (cached) yes
checking for IceOpenConnection in -lICE... (cached) yes
checking for XpmCreatePixmapFromData in -lXpm... (cached) yes
checking if X11 header files implicitly declare return values... no
checking size of wchar_t is 2 bytes... (cached) no
checking --enable-gui argument... yes/auto - automatic GUI support
checking whether or not to look for GTK+ 2... yes
checking whether or not to look for GNOME... no
checking whether or not to look for Motif... yes
checking whether or not to look for Athena... yes
checking whether or not to look for neXtaw... yes
checking whether or not to look for Carbon... yes
checking for pkg-config... (cached) /usr/bin/pkg-config
checking --disable-gtktest argument... gtk test enabled
no
checking for location of Motif GUI includes... <not found>
checking if Athena header files can be found... no
checking if neXtaw header files can be found... no
checking for X11/SM/SMlib.h... (cached) yes
checking for X11/xpm.h... (cached) yes
checking for X11/Sunkeysym.h... (cached) yes
checking for XIMText in X11/Xlib.h... yes
checking for /proc link to executable... /proc/self/exe
checking for CYGWIN or MSYS environment... no
checking whether toupper is broken... (cached) no
checking whether __DATE__ and __TIME__ work... yes
checking whether __attribute__((unused)) is allowed... yes
checking for elf.h... (cached) yes
checking for main in -lelf... (cached) no
checking for dirent.h that defines DIR... (cached) yes
checking for library containing opendir... (cached) none required
checking for stdint.h... (cached) yes
checking for stdlib.h... (cached) yes
checking for string.h... (cached) yes
checking for sys/select.h... (cached) yes
checking for sys/utsname.h... (cached) yes
checking for termcap.h... (cached) yes
checking for fcntl.h... (cached) yes
checking for sgtty.h... (cached) yes
checking for sys/ioctl.h... (cached) yes
checking for sys/time.h... (cached) yes
checking for sys/types.h... (cached) yes
checking for termio.h... (cached) yes
checking for iconv.h... (cached) yes
checking for inttypes.h... (cached) yes
checking for langinfo.h... (cached) yes
checking for math.h... (cached) yes
checking for unistd.h... (cached) yes
checking for stropts.h... (cached) yes
checking for errno.h... (cached) yes
checking for sys/resource.h... (cached) yes
checking for sys/systeminfo.h... (cached) no
checking for locale.h... (cached) yes
checking for sys/stream.h... (cached) no
checking for termios.h... (cached) yes
checking for libc.h... (cached) no
checking for sys/statfs.h... (cached) yes
checking for poll.h... (cached) yes
checking for sys/poll.h... (cached) yes
checking for pwd.h... (cached) yes
checking for utime.h... (cached) yes
checking for sys/param.h... (cached) yes
checking for sys/ptms.h... (cached) no
checking for libintl.h... (cached) yes
checking for libgen.h... (cached) yes
checking for util/debug.h... (cached) no
checking for util/msg18n.h... (cached) no
checking for frame.h... (cached) no
checking for sys/acl.h... (cached) no
checking for sys/access.h... (cached) no
checking for sys/sysinfo.h... (cached) yes
checking for wchar.h... (cached) yes
checking for wctype.h... (cached) yes
checking for sys/ptem.h... (cached) no
checking for sys/sysctl.h... (cached) yes
checking for pthread_np.h... no
checking for strings.h... (cached) yes
checking if strings.h can be included after string.h... yes
checking whether gcc needs -traditional... (cached) no
checking for an ANSI C-conforming const... (cached) yes
checking for working volatile... (cached) yes
checking for mode_t... (cached) yes
checking for off_t... (cached) yes
checking for pid_t... (cached) yes
checking for size_t... (cached) yes
checking for uid_t in sys/types.h... (cached) yes
checking for uint32_t... (cached) yes
checking whether time.h and sys/time.h may both be included... (cached) yes
checking for ino_t... (cached) yes
checking for dev_t... (cached) yes
checking whether byte ordering is bigendian... (cached) no
checking for inline... (cached) inline
checking for rlim_t... (cached) yes
checking for stack_t... (cached) yes
checking whether stack_t has an ss_base field... no
checking --with-tlib argument... empty: automatic terminal library selection
checking for tgetent in -ltinfo... (cached) yes
checking whether we talk terminfo... (cached) yes
checking what tgetent() returns for an unknown terminal... (cached) zero
checking whether termcap.h contains ospeed... yes
checking whether termcap.h contains UP, BC and PC... yes
checking whether tputs() uses outfuntype... no
checking whether sys/select.h and sys/time.h may both be included... yes
checking for /dev/ptc... no
checking for SVR4 ptys... yes
checking for ptyranges... don't know
checking default tty permissions/group... (cached) world
checking return type of signal handlers... (cached) void
checking for struct sigcontext... yes
checking getcwd implementation is broken... (cached) no
checking for fchdir... (cached) yes
checking for fchown... (cached) yes
checking for fchmod... (cached) yes
checking for fsync... (cached) yes
checking for getcwd... (cached) yes
checking for getpseudotty... (cached) no
checking for getpwent... (cached) yes
checking for getpwnam... (cached) yes
checking for getpwuid... (cached) yes
checking for getrlimit... (cached) yes
checking for gettimeofday... (cached) yes
checking for localtime_r... (cached) yes
checking for lstat... (cached) yes
checking for memset... (cached) yes
checking for mkdtemp... (cached) yes
checking for nanosleep... (cached) yes
checking for opendir... (cached) yes
checking for putenv... (cached) yes
checking for qsort... (cached) yes
checking for readlink... (cached) yes
checking for select... (cached) yes
checking for setenv... (cached) yes
checking for getpgid... (cached) yes
checking for setpgid... (cached) yes
checking for setsid... (cached) yes
checking for sigaltstack... (cached) yes
checking for sigstack... (cached) yes
checking for sigset... (cached) yes
checking for sigsetjmp... (cached) no
checking for sigaction... (cached) yes
checking for sigprocmask... (cached) yes
checking for sigvec... (cached) no
checking for strcasecmp... (cached) yes
checking for strerror... (cached) yes
checking for strftime... (cached) yes
checking for stricmp... (cached) no
checking for strncasecmp... (cached) yes
checking for strnicmp... (cached) no
checking for strpbrk... (cached) yes
checking for strptime... (cached) yes
checking for strtol... (cached) yes
checking for tgetent... (cached) yes
checking for towlower... (cached) yes
checking for towupper... (cached) yes
checking for iswupper... (cached) yes
checking for tzset... (cached) yes
checking for usleep... (cached) yes
checking for utime... (cached) yes
checking for utimes... (cached) yes
checking for mblen... (cached) yes
checking for ftruncate... (cached) yes
checking for unsetenv... (cached) yes
checking for posix_openpt... (cached) yes
checking for sys/select.h... (cached) yes
checking for sys/socket.h... (cached) yes
checking types of arguments for select... (cached) int,fd_set *,struct timeval *
checking for _LARGEFILE_SOURCE value needed for large files... (cached) no
checking for special C compiler options needed for large files... (cached) no
checking for _FILE_OFFSET_BITS value needed for large files... (cached) no
checking --enable-canberra argument... Defaulting to yes
checking for libcanberra... no; try installing libcanberra-dev
checking for st_blksize... yes
checking whether stat() ignores a trailing slash... (cached) no
checking for iconv_open()... yes
checking for nl_langinfo(CODESET)... yes
checking for strtod in -lm... (cached) yes
checking for strtod() and other floating point functions... yes
checking for isinf()... yes
checking for isnan()... yes
checking --disable-acl argument... no
checking for acl_get_file in -lposix1e... (cached) no
checking for acl_get_file in -lacl... (cached) no
checking for POSIX ACL support... no
checking for acl_get in -lsec... (cached) no
checking for Solaris ACL support... no
checking for AIX ACL support... no
checking --disable-gpm argument... no
checking for gpm... (cached) no
checking --disable-sysmouse argument... no
checking for sysmouse... (cached) no
checking for FD_CLOEXEC... yes
checking for rename... yes
checking for sysctl... not usable
checking for sysinfo... yes
checking for sysinfo.mem_unit... yes
checking for sysconf... yes
checking size of int... (cached) 4
checking size of long... (cached) 8
checking size of time_t... (cached) 8
checking size of off_t... (cached) 8
checking uint32_t is 32 bits... ok
checking whether memmove handles overlaps... (cached) yes
checking whether X_LOCALE needed... no
checking whether Xutf8SetWMProperties() can be used... yes
checking for _xpg4_setrunelocale in -lxpg4... (cached) no
checking how to create tags... ctags
checking how to run man with a section nr... man -s
checking --disable-nls argument... no
checking for msgfmt... (cached) msgfmt
checking for NLS... gettext() works
checking for bind_textdomain_codeset... (cached) yes
checking for _nl_msg_cat_cntr... yes
checking if msgfmt supports --desktop... yes
checking for dlfcn.h... (cached) yes
checking for dlopen()... no
checking for dlopen() in -ldl... yes
checking for dlsym()... yes
checking for setjmp.h... (cached) yes
checking for GCC 3 or later... yes
checking whether we need -D_FORTIFY_SOURCE=1... yes
checking whether we need to force -D_FILE_OFFSET_BITS=64... no
checking linker --as-needed support... yes
configure: creating auto/config.status
config.status: creating auto/config.mk
config.status: creating auto/config.h
config.status: auto/config.h is unchanged
</code>```

Then, I typed make and obtained this error message:

```<code>Starting make in the src directory.
If there are problems, cd to the src directory and run make there
cd src && make first
make[1] : on entre dans le répertoire « /home/user/vimtemp/src »
creating auto/pathdef.c
gcc -c -I. -Iproto -DHAVE_CONFIG_H     -g -O2 -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=1        -o objects/pathdef.o auto/pathdef.c
gcc -c -I. -I/home/user/venvs/fundreader/include/python3.6m -pthread -fPIE  -Iproto -DHAVE_CONFIG_H     -g -O2 -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=1        -o objects/if_python3.o if_python3.c
if_python3.c:69:10: fatal error: Python.h: Aucun fichier ou dossier de ce type
 #include <Python.h>
          ^~~~~~~~~~
compilation terminated.
Makefile:3266: recipe for target 'objects/if_python3.o' failed
make[1]: *** [objects/if_python3.o] Error 1
make[1] : on quitte le répertoire « /home/user/vimtemp/src »
Makefile:26: recipe for target 'first' failed
make: *** [first] Error 2
</code>```

How to make make run without errors so that I can run make install?

答:
You manually installed Python-3.6m into directory /home/user/venvs/fundreader/ but the installation was incomplete: file /home/user/venvs/fundreader/include/python-3.6m/Python.h was not created.

(Also please read this: http://lzsiga.users.sourceforge.net/aix-linking.html#Q0007 )

Body:
I am trying to compile vim with python3 support.

I cloned vim: git clone https://github.com/vim/vim and ran:

./configure --enable-python3interp

Output:

configure: loading cache auto/config.cache
checking whether make sets $(MAKE)... (cached) yes
checking for gcc... (cached) gcc
checking whether the C compiler works... yes
checking for C compiler default output file name... a.out
checking for suffix of executables...
checking whether we are cross compiling... no
checking for suffix of object files... (cached) o
checking whether we are using the GNU C compiler... (cached) yes
checking whether gcc accepts -g... (cached) yes
checking for gcc option to accept ISO C89... (cached) none needed
checking for gcc option to accept ISO C99... (cached) none needed
checking how to run the C preprocessor... (cached) gcc -E
checking for grep that handles long lines and -e... (cached) /bin/grep
checking for egrep... (cached) /bin/grep -E
checking for fgrep... (cached) /bin/grep -F
checking for library containing strerror... (cached) none required
checking for gawk... (cached) mawk
checking for strip... (cached) strip
checking for ANSI C header files... (cached) yes
checking for sys/wait.h that is POSIX.1 compatible... (cached) yes
checking for unsigned long long int... (cached) yes
checking for long long int... (cached) yes
checking if the compiler supports trailing commas... yes
checking if the compiler supports C++ comments... yes
checking --enable-fail-if-missing argument... no
checking for clang version... N/A
configure: checking for buggy tools...
checking for BeOS... no
checking for QNX... no
checking for Darwin (Mac OS X)... no
checking for AvailabilityMacros.h... (cached) no
checking --with-local-dir argument... Defaulting to /usr/local
checking --with-vim-name argument... Defaulting to vim
checking --with-ex-name argument... Defaulting to ex
checking --with-view-name argument... Defaulting to view
checking --with-global-runtime argument... no
checking --with-modified-by argument... no
checking if character set is EBCDIC... no
checking --disable-smack argument... no
checking for linux/xattr.h... (cached) yes
checking for attr/xattr.h... (cached) no
checking --disable-selinux argument... no
checking for is_selinux_enabled in -lselinux... (cached) no
checking --with-features argument... Defaulting to huge
checking --with-compiledby argument... no
checking --disable-xsmp argument... no
checking --disable-xsmp-interact argument... no
checking --enable-luainterp argument... no
checking --enable-mzschemeinterp argument... no
checking --enable-perlinterp argument... no
checking --enable-pythoninterp argument... no
checking --enable-python3interp argument... yes
checking --with-python3-command argument... no
checking Python version... (cached) 3.6
checking Python is 3.0 or better... yep
checking Python's abiflags... (cached) m
checking Python's install prefix... (cached) /home/user/venvs/fundreader
checking Python's execution prefix... (cached) /home/user/venvs/fundreader
(cached) checking Python's configuration directory... (cached) /home/user/anaconda3/lib/python3.6/config-3.6m-x86_64-linux-gnu
(cached) checking Python3's dll name... (cached) libpython3.6m.a
checking if -pthread should be used... yes
checking if compile and link flags for Python 3 are sane... yes
checking if -fPIE can be added for Python3... yes
checking --enable-tclinterp argument... no
checking --enable-rubyinterp argument... no
checking --enable-cscope argument... no
checking --disable-netbeans argument... no
checking --disable-channel argument... no
checking for socket in -lsocket... (cached) no
checking for gethostbyname in -lnsl... (cached) yes
checking whether compiling with process communication is possible... yes
checking --enable-terminal argument... defaulting to yes
checking --enable-autoservername argument... no
checking --enable-multibyte argument... yes
checking --disable-rightleft argument... no
checking --disable-arabic argument... no
checking --enable-xim argument... defaulting to auto
checking --enable-fontset argument... no
checking for xmkmf... no
checking for X... (cached) libraries , headers
checking for gethostbyname... (cached) yes
checking for connect... (cached) yes
checking for remove... (cached) yes
checking for shmat... (cached) yes
checking for IceConnectionNumber in -lICE... (cached) yes
checking if X11 header files can be found... yes
checking for _XdmcpAuthDoIt in -lXdmcp... (cached) yes
checking for IceOpenConnection in -lICE... (cached) yes
checking for XpmCreatePixmapFromData in -lXpm... (cached) yes
checking if X11 header files implicitly declare return values... no
checking size of wchar_t is 2 bytes... (cached) no
checking --enable-gui argument... yes/auto - automatic GUI support
checking whether or not to look for GTK+ 2... yes
checking whether or not to look for GNOME... no
checking whether or not to look for Motif... yes
checking whether or not to look for Athena... yes
checking whether or not to look for neXtaw... yes
checking whether or not to look for Carbon... yes
checking for pkg-config... (cached) /usr/bin/pkg-config
checking --disable-gtktest argument... gtk test enabled
no
checking for location of Motif GUI includes... <not found>
checking if Athena header files can be found... no
checking if neXtaw header files can be found... no
checking for X11/SM/SMlib.h... (cached) yes
checking for X11/xpm.h... (cached) yes
checking for X11/Sunkeysym.h... (cached) yes
checking for XIMText in X11/Xlib.h... yes
checking for /proc link to executable... /proc/self/exe
checking for CYGWIN or MSYS environment... no
checking whether toupper is broken... (cached) no
checking whether __DATE__ and __TIME__ work... yes
checking whether __attribute__((unused)) is allowed... yes
checking for elf.h... (cached) yes
checking for main in -lelf... (cached) no
checking for dirent.h that defines DIR... (cached) yes
checking for library containing opendir... (cached) none required
checking for stdint.h... (cached) yes
checking for stdlib.h... (cached) yes
checking for string.h... (cached) yes
checking for sys/select.h... (cached) yes
checking for sys/utsname.h... (cached) yes
checking for termcap.h... (cached) yes
checking for fcntl.h... (cached) yes
checking for sgtty.h... (cached) yes
checking for sys/ioctl.h... (cached) yes
checking for sys/time.h... (cached) yes
checking for sys/types.h... (cached) yes
checking for termio.h... (cached) yes
checking for iconv.h... (cached) yes
checking for inttypes.h... (cached) yes
checking for langinfo.h... (cached) yes
checking for math.h... (cached) yes
checking for unistd.h... (cached) yes
checking for stropts.h... (cached) yes
checking for errno.h... (cached) yes
checking for sys/resource.h... (cached) yes
checking for sys/systeminfo.h... (cached) no
checking for locale.h... (cached) yes
checking for sys/stream.h... (cached) no
checking for termios.h... (cached) yes
checking for libc.h... (cached) no
checking for sys/statfs.h... (cached) yes
checking for poll.h... (cached) yes
checking for sys/poll.h... (cached) yes
checking for pwd.h... (cached) yes
checking for utime.h... (cached) yes
checking for sys/param.h... (cached) yes
checking for sys/ptms.h... (cached) no
checking for libintl.h... (cached) yes
checking for libgen.h... (cached) yes
checking for util/debug.h... (cached) no
checking for util/msg18n.h... (cached) no
checking for frame.h... (cached) no
checking for sys/acl.h... (cached) no
checking for sys/access.h... (cached) no
checking for sys/sysinfo.h... (cached) yes
checking for wchar.h... (cached) yes
checking for wctype.h... (cached) yes
checking for sys/ptem.h... (cached) no
checking for sys/sysctl.h... (cached) yes
checking for pthread_np.h... no
checking for strings.h... (cached) yes
checking if strings.h can be included after string.h... yes
checking whether gcc needs -traditional... (cached) no
checking for an ANSI C-conforming const... (cached) yes
checking for working volatile... (cached) yes
checking for mode_t... (cached) yes
checking for off_t... (cached) yes
checking for pid_t... (cached) yes
checking for size_t... (cached) yes
checking for uid_t in sys/types.h... (cached) yes
checking for uint32_t... (cached) yes
checking whether time.h and sys/time.h may both be included... (cached) yes
checking for ino_t... (cached) yes
checking for dev_t... (cached) yes
checking whether byte ordering is bigendian... (cached) no
checking for inline... (cached) inline
checking for rlim_t... (cached) yes
checking for stack_t... (cached) yes
checking whether stack_t has an ss_base field... no
checking --with-tlib argument... empty: automatic terminal library selection
checking for tgetent in -ltinfo... (cached) yes
checking whether we talk terminfo... (cached) yes
checking what tgetent() returns for an unknown terminal... (cached) zero
checking whether termcap.h contains ospeed... yes
checking whether termcap.h contains UP, BC and PC... yes
checking whether tputs() uses outfuntype... no
checking whether sys/select.h and sys/time.h may both be included... yes
checking for /dev/ptc... no
checking for SVR4 ptys... yes
checking for ptyranges... don't know
checking default tty permissions/group... (cached) world
checking return type of signal handlers... (cached) void
checking for struct sigcontext... yes
checking getcwd implementation is broken... (cached) no
checking for fchdir... (cached) yes
checking for fchown... (cached) yes
checking for fchmod... (cached) yes
checking for fsync... (cached) yes
checking for getcwd... (cached) yes
checking for getpseudotty... (cached) no
checking for getpwent... (cached) yes
checking for getpwnam... (cached) yes
checking for getpwuid... (cached) yes
checking for getrlimit... (cached) yes
checking for gettimeofday... (cached) yes
checking for localtime_r... (cached) yes
checking for lstat... (cached) yes
checking for memset... (cached) yes
checking for mkdtemp... (cached) yes
checking for nanosleep... (cached) yes
checking for opendir... (cached) yes
checking for putenv... (cached) yes
checking for qsort... (cached) yes
checking for readlink... (cached) yes
checking for select... (cached) yes
checking for setenv... (cached) yes
checking for getpgid... (cached) yes
checking for setpgid... (cached) yes
checking for setsid... (cached) yes
checking for sigaltstack... (cached) yes
checking for sigstack... (cached) yes
checking for sigset... (cached) yes
checking for sigsetjmp... (cached) no
checking for sigaction... (cached) yes
checking for sigprocmask... (cached) yes
checking for sigvec... (cached) no
checking for strcasecmp... (cached) yes
checking for strerror... (cached) yes
checking for strftime... (cached) yes
checking for stricmp... (cached) no
checking for strncasecmp... (cached) yes
checking for strnicmp... (cached) no
checking for strpbrk... (cached) yes
checking for strptime... (cached) yes
checking for strtol... (cached) yes
checking for tgetent... (cached) yes
checking for towlower... (cached) yes
checking for towupper... (cached) yes
checking for iswupper... (cached) yes
checking for tzset... (cached) yes
checking for usleep... (cached) yes
checking for utime... (cached) yes
checking for utimes... (cached) yes
checking for mblen... (cached) yes
checking for ftruncate... (cached) yes
checking for unsetenv... (cached) yes
checking for posix_openpt... (cached) yes
checking for sys/select.h... (cached) yes
checking for sys/socket.h... (cached) yes
checking types of arguments for select... (cached) int,fd_set *,struct timeval *
checking for _LARGEFILE_SOURCE value needed for large files... (cached) no
checking for special C compiler options needed for large files... (cached) no
checking for _FILE_OFFSET_BITS value needed for large files... (cached) no
checking --enable-canberra argument... Defaulting to yes
checking for libcanberra... no; try installing libcanberra-dev
checking for st_blksize... yes
checking whether stat() ignores a trailing slash... (cached) no
checking for iconv_open()... yes
checking for nl_langinfo(CODESET)... yes
checking for strtod in -lm... (cached) yes
checking for strtod() and other floating point functions... yes
checking for isinf()... yes
checking for isnan()... yes
checking --disable-acl argument... no
checking for acl_get_file in -lposix1e... (cached) no
checking for acl_get_file in -lacl... (cached) no
checking for POSIX ACL support... no
checking for acl_get in -lsec... (cached) no
checking for Solaris ACL support... no
checking for AIX ACL support... no
checking --disable-gpm argument... no
checking for gpm... (cached) no
checking --disable-sysmouse argument... no
checking for sysmouse... (cached) no
checking for FD_CLOEXEC... yes
checking for rename... yes
checking for sysctl... not usable
checking for sysinfo... yes
checking for sysinfo.mem_unit... yes
checking for sysconf... yes
checking size of int... (cached) 4
checking size of long... (cached) 8
checking size of time_t... (cached) 8
checking size of off_t... (cached) 8
checking uint32_t is 32 bits... ok
checking whether memmove handles overlaps... (cached) yes
checking whether X_LOCALE needed... no
checking whether Xutf8SetWMProperties() can be used... yes
checking for _xpg4_setrunelocale in -lxpg4... (cached) no
checking how to create tags... ctags
checking how to run man with a section nr... man -s
checking --disable-nls argument... no
checking for msgfmt... (cached) msgfmt
checking for NLS... gettext() works
checking for bind_textdomain_codeset... (cached) yes
checking for _nl_msg_cat_cntr... yes
checking if msgfmt supports --desktop... yes
checking for dlfcn.h... (cached) yes
checking for dlopen()... no
checking for dlopen() in -ldl... yes
checking for dlsym()... yes
checking for setjmp.h... (cached) yes
checking for GCC 3 or later... yes
checking whether we need -D_FORTIFY_SOURCE=1... yes
checking whether we need to force -D_FILE_OFFSET_BITS=64... no
checking linker --as-needed support... yes
configure: creating auto/config.status
config.status: creating auto/config.mk
config.status: creating auto/config.h
config.status: auto/config.h is unchanged

Then, I typed make and obtained this error message:

Starting make in the src directory.
If there are problems, cd to the src directory and run make there
cd src && make first
make[1] : on entre dans le répertoire « /home/user/vimtemp/src »
creating auto/pathdef.c
gcc -c -I. -Iproto -DHAVE_CONFIG_H     -g -O2 -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=1        -o objects/pathdef.o auto/pathdef.c
gcc -c -I. -I/home/user/venvs/fundreader/include/python3.6m -pthread -fPIE  -Iproto -DHAVE_CONFIG_H     -g -O2 -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=1        -o objects/if_python3.o if_python3.c
if_python3.c:69:10: fatal error: Python.h: Aucun fichier ou dossier de ce type
 #include <Python.h>
          ^~~~~~~~~~
compilation terminated.
Makefile:3266: recipe for target 'objects/if_python3.o' failed
make[1]: *** [objects/if_python3.o] Error 1
make[1] : on quitte le répertoire « /home/user/vimtemp/src »
Makefile:26: recipe for target 'first' failed
make: *** [first] Error 2

How to make make run without errors so that I can run make install?


问:
MySQL Sub Queries With WHERE condition outside
Is this possible in sub queries?

```<code>SELECT (SELECT count(*) FROM employee WHERE age is not null) as NAME,
       (SELECT count(*) FROM employee WHERE age is null) as NamewithoutAge FROM table WHERE name in('List of name')
</code>```

instead of

```<code>SELECT (SELECT count(*) FROM employee WHERE age is not null and name in('List of name')) as NAME,
       (SELECT count(*) FROM employee WHERE age is null and name in('List of name')) as NamewithoutAge
</code>```

答:
COUNT(field) counts NOT NULL values only. So

SELECT
  COUNT(age) AS name_count,
  (COUNT(*) - COUNT(age)) AS name_without_age_count
FROM employee
WHERE name in('List of name')
```

Body:
Is this possible in sub queries?

SELECT (SELECT count(*) FROM employee WHERE age is not null) as NAME,
       (SELECT count(*) FROM employee WHERE age is null) as NamewithoutAge FROM table WHERE name in('List of name')

instead of

SELECT (SELECT count(*) FROM employee WHERE age is not null and name in('List of name')) as NAME,
       (SELECT count(*) FROM employee WHERE age is null and name in('List of name')) as NamewithoutAge


问:
Using a NamedQuery with a composite class
I have the following class defined in my mapping XML file:

```<code><class name="com.data.StateRefData" table="STATE_REF">
   <composite-id name="primaryKey" class="com.data.StateRefPkData">
       <key-property name="countryCode">
           <column name="COUNTRY_CODE"  />
        </key-property>

        <key-property name="state">
            <column name="STATE"  />
        </key-property>
    </composite-id>

   <property name="dialingCode" column="DIALING_CODE"></property>
   <property name="isActive" column="IS_ACTIVE"></property>
   <property name="localeCode" column="LOCALE_CODE"></property>
   <property name="stName" column="ST_NAME"></property>
</class>
</code>```

I am trying to define a NameQuery for this class. What I tried was:

```<code><query name="findState">
    <![CDATA[ from
      com.data.StateRefData
        WHERE primaryKey = :primaryKey
    ]]>
 </query>
</code>```

The Java code that I use to call this is:

```<code>Query stateQuery = null;
List<StateRefData> stateList = null;
StateRefPkData primaryKey = new StateRefPkData();
StateRefData filter = new StateRefData();

primaryKey.setCountryCode(inCountryCode);
primaryKey.setState(inStateProvince);
filter.setPrimaryKey(primaryKey);

stateQuery = session.getNamedQuery("findState");
stateQuery.setProperties(filter);
</code>```

However, I get these errors right at the "stateQuery.list()" part:

```<code>[ERROR JDBCExceptionReporter:72] Line 1: Incorrect syntax near ','.
org.hibernate.exception.SQLGrammarException: could not execute query

        at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:59)
   at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
   at org.hibernate.loader.Loader.doList(Loader.java:1596)
   at org.hibernate.loader.Loader.list(Loader.java:1577)
   at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:395)
   at org.hibernate.hql.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:271)
   at org.hibernate.impl.SessionImpl.list(SessionImpl.java:844)
   at org.hibernate.impl.QueryImpl.list(QueryImpl.java:74)
</code>```

Any idea on how to use a NamedQuery with a composite?

Note: I have also tried doing:

```<code>stateQuery.setParameter("primaryKey", primaryKey);
</code>```

and it still has the error.

New (edited):
Here is the HQL and SQL that happens when I execute the code:

```<code>[DEBUG AST:223] --- HQL AST ---
 \-[QUERY] 'query'
    +-[SELECT_FROM] 'SELECT_FROM'
    |  \-[FROM] 'from'
    |     \-[RANGE] 'RANGE'
    |        +-[DOT] '.'
    |        |  +-[DOT] '.'
    |        |  |  +-[DOT] '.'
    |        |  |  |  +-[DOT] '.'
    |        |  |  |  |  +-[IDENT] 'com'
    |        |  |  \-[IDENT] 'data'
    |        |  \-[IDENT] 'StateRefData'
    |        \-[ALIAS] 'd'
    \-[WHERE] 'WHERE'
       \-[EQ] '='
          +-[DOT] '.'
          |  +-[IDENT] 'd'
          |  \-[IDENT] 'primaryKey'
          \-[COLON] ':'
             \-[IDENT] 'primaryKey'

[DEBUG AST:193] --- SQL AST ---
 \-[SELECT] QueryNode: 'SELECT'  querySpaces (STATE_REF)
    +-[SELECT_CLAUSE] SelectClause: '{derived select clause}'
    |  +-[SELECT_EXPR] SelectExpressionImpl: 'statere0_.COUNTRY_CODE as COUNTRY1_, statere0_.STATE as STATE' {FromElement{explicit,not a collection join,not a fetch join,fetch non-lazy properties,classAlias=d,role=null,tableName=STATE_REF,tableAlias=statere0_,colums={,className=com.data.StateRefData}}}
    |  \-[SQL_TOKEN] SqlFragment: 'statere0_.DIALING_CODE as DIALING3_60_, statere0_.IS_ACTIVE as IS4_60_, statere0_.LOCALE_CODE as LOCALE5_60_, statere0_.ST_NAME as ST6_60_'
    +-[FROM] FromClause: 'from' FromClause{level=1, fromElementCounter=1, fromElements=1, fromElementByClassAlias=[d], fromElementByTableAlias=[statere0_], fromElementsByPath=[], collectionJoinFromElementsByPath=[], impliedElements=[]}
    |  \-[FROM_FRAGMENT] FromElement: 'STATE_REF statere0_' FromElement{explicit,not a collection join,not a fetch join,fetch non-lazy properties,classAlias=d,role=null,tableName=STATE_REF,tableAlias=statere0_,colums={,className=com.data.StateRefData}}
    \-[WHERE] SqlNode: 'WHERE'
       \-[EQ] SqlNode: '='
          +-[DOT] DotNode: '(statere0_.COUNTRY_CODE, statere0_.STATE)' {propertyName=primaryKey,dereferenceType=2,propertyPath=primaryKey,path=d.primaryKey,tableAlias=statere0_,className=com.data.StateRefData,classAlias=d}
          |  +-[ALIAS_REF] IdentNode: '(statere0_.COUNTRY_CODE, statere0_.STATE)' {alias=d, className=com.data.StateRefData, tableAlias=statere0_}
          |  \-[IDENT] IdentNode: 'primaryKey' {originalText=primaryKey}
          \-[NAMED_PARAM] SqlNode: '?'
</code>```

答: Is there a chance that inCountryCode or inStateProvince is empty or null?</p>

OwnerDisplayName: Ascalonian

ContentLicense: CC BY-SA 2.5

Body:
I have the following class defined in my mapping XML file:

<class name="com.data.StateRefData" table="STATE_REF">
   <composite-id name="primaryKey" class="com.data.StateRefPkData">
       <key-property name="countryCode">
           <column name="COUNTRY_CODE"  />
        </key-property>

        <key-property name="state">
            <column name="STATE"  />
        </key-property>
    </composite-id>

   <property name="dialingCode" column="DIALING_CODE"></property>
   <property name="isActive" column="IS_ACTIVE"></property>
   <property name="localeCode" column="LOCALE_CODE"></property>
   <property name="stName" column="ST_NAME"></property>
</class>

I am trying to define a NameQuery for this class. What I tried was:

<query name="findState">
    <![CDATA[ from
      com.data.StateRefData
        WHERE primaryKey = :primaryKey
    ]]>
 </query>

The Java code that I use to call this is:

Query stateQuery = null;
List<StateRefData> stateList = null;
StateRefPkData primaryKey = new StateRefPkData();
StateRefData filter = new StateRefData();

primaryKey.setCountryCode(inCountryCode);
primaryKey.setState(inStateProvince);
filter.setPrimaryKey(primaryKey);

stateQuery = session.getNamedQuery("findState");
stateQuery.setProperties(filter);

However, I get these errors right at the "stateQuery.list()" part:

[ERROR JDBCExceptionReporter:72] Line 1: Incorrect syntax near ','.
org.hibernate.exception.SQLGrammarException: could not execute query

        at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:59)
   at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
   at org.hibernate.loader.Loader.doList(Loader.java:1596)
   at org.hibernate.loader.Loader.list(Loader.java:1577)
   at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:395)
   at org.hibernate.hql.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:271)
   at org.hibernate.impl.SessionImpl.list(SessionImpl.java:844)
   at org.hibernate.impl.QueryImpl.list(QueryImpl.java:74)

Any idea on how to use a NamedQuery with a composite?

Note: I have also tried doing:

stateQuery.setParameter("primaryKey", primaryKey);

and it still has the error.

New (edited):
Here is the HQL and SQL that happens when I execute the code:

[DEBUG AST:223] --- HQL AST ---
 \-[QUERY] 'query'
    +-[SELECT_FROM] 'SELECT_FROM'
    |  \-[FROM] 'from'
    |     \-[RANGE] 'RANGE'
    |        +-[DOT] '.'
    |        |  +-[DOT] '.'
    |        |  |  +-[DOT] '.'
    |        |  |  |  +-[DOT] '.'
    |        |  |  |  |  +-[IDENT] 'com'
    |        |  |  \-[IDENT] 'data'
    |        |  \-[IDENT] 'StateRefData'
    |        \-[ALIAS] 'd'
    \-[WHERE] 'WHERE'
       \-[EQ] '='
          +-[DOT] '.'
          |  +-[IDENT] 'd'
          |  \-[IDENT] 'primaryKey'
          \-[COLON] ':'
             \-[IDENT] 'primaryKey'

[DEBUG AST:193] --- SQL AST ---
 \-[SELECT] QueryNode: 'SELECT'  querySpaces (STATE_REF)
    +-[SELECT_CLAUSE] SelectClause: '{derived select clause}'
    |  +-[SELECT_EXPR] SelectExpressionImpl: 'statere0_.COUNTRY_CODE as COUNTRY1_, statere0_.STATE as STATE' {FromElement{explicit,not a collection join,not a fetch join,fetch non-lazy properties,classAlias=d,role=null,tableName=STATE_REF,tableAlias=statere0_,colums={,className=com.data.StateRefData}}}
    |  \-[SQL_TOKEN] SqlFragment: 'statere0_.DIALING_CODE as DIALING3_60_, statere0_.IS_ACTIVE as IS4_60_, statere0_.LOCALE_CODE as LOCALE5_60_, statere0_.ST_NAME as ST6_60_'
    +-[FROM] FromClause: 'from' FromClause{level=1, fromElementCounter=1, fromElements=1, fromElementByClassAlias=[d], fromElementByTableAlias=[statere0_], fromElementsByPath=[], collectionJoinFromElementsByPath=[], impliedElements=[]}
    |  \-[FROM_FRAGMENT] FromElement: 'STATE_REF statere0_' FromElement{explicit,not a collection join,not a fetch join,fetch non-lazy properties,classAlias=d,role=null,tableName=STATE_REF,tableAlias=statere0_,colums={,className=com.data.StateRefData}}
    \-[WHERE] SqlNode: 'WHERE'
       \-[EQ] SqlNode: '='
          +-[DOT] DotNode: '(statere0_.COUNTRY_CODE, statere0_.STATE)' {propertyName=primaryKey,dereferenceType=2,propertyPath=primaryKey,path=d.primaryKey,tableAlias=statere0_,className=com.data.StateRefData,classAlias=d}
          |  +-[ALIAS_REF] IdentNode: '(statere0_.COUNTRY_CODE, statere0_.STATE)' {alias=d, className=com.data.StateRefData, tableAlias=statere0_}
          |  \-[IDENT] IdentNode: 'primaryKey' {originalText=primaryKey}
          \-[NAMED_PARAM] SqlNode: '?'

LastEditorDisplayName: mmyers

OwnerDisplayName: cherouvim


问:
Can a telephony.Phone object be instantiated through the sdk?
I am trying to get a phone object so that I can call and conference two numbers from within my application.

I have tried using the static PhoneFactory.makeDefaultPhones((Context)this) but have not had any luck.

```<code>String phoneFactoryName = "com.android.internal.telephony.PhoneFactory";
String phoneName = "com.android.internal.telephony.Phone";
Class phoneFactoryClass = Class.forName(phoneFactoryName);
Class phoneClass = Class.forName(phoneName);
Method getDefaultPhone = phoneFactoryClass.getMethod("getDefaultPhone");
Object phoneObject = getDefaultPhone.invoke(null);
</code>```

Error - Caused by java.lang.RuntimeException: PhoneFactory.getDefaultPhone must be called from Looper thread

答:
Yes it can be instantiated. But you have to overcome a couple of hurdles:

In your AndroidManifest.xml set

android:sharedUserId="android.uid.phone"

within the <manifest> tag. This is required to prevent a SecurityException from being thrown when protected Intents are sent by the methods you may invoke (like android.intent.action.SIM_STATE_CHANGED).

Set

android:process="com.android.phone"

in your <application> tag. This is required to allow the invocation of getDefaultPhone() / makeDefaultPhone().

To do all this your app must be signed with the system signature key.

Body:
I am trying to get a phone object so that I can call and conference two numbers from within my application.

I have tried using the static PhoneFactory.makeDefaultPhones((Context)this) but have not had any luck.

String phoneFactoryName = "com.android.internal.telephony.PhoneFactory";
String phoneName = "com.android.internal.telephony.Phone";
Class phoneFactoryClass = Class.forName(phoneFactoryName);
Class phoneClass = Class.forName(phoneName);
Method getDefaultPhone = phoneFactoryClass.getMethod("getDefaultPhone");
Object phoneObject = getDefaultPhone.invoke(null);

Error - Caused by java.lang.RuntimeException: PhoneFactory.getDefaultPhone must be called from Looper thread