qid int64 46k 74.7M | question stringlengths 54 37.8k | date stringlengths 10 10 | metadata listlengths 3 3 | response_j stringlengths 17 26k | response_k stringlengths 26 26k |
|---|---|---|---|---|---|
52,810,422 | I go through the book: "Malware Data Science Attack Detection and Attribution" in chapter one and use pefile python module to check the AddressOfEntryPoint,
I found the sample: ircbot.exe's AddressOfEntryPoint is 0xCC00FFEE when I do pe.dump\_info(). This value is quite large and look wrong.
[ircbot.exe's OPTIONAL H... | 2018/10/15 | [
"https://Stackoverflow.com/questions/52810422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5742815/"
] | try this
```
select * from yourtable where youcolumn like '%''%'
``` | I hope this solves your problem
% **'** % -> Finds any values that have " **'** " in any position
By executing below query you will get the result which have '(single quote) in them
```
SELECT * FROM TABLE_NAME WHERE COLUMN_NAME LIKE "%'%"
```
i have executed the same query [enter image description here](https:/... |
52,810,422 | I go through the book: "Malware Data Science Attack Detection and Attribution" in chapter one and use pefile python module to check the AddressOfEntryPoint,
I found the sample: ircbot.exe's AddressOfEntryPoint is 0xCC00FFEE when I do pe.dump\_info(). This value is quite large and look wrong.
[ircbot.exe's OPTIONAL H... | 2018/10/15 | [
"https://Stackoverflow.com/questions/52810422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5742815/"
] | ```
CREATE TABLE #TEST
( Test_Column VARCHAR(MAX));
INSERT INTO #TEST VALUES
('10011-RIO MARE EXTRA''')
SELECT *
FROM #TEST
WHERE Test_Column LIKE '%''%'
```
The escape character for ' is ' used twice -> ''. | try this
```
select * from yourtable where youcolumn like '%''%'
``` |
52,810,422 | I go through the book: "Malware Data Science Attack Detection and Attribution" in chapter one and use pefile python module to check the AddressOfEntryPoint,
I found the sample: ircbot.exe's AddressOfEntryPoint is 0xCC00FFEE when I do pe.dump\_info(). This value is quite large and look wrong.
[ircbot.exe's OPTIONAL H... | 2018/10/15 | [
"https://Stackoverflow.com/questions/52810422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5742815/"
] | Find records with single quotes in the table
```
SELECT *
FROM [tableName]
where Name like '%''%'
``` | I hope this solves your problem
% **'** % -> Finds any values that have " **'** " in any position
By executing below query you will get the result which have '(single quote) in them
```
SELECT * FROM TABLE_NAME WHERE COLUMN_NAME LIKE "%'%"
```
i have executed the same query [enter image description here](https:/... |
52,810,422 | I go through the book: "Malware Data Science Attack Detection and Attribution" in chapter one and use pefile python module to check the AddressOfEntryPoint,
I found the sample: ircbot.exe's AddressOfEntryPoint is 0xCC00FFEE when I do pe.dump\_info(). This value is quite large and look wrong.
[ircbot.exe's OPTIONAL H... | 2018/10/15 | [
"https://Stackoverflow.com/questions/52810422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5742815/"
] | ```
CREATE TABLE #TEST
( Test_Column VARCHAR(MAX));
INSERT INTO #TEST VALUES
('10011-RIO MARE EXTRA''')
SELECT *
FROM #TEST
WHERE Test_Column LIKE '%''%'
```
The escape character for ' is ' used twice -> ''. | I hope this solves your problem
% **'** % -> Finds any values that have " **'** " in any position
By executing below query you will get the result which have '(single quote) in them
```
SELECT * FROM TABLE_NAME WHERE COLUMN_NAME LIKE "%'%"
```
i have executed the same query [enter image description here](https:/... |
52,810,422 | I go through the book: "Malware Data Science Attack Detection and Attribution" in chapter one and use pefile python module to check the AddressOfEntryPoint,
I found the sample: ircbot.exe's AddressOfEntryPoint is 0xCC00FFEE when I do pe.dump\_info(). This value is quite large and look wrong.
[ircbot.exe's OPTIONAL H... | 2018/10/15 | [
"https://Stackoverflow.com/questions/52810422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5742815/"
] | ```
CREATE TABLE #TEST
( Test_Column VARCHAR(MAX));
INSERT INTO #TEST VALUES
('10011-RIO MARE EXTRA''')
SELECT *
FROM #TEST
WHERE Test_Column LIKE '%''%'
```
The escape character for ' is ' used twice -> ''. | Find records with single quotes in the table
```
SELECT *
FROM [tableName]
where Name like '%''%'
``` |
15,417,574 | For python / pandas I find that df.to\_csv(fname) works at a speed of ~1 mln rows per min. I can sometimes improve performance by a factor of 7 like this:
```
def df2csv(df,fname,myformats=[],sep=','):
"""
# function is faster than to_csv
# 7 times faster for numbers if formats are specified,
# 2 times ... | 2013/03/14 | [
"https://Stackoverflow.com/questions/15417574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1442475/"
] | Lev. Pandas has rewritten `to_csv` to make a big improvement in native speed. The process is now i/o bound, accounts for many subtle dtype issues, and quote cases. Here is our performance results vs. 0.10.1 (in the upcoming 0.11) release. These are in `ms`, lower ratio is better.
```
Results:
... | Your `df_to_csv` function is very nice, except it does a lot of assumptions and doesn't work for the general case.
If it works for you, that's good, but be aware that it is not a general solution. CSV can contain commas, so what happens if there is this tuple to be written? `('a,b','c')`
The python `csv` module would... |
15,417,574 | For python / pandas I find that df.to\_csv(fname) works at a speed of ~1 mln rows per min. I can sometimes improve performance by a factor of 7 like this:
```
def df2csv(df,fname,myformats=[],sep=','):
"""
# function is faster than to_csv
# 7 times faster for numbers if formats are specified,
# 2 times ... | 2013/03/14 | [
"https://Stackoverflow.com/questions/15417574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1442475/"
] | use chunksize. I have found that makes a hell lot of difference. If you have memory in hand use good chunksize (no of rows) to get into memory and then write once. | Your `df_to_csv` function is very nice, except it does a lot of assumptions and doesn't work for the general case.
If it works for you, that's good, but be aware that it is not a general solution. CSV can contain commas, so what happens if there is this tuple to be written? `('a,b','c')`
The python `csv` module would... |
15,417,574 | For python / pandas I find that df.to\_csv(fname) works at a speed of ~1 mln rows per min. I can sometimes improve performance by a factor of 7 like this:
```
def df2csv(df,fname,myformats=[],sep=','):
"""
# function is faster than to_csv
# 7 times faster for numbers if formats are specified,
# 2 times ... | 2013/03/14 | [
"https://Stackoverflow.com/questions/15417574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1442475/"
] | In 2019 for cases like this, it may be better to just use numpy. Look at the timings:
```
aa.to_csv('pandas_to_csv', index=False)
# 6.47 s
df2csv(aa,'code_from_question', myformats=['%d','%.1f','%.1f','%.1f'])
# 4.59 s
from numpy import savetxt
savetxt(
'numpy_savetxt', aa.values, fmt='%d,%.1f,%.1f,%.1f',
h... | Your `df_to_csv` function is very nice, except it does a lot of assumptions and doesn't work for the general case.
If it works for you, that's good, but be aware that it is not a general solution. CSV can contain commas, so what happens if there is this tuple to be written? `('a,b','c')`
The python `csv` module would... |
15,417,574 | For python / pandas I find that df.to\_csv(fname) works at a speed of ~1 mln rows per min. I can sometimes improve performance by a factor of 7 like this:
```
def df2csv(df,fname,myformats=[],sep=','):
"""
# function is faster than to_csv
# 7 times faster for numbers if formats are specified,
# 2 times ... | 2013/03/14 | [
"https://Stackoverflow.com/questions/15417574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1442475/"
] | I had the same question earlier today. Using to\_csv took my dataframe 1hr 27min.
I found a package called pyarrow that reduced this to about 10min. This seemed like the most straight forward solution to me.
To use:
```
#install with conda then import
import pyarrow as pa
import pyarrow.csv as csv
#convert format -... | Your `df_to_csv` function is very nice, except it does a lot of assumptions and doesn't work for the general case.
If it works for you, that's good, but be aware that it is not a general solution. CSV can contain commas, so what happens if there is this tuple to be written? `('a,b','c')`
The python `csv` module would... |
15,417,574 | For python / pandas I find that df.to\_csv(fname) works at a speed of ~1 mln rows per min. I can sometimes improve performance by a factor of 7 like this:
```
def df2csv(df,fname,myformats=[],sep=','):
"""
# function is faster than to_csv
# 7 times faster for numbers if formats are specified,
# 2 times ... | 2013/03/14 | [
"https://Stackoverflow.com/questions/15417574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1442475/"
] | Lev. Pandas has rewritten `to_csv` to make a big improvement in native speed. The process is now i/o bound, accounts for many subtle dtype issues, and quote cases. Here is our performance results vs. 0.10.1 (in the upcoming 0.11) release. These are in `ms`, lower ratio is better.
```
Results:
... | use chunksize. I have found that makes a hell lot of difference. If you have memory in hand use good chunksize (no of rows) to get into memory and then write once. |
15,417,574 | For python / pandas I find that df.to\_csv(fname) works at a speed of ~1 mln rows per min. I can sometimes improve performance by a factor of 7 like this:
```
def df2csv(df,fname,myformats=[],sep=','):
"""
# function is faster than to_csv
# 7 times faster for numbers if formats are specified,
# 2 times ... | 2013/03/14 | [
"https://Stackoverflow.com/questions/15417574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1442475/"
] | Lev. Pandas has rewritten `to_csv` to make a big improvement in native speed. The process is now i/o bound, accounts for many subtle dtype issues, and quote cases. Here is our performance results vs. 0.10.1 (in the upcoming 0.11) release. These are in `ms`, lower ratio is better.
```
Results:
... | I had the same question earlier today. Using to\_csv took my dataframe 1hr 27min.
I found a package called pyarrow that reduced this to about 10min. This seemed like the most straight forward solution to me.
To use:
```
#install with conda then import
import pyarrow as pa
import pyarrow.csv as csv
#convert format -... |
15,417,574 | For python / pandas I find that df.to\_csv(fname) works at a speed of ~1 mln rows per min. I can sometimes improve performance by a factor of 7 like this:
```
def df2csv(df,fname,myformats=[],sep=','):
"""
# function is faster than to_csv
# 7 times faster for numbers if formats are specified,
# 2 times ... | 2013/03/14 | [
"https://Stackoverflow.com/questions/15417574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1442475/"
] | In 2019 for cases like this, it may be better to just use numpy. Look at the timings:
```
aa.to_csv('pandas_to_csv', index=False)
# 6.47 s
df2csv(aa,'code_from_question', myformats=['%d','%.1f','%.1f','%.1f'])
# 4.59 s
from numpy import savetxt
savetxt(
'numpy_savetxt', aa.values, fmt='%d,%.1f,%.1f,%.1f',
h... | use chunksize. I have found that makes a hell lot of difference. If you have memory in hand use good chunksize (no of rows) to get into memory and then write once. |
15,417,574 | For python / pandas I find that df.to\_csv(fname) works at a speed of ~1 mln rows per min. I can sometimes improve performance by a factor of 7 like this:
```
def df2csv(df,fname,myformats=[],sep=','):
"""
# function is faster than to_csv
# 7 times faster for numbers if formats are specified,
# 2 times ... | 2013/03/14 | [
"https://Stackoverflow.com/questions/15417574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1442475/"
] | use chunksize. I have found that makes a hell lot of difference. If you have memory in hand use good chunksize (no of rows) to get into memory and then write once. | I had the same question earlier today. Using to\_csv took my dataframe 1hr 27min.
I found a package called pyarrow that reduced this to about 10min. This seemed like the most straight forward solution to me.
To use:
```
#install with conda then import
import pyarrow as pa
import pyarrow.csv as csv
#convert format -... |
15,417,574 | For python / pandas I find that df.to\_csv(fname) works at a speed of ~1 mln rows per min. I can sometimes improve performance by a factor of 7 like this:
```
def df2csv(df,fname,myformats=[],sep=','):
"""
# function is faster than to_csv
# 7 times faster for numbers if formats are specified,
# 2 times ... | 2013/03/14 | [
"https://Stackoverflow.com/questions/15417574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1442475/"
] | In 2019 for cases like this, it may be better to just use numpy. Look at the timings:
```
aa.to_csv('pandas_to_csv', index=False)
# 6.47 s
df2csv(aa,'code_from_question', myformats=['%d','%.1f','%.1f','%.1f'])
# 4.59 s
from numpy import savetxt
savetxt(
'numpy_savetxt', aa.values, fmt='%d,%.1f,%.1f,%.1f',
h... | I had the same question earlier today. Using to\_csv took my dataframe 1hr 27min.
I found a package called pyarrow that reduced this to about 10min. This seemed like the most straight forward solution to me.
To use:
```
#install with conda then import
import pyarrow as pa
import pyarrow.csv as csv
#convert format -... |
34,336,040 | I am trying to extract the ranking text number from this link [link example: kaggle user ranking no1](https://www.kaggle.com/titericz). More clear in an image:
[](https://i.stack.imgur.com/sClUu.png)
I am using the following code:
```
def get_single... | 2015/12/17 | [
"https://Stackoverflow.com/questions/34336040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4157666/"
] | The data is databound using javascript, as the "data-bind" attribute suggests.
However, if you download the page with e.g. `wget`, you'll see that the rankingText value is actually there inside this script element on initial load:
```
<script type="text/javascript"
profile: {
...
"ranking": 96,
"rankingText": "... | This could because of dynamic data filling.
Some javascript code, fill this tag after page loading. Thus if you fetch the html using requests it is not filled yet.
```
<h4 data-bind="text: rankingText"></h4>
```
Please take a look at [Selenium web driver](http://www.seleniumhq.org/projects/webdriver/). Using this ... |
34,336,040 | I am trying to extract the ranking text number from this link [link example: kaggle user ranking no1](https://www.kaggle.com/titericz). More clear in an image:
[](https://i.stack.imgur.com/sClUu.png)
I am using the following code:
```
def get_single... | 2015/12/17 | [
"https://Stackoverflow.com/questions/34336040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4157666/"
] | If you aren't going to try browser automation through `selenium` as @Ali suggested, you would have to *parse the javascript containing the desired information*. You can do this in different ways. Here is a working code that locates the `script` by a [regular expression pattern](http://www.crummy.com/software/BeautifulS... | This could because of dynamic data filling.
Some javascript code, fill this tag after page loading. Thus if you fetch the html using requests it is not filled yet.
```
<h4 data-bind="text: rankingText"></h4>
```
Please take a look at [Selenium web driver](http://www.seleniumhq.org/projects/webdriver/). Using this ... |
34,336,040 | I am trying to extract the ranking text number from this link [link example: kaggle user ranking no1](https://www.kaggle.com/titericz). More clear in an image:
[](https://i.stack.imgur.com/sClUu.png)
I am using the following code:
```
def get_single... | 2015/12/17 | [
"https://Stackoverflow.com/questions/34336040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4157666/"
] | I have solved your problem using regex on the plain text:
```
def get_single_item_data(item_url):
sourceCode = requests.get(item_url)
plainText = sourceCode.text
#soup = BeautifulSoup(plainText, "html.parser")
pattern = re.compile("ranking\": [0-9]+")
name = pattern.search(plainText)
ranking = ... | This could because of dynamic data filling.
Some javascript code, fill this tag after page loading. Thus if you fetch the html using requests it is not filled yet.
```
<h4 data-bind="text: rankingText"></h4>
```
Please take a look at [Selenium web driver](http://www.seleniumhq.org/projects/webdriver/). Using this ... |
34,336,040 | I am trying to extract the ranking text number from this link [link example: kaggle user ranking no1](https://www.kaggle.com/titericz). More clear in an image:
[](https://i.stack.imgur.com/sClUu.png)
I am using the following code:
```
def get_single... | 2015/12/17 | [
"https://Stackoverflow.com/questions/34336040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4157666/"
] | If you aren't going to try browser automation through `selenium` as @Ali suggested, you would have to *parse the javascript containing the desired information*. You can do this in different ways. Here is a working code that locates the `script` by a [regular expression pattern](http://www.crummy.com/software/BeautifulS... | The data is databound using javascript, as the "data-bind" attribute suggests.
However, if you download the page with e.g. `wget`, you'll see that the rankingText value is actually there inside this script element on initial load:
```
<script type="text/javascript"
profile: {
...
"ranking": 96,
"rankingText": "... |
34,336,040 | I am trying to extract the ranking text number from this link [link example: kaggle user ranking no1](https://www.kaggle.com/titericz). More clear in an image:
[](https://i.stack.imgur.com/sClUu.png)
I am using the following code:
```
def get_single... | 2015/12/17 | [
"https://Stackoverflow.com/questions/34336040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4157666/"
] | The data is databound using javascript, as the "data-bind" attribute suggests.
However, if you download the page with e.g. `wget`, you'll see that the rankingText value is actually there inside this script element on initial load:
```
<script type="text/javascript"
profile: {
...
"ranking": 96,
"rankingText": "... | I have solved your problem using regex on the plain text:
```
def get_single_item_data(item_url):
sourceCode = requests.get(item_url)
plainText = sourceCode.text
#soup = BeautifulSoup(plainText, "html.parser")
pattern = re.compile("ranking\": [0-9]+")
name = pattern.search(plainText)
ranking = ... |
34,336,040 | I am trying to extract the ranking text number from this link [link example: kaggle user ranking no1](https://www.kaggle.com/titericz). More clear in an image:
[](https://i.stack.imgur.com/sClUu.png)
I am using the following code:
```
def get_single... | 2015/12/17 | [
"https://Stackoverflow.com/questions/34336040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4157666/"
] | If you aren't going to try browser automation through `selenium` as @Ali suggested, you would have to *parse the javascript containing the desired information*. You can do this in different ways. Here is a working code that locates the `script` by a [regular expression pattern](http://www.crummy.com/software/BeautifulS... | I have solved your problem using regex on the plain text:
```
def get_single_item_data(item_url):
sourceCode = requests.get(item_url)
plainText = sourceCode.text
#soup = BeautifulSoup(plainText, "html.parser")
pattern = re.compile("ranking\": [0-9]+")
name = pattern.search(plainText)
ranking = ... |
46,465,389 | I have a python string like this;
```
input_str = "2548,0.8987,0.8987,0.1548"
```
I want to remove the sub-string at the end after the last comma, including the comma itself.
The output string should look like this;
```
output_str = "2548,0.8987,0.8987"
```
I am using python v3.6 | 2017/09/28 | [
"https://Stackoverflow.com/questions/46465389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3848207/"
] | With `split` and `join`
=======================
```
','.join(input_str.split(',')[:-1])
```
### Explanation
```
# Split string by the commas
>>> input_str.split(',')
['2548', '0.8987', '0.8987', '0.1548']
# Take all but last part
>>> input_str.split(',')[:-1]
['2548', '0.8987', '0.8987']
# Join the parts with com... | There's [the split function](https://www.tutorialspoint.com/python/string_split.htm) for python :
```
print input_str.split(',')
```
Will return :
```
['2548,0.8987,0.8987', '0.1548']
```
But in case you have multiple commas, [rsplit is here for that](https://docs.python.org/2/library/stdtypes.html#str.rsplit) :
... |
46,465,389 | I have a python string like this;
```
input_str = "2548,0.8987,0.8987,0.1548"
```
I want to remove the sub-string at the end after the last comma, including the comma itself.
The output string should look like this;
```
output_str = "2548,0.8987,0.8987"
```
I am using python v3.6 | 2017/09/28 | [
"https://Stackoverflow.com/questions/46465389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3848207/"
] | With `split` and `join`
=======================
```
','.join(input_str.split(',')[:-1])
```
### Explanation
```
# Split string by the commas
>>> input_str.split(',')
['2548', '0.8987', '0.8987', '0.1548']
# Take all but last part
>>> input_str.split(',')[:-1]
['2548', '0.8987', '0.8987']
# Join the parts with com... | You can try this simplest one. Here we are using `split`, `pop` and `join` to achieve desired result.
[**Try this code snippet here**](https://eval.in/870194)
```
input_str = "2548,0.8987,0.8987,0.1548"
list= input_str.split(",") #Split string over ,
list.pop() #pop last element
print(",".join(list)) #joining list ag... |
46,465,389 | I have a python string like this;
```
input_str = "2548,0.8987,0.8987,0.1548"
```
I want to remove the sub-string at the end after the last comma, including the comma itself.
The output string should look like this;
```
output_str = "2548,0.8987,0.8987"
```
I am using python v3.6 | 2017/09/28 | [
"https://Stackoverflow.com/questions/46465389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3848207/"
] | With `split` and `join`
=======================
```
','.join(input_str.split(',')[:-1])
```
### Explanation
```
# Split string by the commas
>>> input_str.split(',')
['2548', '0.8987', '0.8987', '0.1548']
# Take all but last part
>>> input_str.split(',')[:-1]
['2548', '0.8987', '0.8987']
# Join the parts with com... | Assuming that there is definitely a comma in your string:
```
output_str = input_str[:input_str.rindex(',')]
```
That is "Take everything from the start of the string up to the last index of a comma". |
46,465,389 | I have a python string like this;
```
input_str = "2548,0.8987,0.8987,0.1548"
```
I want to remove the sub-string at the end after the last comma, including the comma itself.
The output string should look like this;
```
output_str = "2548,0.8987,0.8987"
```
I am using python v3.6 | 2017/09/28 | [
"https://Stackoverflow.com/questions/46465389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3848207/"
] | With `split` and `join`
=======================
```
','.join(input_str.split(',')[:-1])
```
### Explanation
```
# Split string by the commas
>>> input_str.split(',')
['2548', '0.8987', '0.8987', '0.1548']
# Take all but last part
>>> input_str.split(',')[:-1]
['2548', '0.8987', '0.8987']
# Join the parts with com... | Here you go
```
sep = ','
count = input_str.count(sep)
int i=0;
output = ''
while(i<count):
output += input_str.split(sep, 1)[i]
i++
input_str = output
``` |
46,465,389 | I have a python string like this;
```
input_str = "2548,0.8987,0.8987,0.1548"
```
I want to remove the sub-string at the end after the last comma, including the comma itself.
The output string should look like this;
```
output_str = "2548,0.8987,0.8987"
```
I am using python v3.6 | 2017/09/28 | [
"https://Stackoverflow.com/questions/46465389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3848207/"
] | There's [the split function](https://www.tutorialspoint.com/python/string_split.htm) for python :
```
print input_str.split(',')
```
Will return :
```
['2548,0.8987,0.8987', '0.1548']
```
But in case you have multiple commas, [rsplit is here for that](https://docs.python.org/2/library/stdtypes.html#str.rsplit) :
... | Here you go
```
sep = ','
count = input_str.count(sep)
int i=0;
output = ''
while(i<count):
output += input_str.split(sep, 1)[i]
i++
input_str = output
``` |
46,465,389 | I have a python string like this;
```
input_str = "2548,0.8987,0.8987,0.1548"
```
I want to remove the sub-string at the end after the last comma, including the comma itself.
The output string should look like this;
```
output_str = "2548,0.8987,0.8987"
```
I am using python v3.6 | 2017/09/28 | [
"https://Stackoverflow.com/questions/46465389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3848207/"
] | You can try this simplest one. Here we are using `split`, `pop` and `join` to achieve desired result.
[**Try this code snippet here**](https://eval.in/870194)
```
input_str = "2548,0.8987,0.8987,0.1548"
list= input_str.split(",") #Split string over ,
list.pop() #pop last element
print(",".join(list)) #joining list ag... | Here you go
```
sep = ','
count = input_str.count(sep)
int i=0;
output = ''
while(i<count):
output += input_str.split(sep, 1)[i]
i++
input_str = output
``` |
46,465,389 | I have a python string like this;
```
input_str = "2548,0.8987,0.8987,0.1548"
```
I want to remove the sub-string at the end after the last comma, including the comma itself.
The output string should look like this;
```
output_str = "2548,0.8987,0.8987"
```
I am using python v3.6 | 2017/09/28 | [
"https://Stackoverflow.com/questions/46465389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3848207/"
] | Assuming that there is definitely a comma in your string:
```
output_str = input_str[:input_str.rindex(',')]
```
That is "Take everything from the start of the string up to the last index of a comma". | Here you go
```
sep = ','
count = input_str.count(sep)
int i=0;
output = ''
while(i<count):
output += input_str.split(sep, 1)[i]
i++
input_str = output
``` |
71,310,217 | My goal is to use gpu(GE FORCE GTX 850M). I have tried according to this guide(<https://docs.anaconda.com/anaconda/user-guide/tasks/tensorflow/>). Tensoflow 2.8 is installed and keras also. But when I execute the test code, the output is as below. It must be that the code does not or cannot use gpu. What went wrong?
`... | 2022/03/01 | [
"https://Stackoverflow.com/questions/71310217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5554839/"
] | The anaconda guide looks outdated, because since Tensorflow 2.0, tensorflow and tensorflow-gpu are merged into one.
If you are using Tensorflow 2, I would advise you this guide <https://www.tensorflow.org/install/gpu> which has worked for me (do not download the latest cuDNN SDK version which is bugged but the one ind... | In this guide <https://www.tensorflow.org/install/source_windows>, there are version configuration .It helped. |
9,430,644 | ```
class test:
def __init__(self):
test_dict = {'1': 'one', '2': 'two'}
def test_function(self):
print self.test_dict
if __name__ == '__main__':
t = test()
print t.test_dict
```
Error:
```
AttributeError: test instance has no attribute 'test_dict'
```
Also, if i execute code: `t.t... | 2012/02/24 | [
"https://Stackoverflow.com/questions/9430644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1031769/"
] | You forgot `self`.
Change this:
```
def __init__(self):
test_dict = {'1': 'one', '2': 'two'}
```
with:
```
def __init__(self):
self.test_dict = {'1': 'one', '2': 'two'}
```
`self` is your *instance* inside the methods in your class. That is not because `self` is a special keyword but because `self` is us... | You made an error in your `__init__`. This:
```
def __init__(self):
test_dict = {'1': 'one', '2': 'two'}
```
Should be:
```
def __init__(self):
self.test_dict = {'1': 'one', '2': 'two'}
``` |
9,430,644 | ```
class test:
def __init__(self):
test_dict = {'1': 'one', '2': 'two'}
def test_function(self):
print self.test_dict
if __name__ == '__main__':
t = test()
print t.test_dict
```
Error:
```
AttributeError: test instance has no attribute 'test_dict'
```
Also, if i execute code: `t.t... | 2012/02/24 | [
"https://Stackoverflow.com/questions/9430644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1031769/"
] | You forgot `self`.
Change this:
```
def __init__(self):
test_dict = {'1': 'one', '2': 'two'}
```
with:
```
def __init__(self):
self.test_dict = {'1': 'one', '2': 'two'}
```
`self` is your *instance* inside the methods in your class. That is not because `self` is a special keyword but because `self` is us... | Think of classes/instances as dictionaries. Whenever you create instance and call any of its methods, these functions automatically receive instance as first argument (unless function is static or class method).
So, if you want some variable to be stored in instance and later be accessed, put all variables into that f... |
13,174,127 | I want to be able to capture the value of an HTML attribute with a python regexp.
currently I use
```
re.compile( r'=(["\'].*?["\'])', re.IGNORECASE | re.DOTALL )
```
My problem is that I want the regular expression to "remember" whether the attribute started with a single or a double quote.
I found the bug in my c... | 2012/11/01 | [
"https://Stackoverflow.com/questions/13174127",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1616042/"
] | You can capture the first quote and then use a backreference:
```
r'=((["\']).*?\2)'
```
However, regular expressions are [not the proper approach to parsing HTML](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454). You should consider using a DOM pars... | The following would be more efficient in theory:
```
regex = r'"[^"]*"|\'[^']*\''
```
For the reference, here's Jeffrey Friedl's [expression](http://regex.info/dlisting.cgi?ed=3&id=36481) for html tags (from the owl book):
```
< # Opening "<"
( # Any amount of . . .
"[^"]*" # ... |
21,067,443 | I can use the following code to change a string to a variable and then call function of the library that was previously imported.
```
>>> import sys
>>> x = 'sys'
>>> globals()[x]
<module 'sys' (built-in)>
>>> globals()[x].__doc__
```
Without first importing the module, I have an string to variable but I can't use t... | 2014/01/11 | [
"https://Stackoverflow.com/questions/21067443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/610569/"
] | Most Python coders prefer using [`importlib.import_module`](http://docs.python.org/2.7/library/importlib.html#importlib.import_module) instead of `__import__`:
```
>>> from importlib import import_module
>>> mod = raw_input(":")
:sys
>>> sys = import_module(mod)
>>> sys
<module 'sys' (built-in)>
>>> sys.version_info #... | You are looking for [`__import__`](http://docs.python.org/2/library/functions.html#__import__) built-in function:
```
__import__(globals()[y])
```
Basic usage:
```
>>>math = __import__('math')
>>>print math.e
2.718281828459045
```
You can also look into `importlib.import_module` as suggested in another answer and... |
21,067,443 | I can use the following code to change a string to a variable and then call function of the library that was previously imported.
```
>>> import sys
>>> x = 'sys'
>>> globals()[x]
<module 'sys' (built-in)>
>>> globals()[x].__doc__
```
Without first importing the module, I have an string to variable but I can't use t... | 2014/01/11 | [
"https://Stackoverflow.com/questions/21067443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/610569/"
] | Use `__import__` function:
```
x = 'sys'
sys = __import__(x)
``` | You are looking for [`__import__`](http://docs.python.org/2/library/functions.html#__import__) built-in function:
```
__import__(globals()[y])
```
Basic usage:
```
>>>math = __import__('math')
>>>print math.e
2.718281828459045
```
You can also look into `importlib.import_module` as suggested in another answer and... |
21,067,443 | I can use the following code to change a string to a variable and then call function of the library that was previously imported.
```
>>> import sys
>>> x = 'sys'
>>> globals()[x]
<module 'sys' (built-in)>
>>> globals()[x].__doc__
```
Without first importing the module, I have an string to variable but I can't use t... | 2014/01/11 | [
"https://Stackoverflow.com/questions/21067443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/610569/"
] | Most Python coders prefer using [`importlib.import_module`](http://docs.python.org/2.7/library/importlib.html#importlib.import_module) instead of `__import__`:
```
>>> from importlib import import_module
>>> mod = raw_input(":")
:sys
>>> sys = import_module(mod)
>>> sys
<module 'sys' (built-in)>
>>> sys.version_info #... | Use `__import__` function:
```
x = 'sys'
sys = __import__(x)
``` |
46,963,157 | I'm trying to implement an efficient way of creating a frequency table in python, with a rather large numpy input array of `~30 million` entries. Currently I am using a `for-loop`, but it's taking far too long.
The input is an ordered `numpy array` of the form
```
Y = np.array([4, 4, 4, 6, 6, 7, 8, 9, 9, 9..... etc]... | 2017/10/26 | [
"https://Stackoverflow.com/questions/46963157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8840045/"
] | You can simply do this using Counter from collections module. Please see the below code i ran for your test case.
```
import numpy as np
from collections import Counter
Y = np.array([4, 4, 4, 6, 6, 7, 8, 9, 9, 9,10,5,5,5])
print(Counter(Y))
```
It gave the following output
```
Counter({4: 3, 9: 3, 5: 3, 6: 2, 7: 1,... | I think numpy.unique is your solution.
<https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.unique.html>
```
import numpy as np
t = np.random.randint(0, 1000, 100000000)
print(np.unique(t, return_counts=True))
```
This takes ~4 seconds for me.
The collections.Counter approach takes ~10 seconds.
But t... |
46,963,157 | I'm trying to implement an efficient way of creating a frequency table in python, with a rather large numpy input array of `~30 million` entries. Currently I am using a `for-loop`, but it's taking far too long.
The input is an ordered `numpy array` of the form
```
Y = np.array([4, 4, 4, 6, 6, 7, 8, 9, 9, 9..... etc]... | 2017/10/26 | [
"https://Stackoverflow.com/questions/46963157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8840045/"
] | You can simply do this using Counter from collections module. Please see the below code i ran for your test case.
```
import numpy as np
from collections import Counter
Y = np.array([4, 4, 4, 6, 6, 7, 8, 9, 9, 9,10,5,5,5])
print(Counter(Y))
```
It gave the following output
```
Counter({4: 3, 9: 3, 5: 3, 6: 2, 7: 1,... | If your input array `x` is sorted, you can do the following to get the counts in linear time:
```
diff1 = np.diff(x)
# get indices of the elements at which jumps occurred
jumps = np.concatenate([[0], np.where(diff1 > 0)[0] + 1, [len(x)]])
unique_elements = x[jumps[:-1]]
counts = np.diff(jumps)
``` |
36,433,011 | At this moment I have a game that drops falling colored blocks (*obstacles*) from the top of the screen, and the objective is for the player to dodge said (*obstacles*) by moving either left or right.
I currently have set up where every time the user runs the script, the blocks will be a different color, but the probl... | 2016/04/05 | [
"https://Stackoverflow.com/questions/36433011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3777680/"
] | Add relative positioning to the container and absolute positioning to the icon
```
#menui {
left: 0;
position:absolute;
}
.smalltop {
background-color: #FFF;
list-style-type: none;
margin: 0 auto;
position:relative;
}
```
**[jsFiddle example](https://jsfiddle.net/j08691/pzLbruhx/1/)** | Just give property `float:left` to `#menui`, and see the result |
36,433,011 | At this moment I have a game that drops falling colored blocks (*obstacles*) from the top of the screen, and the objective is for the player to dodge said (*obstacles*) by moving either left or right.
I currently have set up where every time the user runs the script, the blocks will be a different color, but the probl... | 2016/04/05 | [
"https://Stackoverflow.com/questions/36433011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3777680/"
] | Add relative positioning to the container and absolute positioning to the icon
```
#menui {
left: 0;
position:absolute;
}
.smalltop {
background-color: #FFF;
list-style-type: none;
margin: 0 auto;
position:relative;
}
```
**[jsFiddle example](https://jsfiddle.net/j08691/pzLbruhx/1/)** | Use [**`display:table\table-row\table-cell`**](http://colintoh.com/blog/display-table-anti-hero) and [**`vertical-align`**](https://developer.mozilla.org/en-US/docs/Web/CSS/vertical-align) on icon
```
#smalllogo {
max-height: 50px;
width: auto;
display: table-cell;
margin: 0 auto;
border: 5px solid black;
... |
71,775,713 | I'm trying to do some interesting integration problems for my Calculus I students under Anaconda python 3.8.5 and sympy version 1.9,
So question 1 is:
integrate(sin(m \* x)\* cos(n \* x), x)
[](https://i.stack.imgur.com/lOzzI.png)
whereas x is the ... | 2022/04/07 | [
"https://Stackoverflow.com/questions/71775713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8438488/"
] | If you want to say that `m` and `n` are not equal (and get the answer you gave) make one odd and one even:
```
>>> var('m',odd=True)
m
>>> var('n',even=True)
n
>>> integrate(sin((m) * x)* cos(n * x), x)
-m*cos(m*x)*cos(n*x)/(m**2 - n**2) - n*sin(m*x)*sin(n*x)/(m**2 - n**2)
```
(You get an interesting result if you j... | First of all, what version of SymPy are you using? You can verify that with:
```py
import sympy as sp
print(sp.__version__)
```
If you are using older versions, maybe the solver is having trouble. The following solution has been tested on SymPy 1.9 and 1.10.1.
```py
# define a, x as ordinary symbols with no assumpt... |
7,774,740 | This is an extension question of [PHP pass in $this to function outside class](https://stackoverflow.com/questions/7774444/php-pass-in-this-to-function-outside-class)
And I believe this is what I'm looking for but it's in python not php: [Programmatically determining amount of parameters a function requires - Python](... | 2011/10/14 | [
"https://Stackoverflow.com/questions/7774740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/266763/"
] | Use [Reflection](http://php.net/book.reflection), especially [ReflectionFunction](http://php.net/class.reflectionfunction) in your case.
```
$fct = new ReflectionFunction('client_func');
echo $fct->getNumberOfRequiredParameters();
```
As far as I can see you will find [getParameters()](http://php.net/reflectionfunct... | Only way is with reflection by going to <http://us3.php.net/manual/en/book.reflection.php>
```
class foo {
function bar ($arg1, $arg2) {
// ...
}
}
$method = new ReflectionMethod('foo', 'bar');
$num = $method->getNumberOfParameters();
``` |
60,973,894 | [Open Street Map (pyproj). How to solve syntax issue?](https://stackoverflow.com/questions/59596835/open-street-map-pyproj-how-to-solve-syntax-issue)
has a similar question and the answers there did not help me.
I am using the helper class below a few hundred times and my console gets flooded with warnings:
```
/opt/... | 2020/04/01 | [
"https://Stackoverflow.com/questions/60973894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1497139/"
] | In order to keep using the old syntax (feeding the transformer `(Lon,Lat)` pairs) you can use the `always_xy=True` parameter when creating the transformer object:
```py
from pyproj import Transformer
transformer = Transformer.from_crs(4326, 3857, always_xy=True)
points = [
(6.783333, 51.233333), # Dusseldorf
... | This is my current guess for the fix:
```
#e4326=Proj(init='epsg:4326')
e4326=CRS('EPSG:4326')
#e3857=Proj(init='epsg:3857')
e3857=CRS('EPSG:3857')
```
**Projection helper class**
```
from pyproj import Proj, CRS,transform
class Projection:
'''
helper to project lat/lon values to map
''... |
66,514,262 | i want to plot a graphs of my csv file data
now i want epoch as x axis and on y axis the label "acc" and "val\_acc" is plot i try the following code but it gives blank graph
`
```
x = []
y = []
with open('trainSelfVGG.csv','r') as csvfile:
plots = csv.reader(csvfile, delimiter=',')
for row in plots:
... | 2021/03/07 | [
"https://Stackoverflow.com/questions/66514262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12673562/"
] | You are correct, a string cannot be returned as an array via the `return` statement. When you pass or return an array, only a pointer to its first element is used. Hence the function `get_name()` returns a pointer to the array defined locally with automatic storage (aka *on the stack*). This is incorrect as this array ... | You are returning address of `real_name` from `get_name` method which will go out of scope after the function returns. Instead allocate the memory of string on heap and return its address. Also, the caller would need to free the string memory allocated on the heap to avoid any memory leaks. |
66,514,262 | i want to plot a graphs of my csv file data
now i want epoch as x axis and on y axis the label "acc" and "val\_acc" is plot i try the following code but it gives blank graph
`
```
x = []
y = []
with open('trainSelfVGG.csv','r') as csvfile:
plots = csv.reader(csvfile, delimiter=',')
for row in plots:
... | 2021/03/07 | [
"https://Stackoverflow.com/questions/66514262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12673562/"
] | You are correct, a string cannot be returned as an array via the `return` statement. When you pass or return an array, only a pointer to its first element is used. Hence the function `get_name()` returns a pointer to the array defined locally with automatic storage (aka *on the stack*). This is incorrect as this array ... | Like you said, "However, as far as I know, string cannot be in the form `string_name = call_function()`." To understand the logic behind this, just look at your `get_name()` function:
```
char *get_name(int num)
{
char real_name[30];
if (num==1)
strcpy(real_name,"Jake Peralta");
return real_name;... |
27,088,984 | I am learning python so this question may be a simple question, I am creating a list of cars and their details in a list as bellow:
```
car_specs = [("1. Ford Fiesta - Studio", ["3", "54mpg", "Manual", "£9,995"]),
("2. Ford Focous - Studio", ["5", "48mpg", "Manual", "£17,295"]),
("3. Vauxhall... | 2014/11/23 | [
"https://Stackoverflow.com/questions/27088984",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4284218/"
] | Just append the tuple to the list making sure to separate new\_name from the list with a `,`:
```
new_name = input("What is the name of the new car?")
new_doors = input("How many doors does it have?")
new_efficency = input("What is the fuel efficency of the new car?")
new_gearbox = input("What type of gearbox?")
new_p... | You are not setting the first element go your tuple correctly. You are appending the name to the length of car specs as you expect.
Also new\_name is as string, when you do new\_name[x] your asking python for the x+1th character in that string.
```
new_name = input("What is the name of the new car?")
new_doors = inpu... |
41,474,163 | I was doing Singly-Linked List implementation and I remember Linus Torvalds talking about it [here](https://youtu.be/o8NPllzkFhE?t=890).
In a singly-linked list in order to remove a node we should have access to the previous node and then change the node it is currently pointing to.
Like this
[![enter image descripti... | 2017/01/04 | [
"https://Stackoverflow.com/questions/41474163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1597944/"
] | Sure you can do this in Python. What he's saying is that you have some data structure that represents the list itself and points to the head of the list, and you manipulate that just as you would the pointer in a list item when you're dealing with the first list item.
Now Python is not C so the implementation would be... | You cannot use Linus's specific trick in Python, because, as you well know, Python does not have pointers (as such) or an address-of operator. You can still, however, eliminate a special case for the list head by giving the list a dummy head node. You can do that as an inherent part of the design of your list, or you c... |
41,474,163 | I was doing Singly-Linked List implementation and I remember Linus Torvalds talking about it [here](https://youtu.be/o8NPllzkFhE?t=890).
In a singly-linked list in order to remove a node we should have access to the previous node and then change the node it is currently pointing to.
Like this
[![enter image descripti... | 2017/01/04 | [
"https://Stackoverflow.com/questions/41474163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1597944/"
] | Sure you can do this in Python. What he's saying is that you have some data structure that represents the list itself and points to the head of the list, and you manipulate that just as you would the pointer in a list item when you're dealing with the first list item.
Now Python is not C so the implementation would be... | My first thought upon reading your question was: why would you want to build a singly linked list in python? Python offers a wealth of collection types and you can use these without having to worry about whether they are implemented as singly linked list, as double linked list or as some non-recursive data structure (w... |
41,474,163 | I was doing Singly-Linked List implementation and I remember Linus Torvalds talking about it [here](https://youtu.be/o8NPllzkFhE?t=890).
In a singly-linked list in order to remove a node we should have access to the previous node and then change the node it is currently pointing to.
Like this
[![enter image descripti... | 2017/01/04 | [
"https://Stackoverflow.com/questions/41474163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1597944/"
] | Sure you can do this in Python. What he's saying is that you have some data structure that represents the list itself and points to the head of the list, and you manipulate that just as you would the pointer in a list item when you're dealing with the first list item.
Now Python is not C so the implementation would be... | You need two levels of indirection to do it the way Linus suggests, but you can potentially do it in Python perhaps by having a reference to an object which stores a reference to an object or something of this sort (an index to an index?). That said, I don't think it maps so elegantly or efficiently to Python and it'd ... |
41,474,163 | I was doing Singly-Linked List implementation and I remember Linus Torvalds talking about it [here](https://youtu.be/o8NPllzkFhE?t=890).
In a singly-linked list in order to remove a node we should have access to the previous node and then change the node it is currently pointing to.
Like this
[![enter image descripti... | 2017/01/04 | [
"https://Stackoverflow.com/questions/41474163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1597944/"
] | You cannot use Linus's specific trick in Python, because, as you well know, Python does not have pointers (as such) or an address-of operator. You can still, however, eliminate a special case for the list head by giving the list a dummy head node. You can do that as an inherent part of the design of your list, or you c... | You need two levels of indirection to do it the way Linus suggests, but you can potentially do it in Python perhaps by having a reference to an object which stores a reference to an object or something of this sort (an index to an index?). That said, I don't think it maps so elegantly or efficiently to Python and it'd ... |
41,474,163 | I was doing Singly-Linked List implementation and I remember Linus Torvalds talking about it [here](https://youtu.be/o8NPllzkFhE?t=890).
In a singly-linked list in order to remove a node we should have access to the previous node and then change the node it is currently pointing to.
Like this
[![enter image descripti... | 2017/01/04 | [
"https://Stackoverflow.com/questions/41474163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1597944/"
] | My first thought upon reading your question was: why would you want to build a singly linked list in python? Python offers a wealth of collection types and you can use these without having to worry about whether they are implemented as singly linked list, as double linked list or as some non-recursive data structure (w... | You need two levels of indirection to do it the way Linus suggests, but you can potentially do it in Python perhaps by having a reference to an object which stores a reference to an object or something of this sort (an index to an index?). That said, I don't think it maps so elegantly or efficiently to Python and it'd ... |
34,522,741 | A request comes to tornado's GET handler of a web app.
From the `GET` function, a `blocking_task` function is called. This `blocking_task` function has `@run_on_executor` decorator.
But this execution fails.
Could you please help on this. It seems that motor db is not able to execute the thread.
```
import time
from ... | 2015/12/30 | [
"https://Stackoverflow.com/questions/34522741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5722595/"
] | Finally following code works, Thank you @kwarunek
Also added parameters to the callback function.
```
import time
from concurrent.futures import ThreadPoolExecutor
from tornado import gen, web
from tornado.concurrent import run_on_executor
from tornado.ioloop import IOLoop
import argparse
from common.config import A... | From [docs](http://www.tornadoweb.org/en/stable/concurrent.html#tornado.concurrent.run_on_executor)
>
> IOLoop and executor to be used are determined by the io\_loop and
> executor attributes of self. To use different attributes, pass keyword
> arguments to the decorator
>
>
>
You have to provide a init threadp... |
34,522,741 | A request comes to tornado's GET handler of a web app.
From the `GET` function, a `blocking_task` function is called. This `blocking_task` function has `@run_on_executor` decorator.
But this execution fails.
Could you please help on this. It seems that motor db is not able to execute the thread.
```
import time
from ... | 2015/12/30 | [
"https://Stackoverflow.com/questions/34522741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5722595/"
] | From [docs](http://www.tornadoweb.org/en/stable/concurrent.html#tornado.concurrent.run_on_executor)
>
> IOLoop and executor to be used are determined by the io\_loop and
> executor attributes of self. To use different attributes, pass keyword
> arguments to the decorator
>
>
>
You have to provide a init threadp... | Motor is a non-blocking library, designed to be used from the single `IOLoop` thread. You would use a `ThreadPoolExecutor` with a blocking library like PyMongo, but you must not use other threads with Motor.
Instead, you should call the Motor methods with `yield` directly:
```
@gen.coroutine
def get(self):
yield ... |
34,522,741 | A request comes to tornado's GET handler of a web app.
From the `GET` function, a `blocking_task` function is called. This `blocking_task` function has `@run_on_executor` decorator.
But this execution fails.
Could you please help on this. It seems that motor db is not able to execute the thread.
```
import time
from ... | 2015/12/30 | [
"https://Stackoverflow.com/questions/34522741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5722595/"
] | Finally following code works, Thank you @kwarunek
Also added parameters to the callback function.
```
import time
from concurrent.futures import ThreadPoolExecutor
from tornado import gen, web
from tornado.concurrent import run_on_executor
from tornado.ioloop import IOLoop
import argparse
from common.config import A... | Motor is a non-blocking library, designed to be used from the single `IOLoop` thread. You would use a `ThreadPoolExecutor` with a blocking library like PyMongo, but you must not use other threads with Motor.
Instead, you should call the Motor methods with `yield` directly:
```
@gen.coroutine
def get(self):
yield ... |
61,257,025 | I'm new to python and tkinter and I try to create a tool witch loops every 5 seconds over a directory to list all the files.
In my code the filenames in the list appears only after I interupt the loop.
My goal is to start a loop by clicking on a button to start the endless loop to list the files and a stop button to ... | 2020/04/16 | [
"https://Stackoverflow.com/questions/61257025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10474530/"
] | Unary means one, so what they are talking about is a constructor with a single parameter. The standard name for such a thing is a [conversion constructor](https://stackoverflow.com/questions/15077466/what-is-a-converting-constructor-in-c-what-is-it-for). | Unary refers to one or singular, so a 'Unary constructor' ideally refers to a constructor with a single parameter. |
45,628,813 | Previously I was working without unittests and I had this structure for my project:
```
-main.py
-folderFunctions:
-functionA.py
```
Just using init file in folderFunctions, and importing
```
from folderFunctions import functionA
```
everything was working good.
Now I have also unittests wihch I orga... | 2017/08/11 | [
"https://Stackoverflow.com/questions/45628813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5178905/"
] | If you want your library/application to become bigger and easy to package I hardly recommend to separate source code from test code, because test code shouldn't be packaged in binary distributions (egg or wheel).
You can follow this tree structure:
```
+-- src/
| +-- main.py
| \-- folder_functions/ # <- Python... | The more elegant way is `from folderFunctions.folderTest import testFunctionA` and make sure that you have an `__init__.py` file in the `folderTest` directory. You may also look at this [question](https://stackoverflow.com/questions/8953844/import-module-from-subfolder) |
49,054,768 | I'm going to optimize three variable `x`, `alpha` and `R`.
`X` is a one dimensional vector, `alpha` is a two dimensional vector and `R` is a scalar value. How can I maximize this function?
I write below code:
```
#from scipy.optimize import least_squares
from scipy.optimize import minimize
import numpy as np
sentences... | 2018/03/01 | [
"https://Stackoverflow.com/questions/49054768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2742177/"
] | I find the solution.
```
from scipy.optimize import least_squares
from scipy.optimize import minimize
import numpy as np
def func(x_f, *args, sign=1.0):
""" Objective function """
sentences_lengths, length_constraint, sentences_idx, sentences_scores, damping, pairwise_idx, overlap_matrix\
... | I can do this task.
```
from scipy.optimize import least_squares
from scipy.optimize import minimize
import numpy as np
def func(x_f, *args, sign=1.0):
""" Objective function """
sentences_lengths, length_constraint, sentences_idx, sentences_scores, damping, pairwise_idx, overlap_matrix\
... |
34,586,114 | In Django, the convention is to put all of your static files (i.e css, js) specific to your app into a folder called **static**. So the structure would look like this:
```
mysite/
manage.py
mysite/ --> (settings.py, etc)
myapp/ --> (models.py, views.py, etc)
static/
```
In `mysite/settings.py` I ... | 2016/01/04 | [
"https://Stackoverflow.com/questions/34586114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Collect static files from multiple apps into a single path
----------------------------------------------------------
Well, a single Django *project* may use several *apps*, so while there you only have one `myapp`, it may actually be `myapp1`, `myapp2`, etc
By copying them from inside the individual apps into a sing... | It's useful when there are multiple django apps within the site.
`collectstatic` will then collect static files from all the apps in one place - so that it could be served up in a production environment. |
34,586,114 | In Django, the convention is to put all of your static files (i.e css, js) specific to your app into a folder called **static**. So the structure would look like this:
```
mysite/
manage.py
mysite/ --> (settings.py, etc)
myapp/ --> (models.py, views.py, etc)
static/
```
In `mysite/settings.py` I ... | 2016/01/04 | [
"https://Stackoverflow.com/questions/34586114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Collect static files from multiple apps into a single path
----------------------------------------------------------
Well, a single Django *project* may use several *apps*, so while there you only have one `myapp`, it may actually be `myapp1`, `myapp2`, etc
By copying them from inside the individual apps into a sing... | In the production installation, you want to have persistent URLs. The URL doesn't change unless the file content changes.
This is to prevent having clients to have wrong version of CSS or JS file on their computer when opening a web page from Django. Django staticfiles detects file changes and updates URLs accordingl... |
34,586,114 | In Django, the convention is to put all of your static files (i.e css, js) specific to your app into a folder called **static**. So the structure would look like this:
```
mysite/
manage.py
mysite/ --> (settings.py, etc)
myapp/ --> (models.py, views.py, etc)
static/
```
In `mysite/settings.py` I ... | 2016/01/04 | [
"https://Stackoverflow.com/questions/34586114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Collect static files from multiple apps into a single path
----------------------------------------------------------
Well, a single Django *project* may use several *apps*, so while there you only have one `myapp`, it may actually be `myapp1`, `myapp2`, etc
By copying them from inside the individual apps into a sing... | Django static files can be in many places. A file that is served as `/static/img/icon.png` could [come from many places](https://docs.djangoproject.com/en/3.2/ref/settings/#staticfiles-finders). By default:
* `FileSystemFinder` will look for `img/icon.png` in each of `STATICFILES_DIRS`,
* `AppDirectoriesFinder` will l... |
34,586,114 | In Django, the convention is to put all of your static files (i.e css, js) specific to your app into a folder called **static**. So the structure would look like this:
```
mysite/
manage.py
mysite/ --> (settings.py, etc)
myapp/ --> (models.py, views.py, etc)
static/
```
In `mysite/settings.py` I ... | 2016/01/04 | [
"https://Stackoverflow.com/questions/34586114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | In the production installation, you want to have persistent URLs. The URL doesn't change unless the file content changes.
This is to prevent having clients to have wrong version of CSS or JS file on their computer when opening a web page from Django. Django staticfiles detects file changes and updates URLs accordingl... | It's useful when there are multiple django apps within the site.
`collectstatic` will then collect static files from all the apps in one place - so that it could be served up in a production environment. |
34,586,114 | In Django, the convention is to put all of your static files (i.e css, js) specific to your app into a folder called **static**. So the structure would look like this:
```
mysite/
manage.py
mysite/ --> (settings.py, etc)
myapp/ --> (models.py, views.py, etc)
static/
```
In `mysite/settings.py` I ... | 2016/01/04 | [
"https://Stackoverflow.com/questions/34586114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Django static files can be in many places. A file that is served as `/static/img/icon.png` could [come from many places](https://docs.djangoproject.com/en/3.2/ref/settings/#staticfiles-finders). By default:
* `FileSystemFinder` will look for `img/icon.png` in each of `STATICFILES_DIRS`,
* `AppDirectoriesFinder` will l... | It's useful when there are multiple django apps within the site.
`collectstatic` will then collect static files from all the apps in one place - so that it could be served up in a production environment. |
34,586,114 | In Django, the convention is to put all of your static files (i.e css, js) specific to your app into a folder called **static**. So the structure would look like this:
```
mysite/
manage.py
mysite/ --> (settings.py, etc)
myapp/ --> (models.py, views.py, etc)
static/
```
In `mysite/settings.py` I ... | 2016/01/04 | [
"https://Stackoverflow.com/questions/34586114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Django static files can be in many places. A file that is served as `/static/img/icon.png` could [come from many places](https://docs.djangoproject.com/en/3.2/ref/settings/#staticfiles-finders). By default:
* `FileSystemFinder` will look for `img/icon.png` in each of `STATICFILES_DIRS`,
* `AppDirectoriesFinder` will l... | In the production installation, you want to have persistent URLs. The URL doesn't change unless the file content changes.
This is to prevent having clients to have wrong version of CSS or JS file on their computer when opening a web page from Django. Django staticfiles detects file changes and updates URLs accordingl... |
60,418,192 | Julia newbe here, transitioning from python.
So, I want to build what in Python I would call list, made of lists made of lists. In my case, it's a 1000 long list whose element is a list of 3 lists.
Until now, I have done it this way:
```
BIG_LIST = collect(Array{Int64,1}[[],[],[]] for i in 1:1000)
```
This served... | 2020/02/26 | [
"https://Stackoverflow.com/questions/60418192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10139617/"
] | First, if you know that intermediate lists always have 3 elements, you'll probably be better off using [`Tuple` types](https://docs.julialang.org/en/v1/manual/types/#Tuple-Types-1) for those. And tuples can specify independently the types of their elements. So something like this might suit your purposes:
```
julia> l... | Francois has given you a great answer. I just wanted to raise one other possibility. It sounds like your data has a fairly complicated, but specific, structure. For example, the fact that your outer list has 1000 elements, and your inner list always has 3 lists...
Sometimes in these situations it can be more intuitiv... |
44,651,760 | When I run `python manage.py migrate` on my Django project, I get the following error:
```
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/home/hari/project/env/local/lib/python2.7/site- packages/django/core/management/__init__.py", line 363, in ... | 2017/06/20 | [
"https://Stackoverflow.com/questions/44651760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3186922/"
] | Since you are using a custom User model, you can do 4 steps:
1. Comment out django.contrib.admin in your INSTALLED\_APPS settings
>
>
> ```
> INSTALLED_APPS = [
> ...
> #'django.contrib.admin',
> ...
> ]
>
> ```
>
>
2. Comment out admin path in urls.py
>
>
> ```
> urlpatterns = [
> ...
> #path... | If you set **AUTH\_USER\_MODE**L in **settings.py** like this:
```
AUTH_USER_MODEL = 'custom_user_app_name.User'
```
you should comment this line before run **makemigration** and **migrate** commands. Then you can uncomment this line again. |
44,651,760 | When I run `python manage.py migrate` on my Django project, I get the following error:
```
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/home/hari/project/env/local/lib/python2.7/site- packages/django/core/management/__init__.py", line 363, in ... | 2017/06/20 | [
"https://Stackoverflow.com/questions/44651760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3186922/"
] | Your django\_migrations table in your database is the cause of inconsistency and deleting all the migrations just from local path won't work.
You have to truncate the django\_migrations table from your database and then try applying the migrations again. It should work but if it does not then run makemigrations again ... | This Problem will come most of the time if you extend the User Model post initial migration. Because whenever you extend the Abstract user it will create basic fields which were present un the model like email, first\_name, etc.
Even this is applicable to any abstract model in django.
So a very simple solution for th... |
44,651,760 | When I run `python manage.py migrate` on my Django project, I get the following error:
```
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/home/hari/project/env/local/lib/python2.7/site- packages/django/core/management/__init__.py", line 363, in ... | 2017/06/20 | [
"https://Stackoverflow.com/questions/44651760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3186922/"
] | Lets start off by addressing the issue with most of the answers on this page:
**You never *have* to drop your database if you are using Django's migration system correctly and you *should* never delete migrations once they are comitted**
Now the best solution for you depends on a number of factors which include how e... | first of all backup your data. (copy your db file).
**delete sqlite.db and also the migration folder**.
then, run these commands:
```
./manage.py makemigrations APP_NAME
./manage.py migrate APP_NAME
```
after deleting the DB file and migration folder make sure that write the application name after the migration co... |
44,651,760 | When I run `python manage.py migrate` on my Django project, I get the following error:
```
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/home/hari/project/env/local/lib/python2.7/site- packages/django/core/management/__init__.py", line 363, in ... | 2017/06/20 | [
"https://Stackoverflow.com/questions/44651760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3186922/"
] | Here how to solve this properly.
Follow these steps in your migrations folder inside the project:
1. Delete the \_pycache\_ and the 0001\_initial files.
2. Delete the db.sqlite3 from the root directory (be careful all your data will go away).
3. on the terminal run:
python manage.py makemigrations
python manag... | when you create a new project and with no apps, you run the
```
python manage.py migrate
```
the Django will create 10 tables by default.
If you want create a customer user model which inherit from `AbstractUser` after that, you will encounter this problem as follow message:
>
> django.db.migrations.exceptions.I... |
44,651,760 | When I run `python manage.py migrate` on my Django project, I get the following error:
```
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/home/hari/project/env/local/lib/python2.7/site- packages/django/core/management/__init__.py", line 363, in ... | 2017/06/20 | [
"https://Stackoverflow.com/questions/44651760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3186922/"
] | When you are doing some changes to default user model or you are making a custom user model by abstractuser then lot of times you will face that error
1: Remember when we create a superuser then for logging in we need username and password but if you converted USERNAME\_FIELD = 'email' then now you can't login with us... | Since you are using a custom User model, you can first comment out
```
INSTALLED_APPS = [
...
#'django.contrib.admin',
...
]
```
in your Installed\_Apps settings. And also comment
```
urlpatterns = [
# path('admin/', admin.site.urls)
....
....
]
```
in your base urls.py
Then run
```
python manage.py mi... |
44,651,760 | When I run `python manage.py migrate` on my Django project, I get the following error:
```
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/home/hari/project/env/local/lib/python2.7/site- packages/django/core/management/__init__.py", line 363, in ... | 2017/06/20 | [
"https://Stackoverflow.com/questions/44651760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3186922/"
] | Just **delete all** the `migrations` folders, `__pycache__`, `.pyc` files:
```
find . | grep -E "(__pycache__|\.pyc|\.pyo$|migrations)" | xargs rm -rf
```
then, run:
```
python manage.py makemigrations
python manage.py migrate
``` | first of all backup your data. (copy your db file).
**delete sqlite.db and also the migration folder**.
then, run these commands:
```
./manage.py makemigrations APP_NAME
./manage.py migrate APP_NAME
```
after deleting the DB file and migration folder make sure that write the application name after the migration co... |
44,651,760 | When I run `python manage.py migrate` on my Django project, I get the following error:
```
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/home/hari/project/env/local/lib/python2.7/site- packages/django/core/management/__init__.py", line 363, in ... | 2017/06/20 | [
"https://Stackoverflow.com/questions/44651760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3186922/"
] | Lets start off by addressing the issue with most of the answers on this page:
**You never *have* to drop your database if you are using Django's migration system correctly and you *should* never delete migrations once they are comitted**
Now the best solution for you depends on a number of factors which include how e... | In my case the problem was with pytest starting, where I just altered `--reuse-db` to `--create-db`, run pytest, and changed it back. This fixed my problem |
44,651,760 | When I run `python manage.py migrate` on my Django project, I get the following error:
```
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/home/hari/project/env/local/lib/python2.7/site- packages/django/core/management/__init__.py", line 363, in ... | 2017/06/20 | [
"https://Stackoverflow.com/questions/44651760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3186922/"
] | You can delete directly db.sqlite3, then migrate a new database is automatically generated. It should fix it.
```
rm sqlite3.db
python manage.py makemigrations
python manage.py migrate
``` | **django.db.migrations.exceptions.InconsistentMigrationHistory #On Creating Custom User Model**
I had that same issue today, and none of the above solutions worked, then I thought to erase all the data from my local PostgreSQL database using this following command
```
-- Drop everything from the PostgreSQL database.
... |
44,651,760 | When I run `python manage.py migrate` on my Django project, I get the following error:
```
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/home/hari/project/env/local/lib/python2.7/site- packages/django/core/management/__init__.py", line 363, in ... | 2017/06/20 | [
"https://Stackoverflow.com/questions/44651760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3186922/"
] | Your Error is essentially:
```
Migration "B" is applied before its dependency "A" on database 'default'.
```
**Sanity Check**: First, open your database and look at the records in the 'django\_migrations' table. Records should be listed in Chronological order (ex: A,B,C,D...).
Make sure that the name of the "A" Mi... | First delete all the migrations and db.sqlite3 files and follow these steps:
```
$ ./manage.py makemigrations myapp
$ ./manage.py squashmigrations myapp 0001(may be differ)
```
Delete the old migration file and finally.
```
$ ./manage.py migrate
``` |
44,651,760 | When I run `python manage.py migrate` on my Django project, I get the following error:
```
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/home/hari/project/env/local/lib/python2.7/site- packages/django/core/management/__init__.py", line 363, in ... | 2017/06/20 | [
"https://Stackoverflow.com/questions/44651760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3186922/"
] | You can delete directly db.sqlite3, then migrate a new database is automatically generated. It should fix it.
```
rm sqlite3.db
python manage.py makemigrations
python manage.py migrate
``` | I encountered this when migrating from Wagtail 2.0 to 2.4, but have seen it a few other times when a third party app squashes a migration *after* your current version but before the version you’re migrating to.
The shockingly simple solution in this case at least is:
```
./manage.py migrate
./manage.py makemigrations... |
54,235,347 | I am implementing a GUI in Python/Flask.
The way flask is designed, the local host along with the port number has to be "manually" opened.
Is there a way to automate it so that upon running the code, browser(local host) is automatically opened?
I tried using webbrowser package but it opens the webpage after the sess... | 2019/01/17 | [
"https://Stackoverflow.com/questions/54235347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9557881/"
] | Use timer to start new thread to open web browser.
```
import webbrowser
from threading import Timer
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
def open_browser():
webbrowser.open_new("http://127.0.0.1:5000")
if __name__ == "__main__":
Timer(1, ... | **I'd suggest the following improvement to allow for loading of the browser when in debug mode:**
*Inspired by [this answer](https://stackoverflow.com/a/9476701/10521959), will only load the browser on the first run...*
```
def main():
# The reloader has not yet run - open the browser
if not os.environ.get... |
42,506,954 | I'm calling `curl` from a Perl script to POST a file:
```perl
my $cookie = 'Cookie: _appwebSessionId_=' . $sessionid;
my $reply = `curl -s
-H "Content-type:application/x-www-form-urlencoded"
-H "$cookie"
--data \@portports.txt
http://$ipaddr/... | 2017/02/28 | [
"https://Stackoverflow.com/questions/42506954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4153606/"
] | The `files` parameter encodes your file as a multipart message, which is not what you want. Use the `data` parameter instead:
```
import requests
url = 'http://www.example.com/'
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
cookies = {'_appwebSessionId_': '1234'}
with open('foo', 'rb') as file:
... | First UTF-8 decode your URL.
Put headers and files in a JSON object, lesse all\_data.
Now your code should look like this.
```python
all_data = {
{
'file': ('portports.txt', open('portports.txt', 'rb'))
},
{
'Content-type' : 'application/x-www-form-urlencoded',
'Cookie' : '_appweb... |
57,812,562 | I want to see the full trace of the code till a particular point
so i do
```
...
import traceback
traceback.print_stack()
...
```
Then it will show
```
File ".venv/lib/python3.7/site-packages/django/db/models/query.py", line 144, in __iter__
return compiler.results_iter(tuple_expected=True, chunked_fetch=sel... | 2019/09/05 | [
"https://Stackoverflow.com/questions/57812562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2897115/"
] | Pygments lists the available [lexers](http://pygments.org/docs/lexers/). You can do this with Python3TracebackLexer.
```
from pygments import highlight
from pygments.lexers import Python3TracebackLexer
from pygments.formatters import TerminalTrueColorFormatter
err_str = '''
File ".venv/lib/python3.7/site-packages/d... | Alternatively, use the [rich](https://github.com/willmcgugan/rich) library.
[With just two lines of code](https://rich.readthedocs.io/en/latest/traceback.html), it will prettify your tracebacks... and then some!
```py
from rich.traceback import install
install()
```
How does it look afterwards? Take a gander:
[![F... |
40,081,601 | I have a instance of django deployed in Heroku as follow, Procfile:
```
web: python manage.py collectstatic --noinput ; gunicorn MY_APP.wsgi --log-file -
worker: celery -A MY_APP worker
beat: celery -A MY_APP beat
```
This instance can receive 2000-4000 requests per minute, and sometimes it is too much.
I know I s... | 2016/10/17 | [
"https://Stackoverflow.com/questions/40081601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1073310/"
] | The first thing that springs to mind is to check out connection pooling and/or persistent database connections. Depending on how much database access your app is using, this could significantly increase the number of RPM your app is able to handle.
Check out [this StackOverflow question](https://stackoverflow.com/ques... | The whole point of Heroku is that you can dynamically scale your app. You can spin up new web workers with `heroku ps:scale web+1` for example. |
6,261,459 | Here is a test case I've created for a problem I found out.
For some reason the dict() 'l' in B() does not seem to hold the correct value. See the output below on my Linux 11.04 Ubuntu, python 2.7.1+.
```
class A():
name = None
b = None
def __init__(self, name, bname, cname, dname):
self.name = na... | 2011/06/07 | [
"https://Stackoverflow.com/questions/6261459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | What happened is that you created a class attribute. Create an instance attribute instead by instantiating in `__init__()`. | It looks like you are trying to "declare" instance attributes at the class level. Class attributes have their own specific uses in Python, and it is wrong to put them there if you are not intending to ever use the class attributes
```
class A():
name = None # Don't do this
b = None # Don't do this
def... |
30,969,533 | I have a task to draw a potential graph with 3 variables, x , y, and z. I don't think we can draw the function U(x, y, z) directly with matplotlib. So what I'm planning to do is to draw cross sectional plots of x-y and y-z. I believe this is enough because the function U(x, y, z) has periodic behavior.
I'm quite new t... | 2015/06/21 | [
"https://Stackoverflow.com/questions/30969533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4358807/"
] | String literals in SQL are denoted by single quotes (`'`). Without them, and string would be treated as an object name. Here, you generate a where clause `title = Test`. Both are interpreted as columns names, and the query fails since there's no column `Test`.
To solve this, you could surround `Test` by quotes:
```
... | Change your WHERE clause to be...
```
...
title = 'test'
```
The way it is written it is looking for a column named Test. |
7,360,654 | I am trying to *generate* self signed SSL certificates using Python, so that it is platform independent. My target is the \*.pem format.
I found [this script](http://sunh11373.blogspot.com/2007/04/python-utility-for-converting.html) that generates certificates, but no information how to self-sign them. | 2011/09/09 | [
"https://Stackoverflow.com/questions/7360654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/722291/"
] | The script you've linked doesn't create self-signed certificate; it only creates a request.
To create self-signed certificate you could use [`openssl`](https://www.openssl.org/docs/faq.html#USER4) it is available on all major OSes.
```
$ openssl req -new -x509 -key privkey.pem -out cacert.pem -days 1095
```
If you... | You could use the openssl method that J.F. Sebastian stated from within Python.
Import the OS lib and call the command like this:
```
os.system("openssl req -new -x509 -key privkey.pem -out cacert.pem -days 1095")
```
If it requires user interaction, it might work if you run it via subprocess pipe and allow for raw... |
47,441,401 | I have an 8\*4 numpy array with floats (myarray) and would like to transform it into a dictionary of dataframes (and eventually concatenate it into one dataframe) with pandas in python. I'm coming across the error "ValueError: DataFrame constructor not properly called!" though. Here is the way I attempt it:
```
my... | 2017/11/22 | [
"https://Stackoverflow.com/questions/47441401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8938572/"
] | You are trying to cast a list of 2 numbers to int. [int only takes a number or a string as its argument](https://docs.python.org/3/library/functions.html#int).
What you want is to [map](http://book.pythontips.com/en/latest/map_filter.html#map) the int function to each item in the list.
```
>>> w, h = map(int, input()... | `int(...)` constructs an integer which cannot be unpacked to a tuple `W, H`. What you probably want is
```
W, H = (int(x) for x in input().split(" "))
``` |
40,853,556 | I have a list of tuples in python containing 3-dimenstional data, where each tuple is in the form: (x, y, z, data\_value), i.e., I have data values at each (x, y, z) coordinate. I would like to make a 3D discrete heatmap plot where the colors represent the value of data\_values in my list of tuples. Here, I give an exa... | 2016/11/28 | [
"https://Stackoverflow.com/questions/40853556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3076813/"
] | ### New answer:
It seems we really want to have a 3D Tetris game here ;-)
So here is a way to plot cubes of different color to fill the space given by the arrays `(x,y,z)`.
```
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm
import matplotlib.colorbar
... | I've update the code above to be compatible with newer version of matplot lib.
```py
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colorbar
from matplotlib import cm
viridis = cm.get_cmap('plasma', 8) #Our color map
def cuboid_data(center, size=(1,1,1)):
# code taken from
# http://stac... |
13,855,056 | I have a list of numbers, let's say `[1091, 2053, 4099, 4909, 5023, 9011]`. Here every number has it's permutation in a list too. Now i want to group these permutations of each other, so the list becomes `[[1091, 9011], [2053, 5023], [4099, 4909]]`. I know how to use [`groupby`](http://docs.python.org/2/library/itertoo... | 2012/12/13 | [
"https://Stackoverflow.com/questions/13855056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/596361/"
] | ```
import itertools as it
a = [1091, 2053, 4099, 4909, 5023, 9011]
sort_string = lambda x: sorted(str(x))
[[int(x) for x in v] for k,v in it.groupby(sorted(a, key=sort_string), key=sort_string)]
# [[1091, 9011], [2053, 5023], [4099, 4909]]
``` | You can use `collections.Counter` to represent each number as a tuple of `integer, total_occurrences` and then store all the data in instances in a dictionary:
```
from collections import Counter, defaultdict
dest = defaultdict(list)
data = [1091, 2053, 4099, 4909, 5023, 9011]
data = ((Counter([int(x) for x in str(d... |
13,855,056 | I have a list of numbers, let's say `[1091, 2053, 4099, 4909, 5023, 9011]`. Here every number has it's permutation in a list too. Now i want to group these permutations of each other, so the list becomes `[[1091, 9011], [2053, 5023], [4099, 4909]]`. I know how to use [`groupby`](http://docs.python.org/2/library/itertoo... | 2012/12/13 | [
"https://Stackoverflow.com/questions/13855056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/596361/"
] | ```
import itertools as it
a = [1091, 2053, 4099, 4909, 5023, 9011]
sort_string = lambda x: sorted(str(x))
[[int(x) for x in v] for k,v in it.groupby(sorted(a, key=sort_string), key=sort_string)]
# [[1091, 9011], [2053, 5023], [4099, 4909]]
``` | Represent each number with a normalization which fits your purpose. For your example, a suitable canonical form could be `"".join(sort("".split(str(n))))`; that is, map each number to a string made from a sorted list of the individual digits. |
14,087,547 | **Conclusion:** It's impossible to override or disable Python's built-in escape sequence processing, such that, you can skip using the raw prefix specifier. I dug into Python's internals to figure this out. So if anyone tries designing objects that work on complex strings (like regex) as part of some kind of framework,... | 2012/12/30 | [
"https://Stackoverflow.com/questions/14087547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/482691/"
] | I think you have an understandable confusion about a difference between Python string literals (source code representation), Python string objects in memory, and how that objects can be printed (in what format they can be represented in the output).
If you read some bytes from a file into a bytestring you can write th... | I think you will have to go the join route.
Here's an example:
```
>>> m = {chr(c): '\\x{0}'.format(hex(c)[2:].zfill(2)) for c in xrange(0,256)}
>>>
>>> x = "\x20\x01\x0d\xb8\x85\xa3\x00\x00\x00\x00\x8a\x2e\x03\x70\x73\x34"
>>> print ''.join(map(m.get, x))
\x20\x01\x0d\xb8\x85\xa3\x00\x00\x00\x00\x8a\x2e\x03\x70\x73... |
45,625,042 | I have a master python script, that goes and automates configuring nodes in parallel in a distributed system setup in our lab.
I run multiple instances of kickstart.py and it goes and configures all nodes in parallel. How do I create log handler such that each instance of kickstart.py configures each node separately i... | 2017/08/10 | [
"https://Stackoverflow.com/questions/45625042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8448115/"
] | A solution using `st_distance` from the `sf` package. `my_df_final` is the final output.
```
# Load packages
library(tidyverse)
library(sp)
library(sf)
# Create ID for my_df_1 and my_df_2 based on row id
# This step is not required, just help me to better distinguish each point
my_df_1 <- my_df_1 %>% mutate(ID1 = row... | Based on this [answer](https://stackoverflow.com/questions/31668163/geographic-distance-between-2-lists-of-lat-lon-coordinates) you could do
```
library(geosphere)
mat <- distm(my_df_1[2:1], my_df_2[2:1], fun = distVincentyEllipsoid)
cbind(my_df_1, my_df_2[max.col(-mat),])
```
Which gives:
```
# START_LAT STAR... |
58,351,041 | I am trying to install a virtualenv in windows 10 using a step process I found on some website. The steps are as follows, but only care about 1-4 for now:
1. Run Windows Power Shell as Administrator
2. pip install virtualenv
3. pip install virtualenvwrapper-win
4. mkvirtualenv ‘C:\Users\username\Documents\Virtualenv’
... | 2019/10/12 | [
"https://Stackoverflow.com/questions/58351041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12204393/"
] | The compiler changes the name of the local function, preventing you from calling it using its original name from the debugger. See [this question](https://stackoverflow.com/questions/45337983/why-local-functions-generate-il-different-from-anonymous-methods-and-lambda-expr) for examples. What you can do is temporarily m... | I'll have to say that I haven't tried it and will not bother to do so because there's a lot more to local functions than you think and I would put it very low in terms of priority for the debugger.
Try putting your code in [sharplab.io](https://sharplab.io/) and see what it takes to make that local function. |
53,539,612 | I have a big `tab separated` file like this:
```
chr1 9507728 9517729 0 chr1 9507728 9517729 5S_rRNA
chr1 9537731 9544392 0 chr1 9537731 9547732 5S_rRNA
chr1 9497727 9507728 0 chr1 9497727 9507728 5S_rRNA
chr1 9517729 9527730 0 chr1 9517729 9527730 5S_rRNA
chr8 1118560 1118591 1 ch... | 2018/11/29 | [
"https://Stackoverflow.com/questions/53539612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10657934/"
] | If there is no common data between different clients/orgs, there is no point of having a shared channel between them. Taking care of permissions overs data will complicate your network setup. It would be better to abstract out that detail from network design.
You should have one org corresponding to each client. In ea... | I think you could encrypt every client's data by passing the transient key to chaincode,and just manage the keys, this may be light weight and fesible for your scenery. |
22,650,001 | I have a Django application running on [Dotcloud](http://dotcloud.com/ "Dotcloud"). I have tried to add [Logentries](http://logentries.com/ "Logentries") logging which works in normal usage for my site, but causes my cron jobs to fail with this error -
`Traceback (most recent call last):
File "/home/dotcloud/curren... | 2014/03/26 | [
"https://Stackoverflow.com/questions/22650001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3458323/"
] | This is what you want:
```
List<Card> cards = IntStream.rangeClosed(1, 4)
.boxed()
.flatMap(value ->
IntStream.rangeClosed(1, 13)
.mapToObj(suit -> new Card(value, suit))
)
.collect(Collectors.toList());
```
Points to note:
* you have to box the ints because `flatMap` on primit... | Another way to get what you want (based on Maurice Naftalin's answer):
```
List<Card> cards = IntStream.rangeClosed(1, 4)
.mapToObj(value -> IntStream.rangeClosed(1, 13)
.mapToObj(suit -> new Card(value, suit))
)
.flatMap(Function.identity())
.collect(Collectors.toList())
;
```
Additional points to note:... |
51,634,841 | I have a little project in python to do. I have to parse 4 arguments in my program.
so the commands are:
-i (store the source\_file)
-d (store the destination\_file)
-a (store the a folder named: i386, x64\_86 or all )
-p (store the folder named: Linux, Windows or all)
The folder Linux has 2 folders in: i386 and x64\... | 2018/08/01 | [
"https://Stackoverflow.com/questions/51634841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10123257/"
] | After peeking into [the PHP source code](https://github.com/php/php-src/blob/master/ext/gd/gd.c#L2287), to have some insights about the "[imagecreatefromstring](http://php.net/manual/en/function.imagecreatefromstring.php)" function, I've discovered that it handles only the following image formats:
* JPEG
* PNG
* GIF... | Save your pptx again in PPT 2007 format in open office or MS Powerpoint.Its format issue.You are opening a very recent PPT format with 2007 |
56,581,577 | Python says that TrackerMedianFlow\_create() is no longer an attribute of cv2.
I've looked here but it's not the same: [OpenCV, How to pass parameters into cv2.TrackerMedianFlow\_create function?](https://stackoverflow.com/questions/47723349/opencv-how-to-pass-parameters-into-cv2-trackermedianflow-create-function)
I'v... | 2019/06/13 | [
"https://Stackoverflow.com/questions/56581577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7174600/"
] | for opencv 4.5.1 user
opencv-contrib-python
```
import cv2
cv2.legacy_TrackerMedianFlow()
``` | `TrackerMedianFlow` is a [module within the opencv-contrib package](https://github.com/opencv/opencv_contrib/tree/master/modules/tracking/src), and does not come standard with the official OpenCV distribution. You will need to install the opencv-contrib package to access `TrackerMedianFlow_create()`
Per the [document... |
56,581,577 | Python says that TrackerMedianFlow\_create() is no longer an attribute of cv2.
I've looked here but it's not the same: [OpenCV, How to pass parameters into cv2.TrackerMedianFlow\_create function?](https://stackoverflow.com/questions/47723349/opencv-how-to-pass-parameters-into-cv2-trackermedianflow-create-function)
I'v... | 2019/06/13 | [
"https://Stackoverflow.com/questions/56581577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7174600/"
] | `TrackerMedianFlow` is a [module within the opencv-contrib package](https://github.com/opencv/opencv_contrib/tree/master/modules/tracking/src), and does not come standard with the official OpenCV distribution. You will need to install the opencv-contrib package to access `TrackerMedianFlow_create()`
Per the [document... | It has been installed opencv-contrib-python-4.5.4.60 version,Again AttributeError: module 'cv2' has no attribute 'TrackerMedianFlow\_create',what is the reason |
56,581,577 | Python says that TrackerMedianFlow\_create() is no longer an attribute of cv2.
I've looked here but it's not the same: [OpenCV, How to pass parameters into cv2.TrackerMedianFlow\_create function?](https://stackoverflow.com/questions/47723349/opencv-how-to-pass-parameters-into-cv2-trackermedianflow-create-function)
I'v... | 2019/06/13 | [
"https://Stackoverflow.com/questions/56581577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7174600/"
] | for opencv 4.5.1 user
opencv-contrib-python
```
import cv2
cv2.legacy_TrackerMedianFlow()
``` | It has been installed opencv-contrib-python-4.5.4.60 version,Again AttributeError: module 'cv2' has no attribute 'TrackerMedianFlow\_create',what is the reason |
55,643,507 | I am getting this valid error while preprocessing some data:
```
9:46:56.323 PM default_model Function execution took 6008 ms, finished with status: 'crash'
9:46:56.322 PM default_model Traceback (most recent call last):
File "/user_code/main.py", line 31, in default_model
train, endog, exog, _, _, rawDf = pre... | 2019/04/12 | [
"https://Stackoverflow.com/questions/55643507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/732570/"
] | Your `preprocess` function is declared `async`. This means the code in it isn't actually run where you call `preprocess`, but instead when it is eventually `await`ed or passed to a main loop (like `asyncio.run`). Because the place where it is run is no-longer in the try block in `default_model`, the exception is not ca... | Do the line numbers in the error match up with the line numbers in your code? If not is it possible that you are seeing the error from a version of the code before you added the try...except? |
54,836,440 | There is a chance this is still a problem and the Pyinstaller and/or Folium people have no interest in fixing it, but I'll post it again here in case someone out there has discovered a workaround.
I have a program that creates maps, geocodes etc and recently added the folium package to create some interactive maps in ... | 2019/02/22 | [
"https://Stackoverflow.com/questions/54836440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9431874/"
] | I had the same problem. Pyinstaller could not work with the Python Folium package. I could not get your cx\_Freeze solution to work due to issues with Python 3.7 and cx\_Freeze but with a day of stress I found a Pyinstaller solution which I am sharing with the community.
Firstly you have to edit these 3 files:
1. \... | I could not get this to work using pyinstaller. I had to instead use cx\_Freeze.
`pip install cx_Freeze`
cx\_Freeze requires that a setup.py file is created, typically in the same folder as the main script that is being converted to an exe. My setup.py file looks like this:
```
import sys
from cx_Freeze import setu... |
54,836,440 | There is a chance this is still a problem and the Pyinstaller and/or Folium people have no interest in fixing it, but I'll post it again here in case someone out there has discovered a workaround.
I have a program that creates maps, geocodes etc and recently added the folium package to create some interactive maps in ... | 2019/02/22 | [
"https://Stackoverflow.com/questions/54836440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9431874/"
] | With pyinstaller it works using the above trick. If we need to create a folder, then this script file can be used.
```
import platform
block_cipher = None
a = Analysis(['Test_Beta.py'],
pathex=['C:\\Old desktop\\test\\esky\\fileserver\\test11'],
binaries=[(winsparkle, '.')],
datas=[
("C:\\Users\\kv\\AppData\\... | I could not get this to work using pyinstaller. I had to instead use cx\_Freeze.
`pip install cx_Freeze`
cx\_Freeze requires that a setup.py file is created, typically in the same folder as the main script that is being converted to an exe. My setup.py file looks like this:
```
import sys
from cx_Freeze import setu... |
54,836,440 | There is a chance this is still a problem and the Pyinstaller and/or Folium people have no interest in fixing it, but I'll post it again here in case someone out there has discovered a workaround.
I have a program that creates maps, geocodes etc and recently added the folium package to create some interactive maps in ... | 2019/02/22 | [
"https://Stackoverflow.com/questions/54836440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9431874/"
] | I had the same problem. Pyinstaller could not work with the Python Folium package. I could not get your cx\_Freeze solution to work due to issues with Python 3.7 and cx\_Freeze but with a day of stress I found a Pyinstaller solution which I am sharing with the community.
Firstly you have to edit these 3 files:
1. \... | With pyinstaller it works using the above trick. If we need to create a folder, then this script file can be used.
```
import platform
block_cipher = None
a = Analysis(['Test_Beta.py'],
pathex=['C:\\Old desktop\\test\\esky\\fileserver\\test11'],
binaries=[(winsparkle, '.')],
datas=[
("C:\\Users\\kv\\AppData\\... |
20,364,207 | Hey I've been trying to add Python 3.3 to windows powershell by repacing 27 with 33 in the path.
I tried to post a screenshot but turns out I need 10 rep so I'll just copy and paste what I've attempted:
```
[Enviroment]::SetEnviromentVariable("Path", "$env:Path;C:\Python33", "User")
```
>
```
[Enviroment]::SetEnvi... | 2013/12/03 | [
"https://Stackoverflow.com/questions/20364207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3063721/"
] | Python 3.3 comes with PyLauncher (py.exe), which is installed in the C:\Windows directory (already on the path) and enables any installed Python to be executed via command line as follows:
```
Windows PowerShell
Copyright (C) 2009 Microsoft Corporation. All rights reserved.
PS C:\> py
Python 3.3.3 (v3.3.3:c3896275c0f... | The windows environment variable `path` is searched left to right. If the path to the 2.7 binaries is still in the variable, it will never find the 3.3 binaries, whose path you are appending to the end of the path variable.
Also, you are not adding the path to PowerShell. The windows python binaries are what PowerShel... |
48,272,511 | I have CLI tool I need open ([indy](https://github.com/hyperledger/indy-node/blob/stable/getting-started.md)), and then execute some commands.
So I want to write a bash script to do this for me. Using python as example it might look like:
```
#!/bin/bash
python
print ("hello world")
```
But ofcourse all this doe... | 2018/01/16 | [
"https://Stackoverflow.com/questions/48272511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1068446/"
] | You forgot to add minutes to `setMinutes`:
```
function getUserTimeZoneDateTime() {
var currentUtcDateTime = moment.utc().toDate();
var mod_start = new Date(currentUtcDateTime.setMinutes(currentUtcDateTime.getMinutes() + GlobalValues.OffsetMinutesFromUTC - currentUtcDateTime.getTimezoneOffset()));
var cur... | ```
var now = new Date().getTime();
```
This gets the time and stores it in the variable, here called `now`.
It should get the time wherever the user is.
Hope this helps! |
73,064,635 | I was trying to capture a video in kivy/android using camera4kivy. but it seems that this function won't work. I tried capture video with location, subdir and filename (kwarg\*\*) but still nothing happend.
```
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.image import Image
from came... | 2022/07/21 | [
"https://Stackoverflow.com/questions/73064635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19499522/"
] | You can use `Map` collection:
```
new Map(fooArr.map(i => [i.name, i.surname]));
```
As [mdn says about `Map` collection](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map):
>
> The Map object holds key-value pairs and remembers the original
> insertion order of the keys. Any val... | To add to the previous answer. This React guide explains the arrays and how to use or set your keys for them: <https://reactjs.org/docs/lists-and-keys.html#keys>
I would recommend making `<div>`s for each result or make a `<table>` with `<tr>` and `<td>` to store the individual items. Give each div or row a key and it ... |
73,064,635 | I was trying to capture a video in kivy/android using camera4kivy. but it seems that this function won't work. I tried capture video with location, subdir and filename (kwarg\*\*) but still nothing happend.
```
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.image import Image
from came... | 2022/07/21 | [
"https://Stackoverflow.com/questions/73064635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19499522/"
] | You can use `Map` collection:
```
new Map(fooArr.map(i => [i.name, i.surname]));
```
As [mdn says about `Map` collection](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map):
>
> The Map object holds key-value pairs and remembers the original
> insertion order of the keys. Any val... | You can use `Object.entries` which is similar to `python` `.items`:
```js
const data = {a: 1, b: 2}
console.log(Object.entries(data))
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.