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 |
|---|---|---|---|---|---|
183,033 | This is really two questions, but they are so similar, and to keep it simple, I figured I'd just roll them together:
* **Firstly**: Given an established C# project, what are some decent ways to speed it up beyond just plain in-code optimization?
* **Secondly**: When writing a program from scratch in C#, what are some ... | 2008/10/08 | [
"https://Stackoverflow.com/questions/183033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/145/"
] | A lot of slowness is related to database access. Make your database queries efficient and you'll do a lot for your app. | Don't use to much reflection. |
183,033 | This is really two questions, but they are so similar, and to keep it simple, I figured I'd just roll them together:
* **Firstly**: Given an established C# project, what are some decent ways to speed it up beyond just plain in-code optimization?
* **Secondly**: When writing a program from scratch in C#, what are some ... | 2008/10/08 | [
"https://Stackoverflow.com/questions/183033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/145/"
] | Profile your code. Then you can at least have an understanding of where you can improve. Without profiling you are shooting in the dark... | For Windows Forms on XP and Vista: Turn double buffering on across the board. It does cause transparency issues, so you would definitely want to test the UI:
```
protected override System.Windows.Forms.CreateParams CreateParams {
get {
CreateParams cp = base.CreateParams;
cp.ExStyle = cp.ExStyle... |
183,033 | This is really two questions, but they are so similar, and to keep it simple, I figured I'd just roll them together:
* **Firstly**: Given an established C# project, what are some decent ways to speed it up beyond just plain in-code optimization?
* **Secondly**: When writing a program from scratch in C#, what are some ... | 2008/10/08 | [
"https://Stackoverflow.com/questions/183033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/145/"
] | This is true for any language, not just C#
1. For an existing app, don't do *anything* until you know what's making it slow. IMHO, [this is the best way.](http://www.wikihow.com/Optimize-Your-Program%27s-Performance)
2. For new apps, the problem is how programmers are taught. They are taught to make mountains out of m... | For Windows Forms on XP and Vista: Turn double buffering on across the board. It does cause transparency issues, so you would definitely want to test the UI:
```
protected override System.Windows.Forms.CreateParams CreateParams {
get {
CreateParams cp = base.CreateParams;
cp.ExStyle = cp.ExStyle... |
183,033 | This is really two questions, but they are so similar, and to keep it simple, I figured I'd just roll them together:
* **Firstly**: Given an established C# project, what are some decent ways to speed it up beyond just plain in-code optimization?
* **Secondly**: When writing a program from scratch in C#, what are some ... | 2008/10/08 | [
"https://Stackoverflow.com/questions/183033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/145/"
] | Caching items that result from a query:
```
private Item _myResult;
public Item Result
{
get
{
if (_myResult == null)
{
_myResult = Database.DoQueryForResult();
}
return _myResult;
}
}
```
Its a basic technique that is frequently overlooked by sta... | For Windows Forms on XP and Vista: Turn double buffering on across the board. It does cause transparency issues, so you would definitely want to test the UI:
```
protected override System.Windows.Forms.CreateParams CreateParams {
get {
CreateParams cp = base.CreateParams;
cp.ExStyle = cp.ExStyle... |
11,070,920 | I try to understand the regex in python. How can i split the following sentence with regular expression?
```
"familyname, Givenname A.15.10"
```
this is like the phonebook in python regex <http://docs.python.org/library/re.html>. The person maybe have 2 or more familynames and 2 or more givennames. After the familyn... | 2012/06/17 | [
"https://Stackoverflow.com/questions/11070920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1364181/"
] | What you want to do is first split the family name by ,
`familyname, rest = text.split(',', 1)`
Then you want to split the office with the first space from the right.
`givenname, office = rest.rsplit(' ', 1)` | Assuming that family names don't have a comma, you can take them easily. Given names are sensible to dots. For example:
```
Harney, PJ A.15.10
Harvey, P.J. A.15.10
```
This means that you should probably trim the rest of the record (family names are out) by a mask at the end (regex "maskpattern$"). |
11,070,920 | I try to understand the regex in python. How can i split the following sentence with regular expression?
```
"familyname, Givenname A.15.10"
```
this is like the phonebook in python regex <http://docs.python.org/library/re.html>. The person maybe have 2 or more familynames and 2 or more givennames. After the familyn... | 2012/06/17 | [
"https://Stackoverflow.com/questions/11070920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1364181/"
] | In the regex world it's often easier to "match" rather than "split". When you're "matching" you tell the RE engine directly what kinds of substrings you're looking for, instead of concentrating on separating characters. The requirements in your question are a bit unclear, but let's assume that
* "surname" is everythin... | What you want to do is first split the family name by ,
`familyname, rest = text.split(',', 1)`
Then you want to split the office with the first space from the right.
`givenname, office = rest.rsplit(' ', 1)` |
11,070,920 | I try to understand the regex in python. How can i split the following sentence with regular expression?
```
"familyname, Givenname A.15.10"
```
this is like the phonebook in python regex <http://docs.python.org/library/re.html>. The person maybe have 2 or more familynames and 2 or more givennames. After the familyn... | 2012/06/17 | [
"https://Stackoverflow.com/questions/11070920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1364181/"
] | In the regex world it's often easier to "match" rather than "split". When you're "matching" you tell the RE engine directly what kinds of substrings you're looking for, instead of concentrating on separating characters. The requirements in your question are a bit unclear, but let's assume that
* "surname" is everythin... | Assuming that family names don't have a comma, you can take them easily. Given names are sensible to dots. For example:
```
Harney, PJ A.15.10
Harvey, P.J. A.15.10
```
This means that you should probably trim the rest of the record (family names are out) by a mask at the end (regex "maskpattern$"). |
6,947,210 | how would I add set elements to a string in python? I tried:
```
sett = set(['1', '0'])
elements = ''
for i in sett:
elements.join(i)
```
but no dice. when I print elements the string is empty. help | 2011/08/04 | [
"https://Stackoverflow.com/questions/6947210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/879311/"
] | This should work:
```
sett = set(['1', '0'])
elements = ''
for i in sett:
elements += i
# elements = '10'
```
However, if you're just looking to get a string representation of each element, you can simply do this:
```
elements = ''.join(sett)
# elements = '10'
``` | Don't know what you mean with "add set elements" to a string. But anyway: Strings are immutable in Python, so you cannot add anything to them. |
6,947,210 | how would I add set elements to a string in python? I tried:
```
sett = set(['1', '0'])
elements = ''
for i in sett:
elements.join(i)
```
but no dice. when I print elements the string is empty. help | 2011/08/04 | [
"https://Stackoverflow.com/questions/6947210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/879311/"
] | Strings are immutable.
======================
`elements.join(i)` does not change `elements`. You need to assign the value returned by `join` to something:
```
s = set(['1', '0'])
elements = ''
for i in s:
elements = elements.join(i)
```
But, as others pointed out, this is better still:
```
s = set(['1', '0'])
... | This should work:
```
sett = set(['1', '0'])
elements = ''
for i in sett:
elements += i
# elements = '10'
```
However, if you're just looking to get a string representation of each element, you can simply do this:
```
elements = ''.join(sett)
# elements = '10'
``` |
6,947,210 | how would I add set elements to a string in python? I tried:
```
sett = set(['1', '0'])
elements = ''
for i in sett:
elements.join(i)
```
but no dice. when I print elements the string is empty. help | 2011/08/04 | [
"https://Stackoverflow.com/questions/6947210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/879311/"
] | I believe you want this:
```
s = set(['1', '2'])
asString = ''.join(s)
```
Be aware that sets are not ordered like lists are. They'll be in the order added typically until something is removed, but the order could be different than the order you added them. | This should work:
```
sett = set(['1', '0'])
elements = ''
for i in sett:
elements += i
# elements = '10'
```
However, if you're just looking to get a string representation of each element, you can simply do this:
```
elements = ''.join(sett)
# elements = '10'
``` |
6,947,210 | how would I add set elements to a string in python? I tried:
```
sett = set(['1', '0'])
elements = ''
for i in sett:
elements.join(i)
```
but no dice. when I print elements the string is empty. help | 2011/08/04 | [
"https://Stackoverflow.com/questions/6947210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/879311/"
] | Strings are immutable.
======================
`elements.join(i)` does not change `elements`. You need to assign the value returned by `join` to something:
```
s = set(['1', '0'])
elements = ''
for i in s:
elements = elements.join(i)
```
But, as others pointed out, this is better still:
```
s = set(['1', '0'])
... | Don't know what you mean with "add set elements" to a string. But anyway: Strings are immutable in Python, so you cannot add anything to them. |
6,947,210 | how would I add set elements to a string in python? I tried:
```
sett = set(['1', '0'])
elements = ''
for i in sett:
elements.join(i)
```
but no dice. when I print elements the string is empty. help | 2011/08/04 | [
"https://Stackoverflow.com/questions/6947210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/879311/"
] | ```
>>> ''.join(set(['1','2']))
'12'
```
I guess this is what you want. | Don't know what you mean with "add set elements" to a string. But anyway: Strings are immutable in Python, so you cannot add anything to them. |
6,947,210 | how would I add set elements to a string in python? I tried:
```
sett = set(['1', '0'])
elements = ''
for i in sett:
elements.join(i)
```
but no dice. when I print elements the string is empty. help | 2011/08/04 | [
"https://Stackoverflow.com/questions/6947210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/879311/"
] | I believe you want this:
```
s = set(['1', '2'])
asString = ''.join(s)
```
Be aware that sets are not ordered like lists are. They'll be in the order added typically until something is removed, but the order could be different than the order you added them. | Don't know what you mean with "add set elements" to a string. But anyway: Strings are immutable in Python, so you cannot add anything to them. |
6,947,210 | how would I add set elements to a string in python? I tried:
```
sett = set(['1', '0'])
elements = ''
for i in sett:
elements.join(i)
```
but no dice. when I print elements the string is empty. help | 2011/08/04 | [
"https://Stackoverflow.com/questions/6947210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/879311/"
] | Strings are immutable.
======================
`elements.join(i)` does not change `elements`. You need to assign the value returned by `join` to something:
```
s = set(['1', '0'])
elements = ''
for i in s:
elements = elements.join(i)
```
But, as others pointed out, this is better still:
```
s = set(['1', '0'])
... | ```
>>> ''.join(set(['1','2']))
'12'
```
I guess this is what you want. |
6,947,210 | how would I add set elements to a string in python? I tried:
```
sett = set(['1', '0'])
elements = ''
for i in sett:
elements.join(i)
```
but no dice. when I print elements the string is empty. help | 2011/08/04 | [
"https://Stackoverflow.com/questions/6947210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/879311/"
] | I believe you want this:
```
s = set(['1', '2'])
asString = ''.join(s)
```
Be aware that sets are not ordered like lists are. They'll be in the order added typically until something is removed, but the order could be different than the order you added them. | Strings are immutable.
======================
`elements.join(i)` does not change `elements`. You need to assign the value returned by `join` to something:
```
s = set(['1', '0'])
elements = ''
for i in s:
elements = elements.join(i)
```
But, as others pointed out, this is better still:
```
s = set(['1', '0'])
... |
6,947,210 | how would I add set elements to a string in python? I tried:
```
sett = set(['1', '0'])
elements = ''
for i in sett:
elements.join(i)
```
but no dice. when I print elements the string is empty. help | 2011/08/04 | [
"https://Stackoverflow.com/questions/6947210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/879311/"
] | I believe you want this:
```
s = set(['1', '2'])
asString = ''.join(s)
```
Be aware that sets are not ordered like lists are. They'll be in the order added typically until something is removed, but the order could be different than the order you added them. | ```
>>> ''.join(set(['1','2']))
'12'
```
I guess this is what you want. |
70,148,408 | I am new to learning python but I can't seem to find out how to make the first part of the while loop run in the background while the second part is running. Putting in the input I set allows the first part to run twice but then pauses it.
Here is the code
```
import time
def money():
coins = 0
multiplyer =... | 2021/11/28 | [
"https://Stackoverflow.com/questions/70148408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16408072/"
] | I think you need to refactor your `onSubmit` function to make it `async` so `isSubmitting` will stay `true` during your `signIn` call.
```js
const onSubmit = async (data) => {
await signIn(data.email, data.password)
.then((response) => console.log(response))
.catch((error) => {
let message = nu... | `onSubmit` needs to return a `Promise` for `formState` to update correctly.
```
const onSubmit = (payload) => {
// You need to return a promise.
return new Promise((resolve) => {
setTimeout(() => resolve(), 1000);
});
};
```
References:
* <https://react-hook-form.com/api/useform/formstate/>
* <https://git... |
17,099,808 | I want to implement the following code in more of a pythonic way:
```
odd_rows = table.findAll('tr', attrs = {'class':'odd'}) #contain all tr tags
even_rows = table.findAll('tr', attrs = {'class':'even'})
for rows in odd_rows: #rows equal 1 <tr> tag
rows.findAll('td') #find all the <td> ... | 2013/06/14 | [
"https://Stackoverflow.com/questions/17099808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2407162/"
] | Perhaps:
```
for row in table.findAll('tr', attrs = {'class':'odd'}) + table.findAll('tr', attrs = {'class':'even'}):
for cell in row.findAll('td'):
print cell
```
From a performance standpoint, your original code is better. Combining two lists does use resources.
However, unless you are writing code fo... | ```
for cls in ("odd", "even"):
for rows in table.findAll('tr', class_=cls):
for row in rows.findAll('td'):
print row
``` |
40,785,453 | I have a huge file of data:
**datatable.txt**
```
id1 england male
id2 germany female
... ... ...
```
I have another list of data:
**indexes.txt**
```
id1
id3
id6
id10
id11
```
I want to extract all rows from **datatable.txt** where the id is included in **indexes.txt**.
Is it possible to do this with awk/sed/... | 2016/11/24 | [
"https://Stackoverflow.com/questions/40785453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2662639/"
] | You just need a simple `awk` as
```
awk 'FNR==NR {a[$1]; next}; $1 in a' indexes.csv datatable.csv
id1 england male
```
1. `FNR==NR{a[$1];next}` will process on `indexes.csv` storing the
entries of the array as the content of the first column till the end of
the file.
2. Now on `datatable.csv`, I can match those row... | maybe i overlook something, but i build two test files:
```
a1:
id1
id2
id3
id6
id9
id10
```
and
```
a2:
id1 a 1
id2 b 2
id3 c 3
id4 c 4
id5 e 5
id6 f 6
id7 g 7
id8 h 8
id9 i 9
id10 j 10
```
with
`join a1 a2 2> /dev/null`
I get all lines matched by column one. |
49,760,858 | I need to get data from this API <https://api.storj.io/contacts/f52624d8ef76df81c40853c22f93735581071434> (sample node)
This is my code (python):
```
import requests
f = requests.get('https://api.storj.io/contacts/f52624d8ef76df81c40853c22f93735581071434')
print f.text
```
I want to save only protocol, responseTim... | 2018/04/10 | [
"https://Stackoverflow.com/questions/49760858",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9590393/"
] | ```
import requests
f = requests.get('https://api.storj.io/contacts/f52624d8ef76df81c40853c22f93735581071434')
# Store content as json
answer = f.json()
# List of element you want to keep
items = ['protocol', 'responseTime', 'reputation']
# Display
for item in items:
print(item + ':' + str(answer[item]))
# If y... | This is a very unrefined way to do what you want that you could build off of. You'd need to sub in a path/filename for text.txt.
```
import requests
import json
f = requests.get('https://api.storj.io/contacts/f52624d8ef76df81c40853c22f93735581071434')
t = json.loads(f.text)
with open('text.txt', 'a') as mfile:
mfi... |
49,760,858 | I need to get data from this API <https://api.storj.io/contacts/f52624d8ef76df81c40853c22f93735581071434> (sample node)
This is my code (python):
```
import requests
f = requests.get('https://api.storj.io/contacts/f52624d8ef76df81c40853c22f93735581071434')
print f.text
```
I want to save only protocol, responseTim... | 2018/04/10 | [
"https://Stackoverflow.com/questions/49760858",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9590393/"
] | ```
import requests
f = requests.get('https://api.storj.io/contacts/f52624d8ef76df81c40853c22f93735581071434')
# Store content as json
answer = f.json()
# List of element you want to keep
items = ['protocol', 'responseTime', 'reputation']
# Display
for item in items:
print(item + ':' + str(answer[item]))
# If y... | You just need to transform to a JSON object to be able to access the keys
```
import requests
import simplejson as json
f = requests.get('https://api.storj.io/contacts/f52624d8ef76df81c40853c22f93735581071434')
x = json.loads(f.text)
print 'protocol: {}'.format(x.get('protocol'))
print 'responseTime: {}'.format(x.g... |
20,467,107 | as we know, python has two built-in url lib:
* `urllib`
* `urllib2`
and a third-party lib:
* `urllib3`
if my requirement is only to request a API by GET method, assume it return a JSON string.
which lib I should use? do they have some duplicated functions?
if the `urllib` can implement my require, but after... | 2013/12/09 | [
"https://Stackoverflow.com/questions/20467107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1122265/"
] | As Alexander says in the comments, use `requests`. That's all you need. | I don't really know what you want to do, but you should try with [`requests`](http://requests.readthedocs.org/en/latest/). It's simple and intuitive. |
20,467,107 | as we know, python has two built-in url lib:
* `urllib`
* `urllib2`
and a third-party lib:
* `urllib3`
if my requirement is only to request a API by GET method, assume it return a JSON string.
which lib I should use? do they have some duplicated functions?
if the `urllib` can implement my require, but after... | 2013/12/09 | [
"https://Stackoverflow.com/questions/20467107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1122265/"
] | As Alexander says in the comments, use `requests`. That's all you need. | Personally I avoid to use third-party library when possible, so I can reduce the dependencies' list and improve portability.
urllib and urllib2 are not mutually exclusive and are often mixed in the same project. |
20,467,107 | as we know, python has two built-in url lib:
* `urllib`
* `urllib2`
and a third-party lib:
* `urllib3`
if my requirement is only to request a API by GET method, assume it return a JSON string.
which lib I should use? do they have some duplicated functions?
if the `urllib` can implement my require, but after... | 2013/12/09 | [
"https://Stackoverflow.com/questions/20467107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1122265/"
] | I don't really know what you want to do, but you should try with [`requests`](http://requests.readthedocs.org/en/latest/). It's simple and intuitive. | Personally I avoid to use third-party library when possible, so I can reduce the dependencies' list and improve portability.
urllib and urllib2 are not mutually exclusive and are often mixed in the same project. |
60,388,686 | Can someone please tell me how to downgrade Python 3.6.9 to 3.6.6 on Ubuntu ? I tried the below commands but didnot work
1) pip install python3.6==3.6.6
2) pip install python3.6.6 | 2020/02/25 | [
"https://Stackoverflow.com/questions/60388686",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12651893/"
] | First, verify that 3.6.6 is available:
```sh
apt-cache policy python3.6
```
If available:
```sh
apt-get install python3.6=3.6.6
```
If not available, you'll need to find a repo which has the version you desire and add it to your apt sources list, update, and install:
```sh
echo "<repo url>" >> /etc/apt/sources.l... | One option is to use Anaconda, which allows you to easily use different Python versions on the same computer. [Here are the installation instructions for Anaconda on Linux](https://docs.anaconda.com/anaconda/install/linux/). Then create a Conda environment by running this command:
```
conda create --name myenv python=... |
45,340,587 | How do I use python, mss, and opencv to capture my computer screen and save it as an array of images to form a movie? I am converting to gray-scale so it can be a 3 dimensional array. I would like to store each 2d screen shot in a 3d array for viewing and processing. I am having a hard time constructing an array that s... | 2017/07/27 | [
"https://Stackoverflow.com/questions/45340587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8298595/"
] | A clue perhaps, save screenshots into a list and replay them later (you will have to adapt the sleep time):
```
import time
import cv2
import mss
import numpy
with mss.mss() as sct:
monitor = {'top': 40, 'left': 0, 'width': 800, 'height': 640}
img_matrix = []
for _ in range(100):
# Get raw pizels... | use `collections.OrderedDict()` to saves the sequence
```
import collections
....
fps_list= collections.OrderedDict()
...
fps_list[timer] = fps
``` |
16,438,259 | I've just learned how to use `virtualenv` and I installed Django 1.4.5. I'm assuming that the `virtualenv` created a clean slate for me to work on so with the Django 1.4.5 installed, I copied all my previous files into the `virtualenv` environment.
I tried to run the server but I get an error saying `"no module named ... | 2013/05/08 | [
"https://Stackoverflow.com/questions/16438259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1815710/"
] | When doing in a virtualenv :
```
pip install MySQL-python
```
I got
```
EnvironmentError: mysql_config not found
```
To install mysql\_config, as Artem Fedosov said, first install
```
sudo apt-get install libmysqlclient-dev
```
then everything works fine in virtualenv | The suggested solutions didn't work out for me, because I still got compilation errors after running
```
`$ sudo apt-get install libmysqlclient-dev`
```
so I had to run
```
apt-get install python-dev
```
Then everything worked fine for me with
```
apt-get install python-dev
``` |
16,438,259 | I've just learned how to use `virtualenv` and I installed Django 1.4.5. I'm assuming that the `virtualenv` created a clean slate for me to work on so with the Django 1.4.5 installed, I copied all my previous files into the `virtualenv` environment.
I tried to run the server but I get an error saying `"no module named ... | 2013/05/08 | [
"https://Stackoverflow.com/questions/16438259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1815710/"
] | I recently had exactly this issue (just not in relation to Django). In my case I am developing on Ubuntu 12.04 using the default pip and distribute versions, which are basically a little out of date for `MySQL-python`.
Because you are working in an isolated virtualenv, you can safely follow the suggested instruction w... | The suggested solutions didn't work out for me, because I still got compilation errors after running
```
`$ sudo apt-get install libmysqlclient-dev`
```
so I had to run
```
apt-get install python-dev
```
Then everything worked fine for me with
```
apt-get install python-dev
``` |
16,438,259 | I've just learned how to use `virtualenv` and I installed Django 1.4.5. I'm assuming that the `virtualenv` created a clean slate for me to work on so with the Django 1.4.5 installed, I copied all my previous files into the `virtualenv` environment.
I tried to run the server but I get an error saying `"no module named ... | 2013/05/08 | [
"https://Stackoverflow.com/questions/16438259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1815710/"
] | I recently had exactly this issue (just not in relation to Django). In my case I am developing on Ubuntu 12.04 using the default pip and distribute versions, which are basically a little out of date for `MySQL-python`.
Because you are working in an isolated virtualenv, you can safely follow the suggested instruction w... | MySQL driver for Python (mysql-python) needs libmysqlclient-dev. You can get it with:
```
sudo apt-get update
sudo apt-get install libmysqlclient-dev
```
If python-dev is not installed, you may have to install it too:
```
sudo apt-get install python-dev
```
Now you can install MySQL driver:
```
pip install mysql... |
16,438,259 | I've just learned how to use `virtualenv` and I installed Django 1.4.5. I'm assuming that the `virtualenv` created a clean slate for me to work on so with the Django 1.4.5 installed, I copied all my previous files into the `virtualenv` environment.
I tried to run the server but I get an error saying `"no module named ... | 2013/05/08 | [
"https://Stackoverflow.com/questions/16438259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1815710/"
] | Spent an hour looking through stackoverflow. Evntually found answer [in the other question](https://stackoverflow.com/questions/7475223/mysql-config-not-found-when-installing-mysqldb-python-interface). This is what saved me:
```
sudo apt-get install libmysqlclient-dev
```
mysql\_config goes with the package. | Try this:
**Version Python 2.7**
**MySQL-python** package, you should use either MySQL\_python‑1.2.5‑cp27‑none‑win32.whl or
MySQL\_python‑1.2.5‑cp27‑none‑win\_amd64.whl depending on whether you have installed 32-bit or 64-bit Python.
```
pip install MySQL_python‑1.2.5‑cp27‑none‑win32.whl
```
if you are using **my... |
16,438,259 | I've just learned how to use `virtualenv` and I installed Django 1.4.5. I'm assuming that the `virtualenv` created a clean slate for me to work on so with the Django 1.4.5 installed, I copied all my previous files into the `virtualenv` environment.
I tried to run the server but I get an error saying `"no module named ... | 2013/05/08 | [
"https://Stackoverflow.com/questions/16438259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1815710/"
] | I recently had exactly this issue (just not in relation to Django). In my case I am developing on Ubuntu 12.04 using the default pip and distribute versions, which are basically a little out of date for `MySQL-python`.
Because you are working in an isolated virtualenv, you can safely follow the suggested instruction w... | I had to do this:
```
pip install mysql-python
```
inside the virtualenv |
16,438,259 | I've just learned how to use `virtualenv` and I installed Django 1.4.5. I'm assuming that the `virtualenv` created a clean slate for me to work on so with the Django 1.4.5 installed, I copied all my previous files into the `virtualenv` environment.
I tried to run the server but I get an error saying `"no module named ... | 2013/05/08 | [
"https://Stackoverflow.com/questions/16438259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1815710/"
] | When doing in a virtualenv :
```
pip install MySQL-python
```
I got
```
EnvironmentError: mysql_config not found
```
To install mysql\_config, as Artem Fedosov said, first install
```
sudo apt-get install libmysqlclient-dev
```
then everything works fine in virtualenv | The commands are always run in ubuntu:
```
easy_install -U distribute
```
later
```
sudo apt-get install libmysqlclient-dev
```
and finally
```
pip install MySQL-python
``` |
16,438,259 | I've just learned how to use `virtualenv` and I installed Django 1.4.5. I'm assuming that the `virtualenv` created a clean slate for me to work on so with the Django 1.4.5 installed, I copied all my previous files into the `virtualenv` environment.
I tried to run the server but I get an error saying `"no module named ... | 2013/05/08 | [
"https://Stackoverflow.com/questions/16438259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1815710/"
] | Spent an hour looking through stackoverflow. Evntually found answer [in the other question](https://stackoverflow.com/questions/7475223/mysql-config-not-found-when-installing-mysqldb-python-interface). This is what saved me:
```
sudo apt-get install libmysqlclient-dev
```
mysql\_config goes with the package. | MySQL driver for Python (mysql-python) needs libmysqlclient-dev. You can get it with:
```
sudo apt-get update
sudo apt-get install libmysqlclient-dev
```
If python-dev is not installed, you may have to install it too:
```
sudo apt-get install python-dev
```
Now you can install MySQL driver:
```
pip install mysql... |
16,438,259 | I've just learned how to use `virtualenv` and I installed Django 1.4.5. I'm assuming that the `virtualenv` created a clean slate for me to work on so with the Django 1.4.5 installed, I copied all my previous files into the `virtualenv` environment.
I tried to run the server but I get an error saying `"no module named ... | 2013/05/08 | [
"https://Stackoverflow.com/questions/16438259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1815710/"
] | I recently had exactly this issue (just not in relation to Django). In my case I am developing on Ubuntu 12.04 using the default pip and distribute versions, which are basically a little out of date for `MySQL-python`.
Because you are working in an isolated virtualenv, you can safely follow the suggested instruction w... | The commands are always run in ubuntu:
```
easy_install -U distribute
```
later
```
sudo apt-get install libmysqlclient-dev
```
and finally
```
pip install MySQL-python
``` |
16,438,259 | I've just learned how to use `virtualenv` and I installed Django 1.4.5. I'm assuming that the `virtualenv` created a clean slate for me to work on so with the Django 1.4.5 installed, I copied all my previous files into the `virtualenv` environment.
I tried to run the server but I get an error saying `"no module named ... | 2013/05/08 | [
"https://Stackoverflow.com/questions/16438259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1815710/"
] | When doing in a virtualenv :
```
pip install MySQL-python
```
I got
```
EnvironmentError: mysql_config not found
```
To install mysql\_config, as Artem Fedosov said, first install
```
sudo apt-get install libmysqlclient-dev
```
then everything works fine in virtualenv | Try this:
**Version Python 2.7**
**MySQL-python** package, you should use either MySQL\_python‑1.2.5‑cp27‑none‑win32.whl or
MySQL\_python‑1.2.5‑cp27‑none‑win\_amd64.whl depending on whether you have installed 32-bit or 64-bit Python.
```
pip install MySQL_python‑1.2.5‑cp27‑none‑win32.whl
```
if you are using **my... |
16,438,259 | I've just learned how to use `virtualenv` and I installed Django 1.4.5. I'm assuming that the `virtualenv` created a clean slate for me to work on so with the Django 1.4.5 installed, I copied all my previous files into the `virtualenv` environment.
I tried to run the server but I get an error saying `"no module named ... | 2013/05/08 | [
"https://Stackoverflow.com/questions/16438259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1815710/"
] | I had to do this:
```
pip install mysql-python
```
inside the virtualenv | Try this:
**Version Python 2.7**
**MySQL-python** package, you should use either MySQL\_python‑1.2.5‑cp27‑none‑win32.whl or
MySQL\_python‑1.2.5‑cp27‑none‑win\_amd64.whl depending on whether you have installed 32-bit or 64-bit Python.
```
pip install MySQL_python‑1.2.5‑cp27‑none‑win32.whl
```
if you are using **my... |
65,990,047 | I've been trying to make a keylogger but got this error in python while running the script.
>
> File "C:\Users\David\AppData\Roaming\Python\Python39\site-packages\pynput\_util\_*init*\_.py", line 211, in inner
> return f(self, \*args, \*\*kwargs)
> File "C:\Users\David\AppData\Roaming\Python\Python39\site-packages\py... | 2021/02/01 | [
"https://Stackoverflow.com/questions/65990047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14644110/"
] | Because keys is literally not defined anywhere
**I think you made a spelling mistake.**
You need to replace `key = []` with `keys = []` | I think you have a typo during initialization of the `keys` list. You have declared it as `key` but you need `keys`.
You need:
```
keys = []
```
instead of:
```
key = []
``` |
65,990,047 | I've been trying to make a keylogger but got this error in python while running the script.
>
> File "C:\Users\David\AppData\Roaming\Python\Python39\site-packages\pynput\_util\_*init*\_.py", line 211, in inner
> return f(self, \*args, \*\*kwargs)
> File "C:\Users\David\AppData\Roaming\Python\Python39\site-packages\py... | 2021/02/01 | [
"https://Stackoverflow.com/questions/65990047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14644110/"
] | You have made a typo in line 6 and thus `keys` is not declared anywhere as the error message is telling you (e.g. `NameError: name 'keys' is not defined`).
Line 6 should instead be `keys = []` of `key = []`. | I think you have a typo during initialization of the `keys` list. You have declared it as `key` but you need `keys`.
You need:
```
keys = []
```
instead of:
```
key = []
``` |
4,522,733 | Okay, so I'm admittedly a newbie to programming, but I can't determine how to get python v3.2 to generate a random positive integer between parameters I've given it. Just so you can understand the context, I'm trying to create a guessing-game where the user inputs parameters (say 1 to 50), and the computer generates a ... | 2010/12/23 | [
"https://Stackoverflow.com/questions/4522733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/552834/"
] | Use [random.randrange](http://docs.python.org/dev/py3k/library/random.html#random.randrange) or [random.randint](http://docs.python.org/dev/py3k/library/random.html#random.randint) (Note the links are to the Python 3k docs).
```
In [67]: import random
In [69]: random.randrange(1,10)
Out[69]: 8
``` | You can use `random` module:
```
import random
# Random integer >= 5 and < 10
random.randrange(5, 10)
``` |
50,182,828 | I've installed pillow for python 3 on my macbook successfully. But I still can't use PIL library. I tried uninstalling and installing it again. I've also tried `import Image` without `from PIL` as well. I do not have PIL installed, though. It says
>
> Could not find a version that satisfies the requirement PIL (from... | 2018/05/04 | [
"https://Stackoverflow.com/questions/50182828",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5991761/"
] | If you use `Anaconda`, you may try:
```
conda install Pillow
```
because this works for me. | Pil is depricated and replaced by pillow. Pillow is the official fork of PIL
Install using pip or how you usually do it.
<https://pillow.readthedocs.io/en/5.1.x/index.html> |
28,233,090 | I want to get the width % shown. So that i can monitor the progress.How to get the value using selenium in python.
I don't know how to achieve this. | 2015/01/30 | [
"https://Stackoverflow.com/questions/28233090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4472647/"
] | A `CSS3`-only (actually moved into `CSS4` specs) solution would be the `pointer-events` property, e.g.
```
.media__body:hover:after,
.media__body:hover:before {
...
pointer-events: none;
}
```
supported on [all modern browser](https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events) but only from `IE11` ... | ```
.media__body p { margin-bottom: 1.5em;
position: relative;
z-index:999;
```
}
try this ! |
33,116,636 | I am very new to REGEX and HTML in particular. I know that BeautifulSoup is a way to deal with HTML but would like to try regex
I need to search the text for HTML tags (I use findall). I tried multiple scenarios and examples in Stackoverflow but only got [] (empty string). Here is what I tried:
```
#reHTML = r'(?:<([... | 2015/10/14 | [
"https://Stackoverflow.com/questions/33116636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5287011/"
] | You misunderstood [regex.findall(string[, pos[, endpos]])](https://docs.python.org/3.5/library/re.html?highlight=findall#re.regex.findall)
`HTMLpara = rHTML.findall('http://pythonprogramming.net/parse-website-using- regular-expressions-urllib/', re.IGNORECASE)`
means you will match the `rHTML` pattern with the string(... | This will read in a webpage and find any instances of `<html>` or `</html>`. Is this the solution you are looking for?
```
import re
import urllib2
url = "http://stackoverflow.com"
f = urllib2.urlopen(url)
file = f.read()
p = re.compile("<html>|</html>")
instances = p.findall(file)
print instances
```
Output:
```
... |
15,279,942 | Coming from python I could do something like this.
```
values = (1, 'ab', 2.7)
s = struct.Struct('I 2s f')
packet = s.pack(*values)
```
I can pack together arbitrary types together very simply with python. What is the standard way to do it in Objective C? | 2013/03/07 | [
"https://Stackoverflow.com/questions/15279942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/299648/"
] | Try using something like this:
```
window.addEventListener('load', function() { document.getElementById("demo").innerHTML="Works"; }, false);
``` | Where did you get `document.onready` from? That would **never work**.
To ensure the page is loaded, you could use `window.onload`;
```
window.onload = function () {
document.getElementById("demo").innerHTML="Works";
}
``` |
15,279,942 | Coming from python I could do something like this.
```
values = (1, 'ab', 2.7)
s = struct.Struct('I 2s f')
packet = s.pack(*values)
```
I can pack together arbitrary types together very simply with python. What is the standard way to do it in Objective C? | 2013/03/07 | [
"https://Stackoverflow.com/questions/15279942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/299648/"
] | Try using something like this:
```
window.addEventListener('load', function() { document.getElementById("demo").innerHTML="Works"; }, false);
``` | Your syntax is incorrect.
```
document.ready= function () {
//code to run when page loaded
}
window.onload = function () {
//code to run when page AND images loaded
}
``` |
15,279,942 | Coming from python I could do something like this.
```
values = (1, 'ab', 2.7)
s = struct.Struct('I 2s f')
packet = s.pack(*values)
```
I can pack together arbitrary types together very simply with python. What is the standard way to do it in Objective C? | 2013/03/07 | [
"https://Stackoverflow.com/questions/15279942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/299648/"
] | Where did you get `document.onready` from? That would **never work**.
To ensure the page is loaded, you could use `window.onload`;
```
window.onload = function () {
document.getElementById("demo").innerHTML="Works";
}
``` | Your syntax is incorrect.
```
document.ready= function () {
//code to run when page loaded
}
window.onload = function () {
//code to run when page AND images loaded
}
``` |
53,185,119 | I want to retrieve the list of resources are currently in used region wise by using python script and boto3 library.
for example script have to give me the out put as follows
Region : us-west-2
service: EC2
//resource list//instance ids //Name
service: VPC
//resource list//VPC ids//Name | 2018/11/07 | [
"https://Stackoverflow.com/questions/53185119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4108278/"
] | There's no easy way to do it, but you can achieve this with a few describe calls.
First enumerate through the regions that you use:
```
for regionname in ["us-east-1", "eu-west-1"]
```
Or if you want to check all:
```
ec2client = boto3.client('ec2')
regionresponse = ec2client.describe_regions()
for region in regio... | There is no way to obtain a list of all resources used. You would need to write it yourself.
Alternatively, there are third-party companies offering services that will do this for you (eg [Hava](https://www.hava.io/). |
53,185,119 | I want to retrieve the list of resources are currently in used region wise by using python script and boto3 library.
for example script have to give me the out put as follows
Region : us-west-2
service: EC2
//resource list//instance ids //Name
service: VPC
//resource list//VPC ids//Name | 2018/11/07 | [
"https://Stackoverflow.com/questions/53185119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4108278/"
] | There's no easy way to do it, but you can achieve this with a few describe calls.
First enumerate through the regions that you use:
```
for regionname in ["us-east-1", "eu-west-1"]
```
Or if you want to check all:
```
ec2client = boto3.client('ec2')
regionresponse = ec2client.describe_regions()
for region in regio... | The `aws_list_all` program [available on GitHub](https://github.com/JohannesEbke/aws_list_all) is written in python and is able to find all of the resources you have created in your account.
Currently it lists all of the resources into JSON files together with their meta-data. You can work from the [scripts used for ... |
53,185,119 | I want to retrieve the list of resources are currently in used region wise by using python script and boto3 library.
for example script have to give me the out put as follows
Region : us-west-2
service: EC2
//resource list//instance ids //Name
service: VPC
//resource list//VPC ids//Name | 2018/11/07 | [
"https://Stackoverflow.com/questions/53185119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4108278/"
] | The `aws_list_all` program [available on GitHub](https://github.com/JohannesEbke/aws_list_all) is written in python and is able to find all of the resources you have created in your account.
Currently it lists all of the resources into JSON files together with their meta-data. You can work from the [scripts used for ... | There is no way to obtain a list of all resources used. You would need to write it yourself.
Alternatively, there are third-party companies offering services that will do this for you (eg [Hava](https://www.hava.io/). |
32,714,656 | This a recuring question and i've read many topics some helped a bit ([python Qt: main widget scroll bar](https://stackoverflow.com/questions/2130446/python-qt-main-widget-scroll-bar), [PyQt: Put scrollbars in this](https://stackoverflow.com/questions/14159337/pyqt-put-scrollbars-in-this)), some not at all ([PyQt addin... | 2015/09/22 | [
"https://Stackoverflow.com/questions/32714656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4862605/"
] | There are several things wrong with the example code. The main problems are that you are not using layouts properly, and the content widget is not being added to the scroll-area.
Below is a fixed version (the commented lines are all junk, and can be removed):
```
def setupUi(self, Interface):
# Interface.setObjec... | The scrollbars are grayed out because you made them always visible by setting the scrollbar policy to `Qt.ScrollBarAlwaysOn` but actually there is no content to be scrolled so they are disabled. If you want scrollbars to appear only when they are needed you need to use `Qt.ScrollBarAsNeeded`.
There is no content to b... |
52,456,516 | I am doing a list comprehension in python 3 for list of list serially numbers according to given range. My code works fine with but problem is with big range it slows down and take a lot of time. I there any way to do it other way? I don't want to use numpy.
```
global xy
xy = 0
a = 3
def func(x):
global xy
... | 2018/09/22 | [
"https://Stackoverflow.com/questions/52456516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4217784/"
] | In exactly the form you asked
```
[list(range(x, x + a)) for x in range(1, a**2 + 1, a)]
```
**Optimizations**
If you're only iterating over inner list elements
```
(range(x, x + a) for x in range(1, a**2 + 1, a))
```
If you're only indexing inner elements (for indices `inner` and `outer`)
```
range(1, a**2 + 1... | Try:
```
t = [list(range(a*i + 1, a*(i+1) + 1)) for i in range(a)]
```
It seems pretty fast for a>100 even, though not fast enough for inside a graphical loop or event handler |
52,456,516 | I am doing a list comprehension in python 3 for list of list serially numbers according to given range. My code works fine with but problem is with big range it slows down and take a lot of time. I there any way to do it other way? I don't want to use numpy.
```
global xy
xy = 0
a = 3
def func(x):
global xy
... | 2018/09/22 | [
"https://Stackoverflow.com/questions/52456516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4217784/"
] | In exactly the form you asked
```
[list(range(x, x + a)) for x in range(1, a**2 + 1, a)]
```
**Optimizations**
If you're only iterating over inner list elements
```
(range(x, x + a) for x in range(1, a**2 + 1, a))
```
If you're only indexing inner elements (for indices `inner` and `outer`)
```
range(1, a**2 + 1... | There are multiple ways to do what you have done. You can have a clearer picture once we do a performance check
```
import timeit
# Process 1
setup = '''
global xy
xy =0
a=30
def func(x):
global xy
xy+=1
return xy
'''
code = '''
my_list = []
for x in range(a):
my_list1 = []
for x in range(a):
... |
52,456,516 | I am doing a list comprehension in python 3 for list of list serially numbers according to given range. My code works fine with but problem is with big range it slows down and take a lot of time. I there any way to do it other way? I don't want to use numpy.
```
global xy
xy = 0
a = 3
def func(x):
global xy
... | 2018/09/22 | [
"https://Stackoverflow.com/questions/52456516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4217784/"
] | Try:
```
t = [list(range(a*i + 1, a*(i+1) + 1)) for i in range(a)]
```
It seems pretty fast for a>100 even, though not fast enough for inside a graphical loop or event handler | There are multiple ways to do what you have done. You can have a clearer picture once we do a performance check
```
import timeit
# Process 1
setup = '''
global xy
xy =0
a=30
def func(x):
global xy
xy+=1
return xy
'''
code = '''
my_list = []
for x in range(a):
my_list1 = []
for x in range(a):
... |
18,464,237 | I've have been making changes and uploading them for testing on AppEngine Python 2.7 runtime.
When uploading I only get as far as seeing the message "Getting current resource limits". The next expected message is "Scanning files on local disk", but this never comes, I always get an error instead.
My last successful d... | 2013/08/27 | [
"https://Stackoverflow.com/questions/18464237",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/498463/"
] | I encountered the same problem. Fortunately, I was able to deploy the project successfully.
Just stop the **appengine** from running your project and try to deploy it again.
Hope this helps. | You wouldn't believe it.... I tried deploying again just before posting this question. Everything the same and it works now.
12:30 UK time.... so just a bit of an AppEngine issue? Did anyone else run into this?
Can anyone explain what was going on? I can't be affording to spend 90 minutes messing about everytime I wa... |
61,770,551 | I have a Django project running on my local machine with dev server `manage.py runserver` and I'm trying to run it with Uvicorn before I deploy it in a virtual machine. So in my virtual environment I installed `uvicorn` and started the server, but as you can see below it fails to find Django static css files.
```
(env... | 2020/05/13 | [
"https://Stackoverflow.com/questions/61770551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3423825/"
] | When not running with the built-in development server, you'll need to either
* use [whitenoise](http://whitenoise.evans.io/en/stable/) which does this as a Django/WSGI middleware (my recommendation)
* use [the classic staticfile deployment procedure which collects all static files into some root](https://docs.djangopr... | Add below code your settings.py file
```
STATIC_ROOT = os.path.join(BASE_DIR, 'static', )
```
Add below code in your urls.py
```
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [.
.....] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
```
Then run below... |
50,396,802 | I want to check if an arg was actually passed on the command line when there is a default value for that arg.
Specifically in my case, I am using SCons and scons has a class which inherits from pythons optparse. So my code is like this so far:
```
from SCons.Environment import Environment
from SCons.Script.SConsOptio... | 2018/05/17 | [
"https://Stackoverflow.com/questions/50396802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1644736/"
] | Figured it out.
I didn't add my redirect uri to the list of authorized ones as the option doesn't appear if you set your app type to "Other". I set it to "Web Application" (even though it isn't) and added my redirect uri and that fixed it. | Your code snippet lists "<https://googleapis.com/oauth/v4/token>".
The token endpoint is "<https://googleapis.com/oauth2/v4/token>". |
50,396,802 | I want to check if an arg was actually passed on the command line when there is a default value for that arg.
Specifically in my case, I am using SCons and scons has a class which inherits from pythons optparse. So my code is like this so far:
```
from SCons.Environment import Environment
from SCons.Script.SConsOptio... | 2018/05/17 | [
"https://Stackoverflow.com/questions/50396802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1644736/"
] | For me the issue was that I was sending a GET. You have to send a POST. | Your code snippet lists "<https://googleapis.com/oauth/v4/token>".
The token endpoint is "<https://googleapis.com/oauth2/v4/token>". |
50,396,802 | I want to check if an arg was actually passed on the command line when there is a default value for that arg.
Specifically in my case, I am using SCons and scons has a class which inherits from pythons optparse. So my code is like this so far:
```
from SCons.Environment import Environment
from SCons.Script.SConsOptio... | 2018/05/17 | [
"https://Stackoverflow.com/questions/50396802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1644736/"
] | Your code snippet lists "<https://googleapis.com/oauth/v4/token>".
The token endpoint is "<https://googleapis.com/oauth2/v4/token>". | In my edge case, I was requesting the token pass
```
val tokenRequest = Request.Builder()
.method(
"POST",
"".toRequestBody("application/x-www-form-urlencoded".toMediaType())
)
```
The snippet above didn't work until I changed "POST" to "post". |
50,396,802 | I want to check if an arg was actually passed on the command line when there is a default value for that arg.
Specifically in my case, I am using SCons and scons has a class which inherits from pythons optparse. So my code is like this so far:
```
from SCons.Environment import Environment
from SCons.Script.SConsOptio... | 2018/05/17 | [
"https://Stackoverflow.com/questions/50396802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1644736/"
] | Figured it out.
I didn't add my redirect uri to the list of authorized ones as the option doesn't appear if you set your app type to "Other". I set it to "Web Application" (even though it isn't) and added my redirect uri and that fixed it. | In my edge case, I was requesting the token pass
```
val tokenRequest = Request.Builder()
.method(
"POST",
"".toRequestBody("application/x-www-form-urlencoded".toMediaType())
)
```
The snippet above didn't work until I changed "POST" to "post". |
50,396,802 | I want to check if an arg was actually passed on the command line when there is a default value for that arg.
Specifically in my case, I am using SCons and scons has a class which inherits from pythons optparse. So my code is like this so far:
```
from SCons.Environment import Environment
from SCons.Script.SConsOptio... | 2018/05/17 | [
"https://Stackoverflow.com/questions/50396802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1644736/"
] | For me the issue was that I was sending a GET. You have to send a POST. | In my edge case, I was requesting the token pass
```
val tokenRequest = Request.Builder()
.method(
"POST",
"".toRequestBody("application/x-www-form-urlencoded".toMediaType())
)
```
The snippet above didn't work until I changed "POST" to "post". |
21,678,165 | it's still not a year that i code in python in my spare time, and it is my first programming language. I need to generate serie of numbers in range ("1, 2, 3...99; 1, 2, 3...99;" ) and match them against a list. I managed to do this but the code looks pathetic and i failed in some tasks, for example by skipping series ... | 2014/02/10 | [
"https://Stackoverflow.com/questions/21678165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1348293/"
] | thanks to user2357112 suggestion on using itertools.permutations(xrange(a, b), 4) I did the following and i'm very satisfied, it is fast and nice:
```
def solution(d, a, q):
for i in itertools.permutations(xrange(d, a), q):
#do something
solution(1,100,4)
```
Thanks to this brilliant community as well. | Create array[100], fill it numbers from 0 to 99. Then use random generator to mix them. And then just take needed number of numbers. |
50,595,357 | I have a question of while in python.
How to collect the result values using while?
```
ColumnCount_int = 3
while ColumnCount_int > 0 :
ColumnCount_text = str('<colspec colnum="'+ str(ColumnCount_int) +'"' ' ' 'colname="'+ str(ColumnCount_int) + '">')
Blank_text = ""
Blank_text = Blank_text + ColumnCount_t... | 2018/05/30 | [
"https://Stackoverflow.com/questions/50595357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9817554/"
] | You can fix the code by following where `Blank_text = ""` is moved before `while loop` and `print(Blank_text)` is called after the `loop`.
(**Note**: *since `Blank_text` accumulates, variable name changed to `accumulated_text` as suggested in the comment*):
```
ColumnCount_int = 3
accumulated_text = "" # variable nam... | Try appending it to the new list i created `l`, then do [`''.join(l)`](https://www.tutorialspoint.com/python3/string_join.htm) to output it in one line :
```
l = []
ColumnCount_int = 3
while ColumnCount_int > 0 :
ColumnCount_text = str('<colspec colnum="'+ str(ColumnCount_int) +'"' ' ' 'colname="'+ str(ColumnCou... |
61,027,226 | I have already translated in this project in the same way a number of similar templates in the same directory, which are nearly equal to this one. But this template makes me helpless.
Without a translation tag `{% blocktrans %}` it properly works and renders the variable.
[.But I think that i have problem in python 3.5. Can anyone help me with this error?
[... | 2018/01/22 | [
"https://Stackoverflow.com/questions/48376714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9250190/"
] | It happened to me. Just copy the "object\_detection" folder from "models" folder into the folder where you are running the train.py. I posted the link to the folder from github but you better copy the folder from your local files so it will match with your code perfectly in case you are using an older version of the ob... | Move the object\_detection folder to upper folder
cp /models/research/object\_detection object\_detection |
24,469,353 | New to python so...
I have a list with two columns, like so:
```
>>>print langs
[{u'code': u'en', u'name': u'ENGLISH'}, {u'code': u'hy', u'name': u'ARMENIAN'}, ... {u'code': u'ms', u'name': u'MALAY'}]
```
I would like to add another row with:
code: xx and name: UNKNOWN
Tried with `langs.append` and so on, but ca... | 2014/06/28 | [
"https://Stackoverflow.com/questions/24469353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1662464/"
] | It's pretty easy:
```
>>> langs.append({u'code': u'xx', u'name': u'UNKNOWN'})
```
But I'd use `collections.namedtuple` for this kind of job(when columns are well-defined):
```
In [1]: from collections import namedtuple
In [2]: Lang = namedtuple("Lang", ("code", "name"))
In [3]: langs = []
In [4]: langs.append(Lang(... | This is one way of doing it...
```
langs += [{u'code': u'xx', u'name': u'UNKNOWN'}]
``` |
74,006,179 | i'm new to python and i got a problem with dictionary filter.
I searched a really long time for solution and asked on several discord server, but no one could really help me.
If i have a dictionary like this:
```
[
{"champion": "ahri", "kills": 12, "assists": 7, "deaths": 4, "puuid": "17hd72he7wu"}
{"champion... | 2022/10/09 | [
"https://Stackoverflow.com/questions/74006179",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20198636/"
] | use a list comprehension and cycle through the dictionaries in your list to only keep the one that meets the specified conditions.
```
[
{"champion": ahri, "kills": 12, "assists": 7, "deaths": 4, "puuid": 17hd72he7wu}
{"champion": sett, "kills": 14, "assists": 5, "deaths": 7, "puuid": 2123r3ze7wu}
{"champion": thresh,... | you want something like this:
new\_list = [ x for x in orgininal\_list if x[puuid] == value ]
its called a list comprehension |
74,006,179 | i'm new to python and i got a problem with dictionary filter.
I searched a really long time for solution and asked on several discord server, but no one could really help me.
If i have a dictionary like this:
```
[
{"champion": "ahri", "kills": 12, "assists": 7, "deaths": 4, "puuid": "17hd72he7wu"}
{"champion... | 2022/10/09 | [
"https://Stackoverflow.com/questions/74006179",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20198636/"
] | use a list comprehension and cycle through the dictionaries in your list to only keep the one that meets the specified conditions.
```
[
{"champion": ahri, "kills": 12, "assists": 7, "deaths": 4, "puuid": 17hd72he7wu}
{"champion": sett, "kills": 14, "assists": 5, "deaths": 7, "puuid": 2123r3ze7wu}
{"champion": thresh,... | As the first thing, you should search for a question similar to yours.
* <https://www.programiz.com/python-programming/list-comprehension>
* [How to filter a dictionary according to an arbitrary condition function?](https://stackoverflow.com/questions/2844516/how-to-filter-a-dictionary-according-to-an-arbitrary-condit... |
74,006,179 | i'm new to python and i got a problem with dictionary filter.
I searched a really long time for solution and asked on several discord server, but no one could really help me.
If i have a dictionary like this:
```
[
{"champion": "ahri", "kills": 12, "assists": 7, "deaths": 4, "puuid": "17hd72he7wu"}
{"champion... | 2022/10/09 | [
"https://Stackoverflow.com/questions/74006179",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20198636/"
] | use a list comprehension and cycle through the dictionaries in your list to only keep the one that meets the specified conditions.
```
[
{"champion": ahri, "kills": 12, "assists": 7, "deaths": 4, "puuid": 17hd72he7wu}
{"champion": sett, "kills": 14, "assists": 5, "deaths": 7, "puuid": 2123r3ze7wu}
{"champion": thresh,... | ```
dictionary = [
{"champion": "ahri", "kills": 12, "assists": 7,
"deaths": 4, "puuid": "17hd72he7wu"},
{"champion": "sett", "kills": 14, "assists": 5,
"deaths": 7, "puuid": "2123r3ze7wu"},
{"champion": "thresh", "kills": 9, "assists": 16,
"deaths": 2, "puuid": "32d72h5t5gu"}
]
new... |
73,323,330 | so im learning some python but i got a list out of index error at this point if i put my header index to 0 it works not the way i see it works but ok, but if i get an upper index for header it wont can you help me out why?[photo of my csv file](https://i.stack.imgur.com/cDD13.png)
[heres the first picture of my code][... | 2022/08/11 | [
"https://Stackoverflow.com/questions/73323330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19744452/"
] | When you put your header index as `0` what is output?
Assuming your delimiter is `tab`
```py
with open("sample.csv", "r") as csvfile:
reader = csv.reader(csvfile,delimiter='\t')
headers = next(reader, None)
print(headers[1])
``` | My delimeter was \t after i changed it to it problem all solved |
67,933,453 | I have a file that consists of data shown below
```
GS*642510*18762293*0*0*0*0*0*0*0*HN*056000522*601200162*20210513*101046*200018825*X*005010X214
ST*642510*18762293*1*0*0*0*0*0*0*277*000000001*005010X214
BHT*642510*18762293*1*0*0*0*0*0*0*0085*08*1*20210513*101046*TH
NM1*642510*18762293*1*1*1*1*1*0*0*QC*1*TORIBIO ... | 2021/06/11 | [
"https://Stackoverflow.com/questions/67933453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15153070/"
] | <https://regex101.com/r/khgAVj/1>
[](https://i.stack.imgur.com/5Ru4N.png)
regex pattern: `(\*\w+){9}\*`
Explanation of the regex pattern can be found on the regex101 page on the right side.
There is a code generator and replacing/removing the sec... | You could write a regular expression to solve this, but if you know that you always want to remove the content between the first and ninth stars, then I would split your strings into lists by "\*" and rejoin select slices. For example:
```py
mystring = "GS*642510*18762293*0*0*0*0*0*0*0*HN*056000522*601200162*20210513*... |
67,933,453 | I have a file that consists of data shown below
```
GS*642510*18762293*0*0*0*0*0*0*0*HN*056000522*601200162*20210513*101046*200018825*X*005010X214
ST*642510*18762293*1*0*0*0*0*0*0*277*000000001*005010X214
BHT*642510*18762293*1*0*0*0*0*0*0*0085*08*1*20210513*101046*TH
NM1*642510*18762293*1*1*1*1*1*0*0*QC*1*TORIBIO ... | 2021/06/11 | [
"https://Stackoverflow.com/questions/67933453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15153070/"
] | You could write a regular expression to solve this, but if you know that you always want to remove the content between the first and ninth stars, then I would split your strings into lists by "\*" and rejoin select slices. For example:
```py
mystring = "GS*642510*18762293*0*0*0*0*0*0*0*HN*056000522*601200162*20210513*... | You can also use this [regex](https://regex101.com/r/oK0eO2/2)
```
/\*(.*?\*){9}/g
```
You did not mention in the question that you want only the first occurrence of this pattern in a line. If you are using regex this, or the accepted one, be sure to only take the first match in a line.
In case if the pattern repea... |
67,933,453 | I have a file that consists of data shown below
```
GS*642510*18762293*0*0*0*0*0*0*0*HN*056000522*601200162*20210513*101046*200018825*X*005010X214
ST*642510*18762293*1*0*0*0*0*0*0*277*000000001*005010X214
BHT*642510*18762293*1*0*0*0*0*0*0*0085*08*1*20210513*101046*TH
NM1*642510*18762293*1*1*1*1*1*0*0*QC*1*TORIBIO ... | 2021/06/11 | [
"https://Stackoverflow.com/questions/67933453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15153070/"
] | <https://regex101.com/r/khgAVj/1>
[](https://i.stack.imgur.com/5Ru4N.png)
regex pattern: `(\*\w+){9}\*`
Explanation of the regex pattern can be found on the regex101 page on the right side.
There is a code generator and replacing/removing the sec... | You can also use this [regex](https://regex101.com/r/oK0eO2/2)
```
/\*(.*?\*){9}/g
```
You did not mention in the question that you want only the first occurrence of this pattern in a line. If you are using regex this, or the accepted one, be sure to only take the first match in a line.
In case if the pattern repea... |
58,335,344 | I want scheduled to run my python script every hour and save the data in elasticsearch index. So that I used a function I wrote, set\_interval which uses the tweepy library. But it doesn't work as I need it to work. It runs every minute and save the data in index. Even after the set that seconds equal to 3600 it runs i... | 2019/10/11 | [
"https://Stackoverflow.com/questions/58335344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11931186/"
] | Why do you need so much complexity to do some task every hour? You can run script every one hour this way below, note that it is runned 1 hour + time to do work:
```
import time
def do_some_work():
print("Do some work")
time.sleep(1)
print("Some work is done!")
if __name__ == "__main__":
time.sleep(6... | Get rid of all timer code just write the logic and
**cron** will do the job for you add this to the end of the file after `crontab -e`
```
0 * * * * /path/to/python /path/to/script.py
```
`0 * * * *` means run at every *zero* minute you can find more explanation [here](https://www.computerhope.com/unix/ucrontab.htm)... |
40,753,137 | suppose I have a list which calls name:
name=['ACCBCDB','CCABACB','CAABBCB']
I want to use python to remove middle B from each element in the list.
the output should display :
['ACCCDB','CCAACB','CAABCB'] | 2016/11/22 | [
"https://Stackoverflow.com/questions/40753137",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6169548/"
] | It is not possible to test for `NULL` values with comparison operators, such as `=`, `<`, or `<>`.
You have to use the `IS NULL` and `IS NOT NULL` operators instead, or you have to use functions like `ISNULL()` and `COALESCE()`
```
Select * From MyTableName where [boolfieldX] <> 1 OR [boolfieldX] IS NULL
```
**OR**... | Hi try to use this query:
```
select * from mytablename where [boolFieldX] is null And [boolFieldX] <> 1
``` |
40,753,137 | suppose I have a list which calls name:
name=['ACCBCDB','CCABACB','CAABBCB']
I want to use python to remove middle B from each element in the list.
the output should display :
['ACCCDB','CCAACB','CAABCB'] | 2016/11/22 | [
"https://Stackoverflow.com/questions/40753137",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6169548/"
] | It is not possible to test for `NULL` values with comparison operators, such as `=`, `<`, or `<>`.
You have to use the `IS NULL` and `IS NOT NULL` operators instead, or you have to use functions like `ISNULL()` and `COALESCE()`
```
Select * From MyTableName where [boolfieldX] <> 1 OR [boolfieldX] IS NULL
```
**OR**... | I believe that it's because null is an unknown value. You can't query against an unknown 'value'. In my opinion, referring to null as a 'value' is an oxymoron because it represents an unknown. Using the operators "Is Null" and "Not Is Null" in conjunction with whatever selection criteria will return the desired results... |
40,753,137 | suppose I have a list which calls name:
name=['ACCBCDB','CCABACB','CAABBCB']
I want to use python to remove middle B from each element in the list.
the output should display :
['ACCCDB','CCAACB','CAABCB'] | 2016/11/22 | [
"https://Stackoverflow.com/questions/40753137",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6169548/"
] | I believe that it's because null is an unknown value. You can't query against an unknown 'value'. In my opinion, referring to null as a 'value' is an oxymoron because it represents an unknown. Using the operators "Is Null" and "Not Is Null" in conjunction with whatever selection criteria will return the desired results... | Hi try to use this query:
```
select * from mytablename where [boolFieldX] is null And [boolFieldX] <> 1
``` |
28,530,928 | I am trying to have a python script execute on the click of an image but whenever the python script gets called it always throws a 500 Internal Server Error? Here is the text from the log
```
[Sun Feb 15 20:31:04 2015] [error] (2)No such file or directory: exec of '/var/www/forward.py' failed
[Sun Feb 15 20:31:04 201... | 2015/02/15 | [
"https://Stackoverflow.com/questions/28530928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4547894/"
] | Things to check:
1. Make sure the script is executable (`chmod +x forward.py`) and that it has a she-bang line (e.g. `#!/usr/bin/env python`).
2. Make sure the script's owner & group match up with what user apache is running as.
3. Try running the script from the command line as the apache user. I see that you're test... | In addition to @lost-theory's recommendations, I would also check to make sure:
* You have executable permission on the script.
* Apache has permission to access the folder/file of the script. For example:
```
<Directory /path/to/your/dir>
<Files *>
Order allow,deny
Allow from all
Require all granted... |
44,579,050 | I am using python and OpenCV. I am trying to find the center and angle of the batteries:
[Image of batteries with random angles:](https://i.stack.imgur.com/qB8S7.jpg)
[](https://i.stack.imgur.com/DgD8p.jpg)
The code than I have is this:
```
import c... | 2017/06/16 | [
"https://Stackoverflow.com/questions/44579050",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8093906/"
] | Almost identical to [one of my other answers](https://stackoverflow.com/questions/43863931/contour-axis-for-image/43883758#43883758). PCA seems to work fine.
```
import cv2
import numpy as np
img = cv2.imread("test_images/battery001.png") #load an image of a single battery
img_gs = cv2.cvtColor(img, cv2.COLOR_BGR2GR... | You can reference the code.
```
import cv2
import imutils
import numpy as np
PIC_PATH = r"E:\temp\Battery.jpg"
image = cv2.imread(PIC_PATH)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
edged = cv2.Canny(gray, 100, 220)
kernel = np.ones((5,5),np.uint8)
closed =... |
44,579,050 | I am using python and OpenCV. I am trying to find the center and angle of the batteries:
[Image of batteries with random angles:](https://i.stack.imgur.com/qB8S7.jpg)
[](https://i.stack.imgur.com/DgD8p.jpg)
The code than I have is this:
```
import c... | 2017/06/16 | [
"https://Stackoverflow.com/questions/44579050",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8093906/"
] | * To find out the center of an object, you can use the [Moments](http://docs.opencv.org/2.4/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html?highlight=moments#moments).
Threshold the image and get the contours of the object with [findContours](http://docs.opencv.org/2.4/modules/imgproc/doc/structural_... | You can reference the code.
```
import cv2
import imutils
import numpy as np
PIC_PATH = r"E:\temp\Battery.jpg"
image = cv2.imread(PIC_PATH)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
edged = cv2.Canny(gray, 100, 220)
kernel = np.ones((5,5),np.uint8)
closed =... |
44,579,050 | I am using python and OpenCV. I am trying to find the center and angle of the batteries:
[Image of batteries with random angles:](https://i.stack.imgur.com/qB8S7.jpg)
[](https://i.stack.imgur.com/DgD8p.jpg)
The code than I have is this:
```
import c... | 2017/06/16 | [
"https://Stackoverflow.com/questions/44579050",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8093906/"
] | Almost identical to [one of my other answers](https://stackoverflow.com/questions/43863931/contour-axis-for-image/43883758#43883758). PCA seems to work fine.
```
import cv2
import numpy as np
img = cv2.imread("test_images/battery001.png") #load an image of a single battery
img_gs = cv2.cvtColor(img, cv2.COLOR_BGR2GR... | * To find out the center of an object, you can use the [Moments](http://docs.opencv.org/2.4/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html?highlight=moments#moments).
Threshold the image and get the contours of the object with [findContours](http://docs.opencv.org/2.4/modules/imgproc/doc/structural_... |
22,948,119 | i am trying to make a program for my computer science class that has us create a lottery game generator. this game has you input your number, then it creates tickets winning tickets to match to your ticket. so if you match 3, it says you matched 3, 4 says 4, 5 says 5 and at 6 matches it will stop the program. my proble... | 2014/04/08 | [
"https://Stackoverflow.com/questions/22948119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3512754/"
] | ```
from random import randint, sample
# Ontario Lotto 6/49 prize schedule
COST = 0.50
PRIZES = [0, 0, 0, 5., 50., 500., 1000000.]
def draw():
return set(sample(range(1, 50), 6))
def get_ints(prompt):
while True:
try:
return [int(i) for i in input(prompt).split()]
except ValueErro... | just keep a record of what you have seen
```
...
costs=0
found = []
while True:
...
if matches==3 and 3 not in found:
found.append(3)
print ("You Matched 3 on try", costs)
elif matches==4 add 4 not in found:
found.append(4)
print ("Cool! 4 matches on try", costs)
...
... |
7,533,677 | ```
a.zip---
-- b.txt
-- c.txt
-- d.txt
```
Methods to process the zip files with Python,
I could expand the zip file to a temporary directory, then process each txt file one bye one
Here, I am more interested to know whether or not python provides such a way so that
I don't have to manually expan... | 2011/09/23 | [
"https://Stackoverflow.com/questions/7533677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/391104/"
] | The [Python standard library](http://docs.python.org/library/zipfile.html) helps you.
Doug Hellman writes very informative posts about selected modules: <https://pymotw.com/3/zipfile/>
To comment on Davids post: From Python 2.7 on the Zipfile object provides a context manager, so the recommended way would be:
```
im... | Yes you can process each file by itself. Take a look at the tutorial [here](http://effbot.org/librarybook/zipfile.htm). For your needs you can do something like this example from that tutorial:
```
import zipfile
file = zipfile.ZipFile("zipfile.zip", "r")
for name in file.namelist():
data = file.read(name)
pri... |
58,381,152 | In training a neural network in Tensorflow 2.0 in python, I'm noticing that training accuracy and loss change dramatically between epochs. I'm aware that the metrics printed are an average over the entire epoch, but accuracy seems to drop significantly after each epoch, despite the average always increasing.
The loss... | 2019/10/14 | [
"https://Stackoverflow.com/questions/58381152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4607066/"
] | It seems this phenomenon comes from the fact that the model has a high batch-to-batch variance in terms of accuracy and loss. This is illustrated if I take a graph of the model with the actual metrics per step as opposed to the average over the epoch:
[ doens't work in Windows with mixed slashes. But kerastuner forms the path with backslashes. So I sh... | The problem it would appear is a Windows issue. Running the same code in a Linux environment had no issue in this regard. |
59,439,124 | The relatively new keras-tuner module for tensorflow-2 is causing the error 'Failed to create a NewWriteableFile'. The tuner.search function is working, it is only after the trial completes that the error is thrown. This is a tutorial from the sentdex Youtube channel.
Here is the code:
```
from tensorflow import kera... | 2019/12/21 | [
"https://Stackoverflow.com/questions/59439124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9447938/"
] | I had the similas problem while using kerastuner in Windows and I've solved it:
1. The first issue is that the path to the log directory may be too long. I had to reduced it.
2. The second problem is that python (or tf) doens't work in Windows with mixed slashes. But kerastuner forms the path with backslashes. So I sh... | In my case, the path exceeds the maximum length of path in windows because the length of generated path by Keras Turner is about 170. After I make my folder shorter, it works normally. |
54,547,986 | I couldn't figure out why I'm getting a `NameError` when trying to access a function inside the class.
This is the code I am having a problem with. Am I missing something?
```
class ArmstrongNumber:
def cubesum(num):
return sum([int(i)**3 for i in list(str(num))])
def PrintArmstrong(num):
if... | 2019/02/06 | [
"https://Stackoverflow.com/questions/54547986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10361602/"
] | Use `classname` before method:
```
class ArmstrongNumber:
def cubesum(num):
return sum([int(i)**3 for i in list(str(num))])
def PrintArmstrong(num):
if ArmstrongNumber.cubesum(num) == num:
return "Armstrong Number"
return "Not an Armstrong Number"
def Armstrong(num):
... | this should be your actual solution if you really want to use class
```
class ArmstrongNumber(object):
def cubesum(self, num):
return sum([int(i)**3 for i in list(str(num))])
def PrintArmstrong(self, num):
if self.cubesum(num) == num:
return "Armstrong Number"
return "Not ... |
32,562,253 | I am trying to run multiple calculations with UI using Tkinter in python where i have to display all the outputs for all the calculations. The problem is, the output for the first calculation is fine but the outputs for further calculations seems to be calculated out of default values. I came to know that i should dest... | 2015/09/14 | [
"https://Stackoverflow.com/questions/32562253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5325381/"
] | Temporary tables always gets created in TempDb. However, it is not necessary that size of TempDb is only due to temporary tables. TempDb is used in various ways
1. Internal objects (Sort & spool, CTE, index rebuild, hash join etc)
2. User objects (Temporary table, table variables)
3. Version store (AFTER/INSTEAD OF tr... | Perhaps you can use following SQL command on temp db files seperately
```
DBCC SHRINKFILE
```
Please refer to <https://support.microsoft.com/en-us/kb/307487> for more information |
5,440,550 | The sample application on the android developers site validates the purchase json using java code. Has anybody had any luck working out how to validate the purchase in python. In particular in GAE?
The following are the relevant excerpts from the android in-app billing [example program](http://developer.android.com/gu... | 2011/03/26 | [
"https://Stackoverflow.com/questions/5440550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/677760/"
] | Here's how i did it:
```
from Crypto.Hash import SHA
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from base64 import b64decode
def chunks(s, n):
for start in range(0, len(s), n):
yield s[start:start+n]
def pem_format(key):
return '\n'.join([
'-----BEGIN PUBLIC KEY-... | I finally figured out that your base64 encoded public key from Google Play is an X.509 subjectPublicKeyInfo DER SEQUENCE, and that the signature scheme is RSASSA-PKCS1-v1\_5 and not RSASSA-PSS. If you have [PyCrypto](https://www.dlitz.net/software/pycrypto/) installed, it's actually quite easy:
```
import base64
from ... |
5,440,550 | The sample application on the android developers site validates the purchase json using java code. Has anybody had any luck working out how to validate the purchase in python. In particular in GAE?
The following are the relevant excerpts from the android in-app billing [example program](http://developer.android.com/gu... | 2011/03/26 | [
"https://Stackoverflow.com/questions/5440550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/677760/"
] | Here's how i did it:
```
from Crypto.Hash import SHA
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from base64 import b64decode
def chunks(s, n):
for start in range(0, len(s), n):
yield s[start:start+n]
def pem_format(key):
return '\n'.join([
'-----BEGIN PUBLIC KEY-... | Now that we're in 2016, here's how to do it with `cryptography`:
```
import base64
import binascii
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetr... |
5,440,550 | The sample application on the android developers site validates the purchase json using java code. Has anybody had any luck working out how to validate the purchase in python. In particular in GAE?
The following are the relevant excerpts from the android in-app billing [example program](http://developer.android.com/gu... | 2011/03/26 | [
"https://Stackoverflow.com/questions/5440550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/677760/"
] | I finally figured out that your base64 encoded public key from Google Play is an X.509 subjectPublicKeyInfo DER SEQUENCE, and that the signature scheme is RSASSA-PKCS1-v1\_5 and not RSASSA-PSS. If you have [PyCrypto](https://www.dlitz.net/software/pycrypto/) installed, it's actually quite easy:
```
import base64
from ... | Now that we're in 2016, here's how to do it with `cryptography`:
```
import base64
import binascii
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetr... |
44,972,219 | I’m pretty new to Python and I just start to understand the basics.
I’m trying to run a script in a loop to check the temperatures and if the outside temp getting higher than inside or the opposite, the function should print it once and continue to check every 5 seconds, for changed state.
I found a similar [questions]... | 2017/07/07 | [
"https://Stackoverflow.com/questions/44972219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8271048/"
] | Its been long time, but for future readers thought to share some info.
There is a good article that explains the `getItemLayout`, please find it [here](https://medium.com/@jsoendermann/sectionlist-and-getitemlayout-2293b0b916fb)
I also faced `data[index]` as `undefined`. The reason is that `index` is calculated consi... | For some reason the `react-native-get-item-layout` package keeps crashing with `"height: <<NaN>>"` so I had to write my [own RN SectionList getItemLayout](https://npmjs.com/package/sectionlist-get-itemlayout) . It uses the same interface as the former.
Like the `package` it's also an `O(n)`. |
44,972,219 | I’m pretty new to Python and I just start to understand the basics.
I’m trying to run a script in a loop to check the temperatures and if the outside temp getting higher than inside or the opposite, the function should print it once and continue to check every 5 seconds, for changed state.
I found a similar [questions]... | 2017/07/07 | [
"https://Stackoverflow.com/questions/44972219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8271048/"
] | Similar to uxxi we ended up writing up our own implementation based off of `react-native-get-item-layout` but there is an important distinction to make.
Wiring either method to the SectionList getItemLayout parameter re-executes the same iterations over the data for every item being rendered. The overhead added by th... | For some reason the `react-native-get-item-layout` package keeps crashing with `"height: <<NaN>>"` so I had to write my [own RN SectionList getItemLayout](https://npmjs.com/package/sectionlist-get-itemlayout) . It uses the same interface as the former.
Like the `package` it's also an `O(n)`. |
9,866,923 | I'm trying to solve this newbie puzzle:
I've created this function:
```
def bucket_loop(htable, key):
bucket = hashtable_get_bucket(htable, key)
for entry in bucket:
if entry[0] == key:
return entry[1]
return None
```
And I have to call it in two ot... | 2012/03/26 | [
"https://Stackoverflow.com/questions/9866923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/955883/"
] | In general, there are three things you can do:
1. Write “setter” functions (ex, `bucket_set`)
2. Return mutable values (ex, `bucket_get(table, key).append(42)` if the value is a `list`)
3. Use a class which overrides `__getitem__` and `__setitem__`
For example, you could have a class like like:
```
class Bucket(obje... | One option that would require few changes would be adding a third argument to `bucket_loop`, optional, to use for assignment:
```
empty = object() # An object that's guaranteed not to be in your htable
def bucket_loop(htable, key, value=empty):
bucket = hashtable_get_bucket(htable, key)
for entry in bucket:
... |
9,866,923 | I'm trying to solve this newbie puzzle:
I've created this function:
```
def bucket_loop(htable, key):
bucket = hashtable_get_bucket(htable, key)
for entry in bucket:
if entry[0] == key:
return entry[1]
return None
```
And I have to call it in two ot... | 2012/03/26 | [
"https://Stackoverflow.com/questions/9866923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/955883/"
] | In general, there are three things you can do:
1. Write “setter” functions (ex, `bucket_set`)
2. Return mutable values (ex, `bucket_get(table, key).append(42)` if the value is a `list`)
3. Use a class which overrides `__getitem__` and `__setitem__`
For example, you could have a class like like:
```
class Bucket(obje... | So you're basically cheating at udacity, which is an online cs class / university? Funny part is you couldn't even declare the question properly. Next time cheat thoroughly and paste the two functions you're supposed to simplify and request someone simplify them by creating a third function with the overlapping code wi... |
9,866,923 | I'm trying to solve this newbie puzzle:
I've created this function:
```
def bucket_loop(htable, key):
bucket = hashtable_get_bucket(htable, key)
for entry in bucket:
if entry[0] == key:
return entry[1]
return None
```
And I have to call it in two ot... | 2012/03/26 | [
"https://Stackoverflow.com/questions/9866923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/955883/"
] | One option that would require few changes would be adding a third argument to `bucket_loop`, optional, to use for assignment:
```
empty = object() # An object that's guaranteed not to be in your htable
def bucket_loop(htable, key, value=empty):
bucket = hashtable_get_bucket(htable, key)
for entry in bucket:
... | So you're basically cheating at udacity, which is an online cs class / university? Funny part is you couldn't even declare the question properly. Next time cheat thoroughly and paste the two functions you're supposed to simplify and request someone simplify them by creating a third function with the overlapping code wi... |
62,065,607 | I run into problems when calling Spark's MinHashLSH's approxSimilarityJoin on a dataframe of (name\_id, name) combinations.
**A summary of the problem I try to solve:**
I have a dataframe of around 30 million unique (name\_id, name) combinations for company names. Some of those names refer to the same company, but a... | 2020/05/28 | [
"https://Stackoverflow.com/questions/62065607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12383245/"
] | `approxSimilarityJoin` will only parallelize well across workers if the tokens being input into MinHash are sufficiently distinct. Since individual character tokens appear frequently across many records; include an `NGram` transformation on your character list to make the appearance of each token less frequent; this wi... | Thanks for the detailed explanation.
What threshold are you using a and how are reducing false -ve? |
62,065,607 | I run into problems when calling Spark's MinHashLSH's approxSimilarityJoin on a dataframe of (name\_id, name) combinations.
**A summary of the problem I try to solve:**
I have a dataframe of around 30 million unique (name\_id, name) combinations for company names. Some of those names refer to the same company, but a... | 2020/05/28 | [
"https://Stackoverflow.com/questions/62065607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12383245/"
] | The answer of @lokk3r really helped me in the right direction here. However, there were some other things that I had to do before I was able to run the program without errors. I will share them to help people out that are having similar problems:
* First of all, I used `NGrams` as @lokk3r suggested instead of just sin... | Thanks for the detailed explanation.
What threshold are you using a and how are reducing false -ve? |
29,970,679 | I have this simple code in Python:
```
import sys
class Crawler(object):
def __init__(self, num_of_runs):
self.run_number = 1
self.num_of_runs = num_of_runs
def single_run(self):
#do stuff
pass
def run(self):
while self.run_number <= self.num_of_runs:
self.single_run()
print s... | 2015/04/30 | [
"https://Stackoverflow.com/questions/29970679",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3717289/"
] | ```
num_of_runs = sys.argv[1]
```
`num_of_runs` is a string at that stage.
```
while self.run_number <= self.num_of_runs:
```
You are comparing a `string` and an `int` here.
A simple way to fix this is to convert it to an int
```
num_of_runs = int(sysargv[1])
```
Another way to deal with this is to use `argpar... | When accepting input from the command line, data is passed as a string. You need to convert this value to an `int` before you pass it to your `Crawler` class:
```
num_of_runs = int(sys.argv[1])
```
---
You can also utilize this to determine if the input is valid. If it doesn't convert to an int, it will throw an er... |
54,873,222 | I have a scenario where the data is like below in a text file:
```
first_id;"second_id";"name";"performer";"criteria"
12345;"13254";"abc";"def";"criteria_1"
65432;"13254";"abc";"ghi";"criteria_1"
24561;"13254";"abc";"pqr";"criteria_2"
24571;"13254";"abc";"jkl";"criteria_2"
first_id;"second_id";"name";"performer";"cri... | 2019/02/25 | [
"https://Stackoverflow.com/questions/54873222",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6909182/"
] | Here's a general answer that will scale up to as many data frames as you have:
```
library(dplyr)
df_list = list(df5 = df5, df6 = df6)
library(dplyr)
big_df = bind_rows(df_list, .id = "source")
big_df = big_df %>% group_by(Year) %>% summarize_if(is.numeric, mean) %>%
mutate(source = "Mean") %>%
bind_rows(big_df)
... | If I understand you right, you would like to plot for the year 2013 10,054185
If you have for every year one line you can create a new col and add this to your existing ggplot:
```
df <- dataframe5$Year
df$total5 <- dataframe5$Total
df$total6 <- dataframe6$Total
df$totalmean <- (df$total5+df$total6)/2
```
By plotti... |
41,951,204 | I am new to python. I'm trying to connect my client with the broker. But I am getting an error "global name 'mqttClient' is not defined".
Can anyone help me to what is wrong with my code.
Here is my code,
**Test.py**
```
#!/usr/bin/env python
import time, threading
import mqttConnector
class UtilsThread(object):
... | 2017/01/31 | [
"https://Stackoverflow.com/questions/41951204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7134849/"
] | * **For MongoDB -**
Use AWS quick start MongoDB
<http://docs.aws.amazon.com/quickstart/latest/mongodb/overview.html>
<http://docs.aws.amazon.com/quickstart/latest/mongodb/architecture.html>
* **For rest of the docker stack i.e NodeJS & Nginx -**
Use the AWS ElasticBeanstalk Multi Container Deployment
<http://docs.aw... | Elastic Beanstalk supports Docker, as [documented here](http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_docker.html). Elastic Beanstalk would manage the EC2 resources for you so that you, which should make things a bit easier on you. |
41,951,204 | I am new to python. I'm trying to connect my client with the broker. But I am getting an error "global name 'mqttClient' is not defined".
Can anyone help me to what is wrong with my code.
Here is my code,
**Test.py**
```
#!/usr/bin/env python
import time, threading
import mqttConnector
class UtilsThread(object):
... | 2017/01/31 | [
"https://Stackoverflow.com/questions/41951204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7134849/"
] | * **For MongoDB -**
Use AWS quick start MongoDB
<http://docs.aws.amazon.com/quickstart/latest/mongodb/overview.html>
<http://docs.aws.amazon.com/quickstart/latest/mongodb/architecture.html>
* **For rest of the docker stack i.e NodeJS & Nginx -**
Use the AWS ElasticBeanstalk Multi Container Deployment
<http://docs.aw... | You can install [Kontena](https://www.kontena.io) to [AWS](https://kontena.io/docs/getting-started/installing/aws-ec2.html) and use that to deploy your application to production environment (of course other cloud providers are also supported). Transition from Docker Compose is very smooth since [kontena.yml](http://kon... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.