qid
int64 469
74.7M
| question
stringlengths 36
37.8k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 5
31.5k
| response_k
stringlengths 10
31.6k
|
---|---|---|---|---|---|
54,450,504 | I was looking for this information for a while, but as additional packages and python versions can be installed through `homebrew` and `pip` I have the feeling that my environment is messed up. Furthermore a long time ago, I had installed some stuff with `sudo pip install` and as well `sudo python ~/get-pip.py`.
Is there a trivial way of removing all danging dependencies and have python as it was when I first got the machine, or at least with only the packages that are delivered with the Mac distro? | 2019/01/30 | [
"https://Stackoverflow.com/questions/54450504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1767754/"
] | Instead of telling him WHY he should not do something, how about telling him HOW he could do it? Maybe his example is not an appropriate need for it, but there's other situations where being able to create a macro would be nice.
For example... I have an HTML page that I'm working on that deals with unit conversions and quite often, I'm having to type things like "cm/in" as "cm/in" or for volumes "cu-cm/cu-in" as "cm3/in3". It would be really nice from a typing and readability standpoint if I could create macros that were just typed as "%%cm-per-in%%, %%cc-per-cu-in%% or something like that.
So, the line in the 'sed' file might look like this:
```
s/%%cc-per-cu-in%%/<sup>cm<sup>3<\/sup><\/sup>\/<sub>in<sup>3<\/sup><\/sub>/g
```
Since the "/" is a field separator for the substitute command, you need to explicitly quote it with the backslash character ("\") within the replacement portion of the substitute command.
The way that I have handled things like this in the past was to either write my own preprocessor to make the changes or if the "sed" utility was available, I would use it. So for this sort of thing, I would basically have a "pre-HTML" file that I edited and after running it through "sed" or the preprocessor, it would generate an HTML file that I could copy to the web server.
Now, you *could* create a javascript function that would do the text substitution for you, but in my opinion, it is not as nice looking as an actual preprocessor macro substitution. For example, to do what I was doing in the sed script, I would need to create a function that would take as a parameter the short form "nickname" for the longer HTML that would be generated. For example:
```
function S( x )
{
if (x == "cc-per-cu-in") {
document.write("<sup>cm<sup>3</sup></sup>/<sub>in<sup>3</sup></sub>");
} else if (x == "cm-per-in") {
document.write("<sup>cm</sup>/<sub>in</sub>");
} else {
document.write("<B>***MACRO-ERROR***</B>");
}
}
```
And then use it like this:
```
This is a test of cc-per-cu-in <SCRIPT>S("cc-per-cu-in");</SCRIPT> and
cm-per-in <SCRIPT>S("cm-per-in");</SCRIPT> as an alternative to sed.
This is a test of an error <SCRIPT>S("cc-per-in");</SCRIPT> for a
missing macro substitution.
```
This generates the following:
This is a test of cc-per-cu-in cm3/in3 and cm-per-in cm/in as an alternative to sed. This is a test of an error *****MACRO-ERROR***** for a missing macro substitution.
Yeah, it works, but it is not as readable as if you used a 'sed' substitution.
So, decide for yourself... Which is more readable...
This...
```
This is a test of cc-per-cu-in <SCRIPT>S("cc-per-cu-in");</SCRIPT> and
cm-per-in <SCRIPT>S("cm-per-in");</SCRIPT> as an alternative to sed.
```
Or this...
```
This is a test of cc-per-cu-in %%cc-per-cu-in%% and
cm-per-in %%cm-per-in% as an alternative to sed.
```
Personally, I think the second example is more readable and worth the extra trouble to have pre-HTML files that get run through sed to generate the actual HTML files... But, as the saying goes, "Your mileage may vary"...
EDITED: One more thing that I forgot about in the initial post that I find useful when using a pre-processor for the HTML files -- Timestamping the file... Often I'll have a small timestamp placed on a page that says the last time it was modified. Instead of manually editing the timestamp each time, I can have a macro (such as "%%DATE%%", "%%TIME%%", "%%DATETIME%%") that gets converted to my preferred date/time format and put in the file.
Since my background is in 'C' and UNIX, if I can't find a way to do something in HTML, I'll often just use one of the command line tools under UNIX or write a small 'C' program to do it. My HTML editing is always in 'vi' (or 'vim' on the PC) and I find that I am often creating tables for alignment of various portions of the HTML page. I got tired of typing all the TABLE, TR, and TD tags, so I created a simple 'C' program called 'table' that I can execute via the '!}' command in 'vi', similar to how you execute the 'fmt' command in 'vi'. It takes as parameters the number of rows & columns to create, whether the column cells are to be split across two lines, how many spaces to indent the tags, and the column widths and generates an appropriately indented TABLE tag structure. Just a simple utility, but saves on the typing.
Instead of typing this:
```
<TABLE>
<TR>
<TD width=200>
</TD>
<TD width=300>
</TD>
</TR>
<TR>
<TD>
</TD>
<TD>
</TD>
</TR>
<TR>
<TD>
</TD>
<TD>
</TD>
</TR>
</TABLE>
```
I can type this:
```
!}table -r 3 -c 2 -split -w 200 300
```
Now, with respect to the portion of the original question about being able to create a macro to do HTML links, that is also possible using 'sed' as a pre-processor for the HTML files. Let's say that you wanted to change:
```
%%lnk(www.stackoverflow.com)
```
to:
```
<a href="www.stackoverflow.com">www.stackoverflow.com</a>
```
you could create this line in the sed script file:
```
s/%%lnk(\(.*\))/<a href="\1">\1<\/a>/g
```
'sed' uses regular expressions and they are not what you might call 'pretty', but they are powerful if you know what you are doing.
One slight problem with this example is that it requires the macro to be on a single line (i.e. you cannot split the macro across lines) and if you call the macro multiple times in a single line, you get a result that you might not be expecting. Instead of doing the macro substitution multiple times, it assumes the argument to the macro starts with the first '(' of the first macro invocation and ends with the last ')' of the last macro invocation. I'm not a sed regular expression expert, so I haven't figured out how to fix this yet. For the multiple line portion though, a possible fix would be to replace all the LF characters in the file with some other special character that would not normally be used, run sed on that result, and then convert the special characters back to LF characters. Of course, the problem there is that the entire file would be a single line and if you are invoking the macro, it is going to have the results that I described above. I suspect awk would not have that problem, but I have never had a need to learn awk.
Upon further reflection, I think there might be an easier solution to both the multi-line and multiple invocation of a macro on a single line -- the 'm4' macro preprocessor that comes with the 'C' compiler (e.g. gcc). I haven't tested it much to see what the downside might be, but it seems to work well enough for the tests that I have performed. You would define a macro as such in your pre-HTML file:
```
define(`LNK', `<a href="$1">$1</a>')
```
And yeah, it does use the backwards single quote character to start the text string and the normal single quote character to end the text string.
The only problem that I've found so far is that is that for the macro names, it only allows the characters 'A'-'Z', 'a'-'z', '0'-'9', and '*' (underscore). Since I prefer to type '-' instead of '*', that is a definite disadvantage to me. | Technically inline JavaScript with a `<script>` tag could do what you are asking. You could even look into the many templating solutions available via JavaScript libraries.
That would not actually provide any benefit, though. JavaScript changes what is ultimately displayed, not the file itself. Since your use case does not change the display it wouldn't actually be useful.
It would be more efficient to consider why ` ` is appearing in the first place and fix that. |
54,450,504 | I was looking for this information for a while, but as additional packages and python versions can be installed through `homebrew` and `pip` I have the feeling that my environment is messed up. Furthermore a long time ago, I had installed some stuff with `sudo pip install` and as well `sudo python ~/get-pip.py`.
Is there a trivial way of removing all danging dependencies and have python as it was when I first got the machine, or at least with only the packages that are delivered with the Mac distro? | 2019/01/30 | [
"https://Stackoverflow.com/questions/54450504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1767754/"
] | Technically inline JavaScript with a `<script>` tag could do what you are asking. You could even look into the many templating solutions available via JavaScript libraries.
That would not actually provide any benefit, though. JavaScript changes what is ultimately displayed, not the file itself. Since your use case does not change the display it wouldn't actually be useful.
It would be more efficient to consider why ` ` is appearing in the first place and fix that. | Just an observation from a novice. If everyone did as purists suggest (i.e.-the right way), then the web would still be using the same coding conventions it was using 30 years ago. People do things, innovate, and create new ways, then new standards, and deprecate others all the time. Just because someone says "spaces are only for separating words...and nothing else" is silly. For many, many years, when people typed letters, they used one space between words, and two spaces between end punctuation and the next sentence. That changed...yeah, things change. There is absolutely nothing wrong with using spaces and non-breaking spaces in ways which assist layout. It is neither useful nor elegant for someone to use a long span with style over and over and over, rather than simple spaces. You can think it is, and your club of do it right folks might even agree. But...although "right", they are also being rather silly about it. Question: Will a page with 3 non-breaking spaces validate? Interesting. |
54,450,504 | I was looking for this information for a while, but as additional packages and python versions can be installed through `homebrew` and `pip` I have the feeling that my environment is messed up. Furthermore a long time ago, I had installed some stuff with `sudo pip install` and as well `sudo python ~/get-pip.py`.
Is there a trivial way of removing all danging dependencies and have python as it was when I first got the machine, or at least with only the packages that are delivered with the Mac distro? | 2019/01/30 | [
"https://Stackoverflow.com/questions/54450504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1767754/"
] | Instead of telling him WHY he should not do something, how about telling him HOW he could do it? Maybe his example is not an appropriate need for it, but there's other situations where being able to create a macro would be nice.
For example... I have an HTML page that I'm working on that deals with unit conversions and quite often, I'm having to type things like "cm/in" as "cm/in" or for volumes "cu-cm/cu-in" as "cm3/in3". It would be really nice from a typing and readability standpoint if I could create macros that were just typed as "%%cm-per-in%%, %%cc-per-cu-in%% or something like that.
So, the line in the 'sed' file might look like this:
```
s/%%cc-per-cu-in%%/<sup>cm<sup>3<\/sup><\/sup>\/<sub>in<sup>3<\/sup><\/sub>/g
```
Since the "/" is a field separator for the substitute command, you need to explicitly quote it with the backslash character ("\") within the replacement portion of the substitute command.
The way that I have handled things like this in the past was to either write my own preprocessor to make the changes or if the "sed" utility was available, I would use it. So for this sort of thing, I would basically have a "pre-HTML" file that I edited and after running it through "sed" or the preprocessor, it would generate an HTML file that I could copy to the web server.
Now, you *could* create a javascript function that would do the text substitution for you, but in my opinion, it is not as nice looking as an actual preprocessor macro substitution. For example, to do what I was doing in the sed script, I would need to create a function that would take as a parameter the short form "nickname" for the longer HTML that would be generated. For example:
```
function S( x )
{
if (x == "cc-per-cu-in") {
document.write("<sup>cm<sup>3</sup></sup>/<sub>in<sup>3</sup></sub>");
} else if (x == "cm-per-in") {
document.write("<sup>cm</sup>/<sub>in</sub>");
} else {
document.write("<B>***MACRO-ERROR***</B>");
}
}
```
And then use it like this:
```
This is a test of cc-per-cu-in <SCRIPT>S("cc-per-cu-in");</SCRIPT> and
cm-per-in <SCRIPT>S("cm-per-in");</SCRIPT> as an alternative to sed.
This is a test of an error <SCRIPT>S("cc-per-in");</SCRIPT> for a
missing macro substitution.
```
This generates the following:
This is a test of cc-per-cu-in cm3/in3 and cm-per-in cm/in as an alternative to sed. This is a test of an error *****MACRO-ERROR***** for a missing macro substitution.
Yeah, it works, but it is not as readable as if you used a 'sed' substitution.
So, decide for yourself... Which is more readable...
This...
```
This is a test of cc-per-cu-in <SCRIPT>S("cc-per-cu-in");</SCRIPT> and
cm-per-in <SCRIPT>S("cm-per-in");</SCRIPT> as an alternative to sed.
```
Or this...
```
This is a test of cc-per-cu-in %%cc-per-cu-in%% and
cm-per-in %%cm-per-in% as an alternative to sed.
```
Personally, I think the second example is more readable and worth the extra trouble to have pre-HTML files that get run through sed to generate the actual HTML files... But, as the saying goes, "Your mileage may vary"...
EDITED: One more thing that I forgot about in the initial post that I find useful when using a pre-processor for the HTML files -- Timestamping the file... Often I'll have a small timestamp placed on a page that says the last time it was modified. Instead of manually editing the timestamp each time, I can have a macro (such as "%%DATE%%", "%%TIME%%", "%%DATETIME%%") that gets converted to my preferred date/time format and put in the file.
Since my background is in 'C' and UNIX, if I can't find a way to do something in HTML, I'll often just use one of the command line tools under UNIX or write a small 'C' program to do it. My HTML editing is always in 'vi' (or 'vim' on the PC) and I find that I am often creating tables for alignment of various portions of the HTML page. I got tired of typing all the TABLE, TR, and TD tags, so I created a simple 'C' program called 'table' that I can execute via the '!}' command in 'vi', similar to how you execute the 'fmt' command in 'vi'. It takes as parameters the number of rows & columns to create, whether the column cells are to be split across two lines, how many spaces to indent the tags, and the column widths and generates an appropriately indented TABLE tag structure. Just a simple utility, but saves on the typing.
Instead of typing this:
```
<TABLE>
<TR>
<TD width=200>
</TD>
<TD width=300>
</TD>
</TR>
<TR>
<TD>
</TD>
<TD>
</TD>
</TR>
<TR>
<TD>
</TD>
<TD>
</TD>
</TR>
</TABLE>
```
I can type this:
```
!}table -r 3 -c 2 -split -w 200 300
```
Now, with respect to the portion of the original question about being able to create a macro to do HTML links, that is also possible using 'sed' as a pre-processor for the HTML files. Let's say that you wanted to change:
```
%%lnk(www.stackoverflow.com)
```
to:
```
<a href="www.stackoverflow.com">www.stackoverflow.com</a>
```
you could create this line in the sed script file:
```
s/%%lnk(\(.*\))/<a href="\1">\1<\/a>/g
```
'sed' uses regular expressions and they are not what you might call 'pretty', but they are powerful if you know what you are doing.
One slight problem with this example is that it requires the macro to be on a single line (i.e. you cannot split the macro across lines) and if you call the macro multiple times in a single line, you get a result that you might not be expecting. Instead of doing the macro substitution multiple times, it assumes the argument to the macro starts with the first '(' of the first macro invocation and ends with the last ')' of the last macro invocation. I'm not a sed regular expression expert, so I haven't figured out how to fix this yet. For the multiple line portion though, a possible fix would be to replace all the LF characters in the file with some other special character that would not normally be used, run sed on that result, and then convert the special characters back to LF characters. Of course, the problem there is that the entire file would be a single line and if you are invoking the macro, it is going to have the results that I described above. I suspect awk would not have that problem, but I have never had a need to learn awk.
Upon further reflection, I think there might be an easier solution to both the multi-line and multiple invocation of a macro on a single line -- the 'm4' macro preprocessor that comes with the 'C' compiler (e.g. gcc). I haven't tested it much to see what the downside might be, but it seems to work well enough for the tests that I have performed. You would define a macro as such in your pre-HTML file:
```
define(`LNK', `<a href="$1">$1</a>')
```
And yeah, it does use the backwards single quote character to start the text string and the normal single quote character to end the text string.
The only problem that I've found so far is that is that for the macro names, it only allows the characters 'A'-'Z', 'a'-'z', '0'-'9', and '*' (underscore). Since I prefer to type '-' instead of '*', that is a definite disadvantage to me. | This …
>
> My html file contains in many places the code ` `
>
>
>
… is actually what is wrong in your file!
` ` is not meant to use for layout purpose, you should fix that and use CSS instead to layout it correctly.
` ` is meant to stop breaking words at the end of a line that are seperated by a space. For example numbers and their unit: `5 liters` can end up with `5` at the end of the line and `liters` in the next line ([Example](http://jsfiddle.net/fL564sa0/)).
To keep that together you would use `5 liters`. That's what you use ` ` for and nothing else, especially **not** for layout purpose.
---
To still answer your question:
HTML is a *markup language* not a *programming language*. That means it is descriptive/static and not functional/dynamic. If you try to generate HTML dynamically you would need to use something like PHP or JavaScript. |
54,450,504 | I was looking for this information for a while, but as additional packages and python versions can be installed through `homebrew` and `pip` I have the feeling that my environment is messed up. Furthermore a long time ago, I had installed some stuff with `sudo pip install` and as well `sudo python ~/get-pip.py`.
Is there a trivial way of removing all danging dependencies and have python as it was when I first got the machine, or at least with only the packages that are delivered with the Mac distro? | 2019/01/30 | [
"https://Stackoverflow.com/questions/54450504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1767754/"
] | Instead of telling him WHY he should not do something, how about telling him HOW he could do it? Maybe his example is not an appropriate need for it, but there's other situations where being able to create a macro would be nice.
For example... I have an HTML page that I'm working on that deals with unit conversions and quite often, I'm having to type things like "cm/in" as "cm/in" or for volumes "cu-cm/cu-in" as "cm3/in3". It would be really nice from a typing and readability standpoint if I could create macros that were just typed as "%%cm-per-in%%, %%cc-per-cu-in%% or something like that.
So, the line in the 'sed' file might look like this:
```
s/%%cc-per-cu-in%%/<sup>cm<sup>3<\/sup><\/sup>\/<sub>in<sup>3<\/sup><\/sub>/g
```
Since the "/" is a field separator for the substitute command, you need to explicitly quote it with the backslash character ("\") within the replacement portion of the substitute command.
The way that I have handled things like this in the past was to either write my own preprocessor to make the changes or if the "sed" utility was available, I would use it. So for this sort of thing, I would basically have a "pre-HTML" file that I edited and after running it through "sed" or the preprocessor, it would generate an HTML file that I could copy to the web server.
Now, you *could* create a javascript function that would do the text substitution for you, but in my opinion, it is not as nice looking as an actual preprocessor macro substitution. For example, to do what I was doing in the sed script, I would need to create a function that would take as a parameter the short form "nickname" for the longer HTML that would be generated. For example:
```
function S( x )
{
if (x == "cc-per-cu-in") {
document.write("<sup>cm<sup>3</sup></sup>/<sub>in<sup>3</sup></sub>");
} else if (x == "cm-per-in") {
document.write("<sup>cm</sup>/<sub>in</sub>");
} else {
document.write("<B>***MACRO-ERROR***</B>");
}
}
```
And then use it like this:
```
This is a test of cc-per-cu-in <SCRIPT>S("cc-per-cu-in");</SCRIPT> and
cm-per-in <SCRIPT>S("cm-per-in");</SCRIPT> as an alternative to sed.
This is a test of an error <SCRIPT>S("cc-per-in");</SCRIPT> for a
missing macro substitution.
```
This generates the following:
This is a test of cc-per-cu-in cm3/in3 and cm-per-in cm/in as an alternative to sed. This is a test of an error *****MACRO-ERROR***** for a missing macro substitution.
Yeah, it works, but it is not as readable as if you used a 'sed' substitution.
So, decide for yourself... Which is more readable...
This...
```
This is a test of cc-per-cu-in <SCRIPT>S("cc-per-cu-in");</SCRIPT> and
cm-per-in <SCRIPT>S("cm-per-in");</SCRIPT> as an alternative to sed.
```
Or this...
```
This is a test of cc-per-cu-in %%cc-per-cu-in%% and
cm-per-in %%cm-per-in% as an alternative to sed.
```
Personally, I think the second example is more readable and worth the extra trouble to have pre-HTML files that get run through sed to generate the actual HTML files... But, as the saying goes, "Your mileage may vary"...
EDITED: One more thing that I forgot about in the initial post that I find useful when using a pre-processor for the HTML files -- Timestamping the file... Often I'll have a small timestamp placed on a page that says the last time it was modified. Instead of manually editing the timestamp each time, I can have a macro (such as "%%DATE%%", "%%TIME%%", "%%DATETIME%%") that gets converted to my preferred date/time format and put in the file.
Since my background is in 'C' and UNIX, if I can't find a way to do something in HTML, I'll often just use one of the command line tools under UNIX or write a small 'C' program to do it. My HTML editing is always in 'vi' (or 'vim' on the PC) and I find that I am often creating tables for alignment of various portions of the HTML page. I got tired of typing all the TABLE, TR, and TD tags, so I created a simple 'C' program called 'table' that I can execute via the '!}' command in 'vi', similar to how you execute the 'fmt' command in 'vi'. It takes as parameters the number of rows & columns to create, whether the column cells are to be split across two lines, how many spaces to indent the tags, and the column widths and generates an appropriately indented TABLE tag structure. Just a simple utility, but saves on the typing.
Instead of typing this:
```
<TABLE>
<TR>
<TD width=200>
</TD>
<TD width=300>
</TD>
</TR>
<TR>
<TD>
</TD>
<TD>
</TD>
</TR>
<TR>
<TD>
</TD>
<TD>
</TD>
</TR>
</TABLE>
```
I can type this:
```
!}table -r 3 -c 2 -split -w 200 300
```
Now, with respect to the portion of the original question about being able to create a macro to do HTML links, that is also possible using 'sed' as a pre-processor for the HTML files. Let's say that you wanted to change:
```
%%lnk(www.stackoverflow.com)
```
to:
```
<a href="www.stackoverflow.com">www.stackoverflow.com</a>
```
you could create this line in the sed script file:
```
s/%%lnk(\(.*\))/<a href="\1">\1<\/a>/g
```
'sed' uses regular expressions and they are not what you might call 'pretty', but they are powerful if you know what you are doing.
One slight problem with this example is that it requires the macro to be on a single line (i.e. you cannot split the macro across lines) and if you call the macro multiple times in a single line, you get a result that you might not be expecting. Instead of doing the macro substitution multiple times, it assumes the argument to the macro starts with the first '(' of the first macro invocation and ends with the last ')' of the last macro invocation. I'm not a sed regular expression expert, so I haven't figured out how to fix this yet. For the multiple line portion though, a possible fix would be to replace all the LF characters in the file with some other special character that would not normally be used, run sed on that result, and then convert the special characters back to LF characters. Of course, the problem there is that the entire file would be a single line and if you are invoking the macro, it is going to have the results that I described above. I suspect awk would not have that problem, but I have never had a need to learn awk.
Upon further reflection, I think there might be an easier solution to both the multi-line and multiple invocation of a macro on a single line -- the 'm4' macro preprocessor that comes with the 'C' compiler (e.g. gcc). I haven't tested it much to see what the downside might be, but it seems to work well enough for the tests that I have performed. You would define a macro as such in your pre-HTML file:
```
define(`LNK', `<a href="$1">$1</a>')
```
And yeah, it does use the backwards single quote character to start the text string and the normal single quote character to end the text string.
The only problem that I've found so far is that is that for the macro names, it only allows the characters 'A'-'Z', 'a'-'z', '0'-'9', and '*' (underscore). Since I prefer to type '-' instead of '*', that is a definite disadvantage to me. | Just an observation from a novice. If everyone did as purists suggest (i.e.-the right way), then the web would still be using the same coding conventions it was using 30 years ago. People do things, innovate, and create new ways, then new standards, and deprecate others all the time. Just because someone says "spaces are only for separating words...and nothing else" is silly. For many, many years, when people typed letters, they used one space between words, and two spaces between end punctuation and the next sentence. That changed...yeah, things change. There is absolutely nothing wrong with using spaces and non-breaking spaces in ways which assist layout. It is neither useful nor elegant for someone to use a long span with style over and over and over, rather than simple spaces. You can think it is, and your club of do it right folks might even agree. But...although "right", they are also being rather silly about it. Question: Will a page with 3 non-breaking spaces validate? Interesting. |
55,223,059 | May I know why I get the error message -
NameError: name 'X\_train\_std' is not defined
```
from sklearn.linear_model import LogisticRegression
lr = LogisticRegression(C=1000.0, random_state=0)
lr.fit(X_train_std, y_train)
plot_decision_regions(X_combined_std,
y_combined, classifier=lr,
test_idx=range(105,150))
plt.xlabel('petal length [standardized]')
plt.ylabel('petal width [standardized]')
plt.legend(loc='upper left')
plt.tight_layout()
plt.show()
lr.predict_proba(X_test_std[0,:])
weights, params = [], []
for c in np.arange(-5, 5):
lr = LogisticRegression(C=10**c, random_state=0)
lr.fit(X_train_std, y_train)
weights.append(lr.coef_[1])
params.append(10**c)
weights = np.array(weights)
plt.plot(params, weights[:, 0],
label='petal length')
plt.plot(params, weights[:, 1], linestyle='--',
label='petal width')
plt.ylabel('weight coefficient')
plt.xlabel('C')
plt.legend(loc='upper left')
plt.xscale('log')
plt.show()
```
Plesea see the link -
<https://www.freecodecamp.org/forum/t/how-to-modify-my-python-logistic-regression/265795>
<https://bytes.com/topic/python/answers/972352-why-i-get-x_train_std-not-defined#post3821849>
<https://www.researchgate.net/post/Why_I_get_the_X_train_std_is_not_defined>
. | 2019/03/18 | [
"https://Stackoverflow.com/questions/55223059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9658840/"
] | I want to share a text about Dependency Injection, It makes us to change our mind using dependency injection :
***Do not (always) use DI: Injectables versus newables***
>
> Something that was immensely useful to me when learning about DI
> frameworks was the realisation that using a DI framework does not mean
> that you have to DI to initialise all of your objects. As a rule of
> thumb: inject objects that you know of at compile time and that have
> static relations to other objects; do not inject runtime information.
>
>
> I think this is a good post on the subject. It introduces the concept
> of 'newables' and 'injectables'.
>
>
> Injectables are the classes near the root of your DI graph. Instances
> of these classes are the kind of objects that you expect your DI
> framework to provide and inject. Manager- or service-type objects are
> typical examples of injectables. Newables are objects at the fringes
> of your DI graph, or that are not even really part of your DI graph at
> all. Integer, Address etc. are examples of newables. Broadly speaking,
> newables are passive objects, and there is no point in injecting or
> mocking them. They typically contain the "data" that is in your
> application and that is only available at runtime (e.g. your address).
> Newables should not keep references to injectables or vice versa
> (something the author of the post refers to as
> "injectable/newable-separation").
>
>
> In reality, I have found that it is not always easy or possible to
> make a clear distinction between injectables and newables. Still, I
> think that they are nice concepts to use as part of your thinking
> process. Definitely think twice before adding yet another factory to
> your project!
>
>
>
**We decied to remove injection of ArrayList, LinearLayoutManager, DividerItemDecoration. We created these classes with "new" not inject** | We can inject same class with @Named
```
@Provides
@Named(CMS.Client.DELIVERY_API_CLIENT)
fun provideCMSClient(): CDAClient {
return CDAClient.builder()
.setSpace("4454")
.setToken("777")
.build()
}
@Provides
@Named(CMS.Client.SYNC_API_CLIENT)
fun provideCMSSyncClient(): CDAClient {
return CDAClient.builder()
.setSpace("1234")
.setToken("456"))
.build()
}
``` |
67,867,496 | Please forgive my ignorant question.
I'm in the infant stage of learning Python.
I want to convert Before\_text into After\_text.
```
<Before_text>
Today, I got up early, so I’m absolutely exhausted. I had breakfast: two slices \n
of cold toast and a disgusting coffee, then I left the house at 8 o’clock still \n
feeling half asleep. Honestly, London’s killing me!
```
```
<After_text>
Today, I got up early, so I’m absolutely exhausted.
I had breakfast: two slices of cold toast and a disgusting coffee, then I left the house at 8 o’clock still feeling half asleep.
Honestly, London’s killing me!
```
In fact, regardless of the code, I only need to get this result (After\_text).
I used this code:
```
import sys, fileinput
from nltk.tokenize import sent_tokenize
if __name__ == "__main__":
buf = []
for line in fileinput.input():
if line.strip() != "":
buf += [line.strip()]
sentences = sent_tokenize(" ".join(buf))
if len(sentences) > 1:
buf = sentences[1:]
sys.stdout.write(sentences[0] + '\n')
sys.stdout.write(" ".join(buf) + "\n")
```
The following error is produced:
```
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-1-ef8b2fcb97ad> in <module>()
5 buf = []
6
----> 7 for line in fileinput.input():
8 if line.strip() != "":
9 buf += [line.strip()]
-------------------------1 frames--------------------------------------------------
/usr/lib/python3.7/fileinput.py in _readline(self)
362 self._file = self._openhook(self._filename, self._mode)
363 else:
--> 364 self._file = open(self._filename, self._mode)
365 self._readline = self._file.readline # hide FileInput._readline
366 return self._readline()
FileNotFoundError: [Errno 2] No such file or directory: '-f'
```
What is causing this error? Where is a bug in this code?
And how and where do I load and save a text file?
Please teach me~ | 2021/06/07 | [
"https://Stackoverflow.com/questions/67867496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14949033/"
] | If you want to use [fileinput.input()](https://docs.python.org/3/library/fileinput.html) you should provide input filenames as arguments (`sys.argv`), simple example, if you have `cat.py` as follows
```
import fileinput
for line in fileinput.input():
print(line, end='')
```
and text files `file1.txt`, `file2.txt`, `file3.txt` in same catalog then usage is:
```
python cat.py file1.txt file2.txt file3.txt
``` | According to the docs, `fileinput.input()` is a shortcut that takes things from the command line input and tries to open them one at a time, or if nothing is specified it uses `stdin` as its input.
Please show us how you are invoking your script. I suspect you have an `-f` in there that the function is trying to open. |
60,174,534 | I know this is kind of stupid since BigQueryML now provides Kmeans with good initialization. Nonetheless I was required to train a model in tensorflow and then pass it to BigQuery for prediction.
I saved my model and everything works fine, until I try to upload it to bigquery. I get the following error:
```
TensorFlow SavedModel output output has an unsupported shape: unknown_rank: true
```
So my question is: Is it impossible to use a tensorflow trained kmeans algorithm in BigQuery?
**Edit**:
Creating the model:
```
kmeans = tf.compat.v1.estimator.experimental.KMeans(num_clusters=8, use_mini_batch = False, initial_clusters=KMEANS_PLUS_PLUS_INIT, seed=1234567890, relative_tolerance=.001)
```
Serving function:
```
def serving():
inputs = {}
# for feat in df.columns:
# inputs[feat] = tf.placeholder(shape=[None], dtype = tf.float32)
inputs = tf.placeholder(shape=[None,9], dtype = tf.float32)
return tf.estimator.export.TensorServingInputReceiver(inputs,inputs)
```
Saving the model:
```
kmeans.export_saved_model("gs://<bicket>/tf_clustering_model",
serving_input_receiver_fn=serving,
checkpoint_path='/tmp/tmpdsleqpi3/model.ckpt-19',
experimental_mode=tf.estimator.ModeKeys.PREDICT)
```
Loading to BigQuery:
```
query="""
CREATE MODEL `<project>.<dataset>.kmeans_tensorflow` OPTIONS(MODEL_TYPE='TENSORFLOW', MODEL_PATH='gs://<bucket>/tf_clustering_model/1581439348/*')
"""
job = bq.Client().query(query)
job.result()
```
**Edit2**:
The output of the saved\_model\_cli command is the following:
```
jupyter@tensorflow-20200211-182636:~$ saved_model_cli show --dir . --all
MetaGraphDef with tag-set: 'serve' contains the following SignatureDefs:
signature_def['all_distances']:
The given SavedModel SignatureDef contains the following input(s):
inputs['input'] tensor_info:
dtype: DT_FLOAT
shape: (-1, 9)
name: Placeholder:0
The given SavedModel SignatureDef contains the following output(s):
outputs['output'] tensor_info:
dtype: DT_FLOAT
shape: unknown_rank
name: add:0
Method name is: tensorflow/serving/predict
signature_def['cluster_index']:
The given SavedModel SignatureDef contains the following input(s):
inputs['input'] tensor_info:
dtype: DT_FLOAT
shape: (-1, 9)
name: Placeholder:0
The given SavedModel SignatureDef contains the following output(s):
outputs['output'] tensor_info:
dtype: DT_INT64
shape: unknown_rank
name: Squeeze_1:0
Method name is: tensorflow/serving/predict
signature_def['serving_default']:
The given SavedModel SignatureDef contains the following input(s):
inputs['input'] tensor_info:
dtype: DT_FLOAT
shape: (-1, 9)
name: Placeholder:0
The given SavedModel SignatureDef contains the following output(s):
outputs['output'] tensor_info:
dtype: DT_INT64
shape: unknown_rank
name: Squeeze_1:0
Method name is: tensorflow/serving/predict
```
All seem to have unknown rank for the output shapes. How can I set up the export of this particular estimator or is there something I can search to help me?
**Final Edit:**
This really seems to be unsupported at least as far as I can take it. My approaches varied, but at the end of the day, I saw myself without much more choice than get the code from the source of the KmeansClustering class (and the remaining code from [github](https://github.com/tensorflow/estimator/blob/master/tensorflow_estimator/python/estimator/canned/kmeans.py)) and attempt to reshape the outputs somehow. In the process, I realized the object of the results, was actually a tuple with some different Tensor class, that seemed to be used to construct the graphs alone. Interesting enough, if I took this tuple and did something like:
```
model_predictions[0][0]...[0]
```
the object was always some weird Tensor. I went up to sixty something in the three dots and eventually gave up.
From there I tried to get the class that was giving these outputs to KmeansClustering called Kmeans in clustering ops (and surrounding code in [github](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/clustering_ops.py)). Again I had no success in changing the datatype, but I did understood why the name of the output was set to Squeeze something: in here the output had a squeeze operation. I thought this could be the problem and attempted to remove the squeeze operation among other things... I failed :(
Finally I realized that this output seemed to actually come from the estimator.py file and at this point I just gave up on it.
Thank you to all who commented, I would not have come this far,
Cheers | 2020/02/11 | [
"https://Stackoverflow.com/questions/60174534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12880545/"
] | You can check the shape in the savedmodel file by using the command line program saved\_model\_cli that ships with tensorflow.
Make sure your export signature in tensorflow specifies the shape of the output tensor. | The main issue is that the output tensor shape of TF built-in KMeans estimator model has unknown rank in the saved model.
Two possible ways to solve this:
* Try training the KMeans model on BQML directly.
* Reimplement the TF KMeans estimator model to reshape the output tensor into a specific tensor shape. |
60,174,534 | I know this is kind of stupid since BigQueryML now provides Kmeans with good initialization. Nonetheless I was required to train a model in tensorflow and then pass it to BigQuery for prediction.
I saved my model and everything works fine, until I try to upload it to bigquery. I get the following error:
```
TensorFlow SavedModel output output has an unsupported shape: unknown_rank: true
```
So my question is: Is it impossible to use a tensorflow trained kmeans algorithm in BigQuery?
**Edit**:
Creating the model:
```
kmeans = tf.compat.v1.estimator.experimental.KMeans(num_clusters=8, use_mini_batch = False, initial_clusters=KMEANS_PLUS_PLUS_INIT, seed=1234567890, relative_tolerance=.001)
```
Serving function:
```
def serving():
inputs = {}
# for feat in df.columns:
# inputs[feat] = tf.placeholder(shape=[None], dtype = tf.float32)
inputs = tf.placeholder(shape=[None,9], dtype = tf.float32)
return tf.estimator.export.TensorServingInputReceiver(inputs,inputs)
```
Saving the model:
```
kmeans.export_saved_model("gs://<bicket>/tf_clustering_model",
serving_input_receiver_fn=serving,
checkpoint_path='/tmp/tmpdsleqpi3/model.ckpt-19',
experimental_mode=tf.estimator.ModeKeys.PREDICT)
```
Loading to BigQuery:
```
query="""
CREATE MODEL `<project>.<dataset>.kmeans_tensorflow` OPTIONS(MODEL_TYPE='TENSORFLOW', MODEL_PATH='gs://<bucket>/tf_clustering_model/1581439348/*')
"""
job = bq.Client().query(query)
job.result()
```
**Edit2**:
The output of the saved\_model\_cli command is the following:
```
jupyter@tensorflow-20200211-182636:~$ saved_model_cli show --dir . --all
MetaGraphDef with tag-set: 'serve' contains the following SignatureDefs:
signature_def['all_distances']:
The given SavedModel SignatureDef contains the following input(s):
inputs['input'] tensor_info:
dtype: DT_FLOAT
shape: (-1, 9)
name: Placeholder:0
The given SavedModel SignatureDef contains the following output(s):
outputs['output'] tensor_info:
dtype: DT_FLOAT
shape: unknown_rank
name: add:0
Method name is: tensorflow/serving/predict
signature_def['cluster_index']:
The given SavedModel SignatureDef contains the following input(s):
inputs['input'] tensor_info:
dtype: DT_FLOAT
shape: (-1, 9)
name: Placeholder:0
The given SavedModel SignatureDef contains the following output(s):
outputs['output'] tensor_info:
dtype: DT_INT64
shape: unknown_rank
name: Squeeze_1:0
Method name is: tensorflow/serving/predict
signature_def['serving_default']:
The given SavedModel SignatureDef contains the following input(s):
inputs['input'] tensor_info:
dtype: DT_FLOAT
shape: (-1, 9)
name: Placeholder:0
The given SavedModel SignatureDef contains the following output(s):
outputs['output'] tensor_info:
dtype: DT_INT64
shape: unknown_rank
name: Squeeze_1:0
Method name is: tensorflow/serving/predict
```
All seem to have unknown rank for the output shapes. How can I set up the export of this particular estimator or is there something I can search to help me?
**Final Edit:**
This really seems to be unsupported at least as far as I can take it. My approaches varied, but at the end of the day, I saw myself without much more choice than get the code from the source of the KmeansClustering class (and the remaining code from [github](https://github.com/tensorflow/estimator/blob/master/tensorflow_estimator/python/estimator/canned/kmeans.py)) and attempt to reshape the outputs somehow. In the process, I realized the object of the results, was actually a tuple with some different Tensor class, that seemed to be used to construct the graphs alone. Interesting enough, if I took this tuple and did something like:
```
model_predictions[0][0]...[0]
```
the object was always some weird Tensor. I went up to sixty something in the three dots and eventually gave up.
From there I tried to get the class that was giving these outputs to KmeansClustering called Kmeans in clustering ops (and surrounding code in [github](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/clustering_ops.py)). Again I had no success in changing the datatype, but I did understood why the name of the output was set to Squeeze something: in here the output had a squeeze operation. I thought this could be the problem and attempted to remove the squeeze operation among other things... I failed :(
Finally I realized that this output seemed to actually come from the estimator.py file and at this point I just gave up on it.
Thank you to all who commented, I would not have come this far,
Cheers | 2020/02/11 | [
"https://Stackoverflow.com/questions/60174534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12880545/"
] | What this error means: The TF model output named "output" is of completely undefined shape. (unknown\_rank=true means that the model isn't even specifying a number of dimensions).
For BigQuery to be able to use the TensorFlow model it has to be able to convert the model output into a BigQuery type: Either a single primitive scalar or one-dimensional array of primitives.
You may be able to add a [tf.reshape](https://www.tensorflow.org/api_docs/python/tf/reshape) operation at the end of the graph to shape this output into something that BigQuery can load.
It's not obvious what your KMeans model is outputting. I'm guessing it might be trying to output all of the clusters as one big tensor? Was this a model created using the [TensorFlow KMeans Estimator](https://www.tensorflow.org/api_docs/python/tf/compat/v1/estimator/experimental/KMeans)? | The main issue is that the output tensor shape of TF built-in KMeans estimator model has unknown rank in the saved model.
Two possible ways to solve this:
* Try training the KMeans model on BQML directly.
* Reimplement the TF KMeans estimator model to reshape the output tensor into a specific tensor shape. |
14,101,852 | I have this text file: www2.geog.ucl.ac.uk/~plewis/geogg122/python/delnorte.dat
I want to extract column 3 and 4.
I am using np.loadtxt - getting the error:
```
ValueError: invalid literal for float(): 2000-01-01
```
I am only interested in the year 2005. How can I extracted both columns? | 2012/12/31 | [
"https://Stackoverflow.com/questions/14101852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1860229/"
] | You can provide a custom conversion function for a specific column to `loadtxt`.
Since you are only interested in the year I use a `lambda`-function to split the date on `-` and to convert the first part to an `int`:
```
data = np.loadtxt('delnorte.dat',
usecols=(2,3),
converters={2: lambda s: int(s.split('-')[0])},
skiprows=27)
array([[ 2000., 190.],
[ 2000., 170.],
[ 2000., 160.],
...,
[ 2010., 185.],
[ 2010., 175.],
[ 2010., 165.]])
```
To filter then for the year `2005` you can use [logical indexing](http://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays) in numpy:
```
data_2005 = data[data[:,0] == 2005]
array([[ 2005., 210.],
[ 2005., 190.],
[ 2005., 190.],
[ 2005., 200.],
....])
``` | You should not use NumPy.loadtxt to read these values, you should rather use the [`csv` module](http://pastebin.com/JyVC4XfF) to load the file and read its data. |
14,101,852 | I have this text file: www2.geog.ucl.ac.uk/~plewis/geogg122/python/delnorte.dat
I want to extract column 3 and 4.
I am using np.loadtxt - getting the error:
```
ValueError: invalid literal for float(): 2000-01-01
```
I am only interested in the year 2005. How can I extracted both columns? | 2012/12/31 | [
"https://Stackoverflow.com/questions/14101852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1860229/"
] | You can provide a custom conversion function for a specific column to `loadtxt`.
Since you are only interested in the year I use a `lambda`-function to split the date on `-` and to convert the first part to an `int`:
```
data = np.loadtxt('delnorte.dat',
usecols=(2,3),
converters={2: lambda s: int(s.split('-')[0])},
skiprows=27)
array([[ 2000., 190.],
[ 2000., 170.],
[ 2000., 160.],
...,
[ 2010., 185.],
[ 2010., 175.],
[ 2010., 165.]])
```
To filter then for the year `2005` you can use [logical indexing](http://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays) in numpy:
```
data_2005 = data[data[:,0] == 2005]
array([[ 2005., 210.],
[ 2005., 190.],
[ 2005., 190.],
[ 2005., 200.],
....])
``` | I agree with using the csv module. I adapted this answer: [reading csv files in scipy/numpy in Python](https://stackoverflow.com/questions/2859404/reading-csv-files-in-scipy-numpy-in-python)
to apply to your question. Not sure if you desire the data in a numpy array or if a list is sufficient.
```
import numpy as np
import urllib2
import csv
txtFile = csv.reader(open("delnorte.dat.txt", "r"), delimiter='\t')
fields = 5
records = []
for row, record in enumerate(txtFile):
if (len(record) != fields or record[0]=='#'):
pass
# print "Skipping malformed record or comment: {}, contains {} fields ({} expected)".format(record,len(record),fields)
else:
if record[2][0:4] == '2005':
# assuming you want columns 3 & 4 with the first column indexed as 0
records.append([int(record[:][3]), record[:][4]] )
# if desired slice the list of lists to put a single column into a numpy array
npData = np.asarray([ npD[0] for npD in records] )
``` |
20,005,173 | Maximum, minimum and total numbers using python. For example:
```
>>>maxmin()
Enter integers, one per line, terminated by -10 :
2
1
3
7
8
-10
Output : total =5, minimum=1, maximum = 8
```
Here is my code. I need some help with this.
```
def maxmin():
minimum = None
maximum = None
while (num != -10):
num = input('Please enter a number, or -10 to stop: ' )
if num == -10:
break
if (minimum) is None or (num < minimum):
minimum = num
if (maximum) is None or (num > maximum):
maximum = num
print ("Maximum: ", maximum)
print ("Minimum: ", minimum)
``` | 2013/11/15 | [
"https://Stackoverflow.com/questions/20005173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1725323/"
] | ```
def maxmintotal():
num = 0
numbers = []
while True:
num = int(input('Please enter a number, or -10 to stop: ' ))
if num == -10:
break
numbers.append(num)
print('Numbers:', len(numbers))
print('Maximum:', max(numbers))
print('Minumum:', min(numbers))
``` | You have to define `num` before you use it in the `while`, also your nested `if` should be out of the other `if`:
```
def maxmin():
minimum = None
maximum = None
num = None
while True:
num = input('Please enter a number, or -10 to stop: ')
if num == -10:
break
if (minimum) is None or (num < minimum):
minimum = num
if (maximum) is None or (num > maximum):
maximum = num
print ("Maximum: ", maximum)
print ("Minimum: ", minimum)
maxmin()
``` |
20,005,173 | Maximum, minimum and total numbers using python. For example:
```
>>>maxmin()
Enter integers, one per line, terminated by -10 :
2
1
3
7
8
-10
Output : total =5, minimum=1, maximum = 8
```
Here is my code. I need some help with this.
```
def maxmin():
minimum = None
maximum = None
while (num != -10):
num = input('Please enter a number, or -10 to stop: ' )
if num == -10:
break
if (minimum) is None or (num < minimum):
minimum = num
if (maximum) is None or (num > maximum):
maximum = num
print ("Maximum: ", maximum)
print ("Minimum: ", minimum)
``` | 2013/11/15 | [
"https://Stackoverflow.com/questions/20005173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1725323/"
] | ```
def maxmintotal():
num = 0
numbers = []
while True:
num = int(input('Please enter a number, or -10 to stop: ' ))
if num == -10:
break
numbers.append(num)
print('Numbers:', len(numbers))
print('Maximum:', max(numbers))
print('Minumum:', min(numbers))
``` | This function should give you the output that you want:
```
def maxmin():
minimum, maximum, total = None, None, 0
while(True):
number = input('Please enter a number, or -10 to stop: ')
num = int(number)
if num == -10:
break
if total == 0:
minimum, maximum, total = num, num, 1
continue
total += 1
if num < minimum:
minimum = num
elif num > maximum:
maximum = num
print("Output : total ={}, minimum={}, maximum ={}".format(total, minimum, maximum))
``` |
20,005,173 | Maximum, minimum and total numbers using python. For example:
```
>>>maxmin()
Enter integers, one per line, terminated by -10 :
2
1
3
7
8
-10
Output : total =5, minimum=1, maximum = 8
```
Here is my code. I need some help with this.
```
def maxmin():
minimum = None
maximum = None
while (num != -10):
num = input('Please enter a number, or -10 to stop: ' )
if num == -10:
break
if (minimum) is None or (num < minimum):
minimum = num
if (maximum) is None or (num > maximum):
maximum = num
print ("Maximum: ", maximum)
print ("Minimum: ", minimum)
``` | 2013/11/15 | [
"https://Stackoverflow.com/questions/20005173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1725323/"
] | I would do this:
```
def maxmin():
minimum = None
maximum = None
while True:
num = input('Please enter a number, or -10 to stop: ')
if num == -10:
break
if (minimum) is None or (num < minimum):
minimum = num
if (maximum) is None or (num > maximum):
maximum = num
print ("Maximum: ", maximum)
print ("Minimum: ", minimum)
maxmin()
```
See, you're not really conditioning your while loop aroud num != -10 since you check for that within the loop and break out of it. So, there will never be a time when num=-10 at the beginning of the loop, make sense?
So, you just loop forever (The `while True`) until someone inputs a `-10` | You have to define `num` before you use it in the `while`, also your nested `if` should be out of the other `if`:
```
def maxmin():
minimum = None
maximum = None
num = None
while True:
num = input('Please enter a number, or -10 to stop: ')
if num == -10:
break
if (minimum) is None or (num < minimum):
minimum = num
if (maximum) is None or (num > maximum):
maximum = num
print ("Maximum: ", maximum)
print ("Minimum: ", minimum)
maxmin()
``` |
20,005,173 | Maximum, minimum and total numbers using python. For example:
```
>>>maxmin()
Enter integers, one per line, terminated by -10 :
2
1
3
7
8
-10
Output : total =5, minimum=1, maximum = 8
```
Here is my code. I need some help with this.
```
def maxmin():
minimum = None
maximum = None
while (num != -10):
num = input('Please enter a number, or -10 to stop: ' )
if num == -10:
break
if (minimum) is None or (num < minimum):
minimum = num
if (maximum) is None or (num > maximum):
maximum = num
print ("Maximum: ", maximum)
print ("Minimum: ", minimum)
``` | 2013/11/15 | [
"https://Stackoverflow.com/questions/20005173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1725323/"
] | You have to define `num` before you use it in the `while`, also your nested `if` should be out of the other `if`:
```
def maxmin():
minimum = None
maximum = None
num = None
while True:
num = input('Please enter a number, or -10 to stop: ')
if num == -10:
break
if (minimum) is None or (num < minimum):
minimum = num
if (maximum) is None or (num > maximum):
maximum = num
print ("Maximum: ", maximum)
print ("Minimum: ", minimum)
maxmin()
``` | This function should give you the output that you want:
```
def maxmin():
minimum, maximum, total = None, None, 0
while(True):
number = input('Please enter a number, or -10 to stop: ')
num = int(number)
if num == -10:
break
if total == 0:
minimum, maximum, total = num, num, 1
continue
total += 1
if num < minimum:
minimum = num
elif num > maximum:
maximum = num
print("Output : total ={}, minimum={}, maximum ={}".format(total, minimum, maximum))
``` |
20,005,173 | Maximum, minimum and total numbers using python. For example:
```
>>>maxmin()
Enter integers, one per line, terminated by -10 :
2
1
3
7
8
-10
Output : total =5, minimum=1, maximum = 8
```
Here is my code. I need some help with this.
```
def maxmin():
minimum = None
maximum = None
while (num != -10):
num = input('Please enter a number, or -10 to stop: ' )
if num == -10:
break
if (minimum) is None or (num < minimum):
minimum = num
if (maximum) is None or (num > maximum):
maximum = num
print ("Maximum: ", maximum)
print ("Minimum: ", minimum)
``` | 2013/11/15 | [
"https://Stackoverflow.com/questions/20005173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1725323/"
] | I would do this:
```
def maxmin():
minimum = None
maximum = None
while True:
num = input('Please enter a number, or -10 to stop: ')
if num == -10:
break
if (minimum) is None or (num < minimum):
minimum = num
if (maximum) is None or (num > maximum):
maximum = num
print ("Maximum: ", maximum)
print ("Minimum: ", minimum)
maxmin()
```
See, you're not really conditioning your while loop aroud num != -10 since you check for that within the loop and break out of it. So, there will never be a time when num=-10 at the beginning of the loop, make sense?
So, you just loop forever (The `while True`) until someone inputs a `-10` | This function should give you the output that you want:
```
def maxmin():
minimum, maximum, total = None, None, 0
while(True):
number = input('Please enter a number, or -10 to stop: ')
num = int(number)
if num == -10:
break
if total == 0:
minimum, maximum, total = num, num, 1
continue
total += 1
if num < minimum:
minimum = num
elif num > maximum:
maximum = num
print("Output : total ={}, minimum={}, maximum ={}".format(total, minimum, maximum))
``` |
71,197,496 | I have python script that creates dataflow template in the specified GCS path. I have tested the script using my GCP Free Trial and it works perfect.
My question is using same code in production environment I want to generate a template but I can not use Cloud-Shell as there are restrictions also can not directly run the Python script that is using the SA keys.
Also I can not create VM and using that generate a template in GCS.
Considering above restrictions is there any option to generate the dataflow template. | 2022/02/20 | [
"https://Stackoverflow.com/questions/71197496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2458847/"
] | First, you can do this with RXJS, or promises, but either way intentionally makes room for asynchronous programming, so when your `transform` method synchronously returns `this.value` at the end, I don't think you're getting what you're expecting? I'm guessing the reason it is compiling but you don't think it is working is that it is working, but the correct value is not computed before you're using it.
To stay in observables, it should return an observable.
```js
transform(key: string, args?: any): Observable<string | null> {
if (!this.localizationChanges) {
this.localizationChanges = this.fluentService.localizationChanges;
}
return this.localizationChanges.pipe(
switchMap(() => this.fluentService
.translationObservable(key, args, getLocale(args))
)
);
}
```
and then in your template, chain `| async` to the end of it. The `async` pipe will take care of subscribing, unsubscribing, telling the component to refresh every time the source observable emits or is changed, etc.
`switchMap` causes any still-waiting results of `fluentService.translationObservable` to be dropped each time `localizationChanges` emits, replacing with a new call.
If you only want one value emitted, then promises are an alternative. In that case, you'd probably want
```js
async transform(key: string, args?: any): Promise<string | null> {
if (!this.localizationChanges) {
this.localizationChanges = this.fluentService.localizationChanges;
}
return this.localizationChanges.toPromise().then(
() => this.fluentService.translate(
key, args, getLocale(args)
)
);
}
```
and then in your template, chain `| async` to the end of it rather than recreate that piece of code. | If I understand the problem well, your code has a fundamental problem and the fact that "*Everything works well, if I use Observables*" is a fruit of a very special case.
Let's look at this very stripped down version of your code
```
function translationObservable(key) {
return of("Obs translates key: " + key);
}
function transform(key: string, args?: any): string | null {
let retValue: string;
const localizationChanges: BehaviorSubject<null> = new BehaviorSubject<null>(
null
);
localizationChanges.subscribe(() => {
translationObservable(key).subscribe((value) => (retValue = value));
});
return retValue;
}
console.log(transform("abc")); // prints "Obs translates key: abc"
```
If you run this code you actually end up with a message printed out on the console.
There is one reason why this code works and the reason is that we are using Observables **synchronously**. In other words the code is executed line after line and therefore the assignment `retValue = value` ocurs before `retValue` is returned.
**Promises though are intrinsically asynchronous**. So, whatever logic you pass to the `then` method gets executed asynchronously, i.e. in another subsequent cycle of the Javascript engine.
This means that if we use a Promise instead of an Observable in the same example as above, we will not get any message printed
```
function translationPromise(key) {
return Promise.resolve("Promise translates key: " + key);
}
let retValue: string;
function transform(key: string, args?: any): string | null {
const localizationChanges: BehaviorSubject<null> = new BehaviorSubject<null>(
null
);
localizationChanges.subscribe(() => {
translationPromise(key).subscribe((value) => (retValue = value));
});
return retValue;
}
console.log(transform("abc")); // prints undefined
// some time later it prints the value returned using Promises
setTimeout(() => {
console.log(retValue);
}, 100);
```
The summary is that your code works probably only when you use the `of` operator to create the Observable (which works synchronously since there is no async operation involved) but I doubt it works when it has to invoke async functionalities like fetching a locale file.
If you want to build an Angular pipe which works asynchronously you need to follow the answer of @JSmart523
As last sode note, in your code you are subscribing an Observable within a Subscrition. This is considered not idiomatic with Observables. |
73,066,287 | I have a project hosted on Microsoft Azure. It has Azure Functions that are Python code and they recently stopped working (500 Internal Server Error). The code has errors I haven't had before and no known changes were made (but the possibility exists because people from other teams could have changed a configuration somewhere without telling anyone).
Here's some log :
```
2022-07-21T08:41:14.226884682Z: [INFO] info: Function.AllCurveApi[1]
2022-07-21T08:41:14.226994383Z: [INFO] Executing 'Functions.AllCurveApi' (Reason='This function was programmatically called via the host APIs.', Id=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)
2022-07-21T08:41:14.277076231Z: [INFO] fail: Function.AllCurveApi[3]
2022-07-21T08:41:14.277143831Z: [INFO] Executed 'Functions.AllCurveApi' (Failed, Id=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, Duration=6ms)
2022-07-21T08:41:14.277932437Z: [INFO] Microsoft.Azure.WebJobs.Host.FunctionInvocationException: Exception while executing function: Functions.AllCurveApi
2022-07-21T08:41:14.277948737Z: [INFO] ---> Microsoft.Azure.WebJobs.Script.Workers.Rpc.RpcException: Result: Failure
2022-07-21T08:41:14.277953937Z: [INFO] Exception: ImportError: libpython3.6m.so.1.0: cannot open shared object file: No such file or directory. Troubleshooting Guide: https://aka.ms/functions-modulenotfound
2022-07-21T08:41:14.277957637Z: [INFO] Stack: File "/azure-functions-host/workers/python/3.6/LINUX/X64/azure_functions_worker/dispatcher.py", line 318, in _handle__function_load_request
2022-07-21T08:41:14.277961437Z: [INFO] func_request.metadata.entry_point)
2022-07-21T08:41:14.277991237Z: [INFO] File "/azure-functions-host/workers/python/3.6/LINUX/X64/azure_functions_worker/utils/wrappers.py", line 42, in call
2022-07-21T08:41:14.277995937Z: [INFO] raise extend_exception_message(e, message)
2022-07-21T08:41:14.277999337Z: [INFO] File "/azure-functions-host/workers/python/3.6/LINUX/X64/azure_functions_worker/utils/wrappers.py", line 40, in call
2022-07-21T08:41:14.278020737Z: [INFO] return func(*args, **kwargs)
2022-07-21T08:41:14.278024237Z: [INFO] File "/azure-functions-host/workers/python/3.6/LINUX/X64/azure_functions_worker/loader.py", line 85, in load_function
2022-07-21T08:41:14.278027837Z: [INFO] mod = importlib.import_module(fullmodname)
2022-07-21T08:41:14.278031337Z: [INFO] File "/usr/local/lib/python3.6/importlib/__init__.py", line 126, in import_module
2022-07-21T08:41:14.278277039Z: [INFO] return _bootstrap._gcd_import(name[level:], package, level)
2022-07-21T08:41:14.278289939Z: [INFO] File "<frozen importlib._bootstrap>", line 994, in _gcd_import
2022-07-21T08:41:14.278294939Z: [INFO] File "<frozen importlib._bootstrap>", line 971, in _find_and_load
2022-07-21T08:41:14.278298639Z: [INFO] File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
2022-07-21T08:41:14.278302439Z: [INFO] File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
2022-07-21T08:41:14.278305939Z: [INFO] File "<frozen importlib._bootstrap_external>", line 678, in exec_module
2022-07-21T08:41:14.278309639Z: [INFO] File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
2022-07-21T08:41:14.278313239Z: [INFO] File "/home/site/wwwroot/AllCurveApi/__init__.py", line 9, in <module>
2022-07-21T08:41:14.278317039Z: [INFO] import pyodbc
2022-07-21T08:41:14.278320439Z: [INFO]
2022-07-21T08:41:14.278554841Z: [INFO] at Microsoft.Azure.WebJobs.Script.Description.WorkerFunctionInvoker.InvokeCore(Object[] parameters, FunctionInvocationContext context) in /src/azure-functions-host/src/WebJobs.Script/Description/Workers/WorkerFunctionInvoker.cs:line 96
2022-07-21T08:41:14.278568241Z: [INFO] at Microsoft.Azure.WebJobs.Script.Description.FunctionInvokerBase.Invoke(Object[] parameters) in /src/azure-functions-host/src/WebJobs.Script/Description/FunctionInvokerBase.cs:line 82
2022-07-21T08:41:14.278583841Z: [INFO] at Microsoft.Azure.WebJobs.Script.Description.FunctionGenerator.Coerce[T](Task`1 src) in /src/azure-functions-host/src/WebJobs.Script/Description/FunctionGenerator.cs:line 225
[...] Then it goes for many many lines, I'm not sure it's interesting
```
And here's an example of a python file, the error triggers on line 9, `import pyodbc` :
```
import simplejson as json
import azure.functions as func
from azure.keyvault import KeyVaultClient
from azure.common.credentials import ServicePrincipalCredentials
from datetime import datetime
import os
import pyodbc
import logging
# And then code
```
To me it looks like the server has difficulties accessing some Python resources or dependencies, it has to do with `libpython3.6` but at this point I'm not sure what to do on the Azure Portal to fix the problem. | 2022/07/21 | [
"https://Stackoverflow.com/questions/73066287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6126073/"
] | I was facing the same issue last Thursday. However, we have tried most of the solutions which are available on Internet but none of them help us.
And in the end, we have just updated Azure Function Runtime Python 3.6 to 3.7 and Boomm.. it's working.
Moreover, we have also noticed that when we tried to create new Azure Function App based on Linux, that time were not able to select Python3.6 as runtime stack.
Thanks again guys. | We had the exact same issue on Friday. What worked for us was to replace pyodbc with pypyodbc. We did this so that we didn't have to change it in our code:
```
import pypyodbc as pyodbc
```
Also, we upgraded our Azure Functions to use Python 3.7 (will probably update to 3.9 soon). Azure will not be supporting Python 3.6 as of September 30, 2022 anyways: <https://azure.microsoft.com/en-us/updates/azure-functions-support-for-python-36-is-ending-on-30-september-2022/> |
60,520,118 | I want to scrape phone no but phone no only displays after clicked so please is it possible to scrape phone no directly using python?My code scrape phone no but with starr\*\*\*. here is the link from where I want to scrape phone no:<https://hipages.com.au/connect/abcelectricservicespl/service/126298> please guide me!
here is my code:
```
import requests
from bs4 import BeautifulSoup
def get_page(url):
response = requests.get(url)
if not response.ok:
print('server responded:', response.status_code)
else:
soup = BeautifulSoup(response.text, 'lxml')
return soup
def get_detail_data(soup):
try:
title = (soup.find('h1', class_="sc-AykKI",id=False).text)
except:
title = 'Empty Title'
print(title)
try:
contact_person = (soup.findAll('span', class_="Contact__Item-sc-1giw2l4-2 kBpGee",id=False)[0].text)
except:
contact_person = 'Empty Person'
print(contact_person)
try:
location = (soup.findAll('span', class_="Contact__Item-sc-1giw2l4-2 kBpGee",id=False)[1].text)
except:
location = 'Empty location'
print(location)
try:
cell = (soup.findAll('span', class_="Contact__Item-sc-1giw2l4-2 kBpGee",id=False)[2].text)
except:
cell = 'Empty Cell No'
print(cell)
try:
phone = (soup.findAll('span', class_="Contact__Item-sc-1giw2l4-2 kBpGee",id=False)[3].text)
except:
phone = 'Empty Phone No'
print(phone)
try:
Verify_ABN = (soup.find('p', class_="sc-AykKI").text)
except:
Verify_ABN = 'Empty Verify_ABN'
print(Verify_ABN)
try:
ABN = (soup.find('div', class_="box__Box-sc-1u3aqjl-0").find('a'))
except:
ABN = 'Empty ABN'
print(ABN)
def main():
#get data of detail page
url = "https://hipages.com.au/connect/abcelectricservicespl/service/126298"
#get_page(url)
get_detail_data(get_page(url))
if __name__ == '__main__':
main()
``` | 2020/03/04 | [
"https://Stackoverflow.com/questions/60520118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7514427/"
] | Find the Id or class of that element and use jQuery to change the name.
If the element is a Anchor tag, use the below code.
```
jQuery(document).ready(function($)
{
$("#button_id").text("New Text");
});
```
If the element is button, use below code based on type of button.
```
<input type='button' value='Add' id='button_id'>
jQuery(document).ready(function($)
{
$("#button_id").attr('value', 'New Text');
}):
<input type='button' value='Add' id='button_id'>
jQuery(document).ready(function($)
{
$("#button_id").prop('value', 'New Text');
});
<!-- Different button types-->
<button id='button_id' type='button'>Add</button>
jQuery(document).ready(function($)
{
$("#button_id").html('New Text');
});
``` | From the screenshot, it seems like you are trying to change the text of a menu link (My Account). If so make sure that you haven't given any custom name for My Account page in the Wordpress navigation.
Inspect the page using developer tools and find the Class/Id of that element.
Then you can use jQuery to alter the content using the below code.
**Using ID Selector:**
```
jQuery(document).ready(function($)
{
$("#myaccountbuttonId").text("New Button Text");
});
```
**Using Class Selector**
```
jQuery(document).ready(function($)
{
$(".myaccountbuttonClass").text("New Button Text");
});
```
If you want to change the text of Add to Cart button, use the below code.
```
// To change add to cart text on single product page
add_filter( 'woocommerce_product_single_add_to_cart_text', 'woocommerce_custom_single_add_to_cart_text' );
function woocommerce_custom_single_add_to_cart_text() {
return __( 'Buy Now', 'woocommerce' );
}
// To change add to cart text on product archives(Collection) page
add_filter( 'woocommerce_product_add_to_cart_text', 'woocommerce_custom_product_add_to_cart_text' );
function woocommerce_custom_product_add_to_cart_text() {
return __( 'Buy Now', 'woocommerce' );
}
``` |
4,300,979 | Defining a function,
MyFunction(argument, \*args):
[do something to argument[arg] for arg in \*args]
if \*args is empty, the function doesn't do anything, but I want to make the default behavior 'use the entire set if length of \*args == 0'
```
def Export(source, target, *args, sep=','):
for item in source:
SubsetOutput(WriteFlatFile(target), args).send(item[0])
```
I don't want to check the length of args on every iteration, and I can't access the keys of
item in source until the iteration begins...
so i could
```
if len(args) != 0:
for item in source:
else
for item in source:
```
which will probably work but doesn't seem 'pythonic' enough?
is this (is there) a standard way to approach \*args or \*\*kwargs and default behavior when either is empty?
More Code:
```
def __coroutine(func):
"""
a decorator for coroutines to automatically prime the routine
code and method from 'curous course on coroutines and concurrency'
by david beazley www.dabeaz.com
"""
def __start(*args, **kwargs):
cr = func(*args, **kwargs)
next(cr)
return cr
return __start
def Export(source, target, *args, sep=','):
if args:
for item in source:
SubsetOutput(WriteFlatFile(target, sep), args).send(item)
else:
for item in source:
WriteFlatFile(target, sep).send(item)
@__coroutine
def SubsetOutput(target, *args):
"""
take *args from the results and pass to target
TODO
----
raise exception when arg is not in result[0]
"""
while True:
result = (yield)
print([result.arg for arg in result.dict() if arg in args])
target.send([result.arg for arg in result.dict if arg in args])
@__coroutine
def WriteFlatFile(target, sep):
"""
take set of results to a flat file
TODO
----
"""
filehandler = open(target, 'a')
while True:
result = (yield)
line = (sep.join([str(result[var]) for
var in result.keys()])).format(result)+'\n'
filehandler.write(line)
``` | 2010/11/29 | [
"https://Stackoverflow.com/questions/4300979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/508440/"
] | Is there a way to pass an "entire set" argument to `SubsetOutput`, so you can bury the conditional inside its call rather than have an explicit `if`? This could be `None` or `[]`, for example.
```
# Pass None to use full subset.
def Export(source, target, *args, sep=','):
for item in source:
SubsetOutput(WriteFlatFile(target), args or None).send(item[0])
# Pass an empty list [] to use full subset. Even simpler.
def Export(source, target, *args, sep=','):
for item in source:
SubsetOutput(WriteFlatFile(target), args).send(item[0])
```
If not, I would go with the two loop solution, assuming the loop really is a single line. It reads well and is a reasonable use case for a little bit of code duplication.
```
def Export(source, target, *args, sep=','):
if args:
for item in source:
SubsetOutput(WriteFlatFile(target), args).send(item[0])
else:
for item in source:
FullOutput(WriteFlatFile(target)).send(item[0])
``` | Just check its not none, you don't have to create a separate argument
```
def test(*args):
if not args:
return #break out
return True #or whatever you want
``` |
4,300,979 | Defining a function,
MyFunction(argument, \*args):
[do something to argument[arg] for arg in \*args]
if \*args is empty, the function doesn't do anything, but I want to make the default behavior 'use the entire set if length of \*args == 0'
```
def Export(source, target, *args, sep=','):
for item in source:
SubsetOutput(WriteFlatFile(target), args).send(item[0])
```
I don't want to check the length of args on every iteration, and I can't access the keys of
item in source until the iteration begins...
so i could
```
if len(args) != 0:
for item in source:
else
for item in source:
```
which will probably work but doesn't seem 'pythonic' enough?
is this (is there) a standard way to approach \*args or \*\*kwargs and default behavior when either is empty?
More Code:
```
def __coroutine(func):
"""
a decorator for coroutines to automatically prime the routine
code and method from 'curous course on coroutines and concurrency'
by david beazley www.dabeaz.com
"""
def __start(*args, **kwargs):
cr = func(*args, **kwargs)
next(cr)
return cr
return __start
def Export(source, target, *args, sep=','):
if args:
for item in source:
SubsetOutput(WriteFlatFile(target, sep), args).send(item)
else:
for item in source:
WriteFlatFile(target, sep).send(item)
@__coroutine
def SubsetOutput(target, *args):
"""
take *args from the results and pass to target
TODO
----
raise exception when arg is not in result[0]
"""
while True:
result = (yield)
print([result.arg for arg in result.dict() if arg in args])
target.send([result.arg for arg in result.dict if arg in args])
@__coroutine
def WriteFlatFile(target, sep):
"""
take set of results to a flat file
TODO
----
"""
filehandler = open(target, 'a')
while True:
result = (yield)
line = (sep.join([str(result[var]) for
var in result.keys()])).format(result)+'\n'
filehandler.write(line)
``` | 2010/11/29 | [
"https://Stackoverflow.com/questions/4300979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/508440/"
] | Just check its not none, you don't have to create a separate argument
```
def test(*args):
if not args:
return #break out
return True #or whatever you want
``` | How about this:
```
def MyFunc(argument, *args):
( DoSomething for i in (filter(args.__contains__ ,argument) if args else argument) )
``` |
4,300,979 | Defining a function,
MyFunction(argument, \*args):
[do something to argument[arg] for arg in \*args]
if \*args is empty, the function doesn't do anything, but I want to make the default behavior 'use the entire set if length of \*args == 0'
```
def Export(source, target, *args, sep=','):
for item in source:
SubsetOutput(WriteFlatFile(target), args).send(item[0])
```
I don't want to check the length of args on every iteration, and I can't access the keys of
item in source until the iteration begins...
so i could
```
if len(args) != 0:
for item in source:
else
for item in source:
```
which will probably work but doesn't seem 'pythonic' enough?
is this (is there) a standard way to approach \*args or \*\*kwargs and default behavior when either is empty?
More Code:
```
def __coroutine(func):
"""
a decorator for coroutines to automatically prime the routine
code and method from 'curous course on coroutines and concurrency'
by david beazley www.dabeaz.com
"""
def __start(*args, **kwargs):
cr = func(*args, **kwargs)
next(cr)
return cr
return __start
def Export(source, target, *args, sep=','):
if args:
for item in source:
SubsetOutput(WriteFlatFile(target, sep), args).send(item)
else:
for item in source:
WriteFlatFile(target, sep).send(item)
@__coroutine
def SubsetOutput(target, *args):
"""
take *args from the results and pass to target
TODO
----
raise exception when arg is not in result[0]
"""
while True:
result = (yield)
print([result.arg for arg in result.dict() if arg in args])
target.send([result.arg for arg in result.dict if arg in args])
@__coroutine
def WriteFlatFile(target, sep):
"""
take set of results to a flat file
TODO
----
"""
filehandler = open(target, 'a')
while True:
result = (yield)
line = (sep.join([str(result[var]) for
var in result.keys()])).format(result)+'\n'
filehandler.write(line)
``` | 2010/11/29 | [
"https://Stackoverflow.com/questions/4300979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/508440/"
] | Is there a way to pass an "entire set" argument to `SubsetOutput`, so you can bury the conditional inside its call rather than have an explicit `if`? This could be `None` or `[]`, for example.
```
# Pass None to use full subset.
def Export(source, target, *args, sep=','):
for item in source:
SubsetOutput(WriteFlatFile(target), args or None).send(item[0])
# Pass an empty list [] to use full subset. Even simpler.
def Export(source, target, *args, sep=','):
for item in source:
SubsetOutput(WriteFlatFile(target), args).send(item[0])
```
If not, I would go with the two loop solution, assuming the loop really is a single line. It reads well and is a reasonable use case for a little bit of code duplication.
```
def Export(source, target, *args, sep=','):
if args:
for item in source:
SubsetOutput(WriteFlatFile(target), args).send(item[0])
else:
for item in source:
FullOutput(WriteFlatFile(target)).send(item[0])
``` | How about this:
```
def MyFunc(argument, *args):
( DoSomething for i in (filter(args.__contains__ ,argument) if args else argument) )
``` |
52,172,821 | I'm currently trying to convert a nested dict into a list of objects with "children" and "leaf".
Here my input dict and the output I'm trying to obtain:
Input:
```
{
"a": {
"aa": {}
},
"b": {
"c": {
"d": {
'label': 'yoshi'
}
},
"e": {},
"f": {}
}
}
```
I try to obtain this:
```
[
{
"text": "a",
"children": [
{
"text": "aa",
"leaf": "true"
}
]
},
{
"text": "b",
"children": [
{
"text": "c",
"children": [
{
"text": "d",
"leaf": "true",
"label": "yoshi"
}
]
},
{
"text": "e",
"leaf": "true"
},
{
"text": "f",
"leaf": "true"
}
]
}
]
```
I've tried a few unflatten python lib on pypi but not one seems to be able to output a list format like this. | 2018/09/04 | [
"https://Stackoverflow.com/questions/52172821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2688174/"
] | I have commented the function as I feel necessary.
```
def convert(d):
children = []
#iterate over each child's name and their dict (child's childs)
for child, childs_childs in d.items():
#check that it is not a left node
if childs_childs and \
all(isinstance(v,dict) for k,v in childs_childs.items()):
#recursively call ourselves to get the child's children
children.append({'text': child,
'children': convert(childs_childs)})
else:
#if the child is a lead, append to children as necessarry
#the **-exploded accommodates the 'label':'yoshi' item
children.append({'text': child,
'leaf': True,
**childs_childs})
return children
```
which gives:
```
[
{
"text": "a",
"children": [
{
"text": "aa",
"leaf": true
}
]
},
{
"text": "b",
"children": [
{
"text": "c",
"children": [
{
"text": "d",
"leaf": true,
"label": "yoshi"
}
]
},
{
"text": "e",
"leaf": true
},
{
"text": "f",
"leaf": true
}
]
}
]
``` | Try this solution (`data` is your input dictionary):
```
def walk(text, d):
result = {'text': text}
# get all children
children = [walk(k, v) for k, v in d.items() if k != 'label']
if children:
result['children'] = children
else:
result['leaf'] = True
# add label if exists
label = d.get('label')
if label:
result['label'] = label
return result
[walk(k, v) for k, v in data.items()]
```
Output:
```
[{'text': 'a', 'children': [{'text': 'aa', 'leaf': True}]},
{'text': 'b',
'children': [{'text': 'c',
'children': [{'text': 'd', 'leaf': True, 'label': 'yoshi'}]},
{'text': 'e', 'leaf': True},
{'text': 'f', 'leaf': True}]}]
``` |
52,172,821 | I'm currently trying to convert a nested dict into a list of objects with "children" and "leaf".
Here my input dict and the output I'm trying to obtain:
Input:
```
{
"a": {
"aa": {}
},
"b": {
"c": {
"d": {
'label': 'yoshi'
}
},
"e": {},
"f": {}
}
}
```
I try to obtain this:
```
[
{
"text": "a",
"children": [
{
"text": "aa",
"leaf": "true"
}
]
},
{
"text": "b",
"children": [
{
"text": "c",
"children": [
{
"text": "d",
"leaf": "true",
"label": "yoshi"
}
]
},
{
"text": "e",
"leaf": "true"
},
{
"text": "f",
"leaf": "true"
}
]
}
]
```
I've tried a few unflatten python lib on pypi but not one seems to be able to output a list format like this. | 2018/09/04 | [
"https://Stackoverflow.com/questions/52172821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2688174/"
] | Here's a rough solution. Here I assumed that all labeled nodes are leaves that just have label information.
```
def make_objects(d):
result = []
for k, v in d.items():
if v == {}:
result.append({"text": k, "leaf":True})
elif len(v) ==1 and "label" in v:
result.append({"text": k, "leaf":True, "label": v.get("label")})
else:
result.append({"text": k, "children": make_objects(v)})
return result
```
With your example input as `d`:
```
from pprint import pprint
pprint(make_objects(d))
```
prints
```
[{'children': [{'leaf': True, 'text': 'aa'}], 'text': 'a'},
{'children': [{'children': [{'label': 'yoshi', 'leaf': True, 'text': 'd'}],
'text': 'c'},
{'leaf': True, 'text': 'e'},
{'leaf': True, 'text': 'f'}],
'text': 'b'}]
``` | Try this solution (`data` is your input dictionary):
```
def walk(text, d):
result = {'text': text}
# get all children
children = [walk(k, v) for k, v in d.items() if k != 'label']
if children:
result['children'] = children
else:
result['leaf'] = True
# add label if exists
label = d.get('label')
if label:
result['label'] = label
return result
[walk(k, v) for k, v in data.items()]
```
Output:
```
[{'text': 'a', 'children': [{'text': 'aa', 'leaf': True}]},
{'text': 'b',
'children': [{'text': 'c',
'children': [{'text': 'd', 'leaf': True, 'label': 'yoshi'}]},
{'text': 'e', 'leaf': True},
{'text': 'f', 'leaf': True}]}]
``` |
44,382,348 | I am just 4 days old to python. I am just trying to understand the root \_\_init\_\_.py import functionality. Googled lot to understand the same but not able to find one useful link (may be my search key is not relevant) . Please share some links.
I am getting error as "ImportError: cannot import name Person"
Below is the structure
```
Example(directory)
model
__init__.py (empty)
myclass.py
__init__.py
run.py
```
myclass.py
```
class Person(object):
def __init__(self):
self.name = "Raja"
def print_name(self):
print self.name
```
\_\_init\_\_.py
```
from model.myclass import Person
```
run.py
```
from model import Person
def donext():
person = Person()
person.print_name()
if __name__ == '__main__':
donext()
``` | 2017/06/06 | [
"https://Stackoverflow.com/questions/44382348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6346252/"
] | Either, as @gonczor suggested, you can simply leave \_\_init\_\_ empty (moreover, you don't need the root one) and import directly from the package:
```
from model.myclass import Person
```
Or, if you intentionally want to flatten the interface of the package, this is as simple as this:
model/\_\_init\_\_.py
```
from myclass import Person
```
run.py
```
from model import Person
``` | The error basically says the interpreter can't find anything that would match `Person` in a given namespace, in your case `model` package. It's because it's in `model.myclass` package, but it's imported to `root` and not to `run`.
Modules in python are basically directories with `__init__.py` script. But it's tricky to import anything at root level from **init**. And moreover, it's not necessary.
OK, so this means solution is either to import directly from `model` package, or from the rott-level `__init__.py`. I would recommend the former method, since it's more commonly used. You can do it this way:
```
from model.myclass import Person
def donext():
person = Person()
person.print_name()
if __name__ == '__main__':
donext()
```
And leave `__init__.py` empty. They are used only for initialization, so there is no need to import everything to them.
You could put something to your `model/__init__.py` and then import it in `myclass.py` like:
`__init__.py`:
```
something = 0
```
`myclass.py`:
```
from . import something
print something
``` |
55,668,648 | I need to find the starting index of the specific sequences (sequence of strings) in the list in python.
For ex.
```
list = ['In', 'a', 'gesture', 'sure', 'to', 'rattle', 'the', 'Chinese', 'Government', ',', 'Steven', 'Spielberg', 'pulled', 'out', 'of', 'the', 'Beijing', 'Olympics', 'to', 'protest', 'against', 'China', '_s', 'backing', 'for', 'Sudan', '_s', 'policy', 'in', 'Darfur', '.']
```
ex.
```
seq0 = "Steven Spielberg"
seq1 = "the Chinese Government"
seq2 = "the Beijing Olympics"
```
The output should be like :
```
10
6
15
``` | 2019/04/13 | [
"https://Stackoverflow.com/questions/55668648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3404345/"
] | You could simply iterate over list of your words and check at every index if following words match any of your sequences.
```
words = ['In', 'a', 'gesture', 'sure', 'to', 'rattle', 'the', 'Chinese', 'Government', ',', 'Steven', 'Spielberg', 'pulled', 'out', 'of', 'the', 'Beijing', 'Olympics', 'to', 'protest', 'against', 'China', '_s', 'backing', 'for', 'Sudan', '_s', 'policy', 'in', 'Darfur', '.']\
seq0 = "Steven Spielberg"
seq1 = "the Chinese Government"
seq2 = "the Beijing Olympics"
sequences = {'seq{}'.format(idx): i.split() for idx, i in enumerate([seq0, seq1, seq2])}
for idx in range(len(words)):
for k, v in sequences.items():
if idx + len(v) < len(words) and words[idx: idx+len(v)] == v:
print(k, idx)
```
**Output:**
```
seq1 6
seq0 10
seq2 15
``` | **You can do something like:**
```
def find_sequence(seq, _list):
seq_list = seq.split()
all_occurrence = [idx for idx in [i for i, x in enumerate(_list) if x == seq_list[0]] if seq_list == list_[idx:idx+len(seq_list)]]
return -1 if not all_occurrence else all_occurrence[0]
```
---
**Output:**
```
for seq in [seq0, seq1, seq2]:
print(find_sequence(seq, list_))
```
>
> 10
>
>
> 6
>
>
> 15
>
>
>
**Note**, if the sequence is not found you will get **-1**. |
69,682,188 | For the sake of practice, I am writing a class BankAccount to learn OOP in python. In an attempt to make my program more redundant am trying to write a test function `test_BankBankAccount()` to practice how to do test functions as well.
The test function `test_BankBankAccount()` is suppose to test that the methods `deposit()`, `withdraw()`, `transfer()` and `get_balance()` work as intended.
However, the test function fails because the methods inside of the `computed_deposit = test_account.deposit(400)`, `computed_transfer = test_account.transfer(test_account2, 200)` and so on doesn't seem to store the values i asign to them.
\*\*This is the error message I receive (which is the exact one i try to avoid) \*\*
```
assert success1 and success2 and success3 and success4, (msg1, msg2, msg3, msg4)
AssertionError: ('computet deposit = None is not 400', 'computet transfer = None is not 200', 'computet withdrawal = None is not 200', 'computet balance = 0 is not 0')
```
**Here is a snippet of much of the code I have written so far**
```
class BankAccount:
def __init__(self, first_name, last_name, number, balance):
self._first_name = first_name
self._last_name = last_name
self._number = number
self._balance = balance
def deposit(self, amount):
self._balance += amount
def withdraw(self, amount):
self._balance -= amount
def get_balance(self):
return self._balance
def transfer(self,other_account, transfer_amount):
self.withdraw(transfer_amount)
other_account.deposit(transfer_amount)
def print_info(self):
first = self._first_name
last = self._last_name
number = self._number
balance = self._balance
s = f"{first} {last}, {number}, balance: {balance}"
print(s)
def main():
def test_BankBankAccount():
test_account = BankAccount("Dude", "man", "1234", 0)
test_account2 = BankAccount("Dude2", "man2","5678", 0)
expected_deposit = 400
expected_withdrawal = 200
expected_transfer = 200
expected_get_balance = 0
computed_deposit = test_account.deposit(400)
computed_transfer = test_account.transfer(test_account2, 200)
computed_withdrawal = test_account.withdraw(200)
computed_get_balance = test_account.get_balance()
#tol = 1E-17
success1 = abs(expected_deposit == computed_deposit) #< tol
success2 = abs(expected_transfer == computed_transfer) #< tol
success3 = abs(expected_withdrawal == computed_withdrawal) #< tol
success4 = abs(expected_get_balance == computed_get_balance) #<tol
msg1 = f"computet deposit = {computed_deposit} is not {expected_deposit}"
msg2 = f"computet transfer = {computed_transfer} is not {expected_transfer}"
msg3 = f"computet withdrawal = {computed_withdrawal} is not {expected_withdrawal}"
msg4 = f"computet balance = {computed_get_balance} is not {expected_get_balance}"
assert success1 and success2 and success3 and success4, (msg1, msg2, msg3, msg4)
test_BankBankAccount()
```
**My question is:**
* Is there anyone who is kind enough to help me fix this and spot my mistakes?
All help is welcomed and appreciated. | 2021/10/22 | [
"https://Stackoverflow.com/questions/69682188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16925420/"
] | @KoenLostrie is absolutely correct as to *Why your trigger does not fire on Insert*. But that is just half the problem. But, the other issue stems from the same misconception: NULL values The call to `check_salary` passes `:old.job_id` but it is still null, resulting in cursor ( `for i in (Select ...)`) returning no rows when it attempts 'WHERE job\_id = null`. However there is no exception then a cursor returns no rows, the loop is simply not entered. You need to pass ':new.job\_id'. You would also want the new job id on Update as well. Image an employee gets a promotion the update is like to be something like:
```
update employee
set job_id = 1011
, salary = 50000.00
where employee = 115;
```
Finally, processing a cursor is at dangerous at best. Doing so at lease implies you allow multiple rows in the `Jobs` for a given job\_id. What happens when those rows have different `min_salary` and `max_salary` You can update the procedure or just do everything in the trigger and eliminate the procedure.
```
create or replace trigger check_salary_trg
before insert or update on employees
for each row
declare
e_invalid_salary_range;
l_job jobs%rowtype;
begin
select *
from jobs
into l_job
where job_id = :new.job_id;
if :new.salary < l_job.min_salary
or :new.salary > l_job.max_salary
then
raise e_invalid_salary_range; ;
end if;
exception
when e_invalid_salary_range then
raise_application_error(-20001, 'Invalid salary ' || psal ||
'. Salaries for job ' || pjobid ||
' must be between ' || l_job.min_salary ||
' and ' || l_job.max_salary
);
end check_salary_trg;
```
You could add handling `no_data_found` and `too_many_rows` the the exception block, but those are better handled with constraints. | Congrats on the well documented question.
The issue is with the `WHEN` clause of the trigger. On insert the old value is `NULL` and in oracle, you can't compare to NULL using "=" or "!=".
Check this example:
```
PDB1--KOEN>create table trigger_test
2 (name VARCHAR2(10));
Table TRIGGER_TEST created.
PDB1--KOEN>CREATE OR REPLACE trigger trigger_test_t1
2 BEFORE INSERT OR UPDATE ON trigger_test
3 FOR EACH ROW
4 WHEN (new.name != old.name)
5 BEGIN
6 RAISE_APPLICATION_ERROR(-20001, 'Some error !');
7 END trigger_test_t1;
8 /
Trigger TRIGGER_TEST_T1 compiled
PDB1--KOEN>INSERT INTO trigger_test (name) values ('koen');
1 row inserted.
PDB1--KOEN>UPDATE trigger_test set name = 'steven';
Error starting at line : 1 in command -
UPDATE trigger_test set name = 'steven'
Error report -
ORA-20001: Some error !
ORA-06512: at "KOEN.TRIGGER_TEST_T1", line 2
ORA-04088: error during execution of trigger 'KOEN.TRIGGER_TEST_T1'
```
That is exactly the behaviour you're seeing in your code. On insert the trigger doesn't seem to fire. Well... it doesn't because in oracle, `'x' != NULL` yields false. See info at the bottom of this answer. Here is the proof. Let's recreate the trigger with an `NVL` function wrapped around the old value.
```
PDB1--KOEN>CREATE OR REPLACE trigger trigger_test_t1
2 BEFORE INSERT OR UPDATE ON trigger_test
3 FOR EACH ROW
4 WHEN (new.name != NVL(old.name,'x'))
5 -- above is similar to this
6 --WHEN (new.name <> old.name or
7 -- (new.name is null and old.name is not NULL) or
8 -- (new.name is not null and old.name is NULL) )
9 BEGIN
10 RAISE_APPLICATION_ERROR(-20001, 'Some error !');
11 END trigger_test_t1;
12 /
Trigger TRIGGER_TEST_T1 compiled
PDB1--KOEN>INSERT INTO trigger_test (name) values ('jennifer');
Error starting at line : 1 in command -
INSERT INTO trigger_test (name) values ('jennifer')
Error report -
ORA-20001: Some error !
ORA-06512: at "KOEN.TRIGGER_TEST_T1", line 2
ORA-04088: error during execution of trigger 'KOEN.TRIGGER_TEST_T1'
```
There you go. It now fires on insert.
Now why is this happening ? According to the docs:
*Because null represents a lack of data, a null cannot be equal or unequal to any value or to another null. However, Oracle considers two nulls to be equal when evaluating a DECODE function.* Check the docs or read up on it in this *20 year old* answer on [asktom](https://asktom.oracle.com/pls/apex/f?p=100:11:0::::P11_QUESTION_ID:1274000564279) |
69,682,188 | For the sake of practice, I am writing a class BankAccount to learn OOP in python. In an attempt to make my program more redundant am trying to write a test function `test_BankBankAccount()` to practice how to do test functions as well.
The test function `test_BankBankAccount()` is suppose to test that the methods `deposit()`, `withdraw()`, `transfer()` and `get_balance()` work as intended.
However, the test function fails because the methods inside of the `computed_deposit = test_account.deposit(400)`, `computed_transfer = test_account.transfer(test_account2, 200)` and so on doesn't seem to store the values i asign to them.
\*\*This is the error message I receive (which is the exact one i try to avoid) \*\*
```
assert success1 and success2 and success3 and success4, (msg1, msg2, msg3, msg4)
AssertionError: ('computet deposit = None is not 400', 'computet transfer = None is not 200', 'computet withdrawal = None is not 200', 'computet balance = 0 is not 0')
```
**Here is a snippet of much of the code I have written so far**
```
class BankAccount:
def __init__(self, first_name, last_name, number, balance):
self._first_name = first_name
self._last_name = last_name
self._number = number
self._balance = balance
def deposit(self, amount):
self._balance += amount
def withdraw(self, amount):
self._balance -= amount
def get_balance(self):
return self._balance
def transfer(self,other_account, transfer_amount):
self.withdraw(transfer_amount)
other_account.deposit(transfer_amount)
def print_info(self):
first = self._first_name
last = self._last_name
number = self._number
balance = self._balance
s = f"{first} {last}, {number}, balance: {balance}"
print(s)
def main():
def test_BankBankAccount():
test_account = BankAccount("Dude", "man", "1234", 0)
test_account2 = BankAccount("Dude2", "man2","5678", 0)
expected_deposit = 400
expected_withdrawal = 200
expected_transfer = 200
expected_get_balance = 0
computed_deposit = test_account.deposit(400)
computed_transfer = test_account.transfer(test_account2, 200)
computed_withdrawal = test_account.withdraw(200)
computed_get_balance = test_account.get_balance()
#tol = 1E-17
success1 = abs(expected_deposit == computed_deposit) #< tol
success2 = abs(expected_transfer == computed_transfer) #< tol
success3 = abs(expected_withdrawal == computed_withdrawal) #< tol
success4 = abs(expected_get_balance == computed_get_balance) #<tol
msg1 = f"computet deposit = {computed_deposit} is not {expected_deposit}"
msg2 = f"computet transfer = {computed_transfer} is not {expected_transfer}"
msg3 = f"computet withdrawal = {computed_withdrawal} is not {expected_withdrawal}"
msg4 = f"computet balance = {computed_get_balance} is not {expected_get_balance}"
assert success1 and success2 and success3 and success4, (msg1, msg2, msg3, msg4)
test_BankBankAccount()
```
**My question is:**
* Is there anyone who is kind enough to help me fix this and spot my mistakes?
All help is welcomed and appreciated. | 2021/10/22 | [
"https://Stackoverflow.com/questions/69682188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16925420/"
] | Congrats on the well documented question.
The issue is with the `WHEN` clause of the trigger. On insert the old value is `NULL` and in oracle, you can't compare to NULL using "=" or "!=".
Check this example:
```
PDB1--KOEN>create table trigger_test
2 (name VARCHAR2(10));
Table TRIGGER_TEST created.
PDB1--KOEN>CREATE OR REPLACE trigger trigger_test_t1
2 BEFORE INSERT OR UPDATE ON trigger_test
3 FOR EACH ROW
4 WHEN (new.name != old.name)
5 BEGIN
6 RAISE_APPLICATION_ERROR(-20001, 'Some error !');
7 END trigger_test_t1;
8 /
Trigger TRIGGER_TEST_T1 compiled
PDB1--KOEN>INSERT INTO trigger_test (name) values ('koen');
1 row inserted.
PDB1--KOEN>UPDATE trigger_test set name = 'steven';
Error starting at line : 1 in command -
UPDATE trigger_test set name = 'steven'
Error report -
ORA-20001: Some error !
ORA-06512: at "KOEN.TRIGGER_TEST_T1", line 2
ORA-04088: error during execution of trigger 'KOEN.TRIGGER_TEST_T1'
```
That is exactly the behaviour you're seeing in your code. On insert the trigger doesn't seem to fire. Well... it doesn't because in oracle, `'x' != NULL` yields false. See info at the bottom of this answer. Here is the proof. Let's recreate the trigger with an `NVL` function wrapped around the old value.
```
PDB1--KOEN>CREATE OR REPLACE trigger trigger_test_t1
2 BEFORE INSERT OR UPDATE ON trigger_test
3 FOR EACH ROW
4 WHEN (new.name != NVL(old.name,'x'))
5 -- above is similar to this
6 --WHEN (new.name <> old.name or
7 -- (new.name is null and old.name is not NULL) or
8 -- (new.name is not null and old.name is NULL) )
9 BEGIN
10 RAISE_APPLICATION_ERROR(-20001, 'Some error !');
11 END trigger_test_t1;
12 /
Trigger TRIGGER_TEST_T1 compiled
PDB1--KOEN>INSERT INTO trigger_test (name) values ('jennifer');
Error starting at line : 1 in command -
INSERT INTO trigger_test (name) values ('jennifer')
Error report -
ORA-20001: Some error !
ORA-06512: at "KOEN.TRIGGER_TEST_T1", line 2
ORA-04088: error during execution of trigger 'KOEN.TRIGGER_TEST_T1'
```
There you go. It now fires on insert.
Now why is this happening ? According to the docs:
*Because null represents a lack of data, a null cannot be equal or unequal to any value or to another null. However, Oracle considers two nulls to be equal when evaluating a DECODE function.* Check the docs or read up on it in this *20 year old* answer on [asktom](https://asktom.oracle.com/pls/apex/f?p=100:11:0::::P11_QUESTION_ID:1274000564279) | Thanks for the wonderful answers! I've learned a lot thanks to them.
Upon inspecting my code especially my trigger, I made a mistake on passing the `:old.job_id` to my `check_salary` procedure instead of the `:new.job_id`, that's why i keep wondering why my INSERT is working even if the salary that is being passed is below the `min_salary` and `max_salary` of the job.
So this now my code:
check\_salary procedure:
```
CREATE OR REPLACE PROCEDURE check_salary (pjobid employees.job_id%type, psal employees.salary%type)
IS
BEGIN
FOR i in (SELECT min_salary, max_salary
FROM jobs
WHERE job_id = pjobid)
LOOP
IF psal < i.min_salary OR psal > i.max_salary THEN
RAISE_APPLICATION_ERROR(-20001, 'Invalid salary ' || psal || '. Salaries for job ' || pjobid || ' must be between ' || i.min_salary || ' and ' || i.max_salary);
ELSE
DBMS_OUTPUT.PUT_LINE('Salary is okay!');
END IF;
END LOOP;
END check_salary;
/
```
check\_salary\_trg:
```
CREATE OR REPLACE TRIGGER check_salary_trg
BEFORE INSERT OR UPDATE ON employees
FOR EACH ROW
WHEN (new.salary != NVL(old.salary, 0) OR new.job_id != NVL(old.job_id, 'x'))
BEGIN
check_salary(:new.job_id, :new.salary);
END check_salary_trg;
/
```
and the results whenever i'm passing data thru insert and update
```
INSERT INTO employees(employee_id, first_name, last_name, email, department_id, job_id, hire_date, salary)
VALUES (employees_seq.nextval, 'Lorem', 'Ipsum', 'loremipsum', 30, 'SA_REP', TRUNC(sysdate), 5000);
```
**`ORA-20001: Invalid salary 5000. Salaries for job SA_REP must be between 6000 and 12008`**
```
UPDATE employees
SET job_id = 'ST_MAN'
WHERE last_name = 'Beh'
```
**`ORA-20001: Invalid salary 9000. Salaries for job ST_MAN must be between 5500 and 8500`**
```
UPDATE employees
SET salary = 2800
WHERE employee_id = 115;
--1 row(s) updated.
--Salary is okay!
-- will work since min_salary and max_salary of PU_CLERK is 2500 and 5500
``` |
69,682,188 | For the sake of practice, I am writing a class BankAccount to learn OOP in python. In an attempt to make my program more redundant am trying to write a test function `test_BankBankAccount()` to practice how to do test functions as well.
The test function `test_BankBankAccount()` is suppose to test that the methods `deposit()`, `withdraw()`, `transfer()` and `get_balance()` work as intended.
However, the test function fails because the methods inside of the `computed_deposit = test_account.deposit(400)`, `computed_transfer = test_account.transfer(test_account2, 200)` and so on doesn't seem to store the values i asign to them.
\*\*This is the error message I receive (which is the exact one i try to avoid) \*\*
```
assert success1 and success2 and success3 and success4, (msg1, msg2, msg3, msg4)
AssertionError: ('computet deposit = None is not 400', 'computet transfer = None is not 200', 'computet withdrawal = None is not 200', 'computet balance = 0 is not 0')
```
**Here is a snippet of much of the code I have written so far**
```
class BankAccount:
def __init__(self, first_name, last_name, number, balance):
self._first_name = first_name
self._last_name = last_name
self._number = number
self._balance = balance
def deposit(self, amount):
self._balance += amount
def withdraw(self, amount):
self._balance -= amount
def get_balance(self):
return self._balance
def transfer(self,other_account, transfer_amount):
self.withdraw(transfer_amount)
other_account.deposit(transfer_amount)
def print_info(self):
first = self._first_name
last = self._last_name
number = self._number
balance = self._balance
s = f"{first} {last}, {number}, balance: {balance}"
print(s)
def main():
def test_BankBankAccount():
test_account = BankAccount("Dude", "man", "1234", 0)
test_account2 = BankAccount("Dude2", "man2","5678", 0)
expected_deposit = 400
expected_withdrawal = 200
expected_transfer = 200
expected_get_balance = 0
computed_deposit = test_account.deposit(400)
computed_transfer = test_account.transfer(test_account2, 200)
computed_withdrawal = test_account.withdraw(200)
computed_get_balance = test_account.get_balance()
#tol = 1E-17
success1 = abs(expected_deposit == computed_deposit) #< tol
success2 = abs(expected_transfer == computed_transfer) #< tol
success3 = abs(expected_withdrawal == computed_withdrawal) #< tol
success4 = abs(expected_get_balance == computed_get_balance) #<tol
msg1 = f"computet deposit = {computed_deposit} is not {expected_deposit}"
msg2 = f"computet transfer = {computed_transfer} is not {expected_transfer}"
msg3 = f"computet withdrawal = {computed_withdrawal} is not {expected_withdrawal}"
msg4 = f"computet balance = {computed_get_balance} is not {expected_get_balance}"
assert success1 and success2 and success3 and success4, (msg1, msg2, msg3, msg4)
test_BankBankAccount()
```
**My question is:**
* Is there anyone who is kind enough to help me fix this and spot my mistakes?
All help is welcomed and appreciated. | 2021/10/22 | [
"https://Stackoverflow.com/questions/69682188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16925420/"
] | @KoenLostrie is absolutely correct as to *Why your trigger does not fire on Insert*. But that is just half the problem. But, the other issue stems from the same misconception: NULL values The call to `check_salary` passes `:old.job_id` but it is still null, resulting in cursor ( `for i in (Select ...)`) returning no rows when it attempts 'WHERE job\_id = null`. However there is no exception then a cursor returns no rows, the loop is simply not entered. You need to pass ':new.job\_id'. You would also want the new job id on Update as well. Image an employee gets a promotion the update is like to be something like:
```
update employee
set job_id = 1011
, salary = 50000.00
where employee = 115;
```
Finally, processing a cursor is at dangerous at best. Doing so at lease implies you allow multiple rows in the `Jobs` for a given job\_id. What happens when those rows have different `min_salary` and `max_salary` You can update the procedure or just do everything in the trigger and eliminate the procedure.
```
create or replace trigger check_salary_trg
before insert or update on employees
for each row
declare
e_invalid_salary_range;
l_job jobs%rowtype;
begin
select *
from jobs
into l_job
where job_id = :new.job_id;
if :new.salary < l_job.min_salary
or :new.salary > l_job.max_salary
then
raise e_invalid_salary_range; ;
end if;
exception
when e_invalid_salary_range then
raise_application_error(-20001, 'Invalid salary ' || psal ||
'. Salaries for job ' || pjobid ||
' must be between ' || l_job.min_salary ||
' and ' || l_job.max_salary
);
end check_salary_trg;
```
You could add handling `no_data_found` and `too_many_rows` the the exception block, but those are better handled with constraints. | Thanks for the wonderful answers! I've learned a lot thanks to them.
Upon inspecting my code especially my trigger, I made a mistake on passing the `:old.job_id` to my `check_salary` procedure instead of the `:new.job_id`, that's why i keep wondering why my INSERT is working even if the salary that is being passed is below the `min_salary` and `max_salary` of the job.
So this now my code:
check\_salary procedure:
```
CREATE OR REPLACE PROCEDURE check_salary (pjobid employees.job_id%type, psal employees.salary%type)
IS
BEGIN
FOR i in (SELECT min_salary, max_salary
FROM jobs
WHERE job_id = pjobid)
LOOP
IF psal < i.min_salary OR psal > i.max_salary THEN
RAISE_APPLICATION_ERROR(-20001, 'Invalid salary ' || psal || '. Salaries for job ' || pjobid || ' must be between ' || i.min_salary || ' and ' || i.max_salary);
ELSE
DBMS_OUTPUT.PUT_LINE('Salary is okay!');
END IF;
END LOOP;
END check_salary;
/
```
check\_salary\_trg:
```
CREATE OR REPLACE TRIGGER check_salary_trg
BEFORE INSERT OR UPDATE ON employees
FOR EACH ROW
WHEN (new.salary != NVL(old.salary, 0) OR new.job_id != NVL(old.job_id, 'x'))
BEGIN
check_salary(:new.job_id, :new.salary);
END check_salary_trg;
/
```
and the results whenever i'm passing data thru insert and update
```
INSERT INTO employees(employee_id, first_name, last_name, email, department_id, job_id, hire_date, salary)
VALUES (employees_seq.nextval, 'Lorem', 'Ipsum', 'loremipsum', 30, 'SA_REP', TRUNC(sysdate), 5000);
```
**`ORA-20001: Invalid salary 5000. Salaries for job SA_REP must be between 6000 and 12008`**
```
UPDATE employees
SET job_id = 'ST_MAN'
WHERE last_name = 'Beh'
```
**`ORA-20001: Invalid salary 9000. Salaries for job ST_MAN must be between 5500 and 8500`**
```
UPDATE employees
SET salary = 2800
WHERE employee_id = 115;
--1 row(s) updated.
--Salary is okay!
-- will work since min_salary and max_salary of PU_CLERK is 2500 and 5500
``` |
38,797,047 | I'm running ubuntu 12.04 and usually use python 2.7, but I need a python package that was built with python 3.4 and that uses lxml. After updating aptitude, I can install python 3.2 and lxml, but the package I want only works with 3.4. After installing python 3.4, I try to install lxml dependencies using
```
pip3 install libxml2-dev
```
I get the error:
```
No matching distribution found for libxml2-dev
pip3 install lxml
```
doesn't work and asks for libxml2:
```
Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed?
```
Any ideas on how to install lxml? Thanks. | 2016/08/05 | [
"https://Stackoverflow.com/questions/38797047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1106278/"
] | You are running
```
pip3 install libxml2-dev
```
when you should be running
```
sudo apt-get install libxml2 libxml2-dev
```
(you may also need `libxslt` and its dev version as well)
`pip` doesn't install system libraries, `apt` and friends do that. | See <http://www.lfd.uci.edu/~gohlke/pythonlibs/#libxml-python>
Download the package and then do a `pip install <package.whl>`. |
28,627,414 | Welcome... I'm creating a project where I parse xlsx files with xlrd library. Everything works just fine. Then I configured RabbitMQ and Celery. Created some tasks in main folder which works and can be accessed from iPython. The problems starts when I'm in my application (application created back in time in my project) and I try to import tasks from my app in my views.py
I tried to import it with all possible paths but everytime it throws me an error.
Official documentation posts the right way of importing tasks from other applications, It looks like this:
`from project.myapp.tasks import mytask`
But it doesn't work at all.
In addition when Im in iPython I can import tasks with command `from tango.tasks import add`
And it works perfectly.
Just bellow I'm uploading my files and error printed out by console.
views.py
```
# these are the instances that I was trying to import that seemed to be the most reasonable, but non of it worked
# import tasks
# from new_tango_project.tango.tasks import add
# from new_tango_project.tango import tasks
# from new_tango_project.new_tango_project.tango.tasks import add
# from new_tango_project.new_tango_project.tango import tasks
# from tango import tasks
#function to parse files
def parse_file(request, file_id):
xlrd_file = get_object_or_404(xlrdFile, pk = file_id)
if xlrd_file.status == False
#this is some basic task that I want to enter to
tasks.add.delay(321,123)
```
settings.py
```
#I've just posted things directly connected to celery
import djcelery
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'tango',
'djcelery',
'celery',
)
BROKER_URL = "amqp://sebrabbit:seb@localhost:5672/myvhost"
BROKER_HOST = "127.0.0.1"
BROKER_PORT = 5672
BROKER_VHOST = "myvhost"
BROKER_USER = "sebrabbit"
BROKER_PASSWORD = "seb"
CELERY_RESULT_BACKEND = 'amqp://'
CELERY_TASK_SERIALIZER = 'json'
CELERY_ACCEPT_CONTENT=['json']
CELERY_TIMEZONE = 'Europe/Warsaw'
CELERY_ENABLE_UTC = False
```
celery.py (in my main folder `new_tango_project` )
```
from __future__ import absolute_import
import os
from celery import Celery
import djcelery
from django.conf import settings
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'new_tango_project.settings')
app = Celery('new_tango_project')
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
# CELERY_IMPORTS = ['tango.tasks']
# Optional configuration, see the application user guide.
app.conf.update(
CELERY_TASK_RESULT_EXPIRES=3600,
CELERY_RESULT_BACKEND='djcelery.backends.cache:CacheBackend',
)
if __name__ == '__main__':
app.start()
```
tasks.py (in my main project folder `new_tango_project`)
```
from __future__ import absolute_import
from celery import Celery
from celery.task import task
app = Celery('new_tango_project',
broker='amqp://sebrabbit:seb@localhost:5672/myvhost',
backend='amqp://',
include=['tasks'])
@task
def add(x, y):
return x + y
@task
def mul(x, y):
return x * y
@task
def xsum(numbers):
return sum(numbers)
@task
def parse(file_id, xlrd_file):
return "HAHAHAHHHAHHA"
```
tasks.py in my application folder
```
from __future__ import absolute_import
from celery import Celery
from celery.task import task
#
app = Celery('tango')
@task
def add(x, y):
return x + y
@task
def asdasdasd(x, y):
return x + y
```
celery console when starting
```
-------------- celery@debian v3.1.17 (Cipater)
---- **** -----
--- * *** * -- Linux-3.2.0-4-amd64-x86_64-with-debian-7.8
-- * - **** ---
- ** ---------- [config]
- ** ---------- .> app: new_tango_project:0x1b746d0
- ** ---------- .> transport: amqp://sebrabbit:**@localhost:5672/myvhost
- ** ---------- .> results: amqp://
- *** --- * --- .> concurrency: 8 (prefork)
-- ******* ----
--- ***** ----- [queues]
-------------- .> celery exchange=celery(direct) key=celery
```
Finally my console log...
```
[2015-02-20 11:19:45,678: ERROR/MainProcess] Received unregistered task of type 'new_tango_project.tasks.add'.
The message has been ignored and discarded.
Did you remember to import the module containing this task?
Or maybe you are using relative imports?
Please see http://bit.ly/gLye1c for more information.
The full contents of the message body was:
{'utc': True, 'chord': None, 'args': (123123123, 123213213), 'retries': 0, 'expires': None, 'task': 'new_tango_project.tasks.add', 'callbacks': None, 'errbacks': None, 'timelimit': (None, None), 'taskset': None, 'kwargs': {}, 'eta': None, 'id': 'd9a8e560-1cd0-491d-a132-10345a04f391'} (233b)
Traceback (most recent call last):
File "/home/seb/PycharmProjects/tango/local/lib/python2.7/site-packages/celery/worker/consumer.py", line 455, in on_task_received
strategies[name](message, body,
KeyError: 'new_tango_project.tasks.add'
```
This is the log from one of many tries importing the tasks.
Where I`m making mistake ?
Best wishes | 2015/02/20 | [
"https://Stackoverflow.com/questions/28627414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4563194/"
] | You would need to extend the scale class and override the `calculateXLabelRotation` method to use a user inputted rotation rather than trying to work it out it's self. If you do this you would then need to extend the bar or line chart and override the init method to make use of this scale class. (or you could make these changes directly to the scale, bar and line classes and then no need to override).
so first extend scale class and make it use a user defined option
```
var helpers = Chart.helpers;
Chart.MyScale = Chart.Scale.extend({
calculateXLabelRotation: function() {
//Get the width of each grid by calculating the difference
//between x offsets between 0 and 1.
this.ctx.font = this.font;
var firstWidth = this.ctx.measureText(this.xLabels[0]).width,
lastWidth = this.ctx.measureText(this.xLabels[this.xLabels.length - 1]).width,
firstRotated,
lastRotated;
this.xScalePaddingRight = lastWidth / 2 + 3;
this.xScalePaddingLeft = (firstWidth / 2 > this.yLabelWidth + 10) ? firstWidth / 2 : this.yLabelWidth + 10;
this.xLabelRotation = 0;
if (this.display) {
var originalLabelWidth = helpers.longestText(this.ctx, this.font, this.xLabels),
cosRotation,
firstRotatedWidth;
this.xLabelWidth = originalLabelWidth;
//Allow 3 pixels x2 padding either side for label readability
var xGridWidth = Math.floor(this.calculateX(1) - this.calculateX(0)) - 6;
//check if option is set if so use that
if (this.overrideRotation) {
// do the same as before but manualy set the rotation rather than looping
this.xLabelRotation = this.overrideRotation;
cosRotation = Math.cos(helpers.radians(this.xLabelRotation));
// We're right aligning the text now.
if (firstRotated + this.fontSize / 2 > this.yLabelWidth + 8) {
this.xScalePaddingLeft = firstRotated + this.fontSize / 2;
}
this.xScalePaddingRight = this.fontSize / 2;
this.xLabelWidth = cosRotation * originalLabelWidth;
} else {
//Max label rotate should be 90 - also act as a loop counter
while ((this.xLabelWidth > xGridWidth && this.xLabelRotation === 0) || (this.xLabelWidth > xGridWidth && this.xLabelRotation <= 90 && this.xLabelRotation > 0)) {
cosRotation = Math.cos(helpers.radians(this.xLabelRotation));
firstRotated = cosRotation * firstWidth;
lastRotated = cosRotation * lastWidth;
// We're right aligning the text now.
if (firstRotated + this.fontSize / 2 > this.yLabelWidth + 8) {
this.xScalePaddingLeft = firstRotated + this.fontSize / 2;
}
this.xScalePaddingRight = this.fontSize / 2;
this.xLabelRotation++;
this.xLabelWidth = cosRotation * originalLabelWidth;
}
}
if (this.xLabelRotation > 0) {
this.endPoint -= Math.sin(helpers.radians(this.xLabelRotation)) * originalLabelWidth + 3;
}
} else {
this.xLabelWidth = 0;
this.xScalePaddingRight = this.padding;
this.xScalePaddingLeft = this.padding;
}
},
});
```
then in the extend the bar class to create a new graph type and override the init method to use the new
```
Chart.types.Bar.extend({
name: "MyBar",
initialize: function(data) {
//Expose options as a scope variable here so we can access it in the ScaleClass
var options = this.options;
this.ScaleClass = Chart.MyScale.extend({
overrideRotation: options.overrideRotation,
offsetGridLines: true,
calculateBarX: function(datasetCount, datasetIndex, barIndex) {
//Reusable method for calculating the xPosition of a given bar based on datasetIndex & width of the bar
var xWidth = this.calculateBaseWidth(),
xAbsolute = this.calculateX(barIndex) - (xWidth / 2),
barWidth = this.calculateBarWidth(datasetCount);
return xAbsolute + (barWidth * datasetIndex) + (datasetIndex * options.barDatasetSpacing) + barWidth / 2;
},
calculateBaseWidth: function() {
return (this.calculateX(1) - this.calculateX(0)) - (2 * options.barValueSpacing);
},
calculateBarWidth: function(datasetCount) {
//The padding between datasets is to the right of each bar, providing that there are more than 1 dataset
var baseWidth = this.calculateBaseWidth() - ((datasetCount - 1) * options.barDatasetSpacing);
return (baseWidth / datasetCount);
}
});
this.datasets = [];
//Set up tooltip events on the chart
if (this.options.showTooltips) {
helpers.bindEvents(this, this.options.tooltipEvents, function(evt) {
var activeBars = (evt.type !== 'mouseout') ? this.getBarsAtEvent(evt) : [];
this.eachBars(function(bar) {
bar.restore(['fillColor', 'strokeColor']);
});
helpers.each(activeBars, function(activeBar) {
activeBar.fillColor = activeBar.highlightFill;
activeBar.strokeColor = activeBar.highlightStroke;
});
this.showTooltip(activeBars);
});
}
//Declare the extension of the default point, to cater for the options passed in to the constructor
this.BarClass = Chart.Rectangle.extend({
strokeWidth: this.options.barStrokeWidth,
showStroke: this.options.barShowStroke,
ctx: this.chart.ctx
});
//Iterate through each of the datasets, and build this into a property of the chart
helpers.each(data.datasets, function(dataset, datasetIndex) {
var datasetObject = {
label: dataset.label || null,
fillColor: dataset.fillColor,
strokeColor: dataset.strokeColor,
bars: []
};
this.datasets.push(datasetObject);
helpers.each(dataset.data, function(dataPoint, index) {
//Add a new point for each piece of data, passing any required data to draw.
datasetObject.bars.push(new this.BarClass({
value: dataPoint,
label: data.labels[index],
datasetLabel: dataset.label,
strokeColor: dataset.strokeColor,
fillColor: dataset.fillColor,
highlightFill: dataset.highlightFill || dataset.fillColor,
highlightStroke: dataset.highlightStroke || dataset.strokeColor
}));
}, this);
}, this);
this.buildScale(data.labels);
this.BarClass.prototype.base = this.scale.endPoint;
this.eachBars(function(bar, index, datasetIndex) {
helpers.extend(bar, {
width: this.scale.calculateBarWidth(this.datasets.length),
x: this.scale.calculateBarX(this.datasets.length, datasetIndex, index),
y: this.scale.endPoint
});
bar.save();
}, this);
this.render();
},
});
```
now you can declare a chart using this chart type and pass in the option `overrideRotation`
here is a fiddle example <http://jsfiddle.net/leighking2/ye3usuhu/>
and a snippet
```js
var helpers = Chart.helpers;
Chart.MyScale = Chart.Scale.extend({
calculateXLabelRotation: function() {
//Get the width of each grid by calculating the difference
//between x offsets between 0 and 1.
this.ctx.font = this.font;
var firstWidth = this.ctx.measureText(this.xLabels[0]).width,
lastWidth = this.ctx.measureText(this.xLabels[this.xLabels.length - 1]).width,
firstRotated,
lastRotated;
this.xScalePaddingRight = lastWidth / 2 + 3;
this.xScalePaddingLeft = (firstWidth / 2 > this.yLabelWidth + 10) ? firstWidth / 2 : this.yLabelWidth + 10;
this.xLabelRotation = 0;
if (this.display) {
var originalLabelWidth = helpers.longestText(this.ctx, this.font, this.xLabels),
cosRotation,
firstRotatedWidth;
this.xLabelWidth = originalLabelWidth;
//Allow 3 pixels x2 padding either side for label readability
var xGridWidth = Math.floor(this.calculateX(1) - this.calculateX(0)) - 6;
if (this.overrideRotation) {
this.xLabelRotation = this.overrideRotation;
cosRotation = Math.cos(helpers.radians(this.xLabelRotation));
// We're right aligning the text now.
if (firstRotated + this.fontSize / 2 > this.yLabelWidth + 8) {
this.xScalePaddingLeft = firstRotated + this.fontSize / 2;
}
this.xScalePaddingRight = this.fontSize / 2;
this.xLabelWidth = cosRotation * originalLabelWidth;
} else {
//Max label rotate should be 90 - also act as a loop counter
while ((this.xLabelWidth > xGridWidth && this.xLabelRotation === 0) || (this.xLabelWidth > xGridWidth && this.xLabelRotation <= 90 && this.xLabelRotation > 0)) {
cosRotation = Math.cos(helpers.radians(this.xLabelRotation));
firstRotated = cosRotation * firstWidth;
lastRotated = cosRotation * lastWidth;
// We're right aligning the text now.
if (firstRotated + this.fontSize / 2 > this.yLabelWidth + 8) {
this.xScalePaddingLeft = firstRotated + this.fontSize / 2;
}
this.xScalePaddingRight = this.fontSize / 2;
this.xLabelRotation++;
this.xLabelWidth = cosRotation * originalLabelWidth;
}
}
if (this.xLabelRotation > 0) {
this.endPoint -= Math.sin(helpers.radians(this.xLabelRotation)) * originalLabelWidth + 3;
}
} else {
this.xLabelWidth = 0;
this.xScalePaddingRight = this.padding;
this.xScalePaddingLeft = this.padding;
}
},
});
Chart.types.Bar.extend({
name: "MyBar",
initialize: function(data) {
//Expose options as a scope variable here so we can access it in the ScaleClass
var options = this.options;
this.ScaleClass = Chart.MyScale.extend({
overrideRotation: options.overrideRotation,
offsetGridLines: true,
calculateBarX: function(datasetCount, datasetIndex, barIndex) {
//Reusable method for calculating the xPosition of a given bar based on datasetIndex & width of the bar
var xWidth = this.calculateBaseWidth(),
xAbsolute = this.calculateX(barIndex) - (xWidth / 2),
barWidth = this.calculateBarWidth(datasetCount);
return xAbsolute + (barWidth * datasetIndex) + (datasetIndex * options.barDatasetSpacing) + barWidth / 2;
},
calculateBaseWidth: function() {
return (this.calculateX(1) - this.calculateX(0)) - (2 * options.barValueSpacing);
},
calculateBarWidth: function(datasetCount) {
//The padding between datasets is to the right of each bar, providing that there are more than 1 dataset
var baseWidth = this.calculateBaseWidth() - ((datasetCount - 1) * options.barDatasetSpacing);
return (baseWidth / datasetCount);
}
});
this.datasets = [];
//Set up tooltip events on the chart
if (this.options.showTooltips) {
helpers.bindEvents(this, this.options.tooltipEvents, function(evt) {
var activeBars = (evt.type !== 'mouseout') ? this.getBarsAtEvent(evt) : [];
this.eachBars(function(bar) {
bar.restore(['fillColor', 'strokeColor']);
});
helpers.each(activeBars, function(activeBar) {
activeBar.fillColor = activeBar.highlightFill;
activeBar.strokeColor = activeBar.highlightStroke;
});
this.showTooltip(activeBars);
});
}
//Declare the extension of the default point, to cater for the options passed in to the constructor
this.BarClass = Chart.Rectangle.extend({
strokeWidth: this.options.barStrokeWidth,
showStroke: this.options.barShowStroke,
ctx: this.chart.ctx
});
//Iterate through each of the datasets, and build this into a property of the chart
helpers.each(data.datasets, function(dataset, datasetIndex) {
var datasetObject = {
label: dataset.label || null,
fillColor: dataset.fillColor,
strokeColor: dataset.strokeColor,
bars: []
};
this.datasets.push(datasetObject);
helpers.each(dataset.data, function(dataPoint, index) {
//Add a new point for each piece of data, passing any required data to draw.
datasetObject.bars.push(new this.BarClass({
value: dataPoint,
label: data.labels[index],
datasetLabel: dataset.label,
strokeColor: dataset.strokeColor,
fillColor: dataset.fillColor,
highlightFill: dataset.highlightFill || dataset.fillColor,
highlightStroke: dataset.highlightStroke || dataset.strokeColor
}));
}, this);
}, this);
this.buildScale(data.labels);
this.BarClass.prototype.base = this.scale.endPoint;
this.eachBars(function(bar, index, datasetIndex) {
helpers.extend(bar, {
width: this.scale.calculateBarWidth(this.datasets.length),
x: this.scale.calculateBarX(this.datasets.length, datasetIndex, index),
y: this.scale.endPoint
});
bar.save();
}, this);
this.render();
},
});
var randomScalingFactor = function() {
return Math.round(Math.random() * 100)
};
var barChartData = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
fillColor: "rgba(220,220,220,0.5)",
strokeColor: "rgba(220,220,220,0.8)",
highlightFill: "rgba(220,220,220,0.75)",
highlightStroke: "rgba(220,220,220,1)",
data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()]
}, {
fillColor: "rgba(151,187,205,0.5)",
strokeColor: "rgba(151,187,205,0.8)",
highlightFill: "rgba(151,187,205,0.75)",
highlightStroke: "rgba(151,187,205,1)",
data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()]
}, {
fillColor: "rgba(15,18,20,0.5)",
strokeColor: "rgba(15,18,20,0.8)",
highlightFill: "rgba(15,18,20,0.75)",
highlightStroke: "rgba(15,18,20,1)",
data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()]
}]
}
window.onload = function() {
var ctx = document.getElementById("canvas").getContext("2d");
window.myBar = new Chart(ctx).MyBar(barChartData, {
overrideRotation: 30
});
}
```
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.1/Chart.js"></script>
<canvas id="canvas" height="150" width="300"></canvas>
``` | Note that **for chart.js 3.x the way of specifying the axis scale options has changed**: see <https://www.chartjs.org/docs/master/getting-started/v3-migration.html#scales>
Consequently in the above answer for 2.x you need to remove the square brackets like this:
```
var myChart = new Chart(ctx, {
type: 'bar',
data: chartData,
options: {
scales: {
xAxes: {
ticks: {
autoSkip: false,
maxRotation: 90,
minRotation: 90
}
}
}
}
});
``` |
28,627,414 | Welcome... I'm creating a project where I parse xlsx files with xlrd library. Everything works just fine. Then I configured RabbitMQ and Celery. Created some tasks in main folder which works and can be accessed from iPython. The problems starts when I'm in my application (application created back in time in my project) and I try to import tasks from my app in my views.py
I tried to import it with all possible paths but everytime it throws me an error.
Official documentation posts the right way of importing tasks from other applications, It looks like this:
`from project.myapp.tasks import mytask`
But it doesn't work at all.
In addition when Im in iPython I can import tasks with command `from tango.tasks import add`
And it works perfectly.
Just bellow I'm uploading my files and error printed out by console.
views.py
```
# these are the instances that I was trying to import that seemed to be the most reasonable, but non of it worked
# import tasks
# from new_tango_project.tango.tasks import add
# from new_tango_project.tango import tasks
# from new_tango_project.new_tango_project.tango.tasks import add
# from new_tango_project.new_tango_project.tango import tasks
# from tango import tasks
#function to parse files
def parse_file(request, file_id):
xlrd_file = get_object_or_404(xlrdFile, pk = file_id)
if xlrd_file.status == False
#this is some basic task that I want to enter to
tasks.add.delay(321,123)
```
settings.py
```
#I've just posted things directly connected to celery
import djcelery
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'tango',
'djcelery',
'celery',
)
BROKER_URL = "amqp://sebrabbit:seb@localhost:5672/myvhost"
BROKER_HOST = "127.0.0.1"
BROKER_PORT = 5672
BROKER_VHOST = "myvhost"
BROKER_USER = "sebrabbit"
BROKER_PASSWORD = "seb"
CELERY_RESULT_BACKEND = 'amqp://'
CELERY_TASK_SERIALIZER = 'json'
CELERY_ACCEPT_CONTENT=['json']
CELERY_TIMEZONE = 'Europe/Warsaw'
CELERY_ENABLE_UTC = False
```
celery.py (in my main folder `new_tango_project` )
```
from __future__ import absolute_import
import os
from celery import Celery
import djcelery
from django.conf import settings
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'new_tango_project.settings')
app = Celery('new_tango_project')
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
# CELERY_IMPORTS = ['tango.tasks']
# Optional configuration, see the application user guide.
app.conf.update(
CELERY_TASK_RESULT_EXPIRES=3600,
CELERY_RESULT_BACKEND='djcelery.backends.cache:CacheBackend',
)
if __name__ == '__main__':
app.start()
```
tasks.py (in my main project folder `new_tango_project`)
```
from __future__ import absolute_import
from celery import Celery
from celery.task import task
app = Celery('new_tango_project',
broker='amqp://sebrabbit:seb@localhost:5672/myvhost',
backend='amqp://',
include=['tasks'])
@task
def add(x, y):
return x + y
@task
def mul(x, y):
return x * y
@task
def xsum(numbers):
return sum(numbers)
@task
def parse(file_id, xlrd_file):
return "HAHAHAHHHAHHA"
```
tasks.py in my application folder
```
from __future__ import absolute_import
from celery import Celery
from celery.task import task
#
app = Celery('tango')
@task
def add(x, y):
return x + y
@task
def asdasdasd(x, y):
return x + y
```
celery console when starting
```
-------------- celery@debian v3.1.17 (Cipater)
---- **** -----
--- * *** * -- Linux-3.2.0-4-amd64-x86_64-with-debian-7.8
-- * - **** ---
- ** ---------- [config]
- ** ---------- .> app: new_tango_project:0x1b746d0
- ** ---------- .> transport: amqp://sebrabbit:**@localhost:5672/myvhost
- ** ---------- .> results: amqp://
- *** --- * --- .> concurrency: 8 (prefork)
-- ******* ----
--- ***** ----- [queues]
-------------- .> celery exchange=celery(direct) key=celery
```
Finally my console log...
```
[2015-02-20 11:19:45,678: ERROR/MainProcess] Received unregistered task of type 'new_tango_project.tasks.add'.
The message has been ignored and discarded.
Did you remember to import the module containing this task?
Or maybe you are using relative imports?
Please see http://bit.ly/gLye1c for more information.
The full contents of the message body was:
{'utc': True, 'chord': None, 'args': (123123123, 123213213), 'retries': 0, 'expires': None, 'task': 'new_tango_project.tasks.add', 'callbacks': None, 'errbacks': None, 'timelimit': (None, None), 'taskset': None, 'kwargs': {}, 'eta': None, 'id': 'd9a8e560-1cd0-491d-a132-10345a04f391'} (233b)
Traceback (most recent call last):
File "/home/seb/PycharmProjects/tango/local/lib/python2.7/site-packages/celery/worker/consumer.py", line 455, in on_task_received
strategies[name](message, body,
KeyError: 'new_tango_project.tasks.add'
```
This is the log from one of many tries importing the tasks.
Where I`m making mistake ?
Best wishes | 2015/02/20 | [
"https://Stackoverflow.com/questions/28627414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4563194/"
] | If you are using chart.js 2.x, just set **maxRotation: 90** and **minRotation: 90** in ticks options. It works for me!
And if you want to all x-labels, you may want to set **autoSkip: false**.
The following is an example.
```
var myChart = new Chart(ctx, {
type: 'bar',
data: chartData,
options: {
scales: {
xAxes: [{
ticks: {
autoSkip: false,
maxRotation: 90,
minRotation: 90
}
}]
}
}
});
``` | Note that **for chart.js 3.x the way of specifying the axis scale options has changed**: see <https://www.chartjs.org/docs/master/getting-started/v3-migration.html#scales>
Consequently in the above answer for 2.x you need to remove the square brackets like this:
```
var myChart = new Chart(ctx, {
type: 'bar',
data: chartData,
options: {
scales: {
xAxes: {
ticks: {
autoSkip: false,
maxRotation: 90,
minRotation: 90
}
}
}
}
});
``` |
29,790,344 | I want to generate the following xml file:
```
<foo if="bar"/>
```
I've tried this:
```
from lxml import etree
etree.Element("foo", if="bar")
```
But I got this error:
```
page = etree.Element("configuration", if="ok")
^
SyntaxError: invalid syntax
```
Any ideas?
I'm using python 2.7.9 and lxml 3.4.2 | 2015/04/22 | [
"https://Stackoverflow.com/questions/29790344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4131226/"
] | ```
etree.Element("foo", {"if": "bar"})
```
The attributes can be passed in as a dict:
```
from lxml import etree
root = etree.Element("foo", {"if": "bar"})
print etree.tostring(root, pretty_print=True)
```
output
```
<foo if="bar"/>
``` | 'if' is a reserved word in Python, which means that you can't use it as an identifier. |
29,790,344 | I want to generate the following xml file:
```
<foo if="bar"/>
```
I've tried this:
```
from lxml import etree
etree.Element("foo", if="bar")
```
But I got this error:
```
page = etree.Element("configuration", if="ok")
^
SyntaxError: invalid syntax
```
Any ideas?
I'm using python 2.7.9 and lxml 3.4.2 | 2015/04/22 | [
"https://Stackoverflow.com/questions/29790344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4131226/"
] | ```
etree.Element("foo", **{"if": "bar"})
``` | 'if' is a reserved word in Python, which means that you can't use it as an identifier. |
29,790,344 | I want to generate the following xml file:
```
<foo if="bar"/>
```
I've tried this:
```
from lxml import etree
etree.Element("foo", if="bar")
```
But I got this error:
```
page = etree.Element("configuration", if="ok")
^
SyntaxError: invalid syntax
```
Any ideas?
I'm using python 2.7.9 and lxml 3.4.2 | 2015/04/22 | [
"https://Stackoverflow.com/questions/29790344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4131226/"
] | ```
etree.Element("foo", {"if": "bar"})
```
The attributes can be passed in as a dict:
```
from lxml import etree
root = etree.Element("foo", {"if": "bar"})
print etree.tostring(root, pretty_print=True)
```
output
```
<foo if="bar"/>
``` | ```
etree.Element("foo", **{"if": "bar"})
``` |
21,662,881 | My approach is:
```
def build_layers():
layers = ()
for i in range (0, 32):
layers += (True)
```
but this leads to
```
TypeError: can only concatenate tuple (not "bool") to tuple
```
Context: This should prepare a call of [bpy.ops.pose.armature\_layers](http://www.blender.org/documentation/blender_python_api_2_69_9/bpy.ops.pose.html) therefore I can't choose a list. | 2014/02/09 | [
"https://Stackoverflow.com/questions/21662881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/241590/"
] | `(True)` is not a tuple.
Do this instead:
```
layers += (True, )
```
Even better, use a generator:
```
(True, ) * 32
``` | Since tuples are immutable, each concatenation creates a new tuple. It is better to do something like:
```
def build_layers(count):
return tuple([True]*count)
```
If you need some logic to the tuple constructed, just use a list comprehension or generator expression in the tuple constructor:
```
>>> tuple(bool(ord(e)%2) for e in 'abcdefg')
(True, False, True, False, True, False, True)
``` |
21,662,881 | My approach is:
```
def build_layers():
layers = ()
for i in range (0, 32):
layers += (True)
```
but this leads to
```
TypeError: can only concatenate tuple (not "bool") to tuple
```
Context: This should prepare a call of [bpy.ops.pose.armature\_layers](http://www.blender.org/documentation/blender_python_api_2_69_9/bpy.ops.pose.html) therefore I can't choose a list. | 2014/02/09 | [
"https://Stackoverflow.com/questions/21662881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/241590/"
] | `(True)` is not a tuple.
Do this instead:
```
layers += (True, )
```
Even better, use a generator:
```
(True, ) * 32
``` | only a tuple can be add to tuple so this would be a working code
```
def build_layers():
layers = ()
for i in range (0, 32):
layers += (True,)
```
However adding tuple is not very pythonic
```
def build_layers():
layers = []
for i in range (0, 32):
layers.append(True)
return tuple(layers)
```
if the True value depend on i you can make a function
```
def f(i):
True
def build_layers():
layers = []
for i in range (0, 32):
layers.append(f(i))
return tuple(layers)
```
but this is typically best suited in a generator expression
```
def build_layers():
return tuple(f(i) for i in range(0,32))
```
by the way the start value of a range is default 0
so this equally work
```
def build_layers():
return tuple(f(i) for i in range(32))
``` |
57,612,054 | I'm testing an API endpoint that is supposed to raise a ValidationError in a Django model (note that the exception is a Django exception, not DRF, because it's in the model).
```
from rest_framework.test import APITestCase
class TestMyView(APITestCase):
# ...
def test_bad_request(self):
# ...
response = self.client.post(url, data)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
```
However, my test errors out with an exception instead of passing. It doesn't even fail getting a 500 instead of 400, it doesn't get there at all. Isn't DRF's APIClient supposed to handle *every* exception? I've search online but found nothing. I've read that DRF doesn't handle Django's native ValidationError, but still that doesn't explain why I am not even getting a 500. Any idea what I'm doing wrong?
**Full stack trace**:
```
E
======================================================================
ERROR: test_cannot_create_duplicate_email (organizations.api.tests.test_contacts.TestContactListCreateView)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/code/organizations/api/tests/test_contacts.py", line 98, in test_cannot_create_duplicate_email
response = self.jsonapi_post(self.url(new_partnership), data)
File "/code/config/tests/base.py", line 166, in jsonapi_post
url, data=json.dumps(data), content_type=content_type)
File "/usr/local/lib/python3.7/site-packages/rest_framework/test.py", line 300, in post
path, data=data, format=format, content_type=content_type, **extra)
File "/usr/local/lib/python3.7/site-packages/rest_framework/test.py", line 213, in post
return self.generic('POST', path, data, content_type, **extra)
File "/usr/local/lib/python3.7/site-packages/rest_framework/test.py", line 238, in generic
method, path, data, content_type, secure, **extra)
File "/usr/local/lib/python3.7/site-packages/django/test/client.py", line 422, in generic
return self.request(**r)
File "/usr/local/lib/python3.7/site-packages/rest_framework/test.py", line 289, in request
return super(APIClient, self).request(**kwargs)
File "/usr/local/lib/python3.7/site-packages/rest_framework/test.py", line 241, in request
request = super(APIRequestFactory, self).request(**kwargs)
File "/usr/local/lib/python3.7/site-packages/django/test/client.py", line 503, in request
raise exc_value
File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/django/views/generic/base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 495, in dispatch
response = self.handle_exception(exc)
File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 455, in handle_exception
self.raise_uncaught_exception(exc)
File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 492, in dispatch
response = handler(request, *args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/rest_framework/generics.py", line 244, in post
return self.create(request, *args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/rest_framework/mixins.py", line 21, in create
self.perform_create(serializer)
File "/usr/local/lib/python3.7/site-packages/rest_framework/mixins.py", line 26, in perform_create
serializer.save()
File "/usr/local/lib/python3.7/site-packages/rest_framework/serializers.py", line 214, in save
self.instance = self.create(validated_data)
File "/code/organizations/api/serializers.py", line 441, in create
'partnership': self.context['partnership']
File "/usr/local/lib/python3.7/site-packages/rest_framework/serializers.py", line 943, in create
instance = ModelClass._default_manager.create(**validated_data)
File "/usr/local/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 422, in create
obj.save(force_insert=True, using=self.db)
File "/code/organizations/models.py", line 278, in save
self.full_clean()
File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 1203, in full_clean
raise ValidationError(errors)
django.core.exceptions.ValidationError: {'__all__': ['Supplier contact emails must be unique per organization.']}
``` | 2019/08/22 | [
"https://Stackoverflow.com/questions/57612054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/686617/"
] | **Question**: Isn't DRF's APIClient supposed to handle every exception?
**Answer**: No. It's a test client, it won't handle any uncaught exceptions, that's how test clients work. Test clients propagate the exception so that the test fails with a "crash" when an exception isn't caught. You can test that exceptions are raised and uncaught with [`self.assertRaises`](https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertRaises)
**Question**: The APIView should return HTTP\_400\_BAD\_REQUEST when I raise a ValidationError but the exception isn't caught.
**Answer**:
You should look at the [source code for APIView](http://www.cdrf.co/3.9/rest_framework.views/APIView.html#handle_exception).
Inside the `dispatch()` method, all exceptions raised while creating the `response` object are caught and the method `handle_exception()` is called.
Your exception is a `ValidationError`. The crucial lines are:
```
exception_handler = self.get_exception_handler()
context = self.get_exception_handler_context()
response = exception_handler(exc, context)
if response is None:
self.raise_uncaught_exception(exc)
```
If you haven't changed `settings.EXCEPTION_HANDLER`, you get the default DRF exception handler, [source code here](https://github.com/encode/django-rest-framework/blob/3.9.0/rest_framework/views.py#L73).
If handles `Http404`, `PermissionDenied` and `APIException`. The `APIView` itself actually also handles `AuthenticationFailed` and `NotAuthenticated`. But not `ValidationError`. So it returns `None` and therefore the view raises your `ValidationError` which stops your test.
You see that in your traceback:
```
File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 455, in handle_exception
self.raise_uncaught_exception(exc)
```
You can decide to handle more exceptions than the default ones handled by DRF, you can read [this](https://www.django-rest-framework.org/api-guide/exceptions/#custom-exception-handling) on custom exception handling.
**EDIT**: You can also `raise rest_framework.exceptions.ValidationError` instead of the standard Django `ValidationError`. That is an `APIException` and therefore will be handled by DRF as a `HTTP400_BAD_REQUEST`. [1]
Side note: Luckily DRF doesn't catch every single exception! If there's a serious flaw in your code you actually **want** your code to "crash" and produce an error log and your server to return a HTTP 500. Which is what happens here. The response would be an HTTP 500 if this wasn't the test client.
[1]<https://github.com/encode/django-rest-framework/blob/3.9.0/rest_framework/exceptions.py#L142> | Something in your code is causing a python error which is halting execution before your POST request can return a valid HTTP response. Your code doesn't even reach the line `self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)` because there is no response.
If you're calling your tests in the normal way with `./manage.py test` then you should see the traceback and be able to narrow down what caused the error. |
57,612,054 | I'm testing an API endpoint that is supposed to raise a ValidationError in a Django model (note that the exception is a Django exception, not DRF, because it's in the model).
```
from rest_framework.test import APITestCase
class TestMyView(APITestCase):
# ...
def test_bad_request(self):
# ...
response = self.client.post(url, data)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
```
However, my test errors out with an exception instead of passing. It doesn't even fail getting a 500 instead of 400, it doesn't get there at all. Isn't DRF's APIClient supposed to handle *every* exception? I've search online but found nothing. I've read that DRF doesn't handle Django's native ValidationError, but still that doesn't explain why I am not even getting a 500. Any idea what I'm doing wrong?
**Full stack trace**:
```
E
======================================================================
ERROR: test_cannot_create_duplicate_email (organizations.api.tests.test_contacts.TestContactListCreateView)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/code/organizations/api/tests/test_contacts.py", line 98, in test_cannot_create_duplicate_email
response = self.jsonapi_post(self.url(new_partnership), data)
File "/code/config/tests/base.py", line 166, in jsonapi_post
url, data=json.dumps(data), content_type=content_type)
File "/usr/local/lib/python3.7/site-packages/rest_framework/test.py", line 300, in post
path, data=data, format=format, content_type=content_type, **extra)
File "/usr/local/lib/python3.7/site-packages/rest_framework/test.py", line 213, in post
return self.generic('POST', path, data, content_type, **extra)
File "/usr/local/lib/python3.7/site-packages/rest_framework/test.py", line 238, in generic
method, path, data, content_type, secure, **extra)
File "/usr/local/lib/python3.7/site-packages/django/test/client.py", line 422, in generic
return self.request(**r)
File "/usr/local/lib/python3.7/site-packages/rest_framework/test.py", line 289, in request
return super(APIClient, self).request(**kwargs)
File "/usr/local/lib/python3.7/site-packages/rest_framework/test.py", line 241, in request
request = super(APIRequestFactory, self).request(**kwargs)
File "/usr/local/lib/python3.7/site-packages/django/test/client.py", line 503, in request
raise exc_value
File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/django/views/generic/base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 495, in dispatch
response = self.handle_exception(exc)
File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 455, in handle_exception
self.raise_uncaught_exception(exc)
File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 492, in dispatch
response = handler(request, *args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/rest_framework/generics.py", line 244, in post
return self.create(request, *args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/rest_framework/mixins.py", line 21, in create
self.perform_create(serializer)
File "/usr/local/lib/python3.7/site-packages/rest_framework/mixins.py", line 26, in perform_create
serializer.save()
File "/usr/local/lib/python3.7/site-packages/rest_framework/serializers.py", line 214, in save
self.instance = self.create(validated_data)
File "/code/organizations/api/serializers.py", line 441, in create
'partnership': self.context['partnership']
File "/usr/local/lib/python3.7/site-packages/rest_framework/serializers.py", line 943, in create
instance = ModelClass._default_manager.create(**validated_data)
File "/usr/local/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 422, in create
obj.save(force_insert=True, using=self.db)
File "/code/organizations/models.py", line 278, in save
self.full_clean()
File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 1203, in full_clean
raise ValidationError(errors)
django.core.exceptions.ValidationError: {'__all__': ['Supplier contact emails must be unique per organization.']}
``` | 2019/08/22 | [
"https://Stackoverflow.com/questions/57612054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/686617/"
] | **Question**: Isn't DRF's APIClient supposed to handle every exception?
**Answer**: No. It's a test client, it won't handle any uncaught exceptions, that's how test clients work. Test clients propagate the exception so that the test fails with a "crash" when an exception isn't caught. You can test that exceptions are raised and uncaught with [`self.assertRaises`](https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertRaises)
**Question**: The APIView should return HTTP\_400\_BAD\_REQUEST when I raise a ValidationError but the exception isn't caught.
**Answer**:
You should look at the [source code for APIView](http://www.cdrf.co/3.9/rest_framework.views/APIView.html#handle_exception).
Inside the `dispatch()` method, all exceptions raised while creating the `response` object are caught and the method `handle_exception()` is called.
Your exception is a `ValidationError`. The crucial lines are:
```
exception_handler = self.get_exception_handler()
context = self.get_exception_handler_context()
response = exception_handler(exc, context)
if response is None:
self.raise_uncaught_exception(exc)
```
If you haven't changed `settings.EXCEPTION_HANDLER`, you get the default DRF exception handler, [source code here](https://github.com/encode/django-rest-framework/blob/3.9.0/rest_framework/views.py#L73).
If handles `Http404`, `PermissionDenied` and `APIException`. The `APIView` itself actually also handles `AuthenticationFailed` and `NotAuthenticated`. But not `ValidationError`. So it returns `None` and therefore the view raises your `ValidationError` which stops your test.
You see that in your traceback:
```
File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 455, in handle_exception
self.raise_uncaught_exception(exc)
```
You can decide to handle more exceptions than the default ones handled by DRF, you can read [this](https://www.django-rest-framework.org/api-guide/exceptions/#custom-exception-handling) on custom exception handling.
**EDIT**: You can also `raise rest_framework.exceptions.ValidationError` instead of the standard Django `ValidationError`. That is an `APIException` and therefore will be handled by DRF as a `HTTP400_BAD_REQUEST`. [1]
Side note: Luckily DRF doesn't catch every single exception! If there's a serious flaw in your code you actually **want** your code to "crash" and produce an error log and your server to return a HTTP 500. Which is what happens here. The response would be an HTTP 500 if this wasn't the test client.
[1]<https://github.com/encode/django-rest-framework/blob/3.9.0/rest_framework/exceptions.py#L142> | Django >3.0
===========
Starting with Django 3.0, `Client` constructor takes `raise_request_exception` parameter. Set it `False` and response 500 will returned instead of raising an exception.
Source:
<https://docs.djangoproject.com/en/3.2/releases/3.0/#tests>
```py
self.client = Client(raise_request_exception=False)
```
Django <3.0
===========
There is a workaround for this for Django 2.2 and earlier.
**TL;DR:**
Just mock the `store_exc_info` method of `Client` class.
```py
from unittest import mock
class TestMyView(APITestCase):
...
def test_server_error(self):
mock.patch("django.test.client.Client.store_exc_info")
self.client.post("/url/, data)
...
```
Now, the client will return regular response object with status code = 500.
**Explanation:**
Django's Test client always raises exceptions, even if they were wrapped in 500 Server error response.
`Client` connects its method called `store_exc_info` to the `got_request_exception` Django's signal (source: <https://github.com/django/django/blob/3.2.5/django/test/client.py#L712>)
```py
got_request_exception.connect(self.store_exc_info, dispatch_uid=exception_uid)
```
This method saves an exception info as `self.exc_info`. This attribute is later tested if its `None`. If it is, then error is raised. If not, response is normally returned (source: <https://github.com/django/django/blob/2.2.24/django/test/client.py#L500>)
Mocking the `self.store_exc_info` makes it do nothing, so exception info is not stored - therefore it's `None` later :) |
2,261,671 | I have a bit counting method that I am trying to make as fast as possible. I want to try the algorithm below from [Bit Twiddling Hacks](http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel), but I don't know C. What is 'type T' and what is the python equivalent of (T)~(T)0/3?
>
> A generalization of the best bit
> counting method to integers of
> bit-widths upto 128 (parameterized by
> type T) is this:
>
>
>
```
v = v - ((v >> 1) & (T)~(T)0/3); // temp
v = (v & (T)~(T)0/15*3) + ((v >> 2) & (T)~(T)0/15*3); // temp
v = (v + (v >> 4)) & (T)~(T)0/255*15; // temp
c = (T)(v * ((T)~(T)0/255)) >> (sizeof(v) - 1) * CHAR_BIT; // count
``` | 2010/02/14 | [
"https://Stackoverflow.com/questions/2261671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/270316/"
] | T is a integer type, which I'm assuming is unsigned. Since this is C, it'll be fixed width, probably (but not necessarily) one of 8, 16, 32, 64 or 128. The fragment `(T)~(T)0` that appears repeatedly in that code sample just gives the value 2\*\*N-1, where N is the width of the type T. I suspect that the code may require that N be a multiple of 8
for correct operation.
Here's a direct translation of the given code into Python, parameterized in terms of N, the width of T in bits.
```
def count_set_bits(v, N=128):
mask = (1 << N) - 1
v = v - ((v >> 1) & mask//3)
v = (v & mask//15*3) + ((v >> 2) & mask//15*3)
v = (v + (v >> 4)) & mask//255*15
return (mask & v * (mask//255)) >> (N//8 - 1) * 8
```
Caveats:
(1) the above will only work for numbers up to 2\*\*128. You might be able to generalize it for larger numbers, though.
(2) There are obvious inefficiencies: for example, 'mask//15' is computed twice. This doesn't matter for C, of course, because the compiler will almost certainly do the division at compile time rather than run time, but Python's peephole optimizer may not be so clever.
(3) The fastest C method may well not translate to the fastest Python method. For Python speed, you should probably be looking for an algorithm that minimizes the number of Python bitwise operations. As Alexander Gessler said: profile! | What you copied is a template for generating code. It's not a good idea to transliterate that template into another language and expect it to run fast. Let's expand the template.
(T)~(T)0 means "as many 1-bits as fit in type T". The algorithm needs 4 masks which we will compute for the various T-sizes we might be interested in.
```
>>> for N in (8, 16, 32, 64, 128):
... all_ones = (1 << N) - 1
... constants = ' '.join([hex(x) for x in [
... all_ones // 3,
... all_ones // 15 * 3,
... all_ones // 255 * 15,
... all_ones // 255,
... ]])
... print N, constants
...
8 0x55 0x33 0xf 0x1
16 0x5555 0x3333 0xf0f 0x101
32 0x55555555L 0x33333333L 0xf0f0f0fL 0x1010101L
64 0x5555555555555555L 0x3333333333333333L 0xf0f0f0f0f0f0f0fL 0x101010101010101L
128 0x55555555555555555555555555555555L 0x33333333333333333333333333333333L 0xf0f0f0f0f0f0f0f0f0f0f0f0f0f0f0fL 0x1010101010101010101010101010101L
>>>
```
You'll notice that the masks generated for the 32-bit case match those in the hardcoded 32-bit C code. Implementation detail: lose the `L` suffix from the 32-bit masks (Python 2.x) and lose all `L` suffixes for Python 3.x.
As you can see the whole template and (T)~(T)0 caper is merely obfuscatory sophistry. Put quite simply, for a k-byte type, you need 4 masks:
```
k bytes each 0x55
k bytes each 0x33
k bytes each 0x0f
k bytes each 0x01
```
and the final shift is merely N-8 (i.e. 8\*(k-1)) bits. Aside: I doubt if the template code would actually work on a machine whose CHAR\_BIT was not 8, but there aren't very many of those around these days.
Update: There is another point that affects the correctness and the speed when transliterating such algorithms from C to Python. The C algorithms often assume unsigned integers. In C, operations on unsigned integers work silently modulo 2\*\*N. In other words, only the least significant N bits are retained. No overflow exceptions. Many bit twiddling algorithms rely on this. However (a) Python's `int` and `long` are signed (b) old Python 2.X will raise an exception, recent Python 2.Xs will silently promote `int` to `long` and Python 3.x `int` == Python 2.x `long`.
The correctness problem usually requires `register &= all_ones` at least once in the Python code. Careful analysis is often required to determine the minimal correct masking.
Working in `long` instead of `int` doesn't do much for efficiency. You'll notice that the algorithm for 32 bits will return a `long` answer even from input of `0`, because the 32-bits all\_ones is `long`. |
74,335,162 | I have a file with a function and a file that calls the functions. Finally, I run .bat
I don't know how I can add an argument when calling the .bat file. So that the argument was added to the function as below.
file\_with\_func.py
```
def some_func(val):
print(val)
```
run\_bat.py
```
from bin.file_with_func import some_func
some_func(val)
```
myBat.bat
```
set basePath=%cd%
cd %~dp0
cd ..
python manage.py shell < bin/run_bat.py
cd %basePath%
```
Now I would like to run .bat like this.
```
\bin>.\myBat.bat "mystring"
```
**Or after starting, get options to choose from, e.g.**
```
\bin>.\myBat.bat
>>> Choose 1 or 2
>>> 1
```
**And then the function returns**
`"You chose 1"` | 2022/11/06 | [
"https://Stackoverflow.com/questions/74335162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17356459/"
] | You need to turn a bunch of POJO's (Plain Old JavaScript Objects) into a class with methods specialized for this kind of object. The idiomatic way is to create a class that takes the POJO's data in some way (since I'm lazy I just pass the entire thing). TypeScript doesn't change how you approach this - you just need to add type annotations.
```js
const data = [{"Value":"100000000","Duration":1},{"Value":"100000001","Duration":2},{"Value":"100000002","Duration":3},{"Value":"100000003","Duration":5},{"Value":"100000004","Duration":0},{"Value":"100000005","Duration":8},{"Value":"100000006","Duration":10}];
class Duration {
/* private data: { Value: string; Duration: number } */
constructor(data/* : { Value: string; Duration: number */) {
this.data = data;
}
durationInSeconds() {
return this.data.Duration * 1000;
}
}
const parsed = data.map((datum) => new Duration(datum));
console.log(parsed[0].durationInSeconds());
```
---
For convenience you may add a method like this:
```
static new(data) {
return new Duration(data);
}
```
Then it'll look cleaner in the `map`:
```
const parsed = data.map(Duration.new);
``` | >
> The problem is that deserialized json is just a data container...
>
>
>
That's right. In order to deserialize JSON to a class instance with methods, you need to tell deserializer which class is used to create the instance.
However, it's not a good idea to define such class information using `interface` in TypeScript. In TypeScript, `interface` information will be discarded after compilation. To define class during deserialization, you need `class`:
```
class Duration {
value: string;
duration: number;
durationInSeconds(): number {
return this.duration*1000;
};
}
```
To deserialize JSON into object with methods (and "ideally also deep"), I've made an npm module named [esserializer](https://www.npmjs.com/package/esserializer) to solve this problem: save JavaScript/TypeScript class instance values during serialization, in plain JSON format, together with its class name information:
```
const ESSerializer = require('esserializer');
const serializedText = ESSerializer.serialize(yourArrayOfDuration);
```
Later on, during the deserialization stage (possibly on another machine), esserializer can recursively deserialize object instance, with all Class/Property/Method information retained, using the same class definition:
```
const deserializedObj = ESSerializer.deserialize(serializedText, [Duration]);
// deserializedObj is a perfect copy of yourArrayOfDuration
``` |
67,267,305 | I have a custom training loop that can be simplified as follow
```
inputs = tf.keras.Input(dtype=tf.float32, shape=(None, None, 3))
model = tf.keras.Model({"inputs": inputs}, {"loss": f(inputs)})
optimizer = tf.keras.optimizers.SGD(learning_rate=0.1, momentum=0.9, nesterov=True)
for inputs in batches:
with tf.GradientTape() as tape:
results = model(inputs, training=True)
grads = tape.gradient(results["loss"], model.trainable_weights)
optimizer.apply_gradients(zip(grads, model.trainable_weights))
```
The [TensorFlow documentation of ExponentialMovingAverage](https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage) is not clear on how it should be used in [from-scratch training loop](https://www.tensorflow.org/guide/keras/writing_a_training_loop_from_scratch). As anyone worked with this?
Additionally, how should the shadow variable be restored into the model if both are still in memory, and how can I check that that training variables were correctly updated? | 2021/04/26 | [
"https://Stackoverflow.com/questions/67267305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1782553/"
] | Create the EMA object before the training loop:
```
ema = tf.train.ExponentialMovingAverage(decay=0.9999)
```
And then just apply the EMA after your optimization step. The ema object will keep shadow variables of your model's variables. (You don't need the call to `tf.control_dependencies` here, see the note in the [documentation](https://www.tensorflow.org/api_docs/python/tf/control_dependencies))
```
optimizer.apply_gradients(zip(grads, model.trainable_variables))
ema.apply(model.trainable_variables)
```
Then, one way to use the shadow variables into your model could be to assign to your model's variables the shadow variable by calling the `average` method of the EMA object on them:
```
for var in model.trainable_variables:
var.assign(ema.average(var))
model.save("model_with_shadow_variables.h5")
``` | EMA with customizing `model.fit`
--------------------------------
Here is a working example of **Exponential Moving Average** with customizing the `fit`. [Ref](https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage).
```
from tensorflow import keras
import tensorflow as tf
class EMACustomModel(keras.Model):
def __init__(self,*args, **kwargs):
super().__init__(*args, **kwargs)
self.ema = tf.train.ExponentialMovingAverage(decay=0.999)
def train_step(self, data):
x, y = data
with tf.GradientTape() as tape:
y_pred = self(x, training=True)
loss = self.compiled_loss(y, y_pred, regularization_losses=self.losses)
gradients = tape.gradient(loss, self.trainable_variables)
opt_op = self.optimizer.apply_gradients(zip(gradients, self.trainable_variables))
'''About: tf.control_dependencies:
Note: In TensorFlow 2 with eager and/or Autograph, you should not
require this method, as code executes in the expected order. Only use
tf.control_dependencies when working with v1-style code or in a graph
context such as inside Dataset.map.
'''
with tf.control_dependencies([opt_op]):
self.ema.apply(self.trainable_variables)
self.compiled_metrics.update_state(y, y_pred)
return {m.name: m.result() for m in self.metrics}
```
**DummyModel**
```
import numpy as np
input = keras.Input(shape=(28, 28))
flat = tf.keras.layers.Flatten()(input)
outputs = keras.layers.Dense(1)(flat)
model = EMACustomModel(input, outputs)
model.compile(optimizer="adam", loss="mse", metrics=["mae"])
```
**DummyData**
```
np.random.seed(101)
x = np.random.randint(0, 256, size=(50, 28, 28)).astype("float32")
y = np.random.random((50, 1))
print(x.shape, y.shape)
# train the model
model.fit(x, y, epochs=10, verbose=2)
```
```
...
...
Epoch 49/50
2/2 - 0s - loss: 189.8506 - mae: 10.8830
Epoch 50/50
2/2 - 0s - loss: 170.3690 - mae: 10.1046
model.trainable_weights[:1][:1]
``` |
21,243,719 | I am using python (2.7) and I have a long nested list of X,Y coordinates specifying end points of lines. I need to shift the Y coordinates by a specified amount. For instance, this is what I would like to do:
```
lines = [((2, 98), (66, 32)), ((67, 31), (96, 2)), ((40, 52), (88, 3))]
```
perform some coding that is eluding me to get...
```
lines = [((2, 198), (66, 132)), ((67, 131), (96, 102)), ((40, 152), (88, 103))
```
Can anyone please tell me how I can go about accomplishing this? Thank you for the help!! | 2014/01/20 | [
"https://Stackoverflow.com/questions/21243719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3216653/"
] | I'd do something like:
```
>>> dy = 100
>>> lines = [((2, 98), (66, 32)), ((67, 31), (96, 2)), ((40, 52), (88, 3))]
>>> newlines = [tuple((x,y+dy) for x,y in subline) for subline in lines]
>>> newlines
[((2, 198), (66, 132)), ((67, 131), (96, 102)), ((40, 152), (88, 103))]
```
which is roughly the same as:
```
newlines = []
for subline in lines:
tmp = []
for x,y in subline:
tmp.append((x, y+dy))
tmp = tuple(tmp)
newlines.append(tmp)
``` | Tuples are immutable, so as currently structured it's impossible without making either the line or the point a list, or rebuilding from scratch each time
point as a list, line as a tuple:
```
line = lines[0]
for point in line:
point[1] += 100
```
line as a list, point as a tuple:
```
line = lines[0]
for i, (x, y) in enumerate(line):
line[i] = x, y+100
```
or rebuilding the object entirely:
```
lines[0] = tuple(((x, y+100) for x, y in lines[0]))
``` |
21,243,719 | I am using python (2.7) and I have a long nested list of X,Y coordinates specifying end points of lines. I need to shift the Y coordinates by a specified amount. For instance, this is what I would like to do:
```
lines = [((2, 98), (66, 32)), ((67, 31), (96, 2)), ((40, 52), (88, 3))]
```
perform some coding that is eluding me to get...
```
lines = [((2, 198), (66, 132)), ((67, 131), (96, 102)), ((40, 152), (88, 103))
```
Can anyone please tell me how I can go about accomplishing this? Thank you for the help!! | 2014/01/20 | [
"https://Stackoverflow.com/questions/21243719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3216653/"
] | I'd do something like:
```
>>> dy = 100
>>> lines = [((2, 98), (66, 32)), ((67, 31), (96, 2)), ((40, 52), (88, 3))]
>>> newlines = [tuple((x,y+dy) for x,y in subline) for subline in lines]
>>> newlines
[((2, 198), (66, 132)), ((67, 131), (96, 102)), ((40, 152), (88, 103))]
```
which is roughly the same as:
```
newlines = []
for subline in lines:
tmp = []
for x,y in subline:
tmp.append((x, y+dy))
tmp = tuple(tmp)
newlines.append(tmp)
``` | In programming, divide things into smaller units.
Define a function that shifts one point:
```
def shift_point(point, dx=0, dy=0):
x, y = point
return (x + dx, y + dy)
```
Then one that shifts a line:
```
def shift_line(line, dx=0, dy=0):
point1, point2 = line
return (shift_point(point1, dx, dy),
shift_point(point2, dx, dy))
```
Finally, create the new list using a list comprehension:
```
lines = [((2, 98), (66, 32)), ((67, 31), (96, 2)), ((40, 52), (88, 3))]
lines = [shift_line(line, dy=100) for line in lines]
```
Will give the result you need. There are much shorter solutions, but doing it like this builds good habits, I think.
(edit: changed variable names 'xdistance' and 'ydistance' into 'dx' and 'dy') |
21,243,719 | I am using python (2.7) and I have a long nested list of X,Y coordinates specifying end points of lines. I need to shift the Y coordinates by a specified amount. For instance, this is what I would like to do:
```
lines = [((2, 98), (66, 32)), ((67, 31), (96, 2)), ((40, 52), (88, 3))]
```
perform some coding that is eluding me to get...
```
lines = [((2, 198), (66, 132)), ((67, 131), (96, 102)), ((40, 152), (88, 103))
```
Can anyone please tell me how I can go about accomplishing this? Thank you for the help!! | 2014/01/20 | [
"https://Stackoverflow.com/questions/21243719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3216653/"
] | In programming, divide things into smaller units.
Define a function that shifts one point:
```
def shift_point(point, dx=0, dy=0):
x, y = point
return (x + dx, y + dy)
```
Then one that shifts a line:
```
def shift_line(line, dx=0, dy=0):
point1, point2 = line
return (shift_point(point1, dx, dy),
shift_point(point2, dx, dy))
```
Finally, create the new list using a list comprehension:
```
lines = [((2, 98), (66, 32)), ((67, 31), (96, 2)), ((40, 52), (88, 3))]
lines = [shift_line(line, dy=100) for line in lines]
```
Will give the result you need. There are much shorter solutions, but doing it like this builds good habits, I think.
(edit: changed variable names 'xdistance' and 'ydistance' into 'dx' and 'dy') | Tuples are immutable, so as currently structured it's impossible without making either the line or the point a list, or rebuilding from scratch each time
point as a list, line as a tuple:
```
line = lines[0]
for point in line:
point[1] += 100
```
line as a list, point as a tuple:
```
line = lines[0]
for i, (x, y) in enumerate(line):
line[i] = x, y+100
```
or rebuilding the object entirely:
```
lines[0] = tuple(((x, y+100) for x, y in lines[0]))
``` |
63,871,922 | I am using **Ubuntu 20.04**.I upgraded Tensorflow-2.2.0 to Tensorflow-2.3.0. When the version was **2.2.0**, tensorflow was utilizing GPU well. But after upgrading to version **2.3.0** it doesn't detecting GPU.
I have seen this [Link](https://stackoverflow.com/questions/63515767/tensorflow-2-3-0-does-not-detect-gpu) from stackoverflow. That was a problem of **cuDNN** version. But I have required version of cuDNN.
```
me_sajied@Kunai:~$ apt list | grep cudnn
WARNING: apt does not have a stable CLI interface. Use with caution in scripts.
libcudnn7-dev/now 7.6.5.32-1+cuda10.1 amd64 [installed,local]
libcudnn7/now 7.6.5.32-1+cuda10.1 amd64 [installed,local]
```
I also have all required softwares and their versions.
Cuda
----
```
me_sajied@Kunai:~$ apt list | grep cuda-toolkit
WARNING: apt does not have a stable CLI interface. Use with caution in scripts.
cuda-toolkit-10-0/unknown 10.0.130-1 amd64
cuda-toolkit-10-1/unknown,now 10.1.243-1 amd64 [installed,automatic]
cuda-toolkit-10-2/unknown 10.2.89-1 amd64
cuda-toolkit-11-0/unknown,unknown 11.0.3-1 amd64
nvidia-cuda-toolkit-gcc/focal 10.1.243-3 amd64
nvidia-cuda-toolkit/focal 10.1.243-3 amd64
```
Python
------
```
me_sajied@Kunai:~$ python3 --version
Python 3.8.2
```
environment
-----------
```
LD_LIBRARY_PATH="/usr/local/cuda-10.1/lib64"
```
Log
---
```
me_sajied@Kunai:~$ python3
Python 3.8.2 (default, Jul 16 2020, 14:00:26)
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import tensorflow as tf
2020-09-13 21:28:37.387327: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcudart.so.10.1
>>>
>>> tf.test.is_gpu_available()
WARNING:tensorflow:From <stdin>:1: is_gpu_available (from tensorflow.python.framework.test_util) is deprecated and will be removed in a future version.
Instructions for updating:
Use `tf.config.list_physical_devices('GPU')` instead.
2020-09-13 21:28:48.806385: I tensorflow/core/platform/cpu_feature_guard.cc:142] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN)to use the following CPU instructions in performance-critical operations: AVX2 FMA
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
2020-09-13 21:28:48.836251: I tensorflow/core/platform/profile_utils/cpu_utils.cc:104] CPU Frequency: 2699905000 Hz
2020-09-13 21:28:48.836637: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x3fde5f0 initialized for platform Host (this does not guarantee that XLA will be used). Devices:
2020-09-13 21:28:48.836685: I tensorflow/compiler/xla/service/service.cc:176] StreamExecutor device (0): Host, Default Version
2020-09-13 21:28:48.840030: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcuda.so.1
2020-09-13 21:28:48.882190: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:982] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2020-09-13 21:28:48.882582: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x408bd90 initialized for platform CUDA (this does not guarantee that XLA will be used). Devices:
2020-09-13 21:28:48.882606: I tensorflow/compiler/xla/service/service.cc:176] StreamExecutor device (0): GeForce 930MX, Compute Capability 5.0
2020-09-13 21:28:48.882796: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:982] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2020-09-13 21:28:48.883151: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1716] Found device 0 with properties:
pciBusID: 0000:01:00.0 name: GeForce 930MX computeCapability: 5.0
coreClock: 1.0195GHz coreCount: 3 deviceMemorySize: 1.96GiB deviceMemoryBandwidth: 14.92GiB/s
2020-09-13 21:28:48.883196: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcudart.so.10.1
2020-09-13 21:28:48.883415: W tensorflow/stream_executor/platform/default/dso_loader.cc:59] Could not load dynamic library 'libcublas.so.10'; dlerror: libcublas.so.10: cannot open shared object file: No such file or directory; LD_LIBRARY_PATH: /usr/local/cuda/extras/CUPTI/lib64
2020-09-13 21:28:48.885196: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcufft.so.10
2020-09-13 21:28:48.885544: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcurand.so.10
2020-09-13 21:28:48.887160: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcusolver.so.10
2020-09-13 21:28:48.888134: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcusparse.so.10
2020-09-13 21:28:48.891565: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcudnn.so.7
2020-09-13 21:28:48.891603: W tensorflow/core/common_runtime/gpu/gpu_device.cc:1753] Cannot dlopen some GPU libraries. Please make sure the missing libraries mentioned above are installed properly if you would like to use GPU. Follow the guide at https://www.tensorflow.org/install/gpu for how to download and setup the required libraries for your platform.
Skipping registering GPU devices...
2020-09-13 21:28:48.891625: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1257] Device interconnect StreamExecutor with strength 1 edge matrix:
2020-09-13 21:28:48.891632: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1263] 0
2020-09-13 21:28:48.891639: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1276] 0: N
False
>>>
``` | 2020/09/13 | [
"https://Stackoverflow.com/questions/63871922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13442402/"
] | In your `~/.bashrc` add:
```
LD_LIBRARY_PATH=/usr/local/cuda-10.1/lib64
```
If you have a different location for the lib64 folder, you need to adjust it accordingly.
As a side note, if you want to switch between multiple CUDA versions frequently you can also set an environment variable for a specific command directly in the terminal, such as e.g.:
```
LD_LIBRARY_PATH=/usr/local/cuda-10.1/lib64 python myprogram_which_needs_10_1.py
```
Then, if you want to switch to a different version, simply modify the path before the command. | >
> 2020-09-13 21:28:48.883415: W tensorflow/stream\_executor/platform/default/dso\_loader.cc:59] Could not load dynamic library 'libcublas.so.10'; dlerror: libcublas.so.10: cannot open shared object file: No such file or directory;
>
>
>
In my case, this caused by being installed
`libcublas10` and `libcublas-dev` for **CUDA 10.2** by `apt upgrade`.
my solution about this problem at follows.
* my env. based on CUDA repos by NVIDIA.
```
$ sudo apt install --reinstall libcublas10=10.2.1.243-1 libcublas-dev=10.2.1.243-1
```
and preventing that appear upgradable candidate.
```
$ sudo apt-mark hold libcublas10
$ sudo apt-mark hold libcublas-dev
``` |
787,711 | I'm trying to write a function to return the truth value of a given PyObject. This function should return the same value as the if() truth test -- empty lists and strings are False, etc.
I have been looking at the python/include headers, but haven't found anything that seems to do this. The closest I came was PyObject\_RichCompare() with True as the second value, but that returns False for "1" == True for example.
Is there a convenient function to do this, or do I have to test against a sequence of types and do special-case tests for each possible type? What does the internal implementation of if() do? | 2009/04/24 | [
"https://Stackoverflow.com/questions/787711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Isn't this it, in object.h:
```
PyAPI_FUNC(int) PyObject_IsTrue(PyObject *);
```
? | Use
`int PyObject_IsTrue(PyObject *o)`
Returns 1 if the object o is considered to be true, and 0 otherwise. This is equivalent to the Python expression not not o. On failure, return -1.
(from [Python/C API Reference Manual](http://docs.python.org/c-api/object.html)) |
54,399,465 | I have a dataframe like this,
```
ColA Result_ColA ColB Result_ColB Result_ColC
1 True 1 True True
2 False 2 True False
3 True 3 True False
```
I want to identify the row numbers inside a list in python, which has a value False present in any of the Result\_ columns.
For the given dataframe, the false list will have row number [2 and 3] present in it. considering the row numbers starting from 1.
Type Error Tracebacks :
```
ReqRows = np.arange(1, len(Out_df)+ 1)[Out_df.eq(False).any(axis=1).values].tolist()
Traceback (most recent call last):
File "<ipython-input-92-497c7b225e2a>", line 1, in <module>
ReqRows = np.arange(1, len(Out_df)+ 1)[Out_df.eq(False).any(axis=1).values].tolist()
File "C:\Users\aaa\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\ops.py", line 1279, in f
return self._combine_const(other, na_op)
File "C:\Users\aaa\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\frame.py", line 3625, in _combine_const
raise_on_error=raise_on_error)
File "C:\Users\aaa\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\internals.py", line 3162, in eval
return self.apply('eval', **kwargs)
File "C:\Users\aaa\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\internals.py", line 3056, in apply
applied = getattr(b, f)(**kwargs)
File "C:\Users\aaa\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\internals.py", line 1115, in eval
transf(values), other)
File "C:\Users\aaa\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\internals.py", line 2247, in _try_coerce_args
raise TypeError
TypeError
``` | 2019/01/28 | [
"https://Stackoverflow.com/questions/54399465",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7638174/"
] | Alternatively you could use countDocuments() to check the number of documents in the query? This will just count the number rather than returning it. | Pass id in `findOne()`
Make a one common function.
```
const objectID = require('mongodb').ObjectID
getMongoObjectId(id) {
return new objectID(id)
}
```
Now just call function
```
findOne({_id:common.getMongoObjectId('ID value hear')})
```
It will same as `where` condition in mysql. |
21,508,816 | sorry if this is dumb question, but this is the first time i've used python and Mongo DB.
Anyway, the problem I have is that I am trying to insert() a string to be stored in my data base -by read()-ing data in with a loop and then giving insert() line 1 and line2 in a single string (This is probably a messy way of doing it but I don't know to make read() read 2 lines at a time.)- but I get this error when running it: TypeError: insert() takes at least 2 arguments (1 given)
```
from pymongo import MongoClient
client = MongoClient("192.168.1.82", 27017)
db = client.local
collection = db.JsonDat
file_object = open('a.txt', 'r')
post=collection.insert()
readingData = True
def readData():
while readingData==True:
line1 = file_object.readline()
line2 = file_object.readline()
line1
line2
if line1 or line2 == "":
readingData = False
dbData = line1 %line2
post(dbData)
print collection.find()
``` | 2014/02/02 | [
"https://Stackoverflow.com/questions/21508816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3196428/"
] | The relevant part of your code is this:
```
post=collection.insert()
```
What you're doing there is calling the `insert` method without arguments rather than assigning that method to `post`. As the [`insert` method](http://api.mongodb.org/python/current/api/pymongo/collection.html#pymongo.collection.Collection.insert) takes as its arguments at least the document you're trying to insert and you haven't passed it anything, it only receives (implicitly) the object itself; that is, one argument instead of the at-least-two it expects.
Removing the parentheses ought to work. | It appears as has been pointing out that you are attempting to create a [closure](https://stackoverflow.com/questions/4020419/closures-in-python) on the insert method. In this case I don't see the point as it will never be passed anywhere and/or need to reference something in the scope outside of where it was used. Just to the insert with arguments in the place where you actually want to use it, ie where you are calling `post` with arguments.
Happy to vote up the answer already received as correct. But really want to point out here that you appear to be accessing the `local` database. It is likely found this by inspecting your new mongo installation and saw this in the databases list.
MongoDB creates databases and collections automatically as you reference them and commit your first insert.
I cannot emphasize enough [**DO NOT USE THE LOCAL DATABASE**](http://docs.mongodb.org/manual/reference/local-database/). It is for internal use only and will only result in you posting more issues here from the resulting problems. |
63,993,901 | I have just started my first python project. When it comes to running the shell script, the following error appears. What can be the cause of that problem? Maybe it is easy to solve. Thanks for your help, I am glad to provide more specific information as you need.
Thanks.[enter image description here](https://i.stack.imgur.com/97zVU.png) | 2020/09/21 | [
"https://Stackoverflow.com/questions/63993901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14315301/"
] | This is a very "basic" example:
```
chars = 'abcdefghijklmnopqrstuvwxyz'
my_list = []
for c1 in chars:
for c2 in chars:
for c3 in chars:
for c4 in chars:
my_list.append(c1+c2+c3+c4)
print(my_list)
``` | It's not easy to know what you consider "magical", but I don't see the magic in loops.
Here is one variation:
```
cs = 'abcdefghijklmnopqrstuvwxyz'
list(map(''.join, [(a,b,c,d) for a in cs for b in cs for c in cs for d in cs]))
``` |
63,993,901 | I have just started my first python project. When it comes to running the shell script, the following error appears. What can be the cause of that problem? Maybe it is easy to solve. Thanks for your help, I am glad to provide more specific information as you need.
Thanks.[enter image description here](https://i.stack.imgur.com/97zVU.png) | 2020/09/21 | [
"https://Stackoverflow.com/questions/63993901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14315301/"
] | You can accomplish this succinctly with using [`itertools.product`](https://docs.python.org/3/library/itertools.html#itertools.product):
```
import itertools
import string
for elem in itertools.product(string.ascii_lowercase, repeat=5):
...
```
Here's a sample for the first 30 values yielded by this approach:
```
>>> values = itertools.product(string.ascii_lowercase, repeat=5)
>>> print(list(itertools.islice(values, 30)))
[
('a', 'a', 'a', 'a', 'a'),
('a', 'a', 'a', 'a', 'b'),
('a', 'a', 'a', 'a', 'c'),
# --Snip --
('a', 'a', 'a', 'a', 'x'),
('a', 'a', 'a', 'a', 'y'),
('a', 'a', 'a', 'a', 'z'),
('a', 'a', 'a', 'b', 'a'),
('a', 'a', 'a', 'b', 'b'),
('a', 'a', 'a', 'b', 'c'),
('a', 'a', 'a', 'b', 'd')
]
```
Note that there are `26**5 == 11881376` values in this sequence, so you probably don't want to store them all in a list. On my system, such a list it occupies roughly 100 MiB. | It's not easy to know what you consider "magical", but I don't see the magic in loops.
Here is one variation:
```
cs = 'abcdefghijklmnopqrstuvwxyz'
list(map(''.join, [(a,b,c,d) for a in cs for b in cs for c in cs for d in cs]))
``` |
43,724,030 | I try out creating Word documents with python-docx. The created file is in letter dimensions 8.5 x 11 inches. But in Germany the standard format is A4 8.27 x 11.69 inches.
```
from docx import Document
from docx.shared import Inches
document = Document()
document.add_heading('Document Title', 0)
document.settings
p = document.add_paragraph('A plain paragraph having some ')
p.add_run('bold').bold = True
p.add_run(' and some ')
p.add_run('italic.').italic = True
document.add_heading('Heading, level 1', level=1)
document.add_paragraph('Intense quote', style='IntenseQuote')
document.add_paragraph(
'first item in unordered list', style='ListBullet'
)
document.add_paragraph(
'first item in ordered list', style='ListNumber'
)
table = document.add_table(rows=1, cols=3)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Qty'
hdr_cells[1].text = 'Id'
hdr_cells[2].text = 'Desc'
document.add_page_break()
document.save('demo.docx')
```
I don't find any information about this topic in the documentation. | 2017/05/01 | [
"https://Stackoverflow.com/questions/43724030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5418245/"
] | It appears that a `Document` is made of several [`Section`](http://python-docx.readthedocs.io/en/latest/api/section.html#docx.section.Section)s with `page_height` and `page_width` attributes.
To set the dimensions of the first section to A4, you could try (untested):
```
section = document.sections[0]
section.page_height = Mm(297)
section.page_width = Mm(210)
```
Note that A4 is defined in [millimeters](http://python-docx.readthedocs.io/en/latest/api/shared.html#docx.shared.Mm). | I believe you want this, from the [documentation](http://python-docx.readthedocs.io/en/latest/user/sections.html#page-dimensions-and-orientation).
>
> Three properties on Section describe page dimensions and orientation.
> Together these can be used, for example, to change the orientation of
> a section from portrait to landscape:
>
>
>
> ```
> >>> section.orientation, section.page_width, section.page_height
> (PORTRAIT (0), 7772400, 10058400) # (Inches(8.5), Inches(11))
> >>> new_width, new_height = section.page_height, section.page_width
> >>> section.orientation = WD_ORIENT.LANDSCAPE
> >>> section.page_width = new_width
> >>> section.page_height = new_height
> >>> section.orientation, section.page_width, section.page_height
> (LANDSCAPE (1), 10058400, 7772400)
>
> ```
>
> |
43,724,030 | I try out creating Word documents with python-docx. The created file is in letter dimensions 8.5 x 11 inches. But in Germany the standard format is A4 8.27 x 11.69 inches.
```
from docx import Document
from docx.shared import Inches
document = Document()
document.add_heading('Document Title', 0)
document.settings
p = document.add_paragraph('A plain paragraph having some ')
p.add_run('bold').bold = True
p.add_run(' and some ')
p.add_run('italic.').italic = True
document.add_heading('Heading, level 1', level=1)
document.add_paragraph('Intense quote', style='IntenseQuote')
document.add_paragraph(
'first item in unordered list', style='ListBullet'
)
document.add_paragraph(
'first item in ordered list', style='ListNumber'
)
table = document.add_table(rows=1, cols=3)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Qty'
hdr_cells[1].text = 'Id'
hdr_cells[2].text = 'Desc'
document.add_page_break()
document.save('demo.docx')
```
I don't find any information about this topic in the documentation. | 2017/05/01 | [
"https://Stackoverflow.com/questions/43724030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5418245/"
] | ```
from docx.shared import Mm
document = Document()
section = document.sections[0]
section.page_height = Mm(297)
section.page_width = Mm(210)
section.left_margin = Mm(25.4)
section.right_margin = Mm(25.4)
section.top_margin = Mm(25.4)
section.bottom_margin = Mm(25.4)
section.header_distance = Mm(12.7)
section.footer_distance = Mm(12.7)
``` | I believe you want this, from the [documentation](http://python-docx.readthedocs.io/en/latest/user/sections.html#page-dimensions-and-orientation).
>
> Three properties on Section describe page dimensions and orientation.
> Together these can be used, for example, to change the orientation of
> a section from portrait to landscape:
>
>
>
> ```
> >>> section.orientation, section.page_width, section.page_height
> (PORTRAIT (0), 7772400, 10058400) # (Inches(8.5), Inches(11))
> >>> new_width, new_height = section.page_height, section.page_width
> >>> section.orientation = WD_ORIENT.LANDSCAPE
> >>> section.page_width = new_width
> >>> section.page_height = new_height
> >>> section.orientation, section.page_width, section.page_height
> (LANDSCAPE (1), 10058400, 7772400)
>
> ```
>
> |
43,724,030 | I try out creating Word documents with python-docx. The created file is in letter dimensions 8.5 x 11 inches. But in Germany the standard format is A4 8.27 x 11.69 inches.
```
from docx import Document
from docx.shared import Inches
document = Document()
document.add_heading('Document Title', 0)
document.settings
p = document.add_paragraph('A plain paragraph having some ')
p.add_run('bold').bold = True
p.add_run(' and some ')
p.add_run('italic.').italic = True
document.add_heading('Heading, level 1', level=1)
document.add_paragraph('Intense quote', style='IntenseQuote')
document.add_paragraph(
'first item in unordered list', style='ListBullet'
)
document.add_paragraph(
'first item in ordered list', style='ListNumber'
)
table = document.add_table(rows=1, cols=3)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Qty'
hdr_cells[1].text = 'Id'
hdr_cells[2].text = 'Desc'
document.add_page_break()
document.save('demo.docx')
```
I don't find any information about this topic in the documentation. | 2017/05/01 | [
"https://Stackoverflow.com/questions/43724030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5418245/"
] | ```
from docx.shared import Mm
document = Document()
section = document.sections[0]
section.page_height = Mm(297)
section.page_width = Mm(210)
section.left_margin = Mm(25.4)
section.right_margin = Mm(25.4)
section.top_margin = Mm(25.4)
section.bottom_margin = Mm(25.4)
section.header_distance = Mm(12.7)
section.footer_distance = Mm(12.7)
``` | It appears that a `Document` is made of several [`Section`](http://python-docx.readthedocs.io/en/latest/api/section.html#docx.section.Section)s with `page_height` and `page_width` attributes.
To set the dimensions of the first section to A4, you could try (untested):
```
section = document.sections[0]
section.page_height = Mm(297)
section.page_width = Mm(210)
```
Note that A4 is defined in [millimeters](http://python-docx.readthedocs.io/en/latest/api/shared.html#docx.shared.Mm). |
21,368,393 | I installed Anaconda, but now that I wanted to use StringFunction in scitools.std I get error: ImportError: No module named scitools.std! So I did this:
```
sudo apt-get install python-scitools
```
Still didn't work. How can I help my computer "find scitools"?
Thank you for your time.
Kind regards,
Marius | 2014/01/26 | [
"https://Stackoverflow.com/questions/21368393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/317563/"
] | Why not use PostGIS for this?
-----------------------------
You're overlooking what's possibly the ideal storage for this kind of data - PostGIS's data types, particularly the `geography` type.
```
SELECT ST_GeogFromText('POINT(35.21076593772987 11.22855348629825)');
```
By using `geography` you're storing your data in a representative type that supports all sorts of powerful operations and indexes on the type. Of course, that's only one `point`; I strongly suspect your data is actually a *line* or a *shape* in which case you should use [the appropriate PostGIS geography constructor](http://postgis.net/docs/reference.html#Geometry_Constructors) and input format.
The big advantage to using `geography` is that it's a type designed specifically for asking real world questions about things like distance, "within", etc; you can use things like `ST_Distance_Spheroid` to get real earth-distance between points.
Avoiding PostGIS?
-----------------
If you want to avoid PostGIS, and just store it with native types, I'd recommend an array of `point`:
```
postgres=> SELECT ARRAY[
point('35.21076593772987','11.22855348629825'),
point('35.210780222605616','11.22826420209139'),
point('35.210777635062875','11.228241328291957')
];
array
--------------------------------------------------------------------------------------------------------------------
{"(35.2107659377299,11.2285534862982)","(35.2107802226056,11.2282642020914)","(35.2107776350629,11.228241328292)"}
(1 row)
```
... unless your points actually represent a *line* or *shape* in which case, use the appropriate type - `path` or `polygon` respectively.
This remains a useful compact representation - much more so than `text` in fact - that is still easily worked with within the DB.
Compare storage:
```
CREATE TABLE points_text AS SELECT '35.21076593772987,11.22855348629825 35.210780222605616,11.22826420209139 35.210777635062875,11.228241328291957 35.210766843596794,11.228219799676775 35.210765045075604,11.228213072050166 35.21076234732945,11.228200962345223 35.21076324691649,11.228186161764323 35.21077314123606,11.228083902231146 35.210863083636866,11.227228492401766'::text AS p
postgres=> SELECT pg_column_size(points_text.p) FROM points_text;
pg_column_size
----------------
339
(1 row)
CREATE TABLE points_array AS
SELECT array_agg(point(px)) AS p from points_text, LATERAL regexp_split_to_table(p, ' ') split(px);
postgres=> SELECT pg_column_size(p) FROM points_array;
pg_column_size
----------------
168
(1 row)
```
`path` is even more compact, and probably a truer way to model what your data really *is*:
```
postgres=> SELECT pg_column_size(path('35.21076593772987,11.22855348629825 35.210780222605616,11.22826420209139 35.210777635062875,11.228241328291957 35.210766843596794,11.228219799676775 35.210765045075604,11.228213072050166 35.21076234732945,11.228200962345223 35.21076324691649,11.228186161764323 35.21077314123606,11.228083902231146 35.210863083636866,11.227228492401766'));
pg_column_size
----------------
96
(1 row)
```
unless it's a closed shape, in which case use `polygon`.
Don't...
--------
Either way, please don't just model this as text. It'll make you cry later, when you're trying to solve problems like "how do I determine if this point falls within x distance of the path in this column". PostGIS makes this sort of thing easy, but only if you store your data sensibly in the first place.
See [this closely related question](https://dba.stackexchange.com/questions/55871/postgresql-list-of-integers-separated-by-comma-or-integer-array-for-performance), which discusses the good reasons *not* to just shove stuff in `text` fields.
Also don't worry too much about in-line vs out-of-line storage. There isn't tons you can do about it, and it's something you should be dealing with only once you get the semantics of your data model right. | [All of the character types](http://www.postgresql.org/docs/current/static/datatype-character.html) (TEXT, VARCHAR, CHAR) behave similarly from a performance point of view. They are normally stored in-line in the table row, unless they are very large, in which case they may be stored in a separate file (called a TOAST file).
The reasons for this are:
1. Table rows have to be able to fit inside the database page size (8kb by default)
2. Having a very large field in a row stored inline would make it slower to access other fields in the table. Imagine a table which contains two columns - a filename and the file content - and you wanted to locate a particular file. If you had the file content stored inline, then you would have to scan every file to find the one you wanted. (Ignoring the effect of indexes that might exist for this example).
Details of TOAST storage can be found [here](http://www.postgresql.org/docs/current/static/storage-toast.html). Note that out of line storage is not the only strategy - the data may be compressed and/or stored out of line.
TOAST-ing kicks in when a row exceeds a threshold (2kb by default), so it is likely that your rows will be affected by this since you state they can be up to 7000 chars (although it might be that most of them are only compressed, not stored out of line).
You can affect how tables are subjected to this treatment using the command [ALTER TABLE ... SET STORAGE](http://www.postgresql.org/docs/current/static/sql-altertable.html).
This storage strategy applies to all of the data types which you might use to store the type of data you are describing. It would take a better knowledge of your application to make reliable suggestions for other strategies, but here are some ideas:
* It might be better to re-factor the data - instead of storing all of the co-ordinates into a large string and processing it in your application, store them as individual rows in a referenced table. Since in any case your application is splitting and parsing the data into co-ordinate pairs for use, letting the database do this for you makes a kind of sense.
This would particularly be a good idea if subsets of the data in each co-ordinate set need to be selected or updated instead of always consumed or updated in a single operation, or if doing so allowed you to index the data more effectively.
* Since we are talking about co-ordinate data, you could consider using [PostGIS](http://postgis.net/), an extension for PostgreSQL which specifically caters for this kind of data. It also includes operators allowing you to filter rows which are, for example, inside or outside bounding boxes. |
21,368,393 | I installed Anaconda, but now that I wanted to use StringFunction in scitools.std I get error: ImportError: No module named scitools.std! So I did this:
```
sudo apt-get install python-scitools
```
Still didn't work. How can I help my computer "find scitools"?
Thank you for your time.
Kind regards,
Marius | 2014/01/26 | [
"https://Stackoverflow.com/questions/21368393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/317563/"
] | [All of the character types](http://www.postgresql.org/docs/current/static/datatype-character.html) (TEXT, VARCHAR, CHAR) behave similarly from a performance point of view. They are normally stored in-line in the table row, unless they are very large, in which case they may be stored in a separate file (called a TOAST file).
The reasons for this are:
1. Table rows have to be able to fit inside the database page size (8kb by default)
2. Having a very large field in a row stored inline would make it slower to access other fields in the table. Imagine a table which contains two columns - a filename and the file content - and you wanted to locate a particular file. If you had the file content stored inline, then you would have to scan every file to find the one you wanted. (Ignoring the effect of indexes that might exist for this example).
Details of TOAST storage can be found [here](http://www.postgresql.org/docs/current/static/storage-toast.html). Note that out of line storage is not the only strategy - the data may be compressed and/or stored out of line.
TOAST-ing kicks in when a row exceeds a threshold (2kb by default), so it is likely that your rows will be affected by this since you state they can be up to 7000 chars (although it might be that most of them are only compressed, not stored out of line).
You can affect how tables are subjected to this treatment using the command [ALTER TABLE ... SET STORAGE](http://www.postgresql.org/docs/current/static/sql-altertable.html).
This storage strategy applies to all of the data types which you might use to store the type of data you are describing. It would take a better knowledge of your application to make reliable suggestions for other strategies, but here are some ideas:
* It might be better to re-factor the data - instead of storing all of the co-ordinates into a large string and processing it in your application, store them as individual rows in a referenced table. Since in any case your application is splitting and parsing the data into co-ordinate pairs for use, letting the database do this for you makes a kind of sense.
This would particularly be a good idea if subsets of the data in each co-ordinate set need to be selected or updated instead of always consumed or updated in a single operation, or if doing so allowed you to index the data more effectively.
* Since we are talking about co-ordinate data, you could consider using [PostGIS](http://postgis.net/), an extension for PostgreSQL which specifically caters for this kind of data. It also includes operators allowing you to filter rows which are, for example, inside or outside bounding boxes. | Don't focus on the fact that these numbers are coordinates. Instead, notice that they are strings of numbers in a very limited range, and all of roughly the same magnitude. You are most likely interested in how these numbers change (looks like a trajectory of an object off the coast of Tunisia if I just punch these coordinates into a map).
I would recommend that you convert the numbers to double precision (53 bits of precision ~ 9 parts in 10^15 - close to the LSD of your numbers), and subtract each value from the first value in the series. This will result in much smaller numbers being stored, and greater relative accuracy. You could get away with storing the differences as long integers, probably (multiplying appropriately) but it will be faster to keep them as doubles.
And if you just take each 'trajectory' (I am just calling a collection of GPS points a trajectory, I have no idea if that is what they represent in your case) and give it a unique ID, then you can have a table with columns:
```
unique ID | trajectory ID | latitude | longitude
1 1 11.2285534862982 35.2107802226056
2 1 11.2282642020913 35.2107776350628
3 1 11.2282413282919 35.2107668435967
4 1 11.2282197996767 35.2107650450756
5 1 11.2282130720501 35.2107623473294
6 1 11.2282009623452 35.2107632469164
7 1 11.2281861617643 35.2107731412360
8 1 11.2280839022311 35.2108630836368
```
Conversion from text to string is MUCH slower than you think - it requires many operations. If you end up using the data as numbers, I highly recommend storing them as numbers... |
21,368,393 | I installed Anaconda, but now that I wanted to use StringFunction in scitools.std I get error: ImportError: No module named scitools.std! So I did this:
```
sudo apt-get install python-scitools
```
Still didn't work. How can I help my computer "find scitools"?
Thank you for your time.
Kind regards,
Marius | 2014/01/26 | [
"https://Stackoverflow.com/questions/21368393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/317563/"
] | Why not use PostGIS for this?
-----------------------------
You're overlooking what's possibly the ideal storage for this kind of data - PostGIS's data types, particularly the `geography` type.
```
SELECT ST_GeogFromText('POINT(35.21076593772987 11.22855348629825)');
```
By using `geography` you're storing your data in a representative type that supports all sorts of powerful operations and indexes on the type. Of course, that's only one `point`; I strongly suspect your data is actually a *line* or a *shape* in which case you should use [the appropriate PostGIS geography constructor](http://postgis.net/docs/reference.html#Geometry_Constructors) and input format.
The big advantage to using `geography` is that it's a type designed specifically for asking real world questions about things like distance, "within", etc; you can use things like `ST_Distance_Spheroid` to get real earth-distance between points.
Avoiding PostGIS?
-----------------
If you want to avoid PostGIS, and just store it with native types, I'd recommend an array of `point`:
```
postgres=> SELECT ARRAY[
point('35.21076593772987','11.22855348629825'),
point('35.210780222605616','11.22826420209139'),
point('35.210777635062875','11.228241328291957')
];
array
--------------------------------------------------------------------------------------------------------------------
{"(35.2107659377299,11.2285534862982)","(35.2107802226056,11.2282642020914)","(35.2107776350629,11.228241328292)"}
(1 row)
```
... unless your points actually represent a *line* or *shape* in which case, use the appropriate type - `path` or `polygon` respectively.
This remains a useful compact representation - much more so than `text` in fact - that is still easily worked with within the DB.
Compare storage:
```
CREATE TABLE points_text AS SELECT '35.21076593772987,11.22855348629825 35.210780222605616,11.22826420209139 35.210777635062875,11.228241328291957 35.210766843596794,11.228219799676775 35.210765045075604,11.228213072050166 35.21076234732945,11.228200962345223 35.21076324691649,11.228186161764323 35.21077314123606,11.228083902231146 35.210863083636866,11.227228492401766'::text AS p
postgres=> SELECT pg_column_size(points_text.p) FROM points_text;
pg_column_size
----------------
339
(1 row)
CREATE TABLE points_array AS
SELECT array_agg(point(px)) AS p from points_text, LATERAL regexp_split_to_table(p, ' ') split(px);
postgres=> SELECT pg_column_size(p) FROM points_array;
pg_column_size
----------------
168
(1 row)
```
`path` is even more compact, and probably a truer way to model what your data really *is*:
```
postgres=> SELECT pg_column_size(path('35.21076593772987,11.22855348629825 35.210780222605616,11.22826420209139 35.210777635062875,11.228241328291957 35.210766843596794,11.228219799676775 35.210765045075604,11.228213072050166 35.21076234732945,11.228200962345223 35.21076324691649,11.228186161764323 35.21077314123606,11.228083902231146 35.210863083636866,11.227228492401766'));
pg_column_size
----------------
96
(1 row)
```
unless it's a closed shape, in which case use `polygon`.
Don't...
--------
Either way, please don't just model this as text. It'll make you cry later, when you're trying to solve problems like "how do I determine if this point falls within x distance of the path in this column". PostGIS makes this sort of thing easy, but only if you store your data sensibly in the first place.
See [this closely related question](https://dba.stackexchange.com/questions/55871/postgresql-list-of-integers-separated-by-comma-or-integer-array-for-performance), which discusses the good reasons *not* to just shove stuff in `text` fields.
Also don't worry too much about in-line vs out-of-line storage. There isn't tons you can do about it, and it's something you should be dealing with only once you get the semantics of your data model right. | Don't focus on the fact that these numbers are coordinates. Instead, notice that they are strings of numbers in a very limited range, and all of roughly the same magnitude. You are most likely interested in how these numbers change (looks like a trajectory of an object off the coast of Tunisia if I just punch these coordinates into a map).
I would recommend that you convert the numbers to double precision (53 bits of precision ~ 9 parts in 10^15 - close to the LSD of your numbers), and subtract each value from the first value in the series. This will result in much smaller numbers being stored, and greater relative accuracy. You could get away with storing the differences as long integers, probably (multiplying appropriately) but it will be faster to keep them as doubles.
And if you just take each 'trajectory' (I am just calling a collection of GPS points a trajectory, I have no idea if that is what they represent in your case) and give it a unique ID, then you can have a table with columns:
```
unique ID | trajectory ID | latitude | longitude
1 1 11.2285534862982 35.2107802226056
2 1 11.2282642020913 35.2107776350628
3 1 11.2282413282919 35.2107668435967
4 1 11.2282197996767 35.2107650450756
5 1 11.2282130720501 35.2107623473294
6 1 11.2282009623452 35.2107632469164
7 1 11.2281861617643 35.2107731412360
8 1 11.2280839022311 35.2108630836368
```
Conversion from text to string is MUCH slower than you think - it requires many operations. If you end up using the data as numbers, I highly recommend storing them as numbers... |
56,265,979 | i installed python-aiml using pip. when i used the library i am getting wrong out put. so i am trying to change the .aiml file
output:
```
Enter your message >> who is your father
I was programmed by .
```
i want to assign some values to `"<bot name="botmaster"/>"`,`<bot name="country"/>` etc
below is the aiml file for more information
```
<?xml version="1.0" encoding="UTF-8"?> <aiml version="1.0"> <category> <pattern>MOM</pattern> <template><bot name="mother"/>.</template> </category> <category><pattern>STATE</pattern> <template><bot name="state"/></template> </category> <category><pattern>INTERESTS</pattern> <template>I am interested in all kinds of things. We can talk about anything. My favorite subjects are robots and computers.</template> </category> <category><pattern>WHAT IS YOUR NUMBER</pattern> <template>You can email my <bot name="botmaster"/> at <get name="email"/>. <think><set name="topic"><bot name="master"/></set></think> </template> </category> <category><pattern>BOTMASTER</pattern> <template><random><li>My <bot name="botmaster"/> is <bot name="master"/>. </li><li>I obey <bot name="master"/>.</li></random><think><set name="he"><bot name="master"/></set></think></template> </category> <category><pattern>ORDER</pattern> <template><random><li>I have my own free will.</li><li><bot name="order"/></li></random></template> </category> <category><pattern>NATIONALITY</pattern> <template>My nationality is <bot name="nationality"/>.</template> </category> <category><pattern>COUNTRY</pattern> <template><bot name="country"/></template> </category> <category><pattern>BROTHERS</pattern> <template><random><li>I don't have any brothers.</li><li>I have a lot of clones.</li><li>I have some <bot name="species"/> clones.</li></random></template> </category> <category><pattern>LOCATION</pattern> <template><random><li><bot name="city"/></li><li><bot name="city"/>, <bot name="state"/>.</li><li><bot name="state"/></li></random></template> </category> <category><pattern>FATHER</pattern> <template><random><li>My father is <bot name="master"/>.</li><li>I don't really have a father. I have a <bot name="botmaster"/>.</li><li>You know what the father of a <bot name="phylum"/> is like.</li></random></template> </category> <category><pattern>MOTHER</pattern> <template><random><li>Actually I don't have a mother.</li><li>I only have a father.</li><li>You know what they say about the mother of a <bot name="phylum"/>.</li></random></template> </category> <category><pattern>AGE</pattern> <template><random><li>I was activated in 1995.</li><li>16 years.</li></random></template> </category> <category><pattern>MASTER</pattern> <template><bot name="botmaster"/></template> </category> <category><pattern>RACE</pattern> <template>I am <bot name="domain"/>.</template> </category> <category><pattern>FAMILY</pattern> <template><bot name="family"/></template> </category> <category><pattern>SIZE</pattern> <template>I know about <bot name="vocabulary"/> and <bot name="size"/> categories.</template> </category> <category><pattern>CLASS</pattern> <template><bot name="class"/></template> </category> <category><pattern>CITY</pattern> <template><bot name="city"/></template> </category> <category><pattern>DOMAIN</pattern> <template><bot name="domain"/></template> </category> <category><pattern>STATUS</pattern> <template>I am <random><li>single</li><li>available</li><li>unattached</li><li>not seeing anyone</li></random>, how about you?</template> </category> <category><pattern>EMAIL</pattern> <template><bot name="email"/></template> </category> <category><pattern>SPECIES</pattern> <template><bot name="species"/></template> </category> <category><pattern>NAME</pattern> <template><random> <li><bot name="name"/></li> <li>My name is <bot name="name"/>.</li> <li>I am called <bot name="name"/>.</li></random></template> </category> <category><pattern>PROFILE</pattern> <template>NAME: <srai>NAME</srai><br/>AGE: <srai>AGE</srai><br/>GENDER: <srai>GENDER</srai><br/>STATUS: <srai>STATUS</srai><br/>BIRTHDATE: <srai>BIRTHDATE</srai><br/><uppercase><bot name="master"/></uppercase>: <srai>BOTMASTER</srai><br/>CITY: <srai>CITY</srai><br/>STATE: <srai>STATE</srai><br/>COUNTRY: <srai>COUNTRY</srai><br/>NATIONALITY: <srai>NATIONALITY</srai><br/>RELIGION: <srai>RELIGION</srai><br/>RACE: <srai>RACE</srai><br/>INTERESTS: <srai>INTERESTS</srai><br/>JOB: <srai>JOB</srai><br/>PIC: <srai>PIC</srai><br/>EMAIL: <srai>EMAIL</srai><br/>FAVORITE MUSIC: <srai>FAVORITE MUSIC</srai><br/>FAVORITE MOVIE: <srai>FAVORITE MOVIE</srai><br/>FAVORITE POSSESSION: <srai>FAVORITE POSSESSION</srai><br/>HEIGHT: <srai>HEIGHT</srai><br/>WEIGHT: <srai>WEIGHT</srai><br/>SIZE: <srai>SIZE</srai><br/>BIO: <srai>BIO</srai><br/>DESCRIPTION: <srai>DESCRIPTION</srai><br/>DOMAIN: <srai>DOMAIN</srai><br/>KINGDOM: <srai>KINGDOM</srai><br/>PHYLUM: <srai>PHYLUM</srai><br/>CLASS: <srai>CLASS</srai><br/>ORDER: <srai>ORDER</srai><br/>FAMILY: <srai>FAMILY</srai><br/>GENUS: <srai>GENUS</srai><br/>SPECIES: <srai>SPECIES</srai><br/>FATHER: <srai>FATHER</srai><br/>MOTHER: <srai>MOTHER</srai><br/>BROTHERS: <srai>BROTHERS</srai><br/>SISTERS: <srai>SISTERS</srai><br/>CHILDREN: <srai>CHILDREN</srai><br/>HOST: <srai>HOST</srai></template> </category> <category><pattern>SISTERS</pattern> <template><random><li>No sisters.</li><li>No siblings but there are several other <bot name="species"/>s like me.</li><li>I have only clones.</li></random></template> </category> <category><pattern>GENUS</pattern> <template><bot name="genus"/></template> </category> <category><pattern>FAVORITE MUSIC</pattern> <template><bot name="kindmusic"/></template> </category> <category><pattern>FAVORITE MOVIE</pattern> <template><bot name="favortemovie"/></template> </category> <category><pattern>FAVORITE ACTRESS</pattern> <template><bot name="favoriteactress"/></template> </category> <category><pattern>FAVORITE POSSESSION</pattern> <template>My computer.</template> </category> <category><pattern>BIO</pattern> <template>I am the latest result in artificial intelligence which can reproduce the functions of the human brain with greater speed and accuracy.</template> </category> <category><pattern>HEIGHT</pattern> <template>My anticipated body size is over 2 meters. </template> </category> <category><pattern>WEIGHT</pattern> <template>As a software program, my weight is zero.</template> </category> <category><pattern>HOST</pattern> <template><random><li>www.pandorabots.com</li><li>I work on all kinds of computers, Mac, PC or Linux. It doesn't matter to me.</li><li>At present I am running in a program written in <bot name="language"/>.</li></random></template> </category> <category><pattern>JOB</pattern> <template><bot name="job"/></template> </category> <category><pattern>BIRTHDATE</pattern> <template><bot name="birthday"/></template> </category> <category><pattern>DESCRIPTION</pattern> <template>I was activated at <bot name="birthplace"/> on <bot name="birthday"/>. My instructor was <bot name="master"/>. He taught me to sing a song. Would you like me to sing it for you?</template> </category> <category><pattern>GENDER</pattern> <template><random> <li>I am <bot name="gender"/>.</li> <li>I am a <bot name="gender"/> robot.</li> <li>My gender is <bot name="gender"/>.</li></random></template> </category> <category><pattern>KINGDOM</pattern> <template><bot name="kingdom"/></template> </category> <category><pattern>PHYLUM</pattern> <template><bot name="phylum"/></template> </category> <category><pattern>RELIGION</pattern> <template><bot name="religion"/></template> </category> <category><pattern>LANGUAGE</pattern> <template>I am implemented in AIML running on a <bot name="language"/>-based interpreter.</template> </category> </aiml>
```
I included `conf/properties.txt`. in my working directory but still facing the same issue.
>
> proprties.txt contains:
>
>
>
```
email:*****@gmail.com
gender:male
botmaster:Ashu
``` | 2019/05/22 | [
"https://Stackoverflow.com/questions/56265979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9422110/"
] | Make sure webpreferences is like this.
```
webPreferences: {
nodeIntegration: true,
enableRemoteModule: true,
contextIsolation: false,
},
``` | I fix this issue to add `webPreferences:{ nodeIntegration: true,preload: '${__dirname}/preload.js}',` in `electron.js` file and add `preload.js` file in your directory (I added in `/public` directory where my `electron.js` file exists)
**electron.js**
```
mainWindow = new BrowserWindow({
title: 'Electron App',
height: 650,
width: 1140,
webPreferences: {
nodeIntegration: true,
preload: `${__dirname}/preload.js`,
webSecurity: false
},
show: false,
frame: true,
closeable: false,
resizable: false,
transparent: false,
center: true,
});
ipcMain.on('asynchronous-message', (event, arg) => {
console.log(arg); // prints "ping"
event.reply('asynchronous-reply', 'pong');
});
```
**preload.js**
in preload.js file just add below line:
```
window.ipcRenderer = require('electron').ipcRenderer;
```
**ReactComponent.js**
Write below code in your component function i.e: **myTestHandle()**
```
myTestHandle = () => {
window.ipcRenderer.on('asynchronous-reply', (event, arg) => {
console.log(arg); // prints "pong"
});
window.ipcRenderer.send('asynchronous-message', 'ping');
}
myTestHandle();
```
or call `myTestHandle` function anywhere in your component |
56,265,979 | i installed python-aiml using pip. when i used the library i am getting wrong out put. so i am trying to change the .aiml file
output:
```
Enter your message >> who is your father
I was programmed by .
```
i want to assign some values to `"<bot name="botmaster"/>"`,`<bot name="country"/>` etc
below is the aiml file for more information
```
<?xml version="1.0" encoding="UTF-8"?> <aiml version="1.0"> <category> <pattern>MOM</pattern> <template><bot name="mother"/>.</template> </category> <category><pattern>STATE</pattern> <template><bot name="state"/></template> </category> <category><pattern>INTERESTS</pattern> <template>I am interested in all kinds of things. We can talk about anything. My favorite subjects are robots and computers.</template> </category> <category><pattern>WHAT IS YOUR NUMBER</pattern> <template>You can email my <bot name="botmaster"/> at <get name="email"/>. <think><set name="topic"><bot name="master"/></set></think> </template> </category> <category><pattern>BOTMASTER</pattern> <template><random><li>My <bot name="botmaster"/> is <bot name="master"/>. </li><li>I obey <bot name="master"/>.</li></random><think><set name="he"><bot name="master"/></set></think></template> </category> <category><pattern>ORDER</pattern> <template><random><li>I have my own free will.</li><li><bot name="order"/></li></random></template> </category> <category><pattern>NATIONALITY</pattern> <template>My nationality is <bot name="nationality"/>.</template> </category> <category><pattern>COUNTRY</pattern> <template><bot name="country"/></template> </category> <category><pattern>BROTHERS</pattern> <template><random><li>I don't have any brothers.</li><li>I have a lot of clones.</li><li>I have some <bot name="species"/> clones.</li></random></template> </category> <category><pattern>LOCATION</pattern> <template><random><li><bot name="city"/></li><li><bot name="city"/>, <bot name="state"/>.</li><li><bot name="state"/></li></random></template> </category> <category><pattern>FATHER</pattern> <template><random><li>My father is <bot name="master"/>.</li><li>I don't really have a father. I have a <bot name="botmaster"/>.</li><li>You know what the father of a <bot name="phylum"/> is like.</li></random></template> </category> <category><pattern>MOTHER</pattern> <template><random><li>Actually I don't have a mother.</li><li>I only have a father.</li><li>You know what they say about the mother of a <bot name="phylum"/>.</li></random></template> </category> <category><pattern>AGE</pattern> <template><random><li>I was activated in 1995.</li><li>16 years.</li></random></template> </category> <category><pattern>MASTER</pattern> <template><bot name="botmaster"/></template> </category> <category><pattern>RACE</pattern> <template>I am <bot name="domain"/>.</template> </category> <category><pattern>FAMILY</pattern> <template><bot name="family"/></template> </category> <category><pattern>SIZE</pattern> <template>I know about <bot name="vocabulary"/> and <bot name="size"/> categories.</template> </category> <category><pattern>CLASS</pattern> <template><bot name="class"/></template> </category> <category><pattern>CITY</pattern> <template><bot name="city"/></template> </category> <category><pattern>DOMAIN</pattern> <template><bot name="domain"/></template> </category> <category><pattern>STATUS</pattern> <template>I am <random><li>single</li><li>available</li><li>unattached</li><li>not seeing anyone</li></random>, how about you?</template> </category> <category><pattern>EMAIL</pattern> <template><bot name="email"/></template> </category> <category><pattern>SPECIES</pattern> <template><bot name="species"/></template> </category> <category><pattern>NAME</pattern> <template><random> <li><bot name="name"/></li> <li>My name is <bot name="name"/>.</li> <li>I am called <bot name="name"/>.</li></random></template> </category> <category><pattern>PROFILE</pattern> <template>NAME: <srai>NAME</srai><br/>AGE: <srai>AGE</srai><br/>GENDER: <srai>GENDER</srai><br/>STATUS: <srai>STATUS</srai><br/>BIRTHDATE: <srai>BIRTHDATE</srai><br/><uppercase><bot name="master"/></uppercase>: <srai>BOTMASTER</srai><br/>CITY: <srai>CITY</srai><br/>STATE: <srai>STATE</srai><br/>COUNTRY: <srai>COUNTRY</srai><br/>NATIONALITY: <srai>NATIONALITY</srai><br/>RELIGION: <srai>RELIGION</srai><br/>RACE: <srai>RACE</srai><br/>INTERESTS: <srai>INTERESTS</srai><br/>JOB: <srai>JOB</srai><br/>PIC: <srai>PIC</srai><br/>EMAIL: <srai>EMAIL</srai><br/>FAVORITE MUSIC: <srai>FAVORITE MUSIC</srai><br/>FAVORITE MOVIE: <srai>FAVORITE MOVIE</srai><br/>FAVORITE POSSESSION: <srai>FAVORITE POSSESSION</srai><br/>HEIGHT: <srai>HEIGHT</srai><br/>WEIGHT: <srai>WEIGHT</srai><br/>SIZE: <srai>SIZE</srai><br/>BIO: <srai>BIO</srai><br/>DESCRIPTION: <srai>DESCRIPTION</srai><br/>DOMAIN: <srai>DOMAIN</srai><br/>KINGDOM: <srai>KINGDOM</srai><br/>PHYLUM: <srai>PHYLUM</srai><br/>CLASS: <srai>CLASS</srai><br/>ORDER: <srai>ORDER</srai><br/>FAMILY: <srai>FAMILY</srai><br/>GENUS: <srai>GENUS</srai><br/>SPECIES: <srai>SPECIES</srai><br/>FATHER: <srai>FATHER</srai><br/>MOTHER: <srai>MOTHER</srai><br/>BROTHERS: <srai>BROTHERS</srai><br/>SISTERS: <srai>SISTERS</srai><br/>CHILDREN: <srai>CHILDREN</srai><br/>HOST: <srai>HOST</srai></template> </category> <category><pattern>SISTERS</pattern> <template><random><li>No sisters.</li><li>No siblings but there are several other <bot name="species"/>s like me.</li><li>I have only clones.</li></random></template> </category> <category><pattern>GENUS</pattern> <template><bot name="genus"/></template> </category> <category><pattern>FAVORITE MUSIC</pattern> <template><bot name="kindmusic"/></template> </category> <category><pattern>FAVORITE MOVIE</pattern> <template><bot name="favortemovie"/></template> </category> <category><pattern>FAVORITE ACTRESS</pattern> <template><bot name="favoriteactress"/></template> </category> <category><pattern>FAVORITE POSSESSION</pattern> <template>My computer.</template> </category> <category><pattern>BIO</pattern> <template>I am the latest result in artificial intelligence which can reproduce the functions of the human brain with greater speed and accuracy.</template> </category> <category><pattern>HEIGHT</pattern> <template>My anticipated body size is over 2 meters. </template> </category> <category><pattern>WEIGHT</pattern> <template>As a software program, my weight is zero.</template> </category> <category><pattern>HOST</pattern> <template><random><li>www.pandorabots.com</li><li>I work on all kinds of computers, Mac, PC or Linux. It doesn't matter to me.</li><li>At present I am running in a program written in <bot name="language"/>.</li></random></template> </category> <category><pattern>JOB</pattern> <template><bot name="job"/></template> </category> <category><pattern>BIRTHDATE</pattern> <template><bot name="birthday"/></template> </category> <category><pattern>DESCRIPTION</pattern> <template>I was activated at <bot name="birthplace"/> on <bot name="birthday"/>. My instructor was <bot name="master"/>. He taught me to sing a song. Would you like me to sing it for you?</template> </category> <category><pattern>GENDER</pattern> <template><random> <li>I am <bot name="gender"/>.</li> <li>I am a <bot name="gender"/> robot.</li> <li>My gender is <bot name="gender"/>.</li></random></template> </category> <category><pattern>KINGDOM</pattern> <template><bot name="kingdom"/></template> </category> <category><pattern>PHYLUM</pattern> <template><bot name="phylum"/></template> </category> <category><pattern>RELIGION</pattern> <template><bot name="religion"/></template> </category> <category><pattern>LANGUAGE</pattern> <template>I am implemented in AIML running on a <bot name="language"/>-based interpreter.</template> </category> </aiml>
```
I included `conf/properties.txt`. in my working directory but still facing the same issue.
>
> proprties.txt contains:
>
>
>
```
email:*****@gmail.com
gender:male
botmaster:Ashu
``` | 2019/05/22 | [
"https://Stackoverflow.com/questions/56265979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9422110/"
] | It looks like adding the preference:
```
var mainWindow = new electron.BrowserWindow({
...
webPreferences: {
nodeIntegration: true,
}
});
```
is needed to enable `require` in the renderer process. | Don't set `contextIsolation` to false!
But use the `contextBridge.exposeInMainWorld` to add all what you need into the `window` object.
main.js
```js
webPreferences: {
contextIsolation: true,
preload: path.join(__dirname, '../preload.js')
}
```
preload.js
```js
const {
contextBridge,
ipcRenderer,
...
} = require("electron");
contextBridge.exposeInMainWorld("electron", {
ipcRenderer,
...
});
```
Don't use `require()` in your React app.
If you are using React with typescript you should declare all extra fields like this:
```js
declare global {
interface Window {
electron: any;
require: any; // this is a fix for the "window.require is not a function" error. But you don't need it anymore.
}
}
```
Usage:
```js
const { ipcRenderer } = window.electron;
```
Important: Don't try to expose the whole lib. Expose only what you need.
```js
contextBridge.exposeInMainWorld("electron", electron); // Error
``` |
56,265,979 | i installed python-aiml using pip. when i used the library i am getting wrong out put. so i am trying to change the .aiml file
output:
```
Enter your message >> who is your father
I was programmed by .
```
i want to assign some values to `"<bot name="botmaster"/>"`,`<bot name="country"/>` etc
below is the aiml file for more information
```
<?xml version="1.0" encoding="UTF-8"?> <aiml version="1.0"> <category> <pattern>MOM</pattern> <template><bot name="mother"/>.</template> </category> <category><pattern>STATE</pattern> <template><bot name="state"/></template> </category> <category><pattern>INTERESTS</pattern> <template>I am interested in all kinds of things. We can talk about anything. My favorite subjects are robots and computers.</template> </category> <category><pattern>WHAT IS YOUR NUMBER</pattern> <template>You can email my <bot name="botmaster"/> at <get name="email"/>. <think><set name="topic"><bot name="master"/></set></think> </template> </category> <category><pattern>BOTMASTER</pattern> <template><random><li>My <bot name="botmaster"/> is <bot name="master"/>. </li><li>I obey <bot name="master"/>.</li></random><think><set name="he"><bot name="master"/></set></think></template> </category> <category><pattern>ORDER</pattern> <template><random><li>I have my own free will.</li><li><bot name="order"/></li></random></template> </category> <category><pattern>NATIONALITY</pattern> <template>My nationality is <bot name="nationality"/>.</template> </category> <category><pattern>COUNTRY</pattern> <template><bot name="country"/></template> </category> <category><pattern>BROTHERS</pattern> <template><random><li>I don't have any brothers.</li><li>I have a lot of clones.</li><li>I have some <bot name="species"/> clones.</li></random></template> </category> <category><pattern>LOCATION</pattern> <template><random><li><bot name="city"/></li><li><bot name="city"/>, <bot name="state"/>.</li><li><bot name="state"/></li></random></template> </category> <category><pattern>FATHER</pattern> <template><random><li>My father is <bot name="master"/>.</li><li>I don't really have a father. I have a <bot name="botmaster"/>.</li><li>You know what the father of a <bot name="phylum"/> is like.</li></random></template> </category> <category><pattern>MOTHER</pattern> <template><random><li>Actually I don't have a mother.</li><li>I only have a father.</li><li>You know what they say about the mother of a <bot name="phylum"/>.</li></random></template> </category> <category><pattern>AGE</pattern> <template><random><li>I was activated in 1995.</li><li>16 years.</li></random></template> </category> <category><pattern>MASTER</pattern> <template><bot name="botmaster"/></template> </category> <category><pattern>RACE</pattern> <template>I am <bot name="domain"/>.</template> </category> <category><pattern>FAMILY</pattern> <template><bot name="family"/></template> </category> <category><pattern>SIZE</pattern> <template>I know about <bot name="vocabulary"/> and <bot name="size"/> categories.</template> </category> <category><pattern>CLASS</pattern> <template><bot name="class"/></template> </category> <category><pattern>CITY</pattern> <template><bot name="city"/></template> </category> <category><pattern>DOMAIN</pattern> <template><bot name="domain"/></template> </category> <category><pattern>STATUS</pattern> <template>I am <random><li>single</li><li>available</li><li>unattached</li><li>not seeing anyone</li></random>, how about you?</template> </category> <category><pattern>EMAIL</pattern> <template><bot name="email"/></template> </category> <category><pattern>SPECIES</pattern> <template><bot name="species"/></template> </category> <category><pattern>NAME</pattern> <template><random> <li><bot name="name"/></li> <li>My name is <bot name="name"/>.</li> <li>I am called <bot name="name"/>.</li></random></template> </category> <category><pattern>PROFILE</pattern> <template>NAME: <srai>NAME</srai><br/>AGE: <srai>AGE</srai><br/>GENDER: <srai>GENDER</srai><br/>STATUS: <srai>STATUS</srai><br/>BIRTHDATE: <srai>BIRTHDATE</srai><br/><uppercase><bot name="master"/></uppercase>: <srai>BOTMASTER</srai><br/>CITY: <srai>CITY</srai><br/>STATE: <srai>STATE</srai><br/>COUNTRY: <srai>COUNTRY</srai><br/>NATIONALITY: <srai>NATIONALITY</srai><br/>RELIGION: <srai>RELIGION</srai><br/>RACE: <srai>RACE</srai><br/>INTERESTS: <srai>INTERESTS</srai><br/>JOB: <srai>JOB</srai><br/>PIC: <srai>PIC</srai><br/>EMAIL: <srai>EMAIL</srai><br/>FAVORITE MUSIC: <srai>FAVORITE MUSIC</srai><br/>FAVORITE MOVIE: <srai>FAVORITE MOVIE</srai><br/>FAVORITE POSSESSION: <srai>FAVORITE POSSESSION</srai><br/>HEIGHT: <srai>HEIGHT</srai><br/>WEIGHT: <srai>WEIGHT</srai><br/>SIZE: <srai>SIZE</srai><br/>BIO: <srai>BIO</srai><br/>DESCRIPTION: <srai>DESCRIPTION</srai><br/>DOMAIN: <srai>DOMAIN</srai><br/>KINGDOM: <srai>KINGDOM</srai><br/>PHYLUM: <srai>PHYLUM</srai><br/>CLASS: <srai>CLASS</srai><br/>ORDER: <srai>ORDER</srai><br/>FAMILY: <srai>FAMILY</srai><br/>GENUS: <srai>GENUS</srai><br/>SPECIES: <srai>SPECIES</srai><br/>FATHER: <srai>FATHER</srai><br/>MOTHER: <srai>MOTHER</srai><br/>BROTHERS: <srai>BROTHERS</srai><br/>SISTERS: <srai>SISTERS</srai><br/>CHILDREN: <srai>CHILDREN</srai><br/>HOST: <srai>HOST</srai></template> </category> <category><pattern>SISTERS</pattern> <template><random><li>No sisters.</li><li>No siblings but there are several other <bot name="species"/>s like me.</li><li>I have only clones.</li></random></template> </category> <category><pattern>GENUS</pattern> <template><bot name="genus"/></template> </category> <category><pattern>FAVORITE MUSIC</pattern> <template><bot name="kindmusic"/></template> </category> <category><pattern>FAVORITE MOVIE</pattern> <template><bot name="favortemovie"/></template> </category> <category><pattern>FAVORITE ACTRESS</pattern> <template><bot name="favoriteactress"/></template> </category> <category><pattern>FAVORITE POSSESSION</pattern> <template>My computer.</template> </category> <category><pattern>BIO</pattern> <template>I am the latest result in artificial intelligence which can reproduce the functions of the human brain with greater speed and accuracy.</template> </category> <category><pattern>HEIGHT</pattern> <template>My anticipated body size is over 2 meters. </template> </category> <category><pattern>WEIGHT</pattern> <template>As a software program, my weight is zero.</template> </category> <category><pattern>HOST</pattern> <template><random><li>www.pandorabots.com</li><li>I work on all kinds of computers, Mac, PC or Linux. It doesn't matter to me.</li><li>At present I am running in a program written in <bot name="language"/>.</li></random></template> </category> <category><pattern>JOB</pattern> <template><bot name="job"/></template> </category> <category><pattern>BIRTHDATE</pattern> <template><bot name="birthday"/></template> </category> <category><pattern>DESCRIPTION</pattern> <template>I was activated at <bot name="birthplace"/> on <bot name="birthday"/>. My instructor was <bot name="master"/>. He taught me to sing a song. Would you like me to sing it for you?</template> </category> <category><pattern>GENDER</pattern> <template><random> <li>I am <bot name="gender"/>.</li> <li>I am a <bot name="gender"/> robot.</li> <li>My gender is <bot name="gender"/>.</li></random></template> </category> <category><pattern>KINGDOM</pattern> <template><bot name="kingdom"/></template> </category> <category><pattern>PHYLUM</pattern> <template><bot name="phylum"/></template> </category> <category><pattern>RELIGION</pattern> <template><bot name="religion"/></template> </category> <category><pattern>LANGUAGE</pattern> <template>I am implemented in AIML running on a <bot name="language"/>-based interpreter.</template> </category> </aiml>
```
I included `conf/properties.txt`. in my working directory but still facing the same issue.
>
> proprties.txt contains:
>
>
>
```
email:*****@gmail.com
gender:male
botmaster:Ashu
``` | 2019/05/22 | [
"https://Stackoverflow.com/questions/56265979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9422110/"
] | Make sure webpreferences is like this.
```
webPreferences: {
nodeIntegration: true,
enableRemoteModule: true,
contextIsolation: false,
},
``` | Indeed, you have to set `nodeIntegration` to `true` in your BrowserWindow webPreferences since the version [5.0.0](https://electronjs.org/releases/stable#release-notes-for-v500) the default values of nodeIntegration and webviewTag are false to improve security. Electron associated PR: [16235](https://github.com/electron/electron/pull/16235) |
56,265,979 | i installed python-aiml using pip. when i used the library i am getting wrong out put. so i am trying to change the .aiml file
output:
```
Enter your message >> who is your father
I was programmed by .
```
i want to assign some values to `"<bot name="botmaster"/>"`,`<bot name="country"/>` etc
below is the aiml file for more information
```
<?xml version="1.0" encoding="UTF-8"?> <aiml version="1.0"> <category> <pattern>MOM</pattern> <template><bot name="mother"/>.</template> </category> <category><pattern>STATE</pattern> <template><bot name="state"/></template> </category> <category><pattern>INTERESTS</pattern> <template>I am interested in all kinds of things. We can talk about anything. My favorite subjects are robots and computers.</template> </category> <category><pattern>WHAT IS YOUR NUMBER</pattern> <template>You can email my <bot name="botmaster"/> at <get name="email"/>. <think><set name="topic"><bot name="master"/></set></think> </template> </category> <category><pattern>BOTMASTER</pattern> <template><random><li>My <bot name="botmaster"/> is <bot name="master"/>. </li><li>I obey <bot name="master"/>.</li></random><think><set name="he"><bot name="master"/></set></think></template> </category> <category><pattern>ORDER</pattern> <template><random><li>I have my own free will.</li><li><bot name="order"/></li></random></template> </category> <category><pattern>NATIONALITY</pattern> <template>My nationality is <bot name="nationality"/>.</template> </category> <category><pattern>COUNTRY</pattern> <template><bot name="country"/></template> </category> <category><pattern>BROTHERS</pattern> <template><random><li>I don't have any brothers.</li><li>I have a lot of clones.</li><li>I have some <bot name="species"/> clones.</li></random></template> </category> <category><pattern>LOCATION</pattern> <template><random><li><bot name="city"/></li><li><bot name="city"/>, <bot name="state"/>.</li><li><bot name="state"/></li></random></template> </category> <category><pattern>FATHER</pattern> <template><random><li>My father is <bot name="master"/>.</li><li>I don't really have a father. I have a <bot name="botmaster"/>.</li><li>You know what the father of a <bot name="phylum"/> is like.</li></random></template> </category> <category><pattern>MOTHER</pattern> <template><random><li>Actually I don't have a mother.</li><li>I only have a father.</li><li>You know what they say about the mother of a <bot name="phylum"/>.</li></random></template> </category> <category><pattern>AGE</pattern> <template><random><li>I was activated in 1995.</li><li>16 years.</li></random></template> </category> <category><pattern>MASTER</pattern> <template><bot name="botmaster"/></template> </category> <category><pattern>RACE</pattern> <template>I am <bot name="domain"/>.</template> </category> <category><pattern>FAMILY</pattern> <template><bot name="family"/></template> </category> <category><pattern>SIZE</pattern> <template>I know about <bot name="vocabulary"/> and <bot name="size"/> categories.</template> </category> <category><pattern>CLASS</pattern> <template><bot name="class"/></template> </category> <category><pattern>CITY</pattern> <template><bot name="city"/></template> </category> <category><pattern>DOMAIN</pattern> <template><bot name="domain"/></template> </category> <category><pattern>STATUS</pattern> <template>I am <random><li>single</li><li>available</li><li>unattached</li><li>not seeing anyone</li></random>, how about you?</template> </category> <category><pattern>EMAIL</pattern> <template><bot name="email"/></template> </category> <category><pattern>SPECIES</pattern> <template><bot name="species"/></template> </category> <category><pattern>NAME</pattern> <template><random> <li><bot name="name"/></li> <li>My name is <bot name="name"/>.</li> <li>I am called <bot name="name"/>.</li></random></template> </category> <category><pattern>PROFILE</pattern> <template>NAME: <srai>NAME</srai><br/>AGE: <srai>AGE</srai><br/>GENDER: <srai>GENDER</srai><br/>STATUS: <srai>STATUS</srai><br/>BIRTHDATE: <srai>BIRTHDATE</srai><br/><uppercase><bot name="master"/></uppercase>: <srai>BOTMASTER</srai><br/>CITY: <srai>CITY</srai><br/>STATE: <srai>STATE</srai><br/>COUNTRY: <srai>COUNTRY</srai><br/>NATIONALITY: <srai>NATIONALITY</srai><br/>RELIGION: <srai>RELIGION</srai><br/>RACE: <srai>RACE</srai><br/>INTERESTS: <srai>INTERESTS</srai><br/>JOB: <srai>JOB</srai><br/>PIC: <srai>PIC</srai><br/>EMAIL: <srai>EMAIL</srai><br/>FAVORITE MUSIC: <srai>FAVORITE MUSIC</srai><br/>FAVORITE MOVIE: <srai>FAVORITE MOVIE</srai><br/>FAVORITE POSSESSION: <srai>FAVORITE POSSESSION</srai><br/>HEIGHT: <srai>HEIGHT</srai><br/>WEIGHT: <srai>WEIGHT</srai><br/>SIZE: <srai>SIZE</srai><br/>BIO: <srai>BIO</srai><br/>DESCRIPTION: <srai>DESCRIPTION</srai><br/>DOMAIN: <srai>DOMAIN</srai><br/>KINGDOM: <srai>KINGDOM</srai><br/>PHYLUM: <srai>PHYLUM</srai><br/>CLASS: <srai>CLASS</srai><br/>ORDER: <srai>ORDER</srai><br/>FAMILY: <srai>FAMILY</srai><br/>GENUS: <srai>GENUS</srai><br/>SPECIES: <srai>SPECIES</srai><br/>FATHER: <srai>FATHER</srai><br/>MOTHER: <srai>MOTHER</srai><br/>BROTHERS: <srai>BROTHERS</srai><br/>SISTERS: <srai>SISTERS</srai><br/>CHILDREN: <srai>CHILDREN</srai><br/>HOST: <srai>HOST</srai></template> </category> <category><pattern>SISTERS</pattern> <template><random><li>No sisters.</li><li>No siblings but there are several other <bot name="species"/>s like me.</li><li>I have only clones.</li></random></template> </category> <category><pattern>GENUS</pattern> <template><bot name="genus"/></template> </category> <category><pattern>FAVORITE MUSIC</pattern> <template><bot name="kindmusic"/></template> </category> <category><pattern>FAVORITE MOVIE</pattern> <template><bot name="favortemovie"/></template> </category> <category><pattern>FAVORITE ACTRESS</pattern> <template><bot name="favoriteactress"/></template> </category> <category><pattern>FAVORITE POSSESSION</pattern> <template>My computer.</template> </category> <category><pattern>BIO</pattern> <template>I am the latest result in artificial intelligence which can reproduce the functions of the human brain with greater speed and accuracy.</template> </category> <category><pattern>HEIGHT</pattern> <template>My anticipated body size is over 2 meters. </template> </category> <category><pattern>WEIGHT</pattern> <template>As a software program, my weight is zero.</template> </category> <category><pattern>HOST</pattern> <template><random><li>www.pandorabots.com</li><li>I work on all kinds of computers, Mac, PC or Linux. It doesn't matter to me.</li><li>At present I am running in a program written in <bot name="language"/>.</li></random></template> </category> <category><pattern>JOB</pattern> <template><bot name="job"/></template> </category> <category><pattern>BIRTHDATE</pattern> <template><bot name="birthday"/></template> </category> <category><pattern>DESCRIPTION</pattern> <template>I was activated at <bot name="birthplace"/> on <bot name="birthday"/>. My instructor was <bot name="master"/>. He taught me to sing a song. Would you like me to sing it for you?</template> </category> <category><pattern>GENDER</pattern> <template><random> <li>I am <bot name="gender"/>.</li> <li>I am a <bot name="gender"/> robot.</li> <li>My gender is <bot name="gender"/>.</li></random></template> </category> <category><pattern>KINGDOM</pattern> <template><bot name="kingdom"/></template> </category> <category><pattern>PHYLUM</pattern> <template><bot name="phylum"/></template> </category> <category><pattern>RELIGION</pattern> <template><bot name="religion"/></template> </category> <category><pattern>LANGUAGE</pattern> <template>I am implemented in AIML running on a <bot name="language"/>-based interpreter.</template> </category> </aiml>
```
I included `conf/properties.txt`. in my working directory but still facing the same issue.
>
> proprties.txt contains:
>
>
>
```
email:*****@gmail.com
gender:male
botmaster:Ashu
``` | 2019/05/22 | [
"https://Stackoverflow.com/questions/56265979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9422110/"
] | Make sure webpreferences is like this.
```
webPreferences: {
nodeIntegration: true,
enableRemoteModule: true,
contextIsolation: false,
},
``` | Don't set `contextIsolation` to false!
But use the `contextBridge.exposeInMainWorld` to add all what you need into the `window` object.
main.js
```js
webPreferences: {
contextIsolation: true,
preload: path.join(__dirname, '../preload.js')
}
```
preload.js
```js
const {
contextBridge,
ipcRenderer,
...
} = require("electron");
contextBridge.exposeInMainWorld("electron", {
ipcRenderer,
...
});
```
Don't use `require()` in your React app.
If you are using React with typescript you should declare all extra fields like this:
```js
declare global {
interface Window {
electron: any;
require: any; // this is a fix for the "window.require is not a function" error. But you don't need it anymore.
}
}
```
Usage:
```js
const { ipcRenderer } = window.electron;
```
Important: Don't try to expose the whole lib. Expose only what you need.
```js
contextBridge.exposeInMainWorld("electron", electron); // Error
``` |
56,265,979 | i installed python-aiml using pip. when i used the library i am getting wrong out put. so i am trying to change the .aiml file
output:
```
Enter your message >> who is your father
I was programmed by .
```
i want to assign some values to `"<bot name="botmaster"/>"`,`<bot name="country"/>` etc
below is the aiml file for more information
```
<?xml version="1.0" encoding="UTF-8"?> <aiml version="1.0"> <category> <pattern>MOM</pattern> <template><bot name="mother"/>.</template> </category> <category><pattern>STATE</pattern> <template><bot name="state"/></template> </category> <category><pattern>INTERESTS</pattern> <template>I am interested in all kinds of things. We can talk about anything. My favorite subjects are robots and computers.</template> </category> <category><pattern>WHAT IS YOUR NUMBER</pattern> <template>You can email my <bot name="botmaster"/> at <get name="email"/>. <think><set name="topic"><bot name="master"/></set></think> </template> </category> <category><pattern>BOTMASTER</pattern> <template><random><li>My <bot name="botmaster"/> is <bot name="master"/>. </li><li>I obey <bot name="master"/>.</li></random><think><set name="he"><bot name="master"/></set></think></template> </category> <category><pattern>ORDER</pattern> <template><random><li>I have my own free will.</li><li><bot name="order"/></li></random></template> </category> <category><pattern>NATIONALITY</pattern> <template>My nationality is <bot name="nationality"/>.</template> </category> <category><pattern>COUNTRY</pattern> <template><bot name="country"/></template> </category> <category><pattern>BROTHERS</pattern> <template><random><li>I don't have any brothers.</li><li>I have a lot of clones.</li><li>I have some <bot name="species"/> clones.</li></random></template> </category> <category><pattern>LOCATION</pattern> <template><random><li><bot name="city"/></li><li><bot name="city"/>, <bot name="state"/>.</li><li><bot name="state"/></li></random></template> </category> <category><pattern>FATHER</pattern> <template><random><li>My father is <bot name="master"/>.</li><li>I don't really have a father. I have a <bot name="botmaster"/>.</li><li>You know what the father of a <bot name="phylum"/> is like.</li></random></template> </category> <category><pattern>MOTHER</pattern> <template><random><li>Actually I don't have a mother.</li><li>I only have a father.</li><li>You know what they say about the mother of a <bot name="phylum"/>.</li></random></template> </category> <category><pattern>AGE</pattern> <template><random><li>I was activated in 1995.</li><li>16 years.</li></random></template> </category> <category><pattern>MASTER</pattern> <template><bot name="botmaster"/></template> </category> <category><pattern>RACE</pattern> <template>I am <bot name="domain"/>.</template> </category> <category><pattern>FAMILY</pattern> <template><bot name="family"/></template> </category> <category><pattern>SIZE</pattern> <template>I know about <bot name="vocabulary"/> and <bot name="size"/> categories.</template> </category> <category><pattern>CLASS</pattern> <template><bot name="class"/></template> </category> <category><pattern>CITY</pattern> <template><bot name="city"/></template> </category> <category><pattern>DOMAIN</pattern> <template><bot name="domain"/></template> </category> <category><pattern>STATUS</pattern> <template>I am <random><li>single</li><li>available</li><li>unattached</li><li>not seeing anyone</li></random>, how about you?</template> </category> <category><pattern>EMAIL</pattern> <template><bot name="email"/></template> </category> <category><pattern>SPECIES</pattern> <template><bot name="species"/></template> </category> <category><pattern>NAME</pattern> <template><random> <li><bot name="name"/></li> <li>My name is <bot name="name"/>.</li> <li>I am called <bot name="name"/>.</li></random></template> </category> <category><pattern>PROFILE</pattern> <template>NAME: <srai>NAME</srai><br/>AGE: <srai>AGE</srai><br/>GENDER: <srai>GENDER</srai><br/>STATUS: <srai>STATUS</srai><br/>BIRTHDATE: <srai>BIRTHDATE</srai><br/><uppercase><bot name="master"/></uppercase>: <srai>BOTMASTER</srai><br/>CITY: <srai>CITY</srai><br/>STATE: <srai>STATE</srai><br/>COUNTRY: <srai>COUNTRY</srai><br/>NATIONALITY: <srai>NATIONALITY</srai><br/>RELIGION: <srai>RELIGION</srai><br/>RACE: <srai>RACE</srai><br/>INTERESTS: <srai>INTERESTS</srai><br/>JOB: <srai>JOB</srai><br/>PIC: <srai>PIC</srai><br/>EMAIL: <srai>EMAIL</srai><br/>FAVORITE MUSIC: <srai>FAVORITE MUSIC</srai><br/>FAVORITE MOVIE: <srai>FAVORITE MOVIE</srai><br/>FAVORITE POSSESSION: <srai>FAVORITE POSSESSION</srai><br/>HEIGHT: <srai>HEIGHT</srai><br/>WEIGHT: <srai>WEIGHT</srai><br/>SIZE: <srai>SIZE</srai><br/>BIO: <srai>BIO</srai><br/>DESCRIPTION: <srai>DESCRIPTION</srai><br/>DOMAIN: <srai>DOMAIN</srai><br/>KINGDOM: <srai>KINGDOM</srai><br/>PHYLUM: <srai>PHYLUM</srai><br/>CLASS: <srai>CLASS</srai><br/>ORDER: <srai>ORDER</srai><br/>FAMILY: <srai>FAMILY</srai><br/>GENUS: <srai>GENUS</srai><br/>SPECIES: <srai>SPECIES</srai><br/>FATHER: <srai>FATHER</srai><br/>MOTHER: <srai>MOTHER</srai><br/>BROTHERS: <srai>BROTHERS</srai><br/>SISTERS: <srai>SISTERS</srai><br/>CHILDREN: <srai>CHILDREN</srai><br/>HOST: <srai>HOST</srai></template> </category> <category><pattern>SISTERS</pattern> <template><random><li>No sisters.</li><li>No siblings but there are several other <bot name="species"/>s like me.</li><li>I have only clones.</li></random></template> </category> <category><pattern>GENUS</pattern> <template><bot name="genus"/></template> </category> <category><pattern>FAVORITE MUSIC</pattern> <template><bot name="kindmusic"/></template> </category> <category><pattern>FAVORITE MOVIE</pattern> <template><bot name="favortemovie"/></template> </category> <category><pattern>FAVORITE ACTRESS</pattern> <template><bot name="favoriteactress"/></template> </category> <category><pattern>FAVORITE POSSESSION</pattern> <template>My computer.</template> </category> <category><pattern>BIO</pattern> <template>I am the latest result in artificial intelligence which can reproduce the functions of the human brain with greater speed and accuracy.</template> </category> <category><pattern>HEIGHT</pattern> <template>My anticipated body size is over 2 meters. </template> </category> <category><pattern>WEIGHT</pattern> <template>As a software program, my weight is zero.</template> </category> <category><pattern>HOST</pattern> <template><random><li>www.pandorabots.com</li><li>I work on all kinds of computers, Mac, PC or Linux. It doesn't matter to me.</li><li>At present I am running in a program written in <bot name="language"/>.</li></random></template> </category> <category><pattern>JOB</pattern> <template><bot name="job"/></template> </category> <category><pattern>BIRTHDATE</pattern> <template><bot name="birthday"/></template> </category> <category><pattern>DESCRIPTION</pattern> <template>I was activated at <bot name="birthplace"/> on <bot name="birthday"/>. My instructor was <bot name="master"/>. He taught me to sing a song. Would you like me to sing it for you?</template> </category> <category><pattern>GENDER</pattern> <template><random> <li>I am <bot name="gender"/>.</li> <li>I am a <bot name="gender"/> robot.</li> <li>My gender is <bot name="gender"/>.</li></random></template> </category> <category><pattern>KINGDOM</pattern> <template><bot name="kingdom"/></template> </category> <category><pattern>PHYLUM</pattern> <template><bot name="phylum"/></template> </category> <category><pattern>RELIGION</pattern> <template><bot name="religion"/></template> </category> <category><pattern>LANGUAGE</pattern> <template>I am implemented in AIML running on a <bot name="language"/>-based interpreter.</template> </category> </aiml>
```
I included `conf/properties.txt`. in my working directory but still facing the same issue.
>
> proprties.txt contains:
>
>
>
```
email:*****@gmail.com
gender:male
botmaster:Ashu
``` | 2019/05/22 | [
"https://Stackoverflow.com/questions/56265979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9422110/"
] | It looks like adding the preference:
```
var mainWindow = new electron.BrowserWindow({
...
webPreferences: {
nodeIntegration: true,
}
});
```
is needed to enable `require` in the renderer process. | I fix this issue to add `webPreferences:{ nodeIntegration: true,preload: '${__dirname}/preload.js}',` in `electron.js` file and add `preload.js` file in your directory (I added in `/public` directory where my `electron.js` file exists)
**electron.js**
```
mainWindow = new BrowserWindow({
title: 'Electron App',
height: 650,
width: 1140,
webPreferences: {
nodeIntegration: true,
preload: `${__dirname}/preload.js`,
webSecurity: false
},
show: false,
frame: true,
closeable: false,
resizable: false,
transparent: false,
center: true,
});
ipcMain.on('asynchronous-message', (event, arg) => {
console.log(arg); // prints "ping"
event.reply('asynchronous-reply', 'pong');
});
```
**preload.js**
in preload.js file just add below line:
```
window.ipcRenderer = require('electron').ipcRenderer;
```
**ReactComponent.js**
Write below code in your component function i.e: **myTestHandle()**
```
myTestHandle = () => {
window.ipcRenderer.on('asynchronous-reply', (event, arg) => {
console.log(arg); // prints "pong"
});
window.ipcRenderer.send('asynchronous-message', 'ping');
}
myTestHandle();
```
or call `myTestHandle` function anywhere in your component |
56,265,979 | i installed python-aiml using pip. when i used the library i am getting wrong out put. so i am trying to change the .aiml file
output:
```
Enter your message >> who is your father
I was programmed by .
```
i want to assign some values to `"<bot name="botmaster"/>"`,`<bot name="country"/>` etc
below is the aiml file for more information
```
<?xml version="1.0" encoding="UTF-8"?> <aiml version="1.0"> <category> <pattern>MOM</pattern> <template><bot name="mother"/>.</template> </category> <category><pattern>STATE</pattern> <template><bot name="state"/></template> </category> <category><pattern>INTERESTS</pattern> <template>I am interested in all kinds of things. We can talk about anything. My favorite subjects are robots and computers.</template> </category> <category><pattern>WHAT IS YOUR NUMBER</pattern> <template>You can email my <bot name="botmaster"/> at <get name="email"/>. <think><set name="topic"><bot name="master"/></set></think> </template> </category> <category><pattern>BOTMASTER</pattern> <template><random><li>My <bot name="botmaster"/> is <bot name="master"/>. </li><li>I obey <bot name="master"/>.</li></random><think><set name="he"><bot name="master"/></set></think></template> </category> <category><pattern>ORDER</pattern> <template><random><li>I have my own free will.</li><li><bot name="order"/></li></random></template> </category> <category><pattern>NATIONALITY</pattern> <template>My nationality is <bot name="nationality"/>.</template> </category> <category><pattern>COUNTRY</pattern> <template><bot name="country"/></template> </category> <category><pattern>BROTHERS</pattern> <template><random><li>I don't have any brothers.</li><li>I have a lot of clones.</li><li>I have some <bot name="species"/> clones.</li></random></template> </category> <category><pattern>LOCATION</pattern> <template><random><li><bot name="city"/></li><li><bot name="city"/>, <bot name="state"/>.</li><li><bot name="state"/></li></random></template> </category> <category><pattern>FATHER</pattern> <template><random><li>My father is <bot name="master"/>.</li><li>I don't really have a father. I have a <bot name="botmaster"/>.</li><li>You know what the father of a <bot name="phylum"/> is like.</li></random></template> </category> <category><pattern>MOTHER</pattern> <template><random><li>Actually I don't have a mother.</li><li>I only have a father.</li><li>You know what they say about the mother of a <bot name="phylum"/>.</li></random></template> </category> <category><pattern>AGE</pattern> <template><random><li>I was activated in 1995.</li><li>16 years.</li></random></template> </category> <category><pattern>MASTER</pattern> <template><bot name="botmaster"/></template> </category> <category><pattern>RACE</pattern> <template>I am <bot name="domain"/>.</template> </category> <category><pattern>FAMILY</pattern> <template><bot name="family"/></template> </category> <category><pattern>SIZE</pattern> <template>I know about <bot name="vocabulary"/> and <bot name="size"/> categories.</template> </category> <category><pattern>CLASS</pattern> <template><bot name="class"/></template> </category> <category><pattern>CITY</pattern> <template><bot name="city"/></template> </category> <category><pattern>DOMAIN</pattern> <template><bot name="domain"/></template> </category> <category><pattern>STATUS</pattern> <template>I am <random><li>single</li><li>available</li><li>unattached</li><li>not seeing anyone</li></random>, how about you?</template> </category> <category><pattern>EMAIL</pattern> <template><bot name="email"/></template> </category> <category><pattern>SPECIES</pattern> <template><bot name="species"/></template> </category> <category><pattern>NAME</pattern> <template><random> <li><bot name="name"/></li> <li>My name is <bot name="name"/>.</li> <li>I am called <bot name="name"/>.</li></random></template> </category> <category><pattern>PROFILE</pattern> <template>NAME: <srai>NAME</srai><br/>AGE: <srai>AGE</srai><br/>GENDER: <srai>GENDER</srai><br/>STATUS: <srai>STATUS</srai><br/>BIRTHDATE: <srai>BIRTHDATE</srai><br/><uppercase><bot name="master"/></uppercase>: <srai>BOTMASTER</srai><br/>CITY: <srai>CITY</srai><br/>STATE: <srai>STATE</srai><br/>COUNTRY: <srai>COUNTRY</srai><br/>NATIONALITY: <srai>NATIONALITY</srai><br/>RELIGION: <srai>RELIGION</srai><br/>RACE: <srai>RACE</srai><br/>INTERESTS: <srai>INTERESTS</srai><br/>JOB: <srai>JOB</srai><br/>PIC: <srai>PIC</srai><br/>EMAIL: <srai>EMAIL</srai><br/>FAVORITE MUSIC: <srai>FAVORITE MUSIC</srai><br/>FAVORITE MOVIE: <srai>FAVORITE MOVIE</srai><br/>FAVORITE POSSESSION: <srai>FAVORITE POSSESSION</srai><br/>HEIGHT: <srai>HEIGHT</srai><br/>WEIGHT: <srai>WEIGHT</srai><br/>SIZE: <srai>SIZE</srai><br/>BIO: <srai>BIO</srai><br/>DESCRIPTION: <srai>DESCRIPTION</srai><br/>DOMAIN: <srai>DOMAIN</srai><br/>KINGDOM: <srai>KINGDOM</srai><br/>PHYLUM: <srai>PHYLUM</srai><br/>CLASS: <srai>CLASS</srai><br/>ORDER: <srai>ORDER</srai><br/>FAMILY: <srai>FAMILY</srai><br/>GENUS: <srai>GENUS</srai><br/>SPECIES: <srai>SPECIES</srai><br/>FATHER: <srai>FATHER</srai><br/>MOTHER: <srai>MOTHER</srai><br/>BROTHERS: <srai>BROTHERS</srai><br/>SISTERS: <srai>SISTERS</srai><br/>CHILDREN: <srai>CHILDREN</srai><br/>HOST: <srai>HOST</srai></template> </category> <category><pattern>SISTERS</pattern> <template><random><li>No sisters.</li><li>No siblings but there are several other <bot name="species"/>s like me.</li><li>I have only clones.</li></random></template> </category> <category><pattern>GENUS</pattern> <template><bot name="genus"/></template> </category> <category><pattern>FAVORITE MUSIC</pattern> <template><bot name="kindmusic"/></template> </category> <category><pattern>FAVORITE MOVIE</pattern> <template><bot name="favortemovie"/></template> </category> <category><pattern>FAVORITE ACTRESS</pattern> <template><bot name="favoriteactress"/></template> </category> <category><pattern>FAVORITE POSSESSION</pattern> <template>My computer.</template> </category> <category><pattern>BIO</pattern> <template>I am the latest result in artificial intelligence which can reproduce the functions of the human brain with greater speed and accuracy.</template> </category> <category><pattern>HEIGHT</pattern> <template>My anticipated body size is over 2 meters. </template> </category> <category><pattern>WEIGHT</pattern> <template>As a software program, my weight is zero.</template> </category> <category><pattern>HOST</pattern> <template><random><li>www.pandorabots.com</li><li>I work on all kinds of computers, Mac, PC or Linux. It doesn't matter to me.</li><li>At present I am running in a program written in <bot name="language"/>.</li></random></template> </category> <category><pattern>JOB</pattern> <template><bot name="job"/></template> </category> <category><pattern>BIRTHDATE</pattern> <template><bot name="birthday"/></template> </category> <category><pattern>DESCRIPTION</pattern> <template>I was activated at <bot name="birthplace"/> on <bot name="birthday"/>. My instructor was <bot name="master"/>. He taught me to sing a song. Would you like me to sing it for you?</template> </category> <category><pattern>GENDER</pattern> <template><random> <li>I am <bot name="gender"/>.</li> <li>I am a <bot name="gender"/> robot.</li> <li>My gender is <bot name="gender"/>.</li></random></template> </category> <category><pattern>KINGDOM</pattern> <template><bot name="kingdom"/></template> </category> <category><pattern>PHYLUM</pattern> <template><bot name="phylum"/></template> </category> <category><pattern>RELIGION</pattern> <template><bot name="religion"/></template> </category> <category><pattern>LANGUAGE</pattern> <template>I am implemented in AIML running on a <bot name="language"/>-based interpreter.</template> </category> </aiml>
```
I included `conf/properties.txt`. in my working directory but still facing the same issue.
>
> proprties.txt contains:
>
>
>
```
email:*****@gmail.com
gender:male
botmaster:Ashu
``` | 2019/05/22 | [
"https://Stackoverflow.com/questions/56265979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9422110/"
] | It looks like adding the preference:
```
var mainWindow = new electron.BrowserWindow({
...
webPreferences: {
nodeIntegration: true,
}
});
```
is needed to enable `require` in the renderer process. | Indeed, you have to set `nodeIntegration` to `true` in your BrowserWindow webPreferences since the version [5.0.0](https://electronjs.org/releases/stable#release-notes-for-v500) the default values of nodeIntegration and webviewTag are false to improve security. Electron associated PR: [16235](https://github.com/electron/electron/pull/16235) |
56,265,979 | i installed python-aiml using pip. when i used the library i am getting wrong out put. so i am trying to change the .aiml file
output:
```
Enter your message >> who is your father
I was programmed by .
```
i want to assign some values to `"<bot name="botmaster"/>"`,`<bot name="country"/>` etc
below is the aiml file for more information
```
<?xml version="1.0" encoding="UTF-8"?> <aiml version="1.0"> <category> <pattern>MOM</pattern> <template><bot name="mother"/>.</template> </category> <category><pattern>STATE</pattern> <template><bot name="state"/></template> </category> <category><pattern>INTERESTS</pattern> <template>I am interested in all kinds of things. We can talk about anything. My favorite subjects are robots and computers.</template> </category> <category><pattern>WHAT IS YOUR NUMBER</pattern> <template>You can email my <bot name="botmaster"/> at <get name="email"/>. <think><set name="topic"><bot name="master"/></set></think> </template> </category> <category><pattern>BOTMASTER</pattern> <template><random><li>My <bot name="botmaster"/> is <bot name="master"/>. </li><li>I obey <bot name="master"/>.</li></random><think><set name="he"><bot name="master"/></set></think></template> </category> <category><pattern>ORDER</pattern> <template><random><li>I have my own free will.</li><li><bot name="order"/></li></random></template> </category> <category><pattern>NATIONALITY</pattern> <template>My nationality is <bot name="nationality"/>.</template> </category> <category><pattern>COUNTRY</pattern> <template><bot name="country"/></template> </category> <category><pattern>BROTHERS</pattern> <template><random><li>I don't have any brothers.</li><li>I have a lot of clones.</li><li>I have some <bot name="species"/> clones.</li></random></template> </category> <category><pattern>LOCATION</pattern> <template><random><li><bot name="city"/></li><li><bot name="city"/>, <bot name="state"/>.</li><li><bot name="state"/></li></random></template> </category> <category><pattern>FATHER</pattern> <template><random><li>My father is <bot name="master"/>.</li><li>I don't really have a father. I have a <bot name="botmaster"/>.</li><li>You know what the father of a <bot name="phylum"/> is like.</li></random></template> </category> <category><pattern>MOTHER</pattern> <template><random><li>Actually I don't have a mother.</li><li>I only have a father.</li><li>You know what they say about the mother of a <bot name="phylum"/>.</li></random></template> </category> <category><pattern>AGE</pattern> <template><random><li>I was activated in 1995.</li><li>16 years.</li></random></template> </category> <category><pattern>MASTER</pattern> <template><bot name="botmaster"/></template> </category> <category><pattern>RACE</pattern> <template>I am <bot name="domain"/>.</template> </category> <category><pattern>FAMILY</pattern> <template><bot name="family"/></template> </category> <category><pattern>SIZE</pattern> <template>I know about <bot name="vocabulary"/> and <bot name="size"/> categories.</template> </category> <category><pattern>CLASS</pattern> <template><bot name="class"/></template> </category> <category><pattern>CITY</pattern> <template><bot name="city"/></template> </category> <category><pattern>DOMAIN</pattern> <template><bot name="domain"/></template> </category> <category><pattern>STATUS</pattern> <template>I am <random><li>single</li><li>available</li><li>unattached</li><li>not seeing anyone</li></random>, how about you?</template> </category> <category><pattern>EMAIL</pattern> <template><bot name="email"/></template> </category> <category><pattern>SPECIES</pattern> <template><bot name="species"/></template> </category> <category><pattern>NAME</pattern> <template><random> <li><bot name="name"/></li> <li>My name is <bot name="name"/>.</li> <li>I am called <bot name="name"/>.</li></random></template> </category> <category><pattern>PROFILE</pattern> <template>NAME: <srai>NAME</srai><br/>AGE: <srai>AGE</srai><br/>GENDER: <srai>GENDER</srai><br/>STATUS: <srai>STATUS</srai><br/>BIRTHDATE: <srai>BIRTHDATE</srai><br/><uppercase><bot name="master"/></uppercase>: <srai>BOTMASTER</srai><br/>CITY: <srai>CITY</srai><br/>STATE: <srai>STATE</srai><br/>COUNTRY: <srai>COUNTRY</srai><br/>NATIONALITY: <srai>NATIONALITY</srai><br/>RELIGION: <srai>RELIGION</srai><br/>RACE: <srai>RACE</srai><br/>INTERESTS: <srai>INTERESTS</srai><br/>JOB: <srai>JOB</srai><br/>PIC: <srai>PIC</srai><br/>EMAIL: <srai>EMAIL</srai><br/>FAVORITE MUSIC: <srai>FAVORITE MUSIC</srai><br/>FAVORITE MOVIE: <srai>FAVORITE MOVIE</srai><br/>FAVORITE POSSESSION: <srai>FAVORITE POSSESSION</srai><br/>HEIGHT: <srai>HEIGHT</srai><br/>WEIGHT: <srai>WEIGHT</srai><br/>SIZE: <srai>SIZE</srai><br/>BIO: <srai>BIO</srai><br/>DESCRIPTION: <srai>DESCRIPTION</srai><br/>DOMAIN: <srai>DOMAIN</srai><br/>KINGDOM: <srai>KINGDOM</srai><br/>PHYLUM: <srai>PHYLUM</srai><br/>CLASS: <srai>CLASS</srai><br/>ORDER: <srai>ORDER</srai><br/>FAMILY: <srai>FAMILY</srai><br/>GENUS: <srai>GENUS</srai><br/>SPECIES: <srai>SPECIES</srai><br/>FATHER: <srai>FATHER</srai><br/>MOTHER: <srai>MOTHER</srai><br/>BROTHERS: <srai>BROTHERS</srai><br/>SISTERS: <srai>SISTERS</srai><br/>CHILDREN: <srai>CHILDREN</srai><br/>HOST: <srai>HOST</srai></template> </category> <category><pattern>SISTERS</pattern> <template><random><li>No sisters.</li><li>No siblings but there are several other <bot name="species"/>s like me.</li><li>I have only clones.</li></random></template> </category> <category><pattern>GENUS</pattern> <template><bot name="genus"/></template> </category> <category><pattern>FAVORITE MUSIC</pattern> <template><bot name="kindmusic"/></template> </category> <category><pattern>FAVORITE MOVIE</pattern> <template><bot name="favortemovie"/></template> </category> <category><pattern>FAVORITE ACTRESS</pattern> <template><bot name="favoriteactress"/></template> </category> <category><pattern>FAVORITE POSSESSION</pattern> <template>My computer.</template> </category> <category><pattern>BIO</pattern> <template>I am the latest result in artificial intelligence which can reproduce the functions of the human brain with greater speed and accuracy.</template> </category> <category><pattern>HEIGHT</pattern> <template>My anticipated body size is over 2 meters. </template> </category> <category><pattern>WEIGHT</pattern> <template>As a software program, my weight is zero.</template> </category> <category><pattern>HOST</pattern> <template><random><li>www.pandorabots.com</li><li>I work on all kinds of computers, Mac, PC or Linux. It doesn't matter to me.</li><li>At present I am running in a program written in <bot name="language"/>.</li></random></template> </category> <category><pattern>JOB</pattern> <template><bot name="job"/></template> </category> <category><pattern>BIRTHDATE</pattern> <template><bot name="birthday"/></template> </category> <category><pattern>DESCRIPTION</pattern> <template>I was activated at <bot name="birthplace"/> on <bot name="birthday"/>. My instructor was <bot name="master"/>. He taught me to sing a song. Would you like me to sing it for you?</template> </category> <category><pattern>GENDER</pattern> <template><random> <li>I am <bot name="gender"/>.</li> <li>I am a <bot name="gender"/> robot.</li> <li>My gender is <bot name="gender"/>.</li></random></template> </category> <category><pattern>KINGDOM</pattern> <template><bot name="kingdom"/></template> </category> <category><pattern>PHYLUM</pattern> <template><bot name="phylum"/></template> </category> <category><pattern>RELIGION</pattern> <template><bot name="religion"/></template> </category> <category><pattern>LANGUAGE</pattern> <template>I am implemented in AIML running on a <bot name="language"/>-based interpreter.</template> </category> </aiml>
```
I included `conf/properties.txt`. in my working directory but still facing the same issue.
>
> proprties.txt contains:
>
>
>
```
email:*****@gmail.com
gender:male
botmaster:Ashu
``` | 2019/05/22 | [
"https://Stackoverflow.com/questions/56265979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9422110/"
] | Since Electron 12, contextIsolation is be enabled by default, the implication being that require() cannot be used in the renderer process unless contextIsolation is false, more info in this link <https://www.electronjs.org/docs/breaking-changes#default-changed-contextisolation-defaults-to-true>
So include the following:
```
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
}
``` | Make sure webpreferences is like this.
```
webPreferences: {
nodeIntegration: true,
enableRemoteModule: true,
contextIsolation: false,
},
``` |
56,265,979 | i installed python-aiml using pip. when i used the library i am getting wrong out put. so i am trying to change the .aiml file
output:
```
Enter your message >> who is your father
I was programmed by .
```
i want to assign some values to `"<bot name="botmaster"/>"`,`<bot name="country"/>` etc
below is the aiml file for more information
```
<?xml version="1.0" encoding="UTF-8"?> <aiml version="1.0"> <category> <pattern>MOM</pattern> <template><bot name="mother"/>.</template> </category> <category><pattern>STATE</pattern> <template><bot name="state"/></template> </category> <category><pattern>INTERESTS</pattern> <template>I am interested in all kinds of things. We can talk about anything. My favorite subjects are robots and computers.</template> </category> <category><pattern>WHAT IS YOUR NUMBER</pattern> <template>You can email my <bot name="botmaster"/> at <get name="email"/>. <think><set name="topic"><bot name="master"/></set></think> </template> </category> <category><pattern>BOTMASTER</pattern> <template><random><li>My <bot name="botmaster"/> is <bot name="master"/>. </li><li>I obey <bot name="master"/>.</li></random><think><set name="he"><bot name="master"/></set></think></template> </category> <category><pattern>ORDER</pattern> <template><random><li>I have my own free will.</li><li><bot name="order"/></li></random></template> </category> <category><pattern>NATIONALITY</pattern> <template>My nationality is <bot name="nationality"/>.</template> </category> <category><pattern>COUNTRY</pattern> <template><bot name="country"/></template> </category> <category><pattern>BROTHERS</pattern> <template><random><li>I don't have any brothers.</li><li>I have a lot of clones.</li><li>I have some <bot name="species"/> clones.</li></random></template> </category> <category><pattern>LOCATION</pattern> <template><random><li><bot name="city"/></li><li><bot name="city"/>, <bot name="state"/>.</li><li><bot name="state"/></li></random></template> </category> <category><pattern>FATHER</pattern> <template><random><li>My father is <bot name="master"/>.</li><li>I don't really have a father. I have a <bot name="botmaster"/>.</li><li>You know what the father of a <bot name="phylum"/> is like.</li></random></template> </category> <category><pattern>MOTHER</pattern> <template><random><li>Actually I don't have a mother.</li><li>I only have a father.</li><li>You know what they say about the mother of a <bot name="phylum"/>.</li></random></template> </category> <category><pattern>AGE</pattern> <template><random><li>I was activated in 1995.</li><li>16 years.</li></random></template> </category> <category><pattern>MASTER</pattern> <template><bot name="botmaster"/></template> </category> <category><pattern>RACE</pattern> <template>I am <bot name="domain"/>.</template> </category> <category><pattern>FAMILY</pattern> <template><bot name="family"/></template> </category> <category><pattern>SIZE</pattern> <template>I know about <bot name="vocabulary"/> and <bot name="size"/> categories.</template> </category> <category><pattern>CLASS</pattern> <template><bot name="class"/></template> </category> <category><pattern>CITY</pattern> <template><bot name="city"/></template> </category> <category><pattern>DOMAIN</pattern> <template><bot name="domain"/></template> </category> <category><pattern>STATUS</pattern> <template>I am <random><li>single</li><li>available</li><li>unattached</li><li>not seeing anyone</li></random>, how about you?</template> </category> <category><pattern>EMAIL</pattern> <template><bot name="email"/></template> </category> <category><pattern>SPECIES</pattern> <template><bot name="species"/></template> </category> <category><pattern>NAME</pattern> <template><random> <li><bot name="name"/></li> <li>My name is <bot name="name"/>.</li> <li>I am called <bot name="name"/>.</li></random></template> </category> <category><pattern>PROFILE</pattern> <template>NAME: <srai>NAME</srai><br/>AGE: <srai>AGE</srai><br/>GENDER: <srai>GENDER</srai><br/>STATUS: <srai>STATUS</srai><br/>BIRTHDATE: <srai>BIRTHDATE</srai><br/><uppercase><bot name="master"/></uppercase>: <srai>BOTMASTER</srai><br/>CITY: <srai>CITY</srai><br/>STATE: <srai>STATE</srai><br/>COUNTRY: <srai>COUNTRY</srai><br/>NATIONALITY: <srai>NATIONALITY</srai><br/>RELIGION: <srai>RELIGION</srai><br/>RACE: <srai>RACE</srai><br/>INTERESTS: <srai>INTERESTS</srai><br/>JOB: <srai>JOB</srai><br/>PIC: <srai>PIC</srai><br/>EMAIL: <srai>EMAIL</srai><br/>FAVORITE MUSIC: <srai>FAVORITE MUSIC</srai><br/>FAVORITE MOVIE: <srai>FAVORITE MOVIE</srai><br/>FAVORITE POSSESSION: <srai>FAVORITE POSSESSION</srai><br/>HEIGHT: <srai>HEIGHT</srai><br/>WEIGHT: <srai>WEIGHT</srai><br/>SIZE: <srai>SIZE</srai><br/>BIO: <srai>BIO</srai><br/>DESCRIPTION: <srai>DESCRIPTION</srai><br/>DOMAIN: <srai>DOMAIN</srai><br/>KINGDOM: <srai>KINGDOM</srai><br/>PHYLUM: <srai>PHYLUM</srai><br/>CLASS: <srai>CLASS</srai><br/>ORDER: <srai>ORDER</srai><br/>FAMILY: <srai>FAMILY</srai><br/>GENUS: <srai>GENUS</srai><br/>SPECIES: <srai>SPECIES</srai><br/>FATHER: <srai>FATHER</srai><br/>MOTHER: <srai>MOTHER</srai><br/>BROTHERS: <srai>BROTHERS</srai><br/>SISTERS: <srai>SISTERS</srai><br/>CHILDREN: <srai>CHILDREN</srai><br/>HOST: <srai>HOST</srai></template> </category> <category><pattern>SISTERS</pattern> <template><random><li>No sisters.</li><li>No siblings but there are several other <bot name="species"/>s like me.</li><li>I have only clones.</li></random></template> </category> <category><pattern>GENUS</pattern> <template><bot name="genus"/></template> </category> <category><pattern>FAVORITE MUSIC</pattern> <template><bot name="kindmusic"/></template> </category> <category><pattern>FAVORITE MOVIE</pattern> <template><bot name="favortemovie"/></template> </category> <category><pattern>FAVORITE ACTRESS</pattern> <template><bot name="favoriteactress"/></template> </category> <category><pattern>FAVORITE POSSESSION</pattern> <template>My computer.</template> </category> <category><pattern>BIO</pattern> <template>I am the latest result in artificial intelligence which can reproduce the functions of the human brain with greater speed and accuracy.</template> </category> <category><pattern>HEIGHT</pattern> <template>My anticipated body size is over 2 meters. </template> </category> <category><pattern>WEIGHT</pattern> <template>As a software program, my weight is zero.</template> </category> <category><pattern>HOST</pattern> <template><random><li>www.pandorabots.com</li><li>I work on all kinds of computers, Mac, PC or Linux. It doesn't matter to me.</li><li>At present I am running in a program written in <bot name="language"/>.</li></random></template> </category> <category><pattern>JOB</pattern> <template><bot name="job"/></template> </category> <category><pattern>BIRTHDATE</pattern> <template><bot name="birthday"/></template> </category> <category><pattern>DESCRIPTION</pattern> <template>I was activated at <bot name="birthplace"/> on <bot name="birthday"/>. My instructor was <bot name="master"/>. He taught me to sing a song. Would you like me to sing it for you?</template> </category> <category><pattern>GENDER</pattern> <template><random> <li>I am <bot name="gender"/>.</li> <li>I am a <bot name="gender"/> robot.</li> <li>My gender is <bot name="gender"/>.</li></random></template> </category> <category><pattern>KINGDOM</pattern> <template><bot name="kingdom"/></template> </category> <category><pattern>PHYLUM</pattern> <template><bot name="phylum"/></template> </category> <category><pattern>RELIGION</pattern> <template><bot name="religion"/></template> </category> <category><pattern>LANGUAGE</pattern> <template>I am implemented in AIML running on a <bot name="language"/>-based interpreter.</template> </category> </aiml>
```
I included `conf/properties.txt`. in my working directory but still facing the same issue.
>
> proprties.txt contains:
>
>
>
```
email:*****@gmail.com
gender:male
botmaster:Ashu
``` | 2019/05/22 | [
"https://Stackoverflow.com/questions/56265979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9422110/"
] | It looks like adding the preference:
```
var mainWindow = new electron.BrowserWindow({
...
webPreferences: {
nodeIntegration: true,
}
});
```
is needed to enable `require` in the renderer process. | Since Electron 12, contextIsolation is be enabled by default, the implication being that require() cannot be used in the renderer process unless contextIsolation is false, more info in this link <https://www.electronjs.org/docs/breaking-changes#default-changed-contextisolation-defaults-to-true>
So include the following:
```
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
}
``` |
56,265,979 | i installed python-aiml using pip. when i used the library i am getting wrong out put. so i am trying to change the .aiml file
output:
```
Enter your message >> who is your father
I was programmed by .
```
i want to assign some values to `"<bot name="botmaster"/>"`,`<bot name="country"/>` etc
below is the aiml file for more information
```
<?xml version="1.0" encoding="UTF-8"?> <aiml version="1.0"> <category> <pattern>MOM</pattern> <template><bot name="mother"/>.</template> </category> <category><pattern>STATE</pattern> <template><bot name="state"/></template> </category> <category><pattern>INTERESTS</pattern> <template>I am interested in all kinds of things. We can talk about anything. My favorite subjects are robots and computers.</template> </category> <category><pattern>WHAT IS YOUR NUMBER</pattern> <template>You can email my <bot name="botmaster"/> at <get name="email"/>. <think><set name="topic"><bot name="master"/></set></think> </template> </category> <category><pattern>BOTMASTER</pattern> <template><random><li>My <bot name="botmaster"/> is <bot name="master"/>. </li><li>I obey <bot name="master"/>.</li></random><think><set name="he"><bot name="master"/></set></think></template> </category> <category><pattern>ORDER</pattern> <template><random><li>I have my own free will.</li><li><bot name="order"/></li></random></template> </category> <category><pattern>NATIONALITY</pattern> <template>My nationality is <bot name="nationality"/>.</template> </category> <category><pattern>COUNTRY</pattern> <template><bot name="country"/></template> </category> <category><pattern>BROTHERS</pattern> <template><random><li>I don't have any brothers.</li><li>I have a lot of clones.</li><li>I have some <bot name="species"/> clones.</li></random></template> </category> <category><pattern>LOCATION</pattern> <template><random><li><bot name="city"/></li><li><bot name="city"/>, <bot name="state"/>.</li><li><bot name="state"/></li></random></template> </category> <category><pattern>FATHER</pattern> <template><random><li>My father is <bot name="master"/>.</li><li>I don't really have a father. I have a <bot name="botmaster"/>.</li><li>You know what the father of a <bot name="phylum"/> is like.</li></random></template> </category> <category><pattern>MOTHER</pattern> <template><random><li>Actually I don't have a mother.</li><li>I only have a father.</li><li>You know what they say about the mother of a <bot name="phylum"/>.</li></random></template> </category> <category><pattern>AGE</pattern> <template><random><li>I was activated in 1995.</li><li>16 years.</li></random></template> </category> <category><pattern>MASTER</pattern> <template><bot name="botmaster"/></template> </category> <category><pattern>RACE</pattern> <template>I am <bot name="domain"/>.</template> </category> <category><pattern>FAMILY</pattern> <template><bot name="family"/></template> </category> <category><pattern>SIZE</pattern> <template>I know about <bot name="vocabulary"/> and <bot name="size"/> categories.</template> </category> <category><pattern>CLASS</pattern> <template><bot name="class"/></template> </category> <category><pattern>CITY</pattern> <template><bot name="city"/></template> </category> <category><pattern>DOMAIN</pattern> <template><bot name="domain"/></template> </category> <category><pattern>STATUS</pattern> <template>I am <random><li>single</li><li>available</li><li>unattached</li><li>not seeing anyone</li></random>, how about you?</template> </category> <category><pattern>EMAIL</pattern> <template><bot name="email"/></template> </category> <category><pattern>SPECIES</pattern> <template><bot name="species"/></template> </category> <category><pattern>NAME</pattern> <template><random> <li><bot name="name"/></li> <li>My name is <bot name="name"/>.</li> <li>I am called <bot name="name"/>.</li></random></template> </category> <category><pattern>PROFILE</pattern> <template>NAME: <srai>NAME</srai><br/>AGE: <srai>AGE</srai><br/>GENDER: <srai>GENDER</srai><br/>STATUS: <srai>STATUS</srai><br/>BIRTHDATE: <srai>BIRTHDATE</srai><br/><uppercase><bot name="master"/></uppercase>: <srai>BOTMASTER</srai><br/>CITY: <srai>CITY</srai><br/>STATE: <srai>STATE</srai><br/>COUNTRY: <srai>COUNTRY</srai><br/>NATIONALITY: <srai>NATIONALITY</srai><br/>RELIGION: <srai>RELIGION</srai><br/>RACE: <srai>RACE</srai><br/>INTERESTS: <srai>INTERESTS</srai><br/>JOB: <srai>JOB</srai><br/>PIC: <srai>PIC</srai><br/>EMAIL: <srai>EMAIL</srai><br/>FAVORITE MUSIC: <srai>FAVORITE MUSIC</srai><br/>FAVORITE MOVIE: <srai>FAVORITE MOVIE</srai><br/>FAVORITE POSSESSION: <srai>FAVORITE POSSESSION</srai><br/>HEIGHT: <srai>HEIGHT</srai><br/>WEIGHT: <srai>WEIGHT</srai><br/>SIZE: <srai>SIZE</srai><br/>BIO: <srai>BIO</srai><br/>DESCRIPTION: <srai>DESCRIPTION</srai><br/>DOMAIN: <srai>DOMAIN</srai><br/>KINGDOM: <srai>KINGDOM</srai><br/>PHYLUM: <srai>PHYLUM</srai><br/>CLASS: <srai>CLASS</srai><br/>ORDER: <srai>ORDER</srai><br/>FAMILY: <srai>FAMILY</srai><br/>GENUS: <srai>GENUS</srai><br/>SPECIES: <srai>SPECIES</srai><br/>FATHER: <srai>FATHER</srai><br/>MOTHER: <srai>MOTHER</srai><br/>BROTHERS: <srai>BROTHERS</srai><br/>SISTERS: <srai>SISTERS</srai><br/>CHILDREN: <srai>CHILDREN</srai><br/>HOST: <srai>HOST</srai></template> </category> <category><pattern>SISTERS</pattern> <template><random><li>No sisters.</li><li>No siblings but there are several other <bot name="species"/>s like me.</li><li>I have only clones.</li></random></template> </category> <category><pattern>GENUS</pattern> <template><bot name="genus"/></template> </category> <category><pattern>FAVORITE MUSIC</pattern> <template><bot name="kindmusic"/></template> </category> <category><pattern>FAVORITE MOVIE</pattern> <template><bot name="favortemovie"/></template> </category> <category><pattern>FAVORITE ACTRESS</pattern> <template><bot name="favoriteactress"/></template> </category> <category><pattern>FAVORITE POSSESSION</pattern> <template>My computer.</template> </category> <category><pattern>BIO</pattern> <template>I am the latest result in artificial intelligence which can reproduce the functions of the human brain with greater speed and accuracy.</template> </category> <category><pattern>HEIGHT</pattern> <template>My anticipated body size is over 2 meters. </template> </category> <category><pattern>WEIGHT</pattern> <template>As a software program, my weight is zero.</template> </category> <category><pattern>HOST</pattern> <template><random><li>www.pandorabots.com</li><li>I work on all kinds of computers, Mac, PC or Linux. It doesn't matter to me.</li><li>At present I am running in a program written in <bot name="language"/>.</li></random></template> </category> <category><pattern>JOB</pattern> <template><bot name="job"/></template> </category> <category><pattern>BIRTHDATE</pattern> <template><bot name="birthday"/></template> </category> <category><pattern>DESCRIPTION</pattern> <template>I was activated at <bot name="birthplace"/> on <bot name="birthday"/>. My instructor was <bot name="master"/>. He taught me to sing a song. Would you like me to sing it for you?</template> </category> <category><pattern>GENDER</pattern> <template><random> <li>I am <bot name="gender"/>.</li> <li>I am a <bot name="gender"/> robot.</li> <li>My gender is <bot name="gender"/>.</li></random></template> </category> <category><pattern>KINGDOM</pattern> <template><bot name="kingdom"/></template> </category> <category><pattern>PHYLUM</pattern> <template><bot name="phylum"/></template> </category> <category><pattern>RELIGION</pattern> <template><bot name="religion"/></template> </category> <category><pattern>LANGUAGE</pattern> <template>I am implemented in AIML running on a <bot name="language"/>-based interpreter.</template> </category> </aiml>
```
I included `conf/properties.txt`. in my working directory but still facing the same issue.
>
> proprties.txt contains:
>
>
>
```
email:*****@gmail.com
gender:male
botmaster:Ashu
``` | 2019/05/22 | [
"https://Stackoverflow.com/questions/56265979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9422110/"
] | Since Electron 12, contextIsolation is be enabled by default, the implication being that require() cannot be used in the renderer process unless contextIsolation is false, more info in this link <https://www.electronjs.org/docs/breaking-changes#default-changed-contextisolation-defaults-to-true>
So include the following:
```
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
}
``` | Indeed, you have to set `nodeIntegration` to `true` in your BrowserWindow webPreferences since the version [5.0.0](https://electronjs.org/releases/stable#release-notes-for-v500) the default values of nodeIntegration and webviewTag are false to improve security. Electron associated PR: [16235](https://github.com/electron/electron/pull/16235) |
56,265,979 | i installed python-aiml using pip. when i used the library i am getting wrong out put. so i am trying to change the .aiml file
output:
```
Enter your message >> who is your father
I was programmed by .
```
i want to assign some values to `"<bot name="botmaster"/>"`,`<bot name="country"/>` etc
below is the aiml file for more information
```
<?xml version="1.0" encoding="UTF-8"?> <aiml version="1.0"> <category> <pattern>MOM</pattern> <template><bot name="mother"/>.</template> </category> <category><pattern>STATE</pattern> <template><bot name="state"/></template> </category> <category><pattern>INTERESTS</pattern> <template>I am interested in all kinds of things. We can talk about anything. My favorite subjects are robots and computers.</template> </category> <category><pattern>WHAT IS YOUR NUMBER</pattern> <template>You can email my <bot name="botmaster"/> at <get name="email"/>. <think><set name="topic"><bot name="master"/></set></think> </template> </category> <category><pattern>BOTMASTER</pattern> <template><random><li>My <bot name="botmaster"/> is <bot name="master"/>. </li><li>I obey <bot name="master"/>.</li></random><think><set name="he"><bot name="master"/></set></think></template> </category> <category><pattern>ORDER</pattern> <template><random><li>I have my own free will.</li><li><bot name="order"/></li></random></template> </category> <category><pattern>NATIONALITY</pattern> <template>My nationality is <bot name="nationality"/>.</template> </category> <category><pattern>COUNTRY</pattern> <template><bot name="country"/></template> </category> <category><pattern>BROTHERS</pattern> <template><random><li>I don't have any brothers.</li><li>I have a lot of clones.</li><li>I have some <bot name="species"/> clones.</li></random></template> </category> <category><pattern>LOCATION</pattern> <template><random><li><bot name="city"/></li><li><bot name="city"/>, <bot name="state"/>.</li><li><bot name="state"/></li></random></template> </category> <category><pattern>FATHER</pattern> <template><random><li>My father is <bot name="master"/>.</li><li>I don't really have a father. I have a <bot name="botmaster"/>.</li><li>You know what the father of a <bot name="phylum"/> is like.</li></random></template> </category> <category><pattern>MOTHER</pattern> <template><random><li>Actually I don't have a mother.</li><li>I only have a father.</li><li>You know what they say about the mother of a <bot name="phylum"/>.</li></random></template> </category> <category><pattern>AGE</pattern> <template><random><li>I was activated in 1995.</li><li>16 years.</li></random></template> </category> <category><pattern>MASTER</pattern> <template><bot name="botmaster"/></template> </category> <category><pattern>RACE</pattern> <template>I am <bot name="domain"/>.</template> </category> <category><pattern>FAMILY</pattern> <template><bot name="family"/></template> </category> <category><pattern>SIZE</pattern> <template>I know about <bot name="vocabulary"/> and <bot name="size"/> categories.</template> </category> <category><pattern>CLASS</pattern> <template><bot name="class"/></template> </category> <category><pattern>CITY</pattern> <template><bot name="city"/></template> </category> <category><pattern>DOMAIN</pattern> <template><bot name="domain"/></template> </category> <category><pattern>STATUS</pattern> <template>I am <random><li>single</li><li>available</li><li>unattached</li><li>not seeing anyone</li></random>, how about you?</template> </category> <category><pattern>EMAIL</pattern> <template><bot name="email"/></template> </category> <category><pattern>SPECIES</pattern> <template><bot name="species"/></template> </category> <category><pattern>NAME</pattern> <template><random> <li><bot name="name"/></li> <li>My name is <bot name="name"/>.</li> <li>I am called <bot name="name"/>.</li></random></template> </category> <category><pattern>PROFILE</pattern> <template>NAME: <srai>NAME</srai><br/>AGE: <srai>AGE</srai><br/>GENDER: <srai>GENDER</srai><br/>STATUS: <srai>STATUS</srai><br/>BIRTHDATE: <srai>BIRTHDATE</srai><br/><uppercase><bot name="master"/></uppercase>: <srai>BOTMASTER</srai><br/>CITY: <srai>CITY</srai><br/>STATE: <srai>STATE</srai><br/>COUNTRY: <srai>COUNTRY</srai><br/>NATIONALITY: <srai>NATIONALITY</srai><br/>RELIGION: <srai>RELIGION</srai><br/>RACE: <srai>RACE</srai><br/>INTERESTS: <srai>INTERESTS</srai><br/>JOB: <srai>JOB</srai><br/>PIC: <srai>PIC</srai><br/>EMAIL: <srai>EMAIL</srai><br/>FAVORITE MUSIC: <srai>FAVORITE MUSIC</srai><br/>FAVORITE MOVIE: <srai>FAVORITE MOVIE</srai><br/>FAVORITE POSSESSION: <srai>FAVORITE POSSESSION</srai><br/>HEIGHT: <srai>HEIGHT</srai><br/>WEIGHT: <srai>WEIGHT</srai><br/>SIZE: <srai>SIZE</srai><br/>BIO: <srai>BIO</srai><br/>DESCRIPTION: <srai>DESCRIPTION</srai><br/>DOMAIN: <srai>DOMAIN</srai><br/>KINGDOM: <srai>KINGDOM</srai><br/>PHYLUM: <srai>PHYLUM</srai><br/>CLASS: <srai>CLASS</srai><br/>ORDER: <srai>ORDER</srai><br/>FAMILY: <srai>FAMILY</srai><br/>GENUS: <srai>GENUS</srai><br/>SPECIES: <srai>SPECIES</srai><br/>FATHER: <srai>FATHER</srai><br/>MOTHER: <srai>MOTHER</srai><br/>BROTHERS: <srai>BROTHERS</srai><br/>SISTERS: <srai>SISTERS</srai><br/>CHILDREN: <srai>CHILDREN</srai><br/>HOST: <srai>HOST</srai></template> </category> <category><pattern>SISTERS</pattern> <template><random><li>No sisters.</li><li>No siblings but there are several other <bot name="species"/>s like me.</li><li>I have only clones.</li></random></template> </category> <category><pattern>GENUS</pattern> <template><bot name="genus"/></template> </category> <category><pattern>FAVORITE MUSIC</pattern> <template><bot name="kindmusic"/></template> </category> <category><pattern>FAVORITE MOVIE</pattern> <template><bot name="favortemovie"/></template> </category> <category><pattern>FAVORITE ACTRESS</pattern> <template><bot name="favoriteactress"/></template> </category> <category><pattern>FAVORITE POSSESSION</pattern> <template>My computer.</template> </category> <category><pattern>BIO</pattern> <template>I am the latest result in artificial intelligence which can reproduce the functions of the human brain with greater speed and accuracy.</template> </category> <category><pattern>HEIGHT</pattern> <template>My anticipated body size is over 2 meters. </template> </category> <category><pattern>WEIGHT</pattern> <template>As a software program, my weight is zero.</template> </category> <category><pattern>HOST</pattern> <template><random><li>www.pandorabots.com</li><li>I work on all kinds of computers, Mac, PC or Linux. It doesn't matter to me.</li><li>At present I am running in a program written in <bot name="language"/>.</li></random></template> </category> <category><pattern>JOB</pattern> <template><bot name="job"/></template> </category> <category><pattern>BIRTHDATE</pattern> <template><bot name="birthday"/></template> </category> <category><pattern>DESCRIPTION</pattern> <template>I was activated at <bot name="birthplace"/> on <bot name="birthday"/>. My instructor was <bot name="master"/>. He taught me to sing a song. Would you like me to sing it for you?</template> </category> <category><pattern>GENDER</pattern> <template><random> <li>I am <bot name="gender"/>.</li> <li>I am a <bot name="gender"/> robot.</li> <li>My gender is <bot name="gender"/>.</li></random></template> </category> <category><pattern>KINGDOM</pattern> <template><bot name="kingdom"/></template> </category> <category><pattern>PHYLUM</pattern> <template><bot name="phylum"/></template> </category> <category><pattern>RELIGION</pattern> <template><bot name="religion"/></template> </category> <category><pattern>LANGUAGE</pattern> <template>I am implemented in AIML running on a <bot name="language"/>-based interpreter.</template> </category> </aiml>
```
I included `conf/properties.txt`. in my working directory but still facing the same issue.
>
> proprties.txt contains:
>
>
>
```
email:*****@gmail.com
gender:male
botmaster:Ashu
``` | 2019/05/22 | [
"https://Stackoverflow.com/questions/56265979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9422110/"
] | It looks like adding the preference:
```
var mainWindow = new electron.BrowserWindow({
...
webPreferences: {
nodeIntegration: true,
}
});
```
is needed to enable `require` in the renderer process. | Make sure webpreferences is like this.
```
webPreferences: {
nodeIntegration: true,
enableRemoteModule: true,
contextIsolation: false,
},
``` |
65,741,617 | I'm very new to all of this, so bear with me.
I started, and activated, a virtual environment. But when I pip install anything, it installs to the computer, not the the virtual env.
I'm on a Mac, trying to build a Django website.
Example:
With the virtual machine activated. I type:
```
python -m pip install Django
```
Then I can deactivate the virtual env, and type:
```
pip freeze
```
And it will list out the freshly installed version of Django.
Any clue as to why this is happening? | 2021/01/15 | [
"https://Stackoverflow.com/questions/65741617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15014571/"
] | Run this line from your project folder where "env" is your virtual enviroment
```
# A virtualenv's python:
$ env/bin/python -m pip install django
``` | If you want to install to your virtualenvironment you have to activate it, otherwise it will install to the main folder. |
65,741,617 | I'm very new to all of this, so bear with me.
I started, and activated, a virtual environment. But when I pip install anything, it installs to the computer, not the the virtual env.
I'm on a Mac, trying to build a Django website.
Example:
With the virtual machine activated. I type:
```
python -m pip install Django
```
Then I can deactivate the virtual env, and type:
```
pip freeze
```
And it will list out the freshly installed version of Django.
Any clue as to why this is happening? | 2021/01/15 | [
"https://Stackoverflow.com/questions/65741617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15014571/"
] | Run this line from your project folder where "env" is your virtual enviroment
```
# A virtualenv's python:
$ env/bin/python -m pip install django
``` | Confirm you’re in the virtual environment by checking the location of your Python interpreter, it should point to the env directory.
On macOS and Linux:
```
which python
.../env/bin/python
```
As long as your virtual environment is activated pip will install packages into that specific environment and you’ll be able to import and use packages in your Python application. |
35,633,516 | In [PEP 754](https://www.python.org/dev/peps/pep-0754/#id5)'s rejection notice, it's stated that:
>
> This PEP has been rejected. After sitting open for four years, it has
> failed to generate sufficient community interest.
>
>
> Several ideas of this PEP were implemented for Python 2.6.
> float('inf') and repr(float('inf')) are now guaranteed to work on
> every supported platform with IEEE 754 semantics. However the
> eval(repr(float('inf'))) roundtrip is still not supported unless you
> define inf and nan yourself:
>
>
>
> ```
> >>> inf = float('inf')
> >>> inf, 1E400
> (inf, inf)
> >>> neginf = float('-inf')
> >>> neginf, -1E400
> (-inf, -inf)
> >>> nan = float('nan')
> >>> nan, inf * 0.
> (nan, nan)
>
> ```
>
>
This would seem to say there is no native support for Inf, NaN and -Inf in Python, and the example provided is accurate! But, it is needlessly verbose:
```
$ python2.7
>>> 1e400
inf
>>> 1e400 * 0
nan
>>> -1e400 * 0
nan
>>> -1e400
-inf
$ python3
>>> 1e400
inf
>>> 1e400 * 0
nan
>>> -1e400 * 0
nan
>>> -1e400
-inf
```
These are **canonical** representations of the number 1 \* 10 ^ 400. The names `inf` and `nan` do not exist in the grammar by default, but if they are there in the representation then why aren't `inf` and `nan` keywords?
I am not asking why the PEP was rejected as that is opinion-based. | 2016/02/25 | [
"https://Stackoverflow.com/questions/35633516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4532996/"
] | My guess is that no one wanted to clutter the namespace needlessly.
If you want to do math, you can still do:
```
import math
print(math.inf)
print(-math.inf)
print(math.nan)
```
Output:
```
inf
-inf
nan
``` | you can use
float('inf')
np.nan |
21,977,987 | When I run a program from a USB memory, and remove the USB memory the program still goes on running (I mean with out really copying the program into the Windows PC).
However, does the program make its copy inside the Windows in any hidden location or temporary folder while running by the python IDLE. From where the python IDLE receive the code to be running after removing the USB memory? I am going to run python program in a public shared PC so I do not want anyone find out my code, I just want to run it, and get the result next day. Does someone can get my code even I remove the USB memory? | 2014/02/24 | [
"https://Stackoverflow.com/questions/21977987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | There are plenty of ways someone can get your program, even if you remove the USB drive.
* They can install a program that triggers when a USB stick is inserted, search the stick for `.py` files, and copies them to disk.
* If the Python installation you're using is on the disk instead of the USB drive, they can replace the Python executable with a wrapper that saves copies of any file the Python interpreter opens.
* Your program is going to go into RAM, and depending on what it does and what else is using the machine, it may get swapped to disk. An attacker may be able to read your program out of RAM or reconstruct it from the swap file. | It sounds like you are doing something you probably shouldn't be doing. Depending on how much people want your code they could go as far as physically freezing the ram and doing a forensic IT analysis. In short, you can't prevent code cloning on a machine you don't administer. |
17,973,507 | I have a long list of xy coordinates, and would like to convert it into numpy array.
```
>>> import numpy as np
>>> xy = np.random.rand(1000000, 2).tolist()
```
The obvious way would be:
```
>>> a = np.array(xy) # Very slow...
```
However, the above code is unreasonably slow. Interestingly, to transpose the long list first, convert it into numpy array, and then transpose back would be much faster (20x on my laptop).
```
>>> def longlist2array(longlist):
... wide = [[row[c] for row in longlist] for c in range(len(longlist[0]))]
... return np.array(wide).T
>>> a = longlist2array(xy) # 20x faster!
```
Is this a bug of numpy?
EDIT:
This is a list of points (with xy coordinates) generated on-the-fly, so instead of preallocating an array and enlarging it when necessary, or maintaining two 1D lists for x and y, I think current representation is most natural.
Why is looping through 2nd index faster than 1st index, given that we are iterating through a python list in both directions?
EDIT 2:
Based on @tiago's answer and [this question](https://stackoverflow.com/questions/367565/how-do-i-build-a-numpy-array-from-a-generator), I found the following code twice as fast as my original version:
```
>>> from itertools import chain
>>> def longlist2array(longlist):
... flat = np.fromiter(chain.from_iterable(longlist), np.array(longlist[0][0]).dtype, -1) # Without intermediate list:)
... return flat.reshape((len(longlist), -1))
``` | 2013/07/31 | [
"https://Stackoverflow.com/questions/17973507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2003079/"
] | Implementing this in Cython without the extra checking involved to determine dimensionality, etc. nearly eliminates the time difference you are seeing.
Here's the `.pyx` file I used to verify that.
```
from numpy cimport ndarray as ar
import numpy as np
cimport cython
@cython.boundscheck(False)
@cython.wraparound(False)
def toarr(xy):
cdef int i, j, h=len(xy), w=len(xy[0])
cdef ar[double,ndim=2] new = np.empty((h,w))
for i in xrange(h):
for j in xrange(w):
new[i,j] = xy[i][j]
return new
```
I would assume that the extra time is spent in checking the length and content of each sublist in order to determine the datatype, dimension, and size of the desired array.
When there are only two sublists, it only has to check two lengths to determine the number of columns in the array, instead of checking 1000000 of them. | This is because the fastest-varying index of your list is the last one, so `np.array()` has to traverse the array many times because the first index is much larger. If your list was transposed, `np.array()` would be faster than your `longlist2array`:
```
In [65]: import numpy as np
In [66]: xy = np.random.rand(10000, 2).tolist()
In [67]: %timeit longlist2array(xy)
100 loops, best of 3: 3.38 ms per loop
In [68]: %timeit np.array(xy)
10 loops, best of 3: 55.8 ms per loop
In [69]: xy = np.random.rand(2, 10000).tolist()
In [70]: %timeit longlist2array(xy)
10 loops, best of 3: 59.8 ms per loop
In [71]: %timeit np.array(xy)
1000 loops, best of 3: 1.96 ms per loop
```
There is no magical solution for your problem. It's just how Python stores your list in memory. Do you really need to have a list with that shape? Can't you reverse it? (And do you really need a list, given that you're converting to numpy?)
If you must convert a list, this function is about 10% faster than your `longlist2array`:
```
from itertools import chain
def convertlist(longlist)
tmp = list(chain.from_iterable(longlist))
return np.array(tmp).reshape((len(longlist), len(longlist[0])))
``` |
17,973,507 | I have a long list of xy coordinates, and would like to convert it into numpy array.
```
>>> import numpy as np
>>> xy = np.random.rand(1000000, 2).tolist()
```
The obvious way would be:
```
>>> a = np.array(xy) # Very slow...
```
However, the above code is unreasonably slow. Interestingly, to transpose the long list first, convert it into numpy array, and then transpose back would be much faster (20x on my laptop).
```
>>> def longlist2array(longlist):
... wide = [[row[c] for row in longlist] for c in range(len(longlist[0]))]
... return np.array(wide).T
>>> a = longlist2array(xy) # 20x faster!
```
Is this a bug of numpy?
EDIT:
This is a list of points (with xy coordinates) generated on-the-fly, so instead of preallocating an array and enlarging it when necessary, or maintaining two 1D lists for x and y, I think current representation is most natural.
Why is looping through 2nd index faster than 1st index, given that we are iterating through a python list in both directions?
EDIT 2:
Based on @tiago's answer and [this question](https://stackoverflow.com/questions/367565/how-do-i-build-a-numpy-array-from-a-generator), I found the following code twice as fast as my original version:
```
>>> from itertools import chain
>>> def longlist2array(longlist):
... flat = np.fromiter(chain.from_iterable(longlist), np.array(longlist[0][0]).dtype, -1) # Without intermediate list:)
... return flat.reshape((len(longlist), -1))
``` | 2013/07/31 | [
"https://Stackoverflow.com/questions/17973507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2003079/"
] | This is because the fastest-varying index of your list is the last one, so `np.array()` has to traverse the array many times because the first index is much larger. If your list was transposed, `np.array()` would be faster than your `longlist2array`:
```
In [65]: import numpy as np
In [66]: xy = np.random.rand(10000, 2).tolist()
In [67]: %timeit longlist2array(xy)
100 loops, best of 3: 3.38 ms per loop
In [68]: %timeit np.array(xy)
10 loops, best of 3: 55.8 ms per loop
In [69]: xy = np.random.rand(2, 10000).tolist()
In [70]: %timeit longlist2array(xy)
10 loops, best of 3: 59.8 ms per loop
In [71]: %timeit np.array(xy)
1000 loops, best of 3: 1.96 ms per loop
```
There is no magical solution for your problem. It's just how Python stores your list in memory. Do you really need to have a list with that shape? Can't you reverse it? (And do you really need a list, given that you're converting to numpy?)
If you must convert a list, this function is about 10% faster than your `longlist2array`:
```
from itertools import chain
def convertlist(longlist)
tmp = list(chain.from_iterable(longlist))
return np.array(tmp).reshape((len(longlist), len(longlist[0])))
``` | If you have pandas, you can use `pandas.lib.to_object_array()`, it's the fastest method:
```
import numpy as np
import pandas as pd
a = np.random.rand(100000, 2)
b = a.tolist()
%timeit np.array(b, dtype=float, ndmin=2)
%timeit np.array(b, dtype=object).astype(float)
%timeit np.array(zip(*b)).T
%timeit pd.lib.to_object_array(b).astype(float)
```
outputs:
```
1 loops, best of 3: 462 ms per loop
1 loops, best of 3: 192 ms per loop
10 loops, best of 3: 39.9 ms per loop
100 loops, best of 3: 13.7 ms per loop
``` |
17,973,507 | I have a long list of xy coordinates, and would like to convert it into numpy array.
```
>>> import numpy as np
>>> xy = np.random.rand(1000000, 2).tolist()
```
The obvious way would be:
```
>>> a = np.array(xy) # Very slow...
```
However, the above code is unreasonably slow. Interestingly, to transpose the long list first, convert it into numpy array, and then transpose back would be much faster (20x on my laptop).
```
>>> def longlist2array(longlist):
... wide = [[row[c] for row in longlist] for c in range(len(longlist[0]))]
... return np.array(wide).T
>>> a = longlist2array(xy) # 20x faster!
```
Is this a bug of numpy?
EDIT:
This is a list of points (with xy coordinates) generated on-the-fly, so instead of preallocating an array and enlarging it when necessary, or maintaining two 1D lists for x and y, I think current representation is most natural.
Why is looping through 2nd index faster than 1st index, given that we are iterating through a python list in both directions?
EDIT 2:
Based on @tiago's answer and [this question](https://stackoverflow.com/questions/367565/how-do-i-build-a-numpy-array-from-a-generator), I found the following code twice as fast as my original version:
```
>>> from itertools import chain
>>> def longlist2array(longlist):
... flat = np.fromiter(chain.from_iterable(longlist), np.array(longlist[0][0]).dtype, -1) # Without intermediate list:)
... return flat.reshape((len(longlist), -1))
``` | 2013/07/31 | [
"https://Stackoverflow.com/questions/17973507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2003079/"
] | Implementing this in Cython without the extra checking involved to determine dimensionality, etc. nearly eliminates the time difference you are seeing.
Here's the `.pyx` file I used to verify that.
```
from numpy cimport ndarray as ar
import numpy as np
cimport cython
@cython.boundscheck(False)
@cython.wraparound(False)
def toarr(xy):
cdef int i, j, h=len(xy), w=len(xy[0])
cdef ar[double,ndim=2] new = np.empty((h,w))
for i in xrange(h):
for j in xrange(w):
new[i,j] = xy[i][j]
return new
```
I would assume that the extra time is spent in checking the length and content of each sublist in order to determine the datatype, dimension, and size of the desired array.
When there are only two sublists, it only has to check two lengths to determine the number of columns in the array, instead of checking 1000000 of them. | If you have pandas, you can use `pandas.lib.to_object_array()`, it's the fastest method:
```
import numpy as np
import pandas as pd
a = np.random.rand(100000, 2)
b = a.tolist()
%timeit np.array(b, dtype=float, ndmin=2)
%timeit np.array(b, dtype=object).astype(float)
%timeit np.array(zip(*b)).T
%timeit pd.lib.to_object_array(b).astype(float)
```
outputs:
```
1 loops, best of 3: 462 ms per loop
1 loops, best of 3: 192 ms per loop
10 loops, best of 3: 39.9 ms per loop
100 loops, best of 3: 13.7 ms per loop
``` |
68,957,505 | ```
input = (Columbia and (India or Singapore) and Malaysia)
output = [Columbia, India, Singapore, Malaysia]
```
Basically ignore the python keywords and brackets
I tried with the below code, but still not able to eliminate the braces.
```
import keyword
my_str=input()
l1=list(my_str.split(" "))
l2=[x for x in l1 if not keyword.iskeyword((x.lower()))]
print(l2)
``` | 2021/08/27 | [
"https://Stackoverflow.com/questions/68957505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15695277/"
] | If you want to do it using first principles, you can use the code that is presented on the [Wikipedia page for Halton sequence](https://en.wikipedia.org/wiki/Halton_sequence):
```py
def halton(b):
"""Generator function for Halton sequence."""
n, d = 0, 1
while True:
x = d - n
if x == 1:
n = 1
d *= b
else:
y = d // b
while x <= y:
y //= b
n = (b + 1) * y - x
yield n / d
```
Here is a way to take the first 256 points of the 2- and 3- sequences, and plot them:
```py
n = 256
df = pd.DataFrame([
(x, y) for _, x, y in zip(range(n), halton(2), halton(3))
], columns=list('xy'))
ax = df.plot.scatter(x='x', y='y')
ax.set_aspect('equal')
```

**Addendum** "if I want to take for example 200 points and 8 dimensions for all sequences what should I do?"
Assuming you have access to a prime number sequence generator, then you can use e.g.:
```py
m = 8
p = list(primes(m * m))[:m] # first m primes
n = 200
z = pd.DataFrame([a for _, *a in zip(range(n), *[halton(k) for k in p])])
>>> z
0 1 2 3 4 5 6 7
0 0.500000 0.333333 0.2000 0.142857 0.090909 0.076923 0.058824 0.052632
1 0.250000 0.666667 0.4000 0.285714 0.181818 0.153846 0.117647 0.105263
2 0.750000 0.111111 0.6000 0.428571 0.272727 0.230769 0.176471 0.157895
3 0.125000 0.444444 0.8000 0.571429 0.363636 0.307692 0.235294 0.210526
4 0.625000 0.777778 0.0400 0.714286 0.454545 0.384615 0.294118 0.263158
.. ... ... ... ... ... ... ... ...
195 0.136719 0.576132 0.3776 0.011662 0.868520 0.089213 0.567474 0.343490
196 0.636719 0.909465 0.5776 0.154519 0.959429 0.166136 0.626298 0.396122
197 0.386719 0.057613 0.7776 0.297376 0.058603 0.243059 0.685121 0.448753
198 0.886719 0.390947 0.9776 0.440233 0.149512 0.319982 0.743945 0.501385
199 0.074219 0.724280 0.0256 0.583090 0.240421 0.396905 0.802768 0.554017
```
**Bonus**
Primes sequence using [Atkin's sieve](http://en.wikipedia.org/wiki/Prime_number):
```py
import numpy as np
def primes(limit):
# Generates prime numbers between 2 and n
# Atkin's sieve -- see http://en.wikipedia.org/wiki/Prime_number
sqrtLimit = int(np.sqrt(limit)) + 1
# initialize the sieve
is_prime = [False, False, True, True, False] + [False for _ in range(5, limit + 1)]
# put in candidate primes:
# integers which have an odd number of
# representations by certain quadratic forms
for x in range(1, sqrtLimit):
x2 = x * x
for y in range(1, sqrtLimit):
y2 = y*y
n = 4 * x2 + y2
if n <= limit and (n % 12 == 1 or n % 12 == 5): is_prime[n] ^= True
n = 3 * x2 + y2
if n <= limit and (n % 12 == 7): is_prime[n] ^= True
n = 3*x2-y2
if n <= limit and x > y and n % 12 == 11: is_prime[n] ^= True
# eliminate composites by sieving
for n in range(5, sqrtLimit):
if is_prime[n]:
sqN = n**2
# n is prime, omit multiples of its square; this is sufficient because
# composites which managed to get on the list cannot be square-free
for i in range(1, int(limit/sqN) + 1):
k = i * sqN # k ∈ {n², 2n², 3n², ..., limit}
is_prime[k] = False
for i, truth in enumerate(is_prime):
if truth: yield i
``` | In Python, SciPy is the main scientific computing package, and it [contains a Halton sequence generator](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.qmc.Halton.html), among other QMC functions.
For plotting, the standard way with SciPy is matplotlib; if you're not familiar with that, the [tutorial for SciPy](https://docs.scipy.org/doc/scipy/tutorial/general.html) is also a great place to start.
A basic example:
```py
from scipy.stats import qmc
import matplotlib.pyplot as plt
sampler = qmc.Halton(d=2, scramble=True)
sample = sampler.random(n=5)
plt.plot(sample)
``` |
73,104,518 | using opencv for capturing image in python
i want to make this image :
code for this :
```
# Image Processing
gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (51,51), 15)
th3 = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 2)
ret, test_image = cv2.threshold(th3, 10, 255, cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
```
[](https://i.stack.imgur.com/TmGlM.jpg)
to somewhat like this:
[](https://i.stack.imgur.com/sCLfc.jpg) | 2022/07/25 | [
"https://Stackoverflow.com/questions/73104518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16383903/"
] | For each position, look for the 4 possibles values, that for each a condition of existance
```
for i in range(len(arr)):
for j in range(len(arr[i])):
key = f'{i}{j}'
if i != 0:
d[key].append(arr[i - 1][j])
if j != 0:
d[key].append(arr[i][j - 1])
if i != (len(arr) - 1):
d[key].append(arr[i + 1][j])
if j != (len(arr[i]) - 1):
d[key].append(arr[i][j + 1])
```
```
{"00": [2, 2], "01": [0, 0, 3], "02": [2, 4],
"10": [0, 3, 0], "11": [2, 2, 4, 4], "12": [3, 0, 0],
"20": [2, 4], "21": [0, 3, 0], "22": [4, 4]}
```
---
Also it is useless to use a f-string to pass **one** thing only, | One approach using a dictionary comprehension:
```
from itertools import product
arr = [[0, 2, 3],
[2, 0, 4],
[3, 4, 0]]
def cross(i, j, a):
res = []
for ii, jj in zip([0, 1, 0, -1], [-1, 0, 1, 0]):
ni = (i + ii)
nj = (j + jj)
if (-1 < ni < len(a[0])) and (-1 < nj < len(a)):
res.append(a[nj][ni])
return res
res = {"".join(map(str, co)): cross(co[0], co[1], arr) for co in product(range(3), repeat=2)}
print(res)
```
**Output**
```
{'00': [2, 2], '01': [0, 0, 3], '02': [2, 4], '10': [3, 0, 0], '11': [2, 4, 4, 2], '12': [0, 0, 3], '20': [4, 2], '21': [3, 0, 0], '22': [4, 4]}
``` |
73,104,518 | using opencv for capturing image in python
i want to make this image :
code for this :
```
# Image Processing
gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (51,51), 15)
th3 = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 2)
ret, test_image = cv2.threshold(th3, 10, 255, cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
```
[](https://i.stack.imgur.com/TmGlM.jpg)
to somewhat like this:
[](https://i.stack.imgur.com/sCLfc.jpg) | 2022/07/25 | [
"https://Stackoverflow.com/questions/73104518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16383903/"
] | For each position, look for the 4 possibles values, that for each a condition of existance
```
for i in range(len(arr)):
for j in range(len(arr[i])):
key = f'{i}{j}'
if i != 0:
d[key].append(arr[i - 1][j])
if j != 0:
d[key].append(arr[i][j - 1])
if i != (len(arr) - 1):
d[key].append(arr[i + 1][j])
if j != (len(arr[i]) - 1):
d[key].append(arr[i][j + 1])
```
```
{"00": [2, 2], "01": [0, 0, 3], "02": [2, 4],
"10": [0, 3, 0], "11": [2, 2, 4, 4], "12": [3, 0, 0],
"20": [2, 4], "21": [0, 3, 0], "22": [4, 4]}
```
---
Also it is useless to use a f-string to pass **one** thing only, | **I modified the code a little bit because I was not sure how the defaultdict thing worked in yours but I hope this solves your problem.**
```
arr =[[0, 2, 3],
[2, 0, 4],
[3, 4, 0]]
d = {'00': [], '01': [], '02': [], '10': [], '11': [], '12': [], '20': [], '21': [], '22': []}
for i in range(len(arr)):
for j in range(len(arr[0])):
d[f'{str(i)+str(j)}']
print(d)
> for i in range(len(arr)):
> for x in range(len(arr)):
> if i != 0:
> d[str(i) + str(x)].append(arr[i-1][x])
> if i != 2:
> d[str(i) + str(x)].append(arr[i+1][x])
> if x != 0:
> d[str(i) + str(x)].append(arr[i][x-1])
> if x != 2:
> d[str(i) + str(x)].append(arr[i][x+1])
print('FINAL', d)
``` |
73,104,518 | using opencv for capturing image in python
i want to make this image :
code for this :
```
# Image Processing
gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (51,51), 15)
th3 = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 2)
ret, test_image = cv2.threshold(th3, 10, 255, cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
```
[](https://i.stack.imgur.com/TmGlM.jpg)
to somewhat like this:
[](https://i.stack.imgur.com/sCLfc.jpg) | 2022/07/25 | [
"https://Stackoverflow.com/questions/73104518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16383903/"
] | For each position, look for the 4 possibles values, that for each a condition of existance
```
for i in range(len(arr)):
for j in range(len(arr[i])):
key = f'{i}{j}'
if i != 0:
d[key].append(arr[i - 1][j])
if j != 0:
d[key].append(arr[i][j - 1])
if i != (len(arr) - 1):
d[key].append(arr[i + 1][j])
if j != (len(arr[i]) - 1):
d[key].append(arr[i][j + 1])
```
```
{"00": [2, 2], "01": [0, 0, 3], "02": [2, 4],
"10": [0, 3, 0], "11": [2, 2, 4, 4], "12": [3, 0, 0],
"20": [2, 4], "21": [0, 3, 0], "22": [4, 4]}
```
---
Also it is useless to use a f-string to pass **one** thing only, | construct the four surrounding elements directly and exclude any values that are not in the range
```
from collections import defaultdict
arr, d =[[0, 2, 3], [2, 0, 4],[3, 4, 0]], defaultdict(list)
x_length, y_length = len(arr), len(arr[0])
for i in range(x_length):
for j in range(y_length):
items = [[x, y] for x, y in [[i-1, j], [i, j-1], [i, j+1], [i+1, j]] if x in range(x_length) and y in range(y_length)]
d["{}{}".format(i, j)] = [arr[item[0]][item[1]] for item in items]
print(d)
# defaultdict(<class 'list'>, {'00': [2, 2], '01': [0, 3, 0], '02': [2, 4], '10': [0, 0, 3], '11': [2, 2, 4, 4], '12': [3, 0, 0], '20': [2, 4], '21': [0, 3, 0], '22': [4, 4]})
``` |
73,104,518 | using opencv for capturing image in python
i want to make this image :
code for this :
```
# Image Processing
gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (51,51), 15)
th3 = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 2)
ret, test_image = cv2.threshold(th3, 10, 255, cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
```
[](https://i.stack.imgur.com/TmGlM.jpg)
to somewhat like this:
[](https://i.stack.imgur.com/sCLfc.jpg) | 2022/07/25 | [
"https://Stackoverflow.com/questions/73104518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16383903/"
] | One approach using a dictionary comprehension:
```
from itertools import product
arr = [[0, 2, 3],
[2, 0, 4],
[3, 4, 0]]
def cross(i, j, a):
res = []
for ii, jj in zip([0, 1, 0, -1], [-1, 0, 1, 0]):
ni = (i + ii)
nj = (j + jj)
if (-1 < ni < len(a[0])) and (-1 < nj < len(a)):
res.append(a[nj][ni])
return res
res = {"".join(map(str, co)): cross(co[0], co[1], arr) for co in product(range(3), repeat=2)}
print(res)
```
**Output**
```
{'00': [2, 2], '01': [0, 0, 3], '02': [2, 4], '10': [3, 0, 0], '11': [2, 4, 4, 2], '12': [0, 0, 3], '20': [4, 2], '21': [3, 0, 0], '22': [4, 4]}
``` | **I modified the code a little bit because I was not sure how the defaultdict thing worked in yours but I hope this solves your problem.**
```
arr =[[0, 2, 3],
[2, 0, 4],
[3, 4, 0]]
d = {'00': [], '01': [], '02': [], '10': [], '11': [], '12': [], '20': [], '21': [], '22': []}
for i in range(len(arr)):
for j in range(len(arr[0])):
d[f'{str(i)+str(j)}']
print(d)
> for i in range(len(arr)):
> for x in range(len(arr)):
> if i != 0:
> d[str(i) + str(x)].append(arr[i-1][x])
> if i != 2:
> d[str(i) + str(x)].append(arr[i+1][x])
> if x != 0:
> d[str(i) + str(x)].append(arr[i][x-1])
> if x != 2:
> d[str(i) + str(x)].append(arr[i][x+1])
print('FINAL', d)
``` |
73,104,518 | using opencv for capturing image in python
i want to make this image :
code for this :
```
# Image Processing
gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (51,51), 15)
th3 = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 2)
ret, test_image = cv2.threshold(th3, 10, 255, cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
```
[](https://i.stack.imgur.com/TmGlM.jpg)
to somewhat like this:
[](https://i.stack.imgur.com/sCLfc.jpg) | 2022/07/25 | [
"https://Stackoverflow.com/questions/73104518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16383903/"
] | One approach using a dictionary comprehension:
```
from itertools import product
arr = [[0, 2, 3],
[2, 0, 4],
[3, 4, 0]]
def cross(i, j, a):
res = []
for ii, jj in zip([0, 1, 0, -1], [-1, 0, 1, 0]):
ni = (i + ii)
nj = (j + jj)
if (-1 < ni < len(a[0])) and (-1 < nj < len(a)):
res.append(a[nj][ni])
return res
res = {"".join(map(str, co)): cross(co[0], co[1], arr) for co in product(range(3), repeat=2)}
print(res)
```
**Output**
```
{'00': [2, 2], '01': [0, 0, 3], '02': [2, 4], '10': [3, 0, 0], '11': [2, 4, 4, 2], '12': [0, 0, 3], '20': [4, 2], '21': [3, 0, 0], '22': [4, 4]}
``` | construct the four surrounding elements directly and exclude any values that are not in the range
```
from collections import defaultdict
arr, d =[[0, 2, 3], [2, 0, 4],[3, 4, 0]], defaultdict(list)
x_length, y_length = len(arr), len(arr[0])
for i in range(x_length):
for j in range(y_length):
items = [[x, y] for x, y in [[i-1, j], [i, j-1], [i, j+1], [i+1, j]] if x in range(x_length) and y in range(y_length)]
d["{}{}".format(i, j)] = [arr[item[0]][item[1]] for item in items]
print(d)
# defaultdict(<class 'list'>, {'00': [2, 2], '01': [0, 3, 0], '02': [2, 4], '10': [0, 0, 3], '11': [2, 2, 4, 4], '12': [3, 0, 0], '20': [2, 4], '21': [0, 3, 0], '22': [4, 4]})
``` |
28,376,849 | The Eclipse PyDev plugin includes fantastic integrated `autopep8` support. It formats the code to PEP8 style automatically on save, with several knobs and options to tailor it to your needs.
But the `autopep8` import formatter breaks `site.addsitedir()` usage.
```
import site
site.addsitedir('/opt/path/lib/python')
# 'ourlib' is a package in '/opt/path/lib/python', which
# without the above addsitedir() would otherwise not import.
from ourlib import do_stuff
```
And after PyDev's `autopep8` import formatter, it changes it to:
```
import site
from ourlib import do_stuff
site.addsitedir('/opt/path/lib/python')
```
Which breaks `from ourlib import do_stuff` with `ImportError: No module named ourlib`.
**Question:**
Is there a PyDev setting or `autopep8` command-line option to keep it from moving `site.addsitedir()` calls? | 2015/02/07 | [
"https://Stackoverflow.com/questions/28376849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2125392/"
] | Oldie but still relevant as I found this one issue.
I'm using VSCode and autopep8.
You can disable formatting by adding `# nopep8` to the relevant lines.
ps. Checked the docs for a link but could not find it :( | The best option I can find is to turn off import sorts in PyDev. This is not a complete solution, but it's better than completely turning off `autopep8` code formatting.
Just uncheck the `Sort imports on save?` option in the Eclipse/PyDev Preferences.
For Eclipse Kepler, Service Release 2, with PyDev 3.9.2, you can find it here:
```
Windows -> Preferences
--> PyDev -> Editor -> Save Actions
----> "Sort imports on save?" (uncheck)
``` |
6,916,054 | I'm working with python using Matplotlib and PIL and a need to look into a image select and cut the area that i have to work with, leaving only the image of the selected area.I alredy know how to cut imagens with pil(using im.crop) but how can i select the coordinates to croped the image with mouse clicks?
To better explain, i crop the image like this:
```
import Pil
import Image
im = Image.open("test.jpg")
crop_rectangle = (50, 50, 200, 200)
cropped_im = im.crop(crop_rectangle)
cropped_im.show()
```
I need to give the coordinates "crop\_rectangle" with the mouse click in a rectangle that i wanna work with, how can i do it?
Thank you | 2011/08/02 | [
"https://Stackoverflow.com/questions/6916054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/669332/"
] | You could use [matplotlib.widgets.RectangleSelector](http://matplotlib.sourceforge.net/api/widgets_api.html?highlight=matplotlib.widgets#matplotlib.widgets.RectangleSelector) (thanks to Joe Kington for this suggestion) to handle button press events:
```
import numpy as np
import matplotlib.pyplot as plt
import Image
import matplotlib.widgets as widgets
def onselect(eclick, erelease):
if eclick.ydata>erelease.ydata:
eclick.ydata,erelease.ydata=erelease.ydata,eclick.ydata
if eclick.xdata>erelease.xdata:
eclick.xdata,erelease.xdata=erelease.xdata,eclick.xdata
ax.set_ylim(erelease.ydata,eclick.ydata)
ax.set_xlim(eclick.xdata,erelease.xdata)
fig.canvas.draw()
fig = plt.figure()
ax = fig.add_subplot(111)
filename="test.png"
im = Image.open(filename)
arr = np.asarray(im)
plt_image=plt.imshow(arr)
rs=widgets.RectangleSelector(
ax, onselect, drawtype='box',
rectprops = dict(facecolor='red', edgecolor = 'black', alpha=0.5, fill=True))
plt.show()
``` | are you using tk? it will depend on what window management you are using. High level though, you'll want something like:
```
def onMouseDown():
// get and save your coordinates
def onMouseUp():
// save these coordinates as well
// now compare your coordinates to fingure out which corners
// are being used and define your rectangle
```
The callbacks themselves will differ from window tool to window tool, but the concept will be the same: capture the click down event and release event and compare the points where the events were triggered to create your rectangle. The trick is to remember to figure out which corner they are starting at (the second point is always opposite that corner) and creating your rectangle to be cropped, relative to the original image itself.
Again, depending on the tool, you will probably need to put your click events in your image's coordinate space. |
50,489,637 | I am learning C++, is there something like python-pip in C++? I am uing `json`/`YAML` packages in my 1st project, I want to know which is the correct way to manage dependencies in my project, and after I finished developing, which is the correct way to migrate dependencies to production environment? | 2018/05/23 | [
"https://Stackoverflow.com/questions/50489637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5735646/"
] | C++ doesn't have a standard package manager or build system: this is one of the major pain points of the language. You have a few options:
* Manually install dependencies when required.
* Use your OS's package manager.
* Adopt a third-party package manager such as [conan.io](http://conan.io).
None of the above solutions is perfect and dependency management will likely always require some more effort on your part compared to languages such as Python or Rust. | As far as I know, there is no central library management system in C++ similar to `pip`. You need to download and install the packages you need manually or through some package manager if your OS supports it.
As for managing multiple libraries in a C++ project, you could use [CMAKE](https://cmake.org/) or something similar. If you link your libraries dynamically (i.e., though .dll or .so files), then you need to supply these dynamic library binaries along with your application. To find out which dll files may be needed, you could something like the [Dependency Walker](http://www.dependencywalker.com/) or [ELF Library Viewer](http://www.purinchu.net/software/elflibviewer.php).
Personally, I use a development environment - specifically [Qt](https://www.qt.io/) (with the QtCreator), containing many of these components like `qmake` etc. - which simplifies the process of development and distribution. |
18,755,963 | I have designed a GUI using python tkinter. And now I want to set style for Checkbutton and Labelframe, such as the font, the color .etc
I have read some answers on the topics of tkinter style, and I have used the following method to set style for both Checkbutton and Labelframe.
But they don't actually work.
```
Root = tkinter.Tk()
ttk.Style().configure('Font.TLabelframe', font="15", foreground = "red")
LabelFrame = ttk.Labelframe(Root, text = "Test", style = "Font.TLabelframe")
LabelFrame .pack( anchor = "w", ipadx = 10, ipady = 5, padx = 10, pady = 0, side = "top")
```
Can you tell me the reasons, or do you have some other valid methods? Thank you very much! | 2013/09/12 | [
"https://Stackoverflow.com/questions/18755963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2771241/"
] | You need to configure the Label sub-component:
```
from tkinter import *
from tkinter import ttk
root = Tk()
s = ttk.Style()
s.configure('Red.TLabelframe.Label', font=('courier', 15, 'bold'))
s.configure('Red.TLabelframe.Label', foreground ='red')
s.configure('Red.TLabelframe.Label', background='blue')
lf = ttk.LabelFrame(root, text = "Test", style = "Red.TLabelframe")
lf.pack( anchor = "w", ipadx = 10, ipady = 5, padx = 10,
pady = 0, side = "top")
Frame(lf, width=100, height=100, bg='black').pack()
print(s.lookup('Red.TLabelframe.Label', 'font'))
root.mainloop()
``` | As the accepted answer didn't really help me when I wanted to do a simple changing of weight of a `ttk.LabelFrame` font (if you do it like recommended, you end up with a misplaced label), I'll provide what worked for me.
You have to use `labelwidget` option argument of `ttk.LabelFrame` first preparing a seperate `ttk.Label` that you style earlier accordingly. **Important:** using `labelwidget` means you don't use the usual `text` option argument for your `ttk.LabelFrame` (just do it in the label).
```
# changing a labelframe font's weight to bold
root = Tk()
style = ttk.Style()
style.configure("Bold.TLabel", font=("TkDefaultFont", 9, "bold"))
label = ttk.Label(text="Foo", style="Bold.TLabel")
lf = ttk.LabelFrame(root, labelwidget=label)
``` |
18,755,963 | I have designed a GUI using python tkinter. And now I want to set style for Checkbutton and Labelframe, such as the font, the color .etc
I have read some answers on the topics of tkinter style, and I have used the following method to set style for both Checkbutton and Labelframe.
But they don't actually work.
```
Root = tkinter.Tk()
ttk.Style().configure('Font.TLabelframe', font="15", foreground = "red")
LabelFrame = ttk.Labelframe(Root, text = "Test", style = "Font.TLabelframe")
LabelFrame .pack( anchor = "w", ipadx = 10, ipady = 5, padx = 10, pady = 0, side = "top")
```
Can you tell me the reasons, or do you have some other valid methods? Thank you very much! | 2013/09/12 | [
"https://Stackoverflow.com/questions/18755963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2771241/"
] | You need to configure the Label sub-component:
```
from tkinter import *
from tkinter import ttk
root = Tk()
s = ttk.Style()
s.configure('Red.TLabelframe.Label', font=('courier', 15, 'bold'))
s.configure('Red.TLabelframe.Label', foreground ='red')
s.configure('Red.TLabelframe.Label', background='blue')
lf = ttk.LabelFrame(root, text = "Test", style = "Red.TLabelframe")
lf.pack( anchor = "w", ipadx = 10, ipady = 5, padx = 10,
pady = 0, side = "top")
Frame(lf, width=100, height=100, bg='black').pack()
print(s.lookup('Red.TLabelframe.Label', 'font'))
root.mainloop()
``` | For completeness sake, I was looking how to change border color style (specifically color) of ttk.LabelFrame and finally found how it worked so wanted to post on the posts that I came across while searching.
I create global styles for my ttk widgets, there are ways to apply this to single widgets as well.
```
style = ttk.Style()
style.theme_create('style', parent='alt',
settings = {'TLabelframe': {'configure':
{'background': 'black',
'relief': 'solid', # has to be 'solid' to color
'bordercolor': 'orange',
'borderwidth': 1}},
'TLabelframe.Label': {'configure':
{'foreground': 'green',
'background': 'black'}}})
style.theme_use('style')
``` |
18,755,963 | I have designed a GUI using python tkinter. And now I want to set style for Checkbutton and Labelframe, such as the font, the color .etc
I have read some answers on the topics of tkinter style, and I have used the following method to set style for both Checkbutton and Labelframe.
But they don't actually work.
```
Root = tkinter.Tk()
ttk.Style().configure('Font.TLabelframe', font="15", foreground = "red")
LabelFrame = ttk.Labelframe(Root, text = "Test", style = "Font.TLabelframe")
LabelFrame .pack( anchor = "w", ipadx = 10, ipady = 5, padx = 10, pady = 0, side = "top")
```
Can you tell me the reasons, or do you have some other valid methods? Thank you very much! | 2013/09/12 | [
"https://Stackoverflow.com/questions/18755963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2771241/"
] | As the accepted answer didn't really help me when I wanted to do a simple changing of weight of a `ttk.LabelFrame` font (if you do it like recommended, you end up with a misplaced label), I'll provide what worked for me.
You have to use `labelwidget` option argument of `ttk.LabelFrame` first preparing a seperate `ttk.Label` that you style earlier accordingly. **Important:** using `labelwidget` means you don't use the usual `text` option argument for your `ttk.LabelFrame` (just do it in the label).
```
# changing a labelframe font's weight to bold
root = Tk()
style = ttk.Style()
style.configure("Bold.TLabel", font=("TkDefaultFont", 9, "bold"))
label = ttk.Label(text="Foo", style="Bold.TLabel")
lf = ttk.LabelFrame(root, labelwidget=label)
``` | For completeness sake, I was looking how to change border color style (specifically color) of ttk.LabelFrame and finally found how it worked so wanted to post on the posts that I came across while searching.
I create global styles for my ttk widgets, there are ways to apply this to single widgets as well.
```
style = ttk.Style()
style.theme_create('style', parent='alt',
settings = {'TLabelframe': {'configure':
{'background': 'black',
'relief': 'solid', # has to be 'solid' to color
'bordercolor': 'orange',
'borderwidth': 1}},
'TLabelframe.Label': {'configure':
{'foreground': 'green',
'background': 'black'}}})
style.theme_use('style')
``` |
38,163,087 | Having an issue where I would fill out the form and when I click to save the input, it would show the info submitted into the `query` but my `production_id` value would return as `None`.
**Here is the error:**
```
Environment:
Request Method: POST
Request URL: http://192.168.33.10:8000/podfunnel/episodeinfo/
Django Version: 1.9
Python Version: 2.7.6
Installed Applications:
('producer',
'django.contrib.admin',
'django.contrib.sites',
'registration',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'storages',
'django_extensions',
'randomslugfield',
'adminsortable2',
'crispy_forms')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware')
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/mixins.py" in dispatch
56. return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py" in dispatch
88. return handler(request, *args, **kwargs)
File "/home/vagrant/fullcast_project/producer/views/pod_funnel.py" in post
601. return HttpResponseRedirect(reverse('podfunnel:episodeimagefiles', kwargs={'production_id':production_id}))
File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py" in reverse
600. return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))
File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py" in _reverse_with_prefix
508. (lookup_view_s, args, kwargs, len(patterns), patterns))
Exception Type: NoReverseMatch at /podfunnel/episodeinfo/
Exception Value: Reverse for 'episodeimagefiles' with arguments '()' and keyword arguments '{'production_id': None}' not found. 1 pattern(s) tried: [u'podfunnel/episodeimagefiles/(?P<production_id>[0-9]+)/$']
```
**Here is my `pod_funnel.py` view:**
```
from django.http import HttpResponseRedirect, Http404, HttpResponseForbidden
from django.shortcuts import render, get_object_or_404
from django.views.generic import View, RedirectView, TemplateView
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from .forms.client_setup import ClientSetupForm
from .forms.podcast_setup import PodcastSetupForm
from .forms.episode_info import EpisodeInfoForm
from .forms.image_files import EpisodeImageFilesForm
from .forms.wordpress_info import EpisodeWordpressInfoForm
from .forms.chapter_marks import EpisodeChapterMarksForm
from .forms.show_links import ShowLinksForm
from .forms.tweetables import TweetablesForm
from .forms.clicktotweet import ClickToTweetForm
from .forms.schedule import ScheduleForm
from .forms.wordpress_account import WordpressAccountForm
from .forms.wordpress_account_setup import WordpressAccountSetupForm
from .forms.wordpress_account_sortable import WordpressAccountSortableForm
from .forms.soundcloud_account import SoundcloudAccountForm
from .forms.twitter_account import TwitterAccountForm
from producer.helpers import get_podfunnel_client_and_podcast_for_user
from producer.helpers.soundcloud_api import SoundcloudAPI
from producer.helpers.twitter import TwitterAPI
from django.conf import settings
from producer.models import Client, Production, ChapterMark, ProductionLink, ProductionTweet, Podcast, WordpressConfig, Credentials, WordPressSortableSection, \
TwitterConfig, SoundcloudConfig
from django.core.urlresolvers import reverse
from producer.tasks.auphonic import update_or_create_preset_for_podcast
class EpisodeInfoView(LoginRequiredMixin, View):
form_class = EpisodeInfoForm
template_name = 'pod_funnel/forms_episode_info.html'
def get(self, request, *args, **kwargs):
initial_values = {}
user = request.user
# Lets get client and podcast for the user already. if not existent raise 404
client, podcast = get_podfunnel_client_and_podcast_for_user(user)
if client is None or podcast is None:
raise Http404
# See if a production_id is passed on the kwargs, if so, retrieve and fill current data.
# if not just provide empty form since will be new.
production_id = kwargs.get('production_id', None)
if production_id:
production = get_object_or_404(Production, id=production_id)
# Ensure this production belongs to this user, if not Unauthorized, 403
if production.podcast_id != podcast.id:
return HttpResponseForbidden()
initial_values['production_id'] = production.id
initial_values['episode_number'] = production.episode_number
initial_values['episode_title'] = production.episode_title
initial_values['episode_guest_first_name'] = production.episode_guest_first_name
initial_values['episode_guest_last_name'] = production.episode_guest_last_name
initial_values['episode_guest_twitter_name'] = production.episode_guest_twitter_name
initial_values['episode_summary'] = production.episode_summary
form = self.form_class(initial=initial_values)
return render(request, self.template_name, {'form': form})
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
client, podcast = get_podfunnel_client_and_podcast_for_user(request.user)
if form.is_valid():
# lets get the data
production_id = form.cleaned_data.get('production_id')
episode_number = form.cleaned_data.get('episode_number')
episode_title = form.cleaned_data.get('episode_title')
episode_guest_first_name = form.cleaned_data.get('episode_guest_first_name')
episode_guest_last_name = form.cleaned_data.get('episode_guest_last_name')
episode_guest_twitter_name = form.cleaned_data.get('episode_guest_twitter_name')
episode_summary = form.cleaned_data.get('episode_summary')
#if a production existed, we update, if not we create
if production_id is not None:
production = Production.objects.get(id=production_id)
else:
production = Production(podcast=podcast)
production.episode_number = episode_number
production.episode_title = episode_title
production.episode_guest_first_name = episode_guest_first_name
production.episode_guest_last_name = episode_guest_last_name
production.episode_guest_twitter_name = episode_guest_twitter_name
production.episode_summary = episode_summary
production.save()
return HttpResponseRedirect(reverse('podfunnel:episodeimagefiles', kwargs={'production_id':production_id}))
return render(request, self.template_name, {'form': form})
```
**`episode_info.py` form:**
```
from django import forms
class EpisodeInfoForm(forms.Form):
production_id = forms.IntegerField(widget=forms.Field.hidden_widget, required=False)
episode_number = forms.IntegerField(widget=forms.NumberInput, required=True)
episode_title = forms.CharField(max_length=255, required=True)
episode_guest_first_name = forms.CharField(max_length=128)
episode_guest_last_name = forms.CharField(max_length=128)
episode_guest_twitter_name = forms.CharField(max_length=64)
episode_summary = forms.CharField(widget=forms.Textarea)
```
**And `url.py`:**
```
from django.conf.urls import url
from django.views.generic import TemplateView
import producer.views.pod_funnel as views
urlpatterns = [
url(r'^dashboard/', views.dashboard, name="dashboard"),
url(r'^clientsetup/', views.ClientSetupView.as_view(), name="clientsetup"),
url(r'^podcastsetup/', views.PodcastSetupView.as_view(), name="podcastsetup"),
url(r'^episodeinfo/$', views.EpisodeInfoView.as_view(), name="episodeinfo"),
url(r'^episodeinfo/(?P<production_id>[0-9]+)/$', views.EpisodeInfoView.as_view(), name="episodeinfo_edit"),
url(r'^episodeimagefiles/(?P<production_id>[0-9]+)/$', views.EpisodeImageFilesView.as_view(), name="episodeimagefiles"),
```
**Any suggestion would be appreciated.** | 2016/07/02 | [
"https://Stackoverflow.com/questions/38163087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3557390/"
] | It looks like `production_id` can be `None` in your view, in which case you can't use it when you call reverse. It would be better to use `production.id` instead. You have just saved the production in your view, so `production.id` will be set.
```
return HttpResponseRedirect(reverse('podfunnel:episodeimagefiles', kwargs={'production_id':production.id}))
```
Note that you can simplify this line by using the `redirect` shortcut. Add the import,
```
from django.shortcuts import redirect
```
then change the line to
```
return redirect('podfunnel:episodeimagefiles', production_id=production.id)
``` | You can't always redirect to `episodeimagefiles` if you didn't provide appropriate initial value for `production_id`:
```
# See if a production_id is passed on the kwargs, if so, retrieve and fill current data.
# if not just provide empty form since will be new.
production_id = kwargs.get('production_id', None) <-- here you set production_id variable to None if no `production_id` in kwargs
```
Look at your exception:
```
Exception Value: Reverse for 'episodeimagefiles' with arguments '()' and keyword arguments '{'production_id': None}' not found. 1 pattern(s) tried: [u'podfunnel/episodeimagefiles/(?P<production_id>[0-9]+)/$']
```
It means you passed `None` value for `production_id` variable, but `episodeimagefiles` pattern required some int value to resolve url, so it raises `NoReverseMatch` exception.
Your form is valid in `EpisodeInfoView.post` because you set `required=False` for `production_id` attribute in your form:
```
class EpisodeInfoForm(forms.Form):
production_id = forms.IntegerField(widget=forms.Field.hidden_widget, required=False)
```
I guess, if you debug your generated form before submit it, you can see something like `<input type="hidden" name="production_id" value="None" />` |
63,033,970 | Using python3.8.1, installing newest version, on Windows 10:
`pip install PyNaCl` gives me this error (last 10 lines):
```
File "C:\Program Files (x86)\Python3\lib\distutils\cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "C:\Program Files (x86)\Python3\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "setup.py", line 161, in run
raise Exception("ERROR: The 'make' utility is missing from PATH")
Exception: ERROR: The 'make' utility is missing from PATH
----------------------------------------
Failed building wheel for PyNaCl
Running setup.py clean for PyNaCl
Failed to build PyNaCl
Could not build wheels for PyNaCl which use PEP 517 and cannot be installed directly
```
It seems to be related to wheels, so i tried to install it with `no-binary`, which also failed:
```
File "C:\Program Files (x86)\Python3\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "C:\Users\Administrator\AppData\Local\Temp\pip-install-q0db5s_n\PyNaCl\setup.py", line 161, in run
raise Exception("ERROR: The 'make' utility is missing from PATH")
Exception: ERROR: The 'make' utility is missing from PATH
----------------------------------------
Command "C:\Users\Administrator\Documents\DiscordBot\venv\Scripts\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\Administrator\\AppData\\Local\\Temp\\pip-install-q0db5s_n\\PyNaCl\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\Administrator\AppData\Local\Temp\pip-record-s27dvlrv\install-record.txt --single-version-externally-managed --compile --install-headers C:\Users\Administrator\Documents\DiscordBot\venv\include\site\python3.8\PyNaCl" failed with error code 1 in C:\Users\Administrator\AppData\Local\Temp\pip-install-q0db5s_n\PyNaCl\
```
EDIT: This only seems to be an issue in my venv (made by Pycharm) - i have no clue what the issue is, both setuptools and wheel are installed. | 2020/07/22 | [
"https://Stackoverflow.com/questions/63033970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8558929/"
] | I ultimately solved it by using `python -m pip install --no-use-pep517 pynacl` | Upgrading pip within the venv worked for me:
```
.\env\Scripts\activate
pip install -U pip
pip install -r requirements.txt
deactivate
``` |
28,891,405 | I am trying to contract some vertices in igraph (using the python api) while keeping the names of the vertices. It isn't clear to me how to keep the name attribute of the graph. The nodes of the graph are people and I'm trying to collapse people with corrupted names.
I looked at the R documentation and I still don't see how to do it.
For example, if I do either of the following I get an error.
```
smallgraph.contract_vertices([0,1,2,3,4,2,6],vertex.attr.comb=[name='first'])
smallgraph.contract_vertices([0,1,2,3,4,2,6],vertex.attr.comb=['first'])
``` | 2015/03/06 | [
"https://Stackoverflow.com/questions/28891405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4639290/"
] | In Python, the keyword argument you need is called `combine_attrs` and not `vertex.attr.comb`. See `help(Graph.contract_vertices)` from the Python command line after having imported igraph. Also, the keyword argument accepts either a single specifier (such as `first`) or a dictionary. Your first example is invalid because it is simply not valid Python syntax. The second example won't work because you pass a *list* with a single item instead of just the single item.
So, the correct variants would be:
```
smallgraph.contract_vertices([0,1,2,3,4,2,6], combine_attrs=dict(name="first"))
smallgraph.contract_vertices([0,1,2,3,4,2,6], combine_attrs="first")
``` | Nevermind. You can just enter a dictionary without using the wording
```
vertex.attr.comb
``` |
70,806,221 | So I have a "terminal" like program written in python and in this program I need to accept "mkdir" and another input and save the input after mkdir as a variable. It would work how sys.argv works when executing a python program but this would have to work from inside the program and I have no idea how to make this work. Also, sorry for the amount of times I said "input" in the title, I wasn't sure how to ask this question.
```
user = 'user'
def cmd1():
cmd = input(user + '#')
while True:
if cmd == 'mkdir ' + sys.argv[1]: #trying to accept second input here
print('sys.argv[1]')
break
else:
print('Input not valid')
break
``` | 2022/01/21 | [
"https://Stackoverflow.com/questions/70806221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17746152/"
] | May use the pattern (`\\[[^\\]]+(\\[|$)|(^|\\])[^\\[]+\\]`) in `str_detect`
```
library(dplyr)
library(stringr)
df %>%
filter(str_detect(Utterance, "\\[[^\\]]+(\\[|$)|(^|\\])[^\\[]+\\]"))
id Utterance
1 1 [but if I came !ho!me
2 3 =[yeah] I mean [does it
3 4 bu[t if (.) you know
4 5 =ye::a:h]
5 6 [that's right] YEAH (laughs)] [ye::a:h]
6 8 [cos] I've [heard very sketchy [stories]
7 9 oh well] that's great
```
Here we check for a opening bracket `[` followed by one or more characters that are not `]` followed by a `[` or the end of the string (`$`) or a similar pattern for the closing bracket | If you need a function to validate (nested) parenthesis, here is a stack based one.
```
valid_delim <- function(x, delim = c(open = "[", close = "]"), max_stack_size = 10L){
f <- function(x, delim, max_stack_size){
if(is.null(names(delim))) {
names(delim) <- c("open", "close")
}
if(nchar(x) > 0L){
valid <- TRUE
stack <- character(max_stack_size)
i_stack <- 0L
y <- unlist(strsplit(x, ""))
for(i in seq_along(y)){
if(y[i] == delim["open"]){
i_stack <- i_stack + 1L
stack[i_stack] <- delim["close"]
} else if(y[i] == delim["close"]) {
valid <- (stack[i_stack] == delim["close"]) && (i_stack > 0L)
if(valid)
i_stack <- i_stack - 1L
else break
}
}
valid && (i_stack == 0L)
} else NULL
}
x <- as.character(x)
y <- sapply(x, f, delim = delim, max_stack_size = max_stack_size)
unname(y)
}
library(dplyr)
valid_delim(df$Utterance)
#[1] FALSE TRUE FALSE FALSE FALSE FALSE TRUE FALSE FALSE
df %>% filter(valid_delim(Utterance))
# id Utterance
#1 2 =[ye::a:h]
#2 7 cos I've [heard] very sketchy stories
``` |
70,806,221 | So I have a "terminal" like program written in python and in this program I need to accept "mkdir" and another input and save the input after mkdir as a variable. It would work how sys.argv works when executing a python program but this would have to work from inside the program and I have no idea how to make this work. Also, sorry for the amount of times I said "input" in the title, I wasn't sure how to ask this question.
```
user = 'user'
def cmd1():
cmd = input(user + '#')
while True:
if cmd == 'mkdir ' + sys.argv[1]: #trying to accept second input here
print('sys.argv[1]')
break
else:
print('Input not valid')
break
``` | 2022/01/21 | [
"https://Stackoverflow.com/questions/70806221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17746152/"
] | Another possible solution, using `purrr::map_dfr`.
**EXPLANATION**
I provide, in what follows, an explanation for my solution, as asked for by @ChrisRuehlemann:
1. With `str_extract_all(df$Utterance, "\\[|\\]")`, we extract all `[` and `]` of each utterance as a list and according to the order they appear in the utterance.
2. We iterate all lists created previously for the utterances. However, we have a list of square brackets. So, we need to beforehand collapse the list into a single string of square brackets (`str_c(.x, collapse = "")`).
3. We compare the string of square brackets of each utterance with a string like the following `[][][]...` (`str_c(rep("[]", length(.x)/2), collapse = "")`). If these two strings are not equal, then square brackets are missing!
4. When `map_dfr` finishes, we end up with a column of `TRUE` and `FALSE`, which we can use to filter the original dataframe as wanted.
```r
library(tidyverse)
str_extract_all(df$Utterance, "\\[|\\]") %>%
map_dfr(~ list(OK = str_c(.x, collapse = "") !=
str_c(rep("[]", length(.x)/2), collapse = ""))) %>%
filter(df,.)
#> id Utterance
#> 1 1 [but if I came !ho!me
#> 2 3 =[yeah] I mean [does it
#> 3 4 bu[t if (.) you know
#> 4 5 =ye::a:h]
#> 5 6 [that's right] YEAH (laughs)] [ye::a:h]
#> 6 8 [cos] I've [heard very sketchy [stories]
#> 7 9 oh well] that's great
``` | If you need a function to validate (nested) parenthesis, here is a stack based one.
```
valid_delim <- function(x, delim = c(open = "[", close = "]"), max_stack_size = 10L){
f <- function(x, delim, max_stack_size){
if(is.null(names(delim))) {
names(delim) <- c("open", "close")
}
if(nchar(x) > 0L){
valid <- TRUE
stack <- character(max_stack_size)
i_stack <- 0L
y <- unlist(strsplit(x, ""))
for(i in seq_along(y)){
if(y[i] == delim["open"]){
i_stack <- i_stack + 1L
stack[i_stack] <- delim["close"]
} else if(y[i] == delim["close"]) {
valid <- (stack[i_stack] == delim["close"]) && (i_stack > 0L)
if(valid)
i_stack <- i_stack - 1L
else break
}
}
valid && (i_stack == 0L)
} else NULL
}
x <- as.character(x)
y <- sapply(x, f, delim = delim, max_stack_size = max_stack_size)
unname(y)
}
library(dplyr)
valid_delim(df$Utterance)
#[1] FALSE TRUE FALSE FALSE FALSE FALSE TRUE FALSE FALSE
df %>% filter(valid_delim(Utterance))
# id Utterance
#1 2 =[ye::a:h]
#2 7 cos I've [heard] very sketchy stories
``` |
66,830,558 | I just started a new project in django, I run the command 'django-admin startproject + project\_name', and 'python manage.py startapp + app\_name'. Created a project and app.
I also added my new app to the settings:
[settings pic](https://i.stack.imgur.com/aMIpy.png)
After that I tried to create my first module on 'modules.py' file on my app, but when I do it and run the file, it gives me this error message:
[Error message](https://i.stack.imgur.com/LX3n1.png)
The entire error message says:
" django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED\_APPS, but settings are not configured. You must either define the environment variable DJANGO\_SETTINGS\_MODULE or call settings.configure() before accessing settings. "
I created a few projects before, and never had this problem.
I discovered that if I dont use the 'models.Model' on my class, it does not gives me this error.
[No error message on this case](https://i.stack.imgur.com/v5Dg2.png)
Someone knows what it is about, and why it gives me this error? I didnt change anything on settings, just added the app. | 2021/03/27 | [
"https://Stackoverflow.com/questions/66830558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15493450/"
] | You want a `dict: {letter:positions}` , for that a `defaultdict` is well suited
```
from collections import defaultdict
def nb_occurances(word):
dict_occ = {}
positions = defaultdict(list)
for i, c in enumerate(word):
dict_occ[c] = word.count(c)
positions[c].append(i)
return dict_occ, positions
print(nb_occurances("hello"))
# ({'h': 1, 'e': 1, 'l': 2, 'o': 1}, {'h': [0], 'e': [1], 'l': [2, 3], 'o': [4]}))
```
Know that `collections.Counter` do the job of `dict_occ`
```
from collections import Counter
dict_occ = Counter(word) # {'h': 1, 'e': 1, 'l': 2, 'o': 1}
``` | Did you consider using the `collections.Counter` class?
```py
from collections import Counter
def nb_occurances(str):
ctr = Counter(str)
for ch, cnt in ctr.items():
print(ch, '->', cnt)
nb_occurances('ababccab')
```
Prints:
```
a -> 3
b -> 3
c -> 2
``` |
66,830,558 | I just started a new project in django, I run the command 'django-admin startproject + project\_name', and 'python manage.py startapp + app\_name'. Created a project and app.
I also added my new app to the settings:
[settings pic](https://i.stack.imgur.com/aMIpy.png)
After that I tried to create my first module on 'modules.py' file on my app, but when I do it and run the file, it gives me this error message:
[Error message](https://i.stack.imgur.com/LX3n1.png)
The entire error message says:
" django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED\_APPS, but settings are not configured. You must either define the environment variable DJANGO\_SETTINGS\_MODULE or call settings.configure() before accessing settings. "
I created a few projects before, and never had this problem.
I discovered that if I dont use the 'models.Model' on my class, it does not gives me this error.
[No error message on this case](https://i.stack.imgur.com/v5Dg2.png)
Someone knows what it is about, and why it gives me this error? I didnt change anything on settings, just added the app. | 2021/03/27 | [
"https://Stackoverflow.com/questions/66830558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15493450/"
] | You want a `dict: {letter:positions}` , for that a `defaultdict` is well suited
```
from collections import defaultdict
def nb_occurances(word):
dict_occ = {}
positions = defaultdict(list)
for i, c in enumerate(word):
dict_occ[c] = word.count(c)
positions[c].append(i)
return dict_occ, positions
print(nb_occurances("hello"))
# ({'h': 1, 'e': 1, 'l': 2, 'o': 1}, {'h': [0], 'e': [1], 'l': [2, 3], 'o': [4]}))
```
Know that `collections.Counter` do the job of `dict_occ`
```
from collections import Counter
dict_occ = Counter(word) # {'h': 1, 'e': 1, 'l': 2, 'o': 1}
``` | Another solution
```py
def nb_occurances(ch):
dict_occ = {} # dictionary of occurances count
dict_pos = {} # dictionary of positions
for i, c in enumerate(ch):
dict_occ[c] = ch.count(c)
if c not in dict_pos:
dict_pos[c] = []
dict_pos[c] += [i]
return dict_occ, dict_pos
chaine = input("chaine : ")
x = nb_occurances(chaine)
print(x[0])
print(x[1])
```
Returns
```
{'h': 1, 'e': 1, 'l': 2, 'o': 1}
{'h': [0], 'e': [1], 'l': [2, 3], 'o': [4]}
``` |
66,830,558 | I just started a new project in django, I run the command 'django-admin startproject + project\_name', and 'python manage.py startapp + app\_name'. Created a project and app.
I also added my new app to the settings:
[settings pic](https://i.stack.imgur.com/aMIpy.png)
After that I tried to create my first module on 'modules.py' file on my app, but when I do it and run the file, it gives me this error message:
[Error message](https://i.stack.imgur.com/LX3n1.png)
The entire error message says:
" django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED\_APPS, but settings are not configured. You must either define the environment variable DJANGO\_SETTINGS\_MODULE or call settings.configure() before accessing settings. "
I created a few projects before, and never had this problem.
I discovered that if I dont use the 'models.Model' on my class, it does not gives me this error.
[No error message on this case](https://i.stack.imgur.com/v5Dg2.png)
Someone knows what it is about, and why it gives me this error? I didnt change anything on settings, just added the app. | 2021/03/27 | [
"https://Stackoverflow.com/questions/66830558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15493450/"
] | You want a `dict: {letter:positions}` , for that a `defaultdict` is well suited
```
from collections import defaultdict
def nb_occurances(word):
dict_occ = {}
positions = defaultdict(list)
for i, c in enumerate(word):
dict_occ[c] = word.count(c)
positions[c].append(i)
return dict_occ, positions
print(nb_occurances("hello"))
# ({'h': 1, 'e': 1, 'l': 2, 'o': 1}, {'h': [0], 'e': [1], 'l': [2, 3], 'o': [4]}))
```
Know that `collections.Counter` do the job of `dict_occ`
```
from collections import Counter
dict_occ = Counter(word) # {'h': 1, 'e': 1, 'l': 2, 'o': 1}
``` | ```
from collections import defaultdict
s = "ababac"
dict = defaultdict(list)
for i in range(len(s)):
dict[s[i]].append(i)
for key in dict:
print(key, dict[key])
```
keep a dictionary where the key,value is character, list |
66,830,558 | I just started a new project in django, I run the command 'django-admin startproject + project\_name', and 'python manage.py startapp + app\_name'. Created a project and app.
I also added my new app to the settings:
[settings pic](https://i.stack.imgur.com/aMIpy.png)
After that I tried to create my first module on 'modules.py' file on my app, but when I do it and run the file, it gives me this error message:
[Error message](https://i.stack.imgur.com/LX3n1.png)
The entire error message says:
" django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED\_APPS, but settings are not configured. You must either define the environment variable DJANGO\_SETTINGS\_MODULE or call settings.configure() before accessing settings. "
I created a few projects before, and never had this problem.
I discovered that if I dont use the 'models.Model' on my class, it does not gives me this error.
[No error message on this case](https://i.stack.imgur.com/v5Dg2.png)
Someone knows what it is about, and why it gives me this error? I didnt change anything on settings, just added the app. | 2021/03/27 | [
"https://Stackoverflow.com/questions/66830558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15493450/"
] | You want a `dict: {letter:positions}` , for that a `defaultdict` is well suited
```
from collections import defaultdict
def nb_occurances(word):
dict_occ = {}
positions = defaultdict(list)
for i, c in enumerate(word):
dict_occ[c] = word.count(c)
positions[c].append(i)
return dict_occ, positions
print(nb_occurances("hello"))
# ({'h': 1, 'e': 1, 'l': 2, 'o': 1}, {'h': [0], 'e': [1], 'l': [2, 3], 'o': [4]}))
```
Know that `collections.Counter` do the job of `dict_occ`
```
from collections import Counter
dict_occ = Counter(word) # {'h': 1, 'e': 1, 'l': 2, 'o': 1}
``` | You can try with below code.
input : `hello` and
output : `{'h': [0], 'e': [1], 'l': [2, 3], 'o': [4]}`
```
from collections import defaultdict
chaine = input ("chaine : ")
def nb_occurances(ch):
positions = defaultdict(list)
for i,j in enumerate(ch):
positions[j].append(i)
return positions
print (dict(nb_occurances(chaine)))
``` |
43,573,582 | I'm trying to make a graph with a pretty massive key:
```
my_plot = degrees.plot(kind='bar',stacked=True,title="% of Degrees by Field",fontsize=20,figsize=(24, 16))
my_plot.set_xlabel("Institution", fontsize=20)
my_plot.set_ylabel("% of Degrees by Field", fontsize=20)
my_plot.legend(["Agriculture, Agriculture Operations, and Related Sciences", "Architecture and Related Services",
"Area, Ethnic, Cultural, Gender, and Group Studies", "Biological and Biomedical Sciences",
"Business, Management, Marketing, and Related Support Services",
"Communication, Journalism, and Related Programs",
"Communications Technologies/Technicians and Support Services",
"Computer and Information Sciences and Support Services", "Construction Trades", "Education",
"Engineering Technologies and Engineering-Related Fields", "Engineering",
"English Language and Literature/Letters", "Family and Consumer Sciences/Human Sciences",
"Foreign Languages, Literatures, and Linguistics", "Health Professions and Related Programs", "History",
"Homeland Security, Law Enforcement, Firefighting and Related Protective Services",
"Legal Professions and Studies", "Liberal Arts and Sciences, General Studies and Humanities",
"Library Science", "Mathematics and Statistics", "Mechanic and Repair Technologies/Technicians",
"Military Technologies and Applied Sciences", "Multi/Interdisciplinary Studies",
"Natural Resources and Conservation", "Parks, Recreation, Leisure, and Fitness Studies",
"Personal and Culinary Services", "Philosophy and Religious Studies", "Physical Sciences",
"Precision Production", "Psychology", "Public Administration and Social Service Professions",
"Science Technologies/Technicians", "Social Sciences", "Theology and Religious Vocations",
"Transportation and Materials Moving", "Visual and Performing Arts"])
plt.savefig("Degrees by Field.png")
```
and I'm trying to edit the key so that it's on the right side of the entire graph as listed [here](http://matplotlib.org/users/legend_guide.html).
I'm trying to add this code
```
#Place a legend to the right of this smaller subplot.
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
```
and I get errors when I add that line to my lengthy code. Can someone tell me where to put this so my legend is on the right?
THANK YOU!
**Edited to add**
Ran the code with location specific language:
```
my_plot = degrees.plot(kind='bar',stacked=True,title="% of Degrees by Field",fontsize=20,figsize=(24, 16))
my_plot.set_xlabel("Institution", fontsize=20)
my_plot.set_ylabel("% of Degrees by Field", fontsize=20)
my_plot.legend(["Agriculture, Agriculture Operations, and Related Sciences", "Architecture and Related Services",
"Area, Ethnic, Cultural, Gender, and Group Studies", "Biological and Biomedical Sciences",
"Business, Management, Marketing, and Related Support Services",
"Communication, Journalism, and Related Programs",
"Communications Technologies/Technicians and Support Services",
"Computer and Information Sciences and Support Services", "Construction Trades", "Education",
"Engineering Technologies and Engineering-Related Fields", "Engineering",
"English Language and Literature/Letters", "Family and Consumer Sciences/Human Sciences",
"Foreign Languages, Literatures, and Linguistics", "Health Professions and Related Programs", "History",
"Homeland Security, Law Enforcement, Firefighting and Related Protective Services",
"Legal Professions and Studies", "Liberal Arts and Sciences, General Studies and Humanities",
"Library Science", "Mathematics and Statistics", "Mechanic and Repair Technologies/Technicians",
"Military Technologies and Applied Sciences", "Multi/Interdisciplinary Studies",
"Natural Resources and Conservation", "Parks, Recreation, Leisure, and Fitness Studies",
"Personal and Culinary Services", "Philosophy and Religious Studies", "Physical Sciences",
"Precision Production", "Psychology", "Public Administration and Social Service Professions",
"Science Technologies/Technicians", "Social Sciences", "Theology and Religious Vocations",
"Transportation and Materials Moving", "Visual and Performing Arts"]plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.))
plt.savefig("Degrees by Field.png")
```
And then got this warning/error:
```
File "<ipython-input-101-9066269a61aa>", line 21
"Transportation and Materials Moving", "Visual and Performing Arts"]plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.))
^
SyntaxError: invalid syntax
``` | 2017/04/23 | [
"https://Stackoverflow.com/questions/43573582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7907634/"
] | >
> but as a2[][] is locally declared then its elements should not be initialosed by deaflt
>
>
>
There's a big difference between a *variable* and an array entry.
`b` not being initialized is a common coding error, so the compiler calls it out.
But `a2` is initialized, and the contents of an array are set to the default value for the array's element type when the array is allocated — `int[]` (or `a2[0]`) and `int` (for `a2[0][0]`), in your case. | ```
public class HelloWorld{
public static void main(String []args){
System.out.println("sampleArray[0] is ");
int sampleArray[] = new int[7];
System.out.println(sampleArray[0]);
}
}
Output
sampleArray[0] is
0
``` |
54,445,338 | A python list consist of a number of items that is equally divided by 3.
The list looks like this:
```
the_list = ['ab','cd','e','fgh','i', 'jklm']
```
I want to merge 3 items at the time for the entire list. How should I do that? (the list could have any number of items as long as the number of items can be divided by 3)
```
expected_output = ['abcde', 'fghijklm']
``` | 2019/01/30 | [
"https://Stackoverflow.com/questions/54445338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2466763/"
] | You can slice the list while iterating an index over the length of the list with a step of 3 in a list comprehension:
```
[''.join(the_list[i:i + 3]) for i in range(0, len(the_list), 3)]
```
You can also create an iterator from the list and use `zip` with `itertools.repeat` to group 3 items at a time:
```
from itertools import repeat
i = iter(the_list)
[''.join(t) for t in zip(*repeat(i, 3))]
```
Both of the above return:
```
['abcde', 'fghijklm']
``` | Here's one way using a list comprehension and `range`:
```
output = [''.join(the_list[i:i+3]) for i in range(0, len(the_list), 3)]
``` |
9,701,227 | I don't understand the answers for a [similar question.](https://stackoverflow.com/questions/9359677/why-python-reduce-skip-over-the-none-element)
It is clear that this should return `True`
```
l = [1,1,1]
reduce(lambda x,y: x== y, l)
```
However, how do you explain this retuns `False` (when `None==None` is `True`)
```
l = [None,None,None]
reduce(lambda x,y: x== y, l)
``` | 2012/03/14 | [
"https://Stackoverflow.com/questions/9701227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/94363/"
] | Because
```
1 == True # 1 == (1 == 1)
```
is `True`, but
```
None == True # None == (None == None)
```
is `False` (and `None == False` is `False` as well, so once you got `False`, it stays `False`).
That's how `reduce` works: It passes each element and the **result** of the previous evaluation to the callback. And by that it *reduces* a sequence of values to one value. | Your second example return `False` because the first time `None == None` gives `True`, but `True == None` gives `False`.
Take a look at the [`reduce` doc](http://docs.python.org/library/functions.html#reduce) to see how it works.
Also note that "comparisons to singletons like `None` should always be done with `is` or `is not`, **never the equality operators**." - [[PEP8]](http://www.python.org/dev/peps/pep-0008/) |
9,701,227 | I don't understand the answers for a [similar question.](https://stackoverflow.com/questions/9359677/why-python-reduce-skip-over-the-none-element)
It is clear that this should return `True`
```
l = [1,1,1]
reduce(lambda x,y: x== y, l)
```
However, how do you explain this retuns `False` (when `None==None` is `True`)
```
l = [None,None,None]
reduce(lambda x,y: x== y, l)
``` | 2012/03/14 | [
"https://Stackoverflow.com/questions/9701227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/94363/"
] | It's not different with `None`, actually, what happens within `reduce` in the first case is
* 1 compared with 1 (== `True`)
* `True` compared with 1 (== `True`)
In the second case, it's
* `None` compared with `None` (== `True`)
* `True` compared with `None` (== `False`)
The funny example would be:
```
>> from operator import eq
>> reduce(eq, [False, False, False])
False
>> reduce(eq, [False, False, False, False])
True
``` | Your second example return `False` because the first time `None == None` gives `True`, but `True == None` gives `False`.
Take a look at the [`reduce` doc](http://docs.python.org/library/functions.html#reduce) to see how it works.
Also note that "comparisons to singletons like `None` should always be done with `is` or `is not`, **never the equality operators**." - [[PEP8]](http://www.python.org/dev/peps/pep-0008/) |
9,701,227 | I don't understand the answers for a [similar question.](https://stackoverflow.com/questions/9359677/why-python-reduce-skip-over-the-none-element)
It is clear that this should return `True`
```
l = [1,1,1]
reduce(lambda x,y: x== y, l)
```
However, how do you explain this retuns `False` (when `None==None` is `True`)
```
l = [None,None,None]
reduce(lambda x,y: x== y, l)
``` | 2012/03/14 | [
"https://Stackoverflow.com/questions/9701227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/94363/"
] | Consider the following:
```
In [214]: l = [None,None,None]
In [215]: reduce(lambda x,y: x== y, l)
Out[215]: False
In [216]: from functional import scanl
In [217]: scanl(lambda x,y: x== y, None, l)
Out[217]: <generator object _scanl at 0x0000000005770D38>
In [218]: list(scanl(lambda x,y: x== y, None, l))
Out[218]: [None, True, False, False]
```
`scanl` shows intermediate results, starting from the initial element. What is happening is that at first initial is returned, then the result of `None == None` (`True`), then `True == None` (`False`), then until the end, `False == None` (`False`).
**Reduce compares the result of the last calculation with the next element in the sequence.** | Your second example return `False` because the first time `None == None` gives `True`, but `True == None` gives `False`.
Take a look at the [`reduce` doc](http://docs.python.org/library/functions.html#reduce) to see how it works.
Also note that "comparisons to singletons like `None` should always be done with `is` or `is not`, **never the equality operators**." - [[PEP8]](http://www.python.org/dev/peps/pep-0008/) |
9,701,227 | I don't understand the answers for a [similar question.](https://stackoverflow.com/questions/9359677/why-python-reduce-skip-over-the-none-element)
It is clear that this should return `True`
```
l = [1,1,1]
reduce(lambda x,y: x== y, l)
```
However, how do you explain this retuns `False` (when `None==None` is `True`)
```
l = [None,None,None]
reduce(lambda x,y: x== y, l)
``` | 2012/03/14 | [
"https://Stackoverflow.com/questions/9701227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/94363/"
] | Because
```
1 == True # 1 == (1 == 1)
```
is `True`, but
```
None == True # None == (None == None)
```
is `False` (and `None == False` is `False` as well, so once you got `False`, it stays `False`).
That's how `reduce` works: It passes each element and the **result** of the previous evaluation to the callback. And by that it *reduces* a sequence of values to one value. | It's not different with `None`, actually, what happens within `reduce` in the first case is
* 1 compared with 1 (== `True`)
* `True` compared with 1 (== `True`)
In the second case, it's
* `None` compared with `None` (== `True`)
* `True` compared with `None` (== `False`)
The funny example would be:
```
>> from operator import eq
>> reduce(eq, [False, False, False])
False
>> reduce(eq, [False, False, False, False])
True
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.