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 |
|---|---|---|---|---|---|
14,657,433 | How do I calculate correlation matrix in python? I have an n-dimensional vector in which each element has 5 dimension. For example my vector looks like
```
[
[0.1, .32, .2, 0.4, 0.8],
[.23, .18, .56, .61, .12],
[.9, .3, .6, .5, .3],
[.34, .75, .91, .19, .21]
]
```
In this case dimension of the vector ... | 2013/02/02 | [
"https://Stackoverflow.com/questions/14657433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1964587/"
] | You can also use np.array if you don't want to write your matrix all over again.
```
import numpy as np
a = np.array([ [0.1, .32, .2, 0.4, 0.8], [.23, .18, .56, .61, .12], [.9, .3, .6, .5, .3], [.34, .75, .91, .19, .21]])
b = np.corrcoef(a)
print b
``` | As I almost missed that comment by @Anton Tarasenko, I'll provide a new answer. So given your array:
```
a = np.array([[0.1, .32, .2, 0.4, 0.8],
[.23, .18, .56, .61, .12],
[.9, .3, .6, .5, .3],
[.34, .75, .91, .19, .21]])
```
If you want the correlation matrix of you... |
6,213,336 | I'm reading lines from a file to then work with them. Each line is composed solely by float numbers.
I have pretty much everything sorted up to convert the lines into arrays.
I basically do (pseudopython code)
```
line=file.readlines()
line=line.split(' ') # Or whatever separator
array=np.array(line)
#And then i... | 2011/06/02 | [
"https://Stackoverflow.com/questions/6213336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/486262/"
] | Quick answer:
```
arrays = []
for line in open(your_file): # no need to use readlines if you don't want to store them
# use a list comprehension to build your array on the fly
new_array = np.array((array.float(i) for i in line.split(' ')))
arrays.append(new_array)
```
If you process often this kind of d... | How about the following:
```
import numpy as np
arrays = []
for line in open('data.txt'):
arrays.append(np.array([float(val) for val in line.rstrip('\n').split(' ') if val != '']))
``` |
6,213,336 | I'm reading lines from a file to then work with them. Each line is composed solely by float numbers.
I have pretty much everything sorted up to convert the lines into arrays.
I basically do (pseudopython code)
```
line=file.readlines()
line=line.split(' ') # Or whatever separator
array=np.array(line)
#And then i... | 2011/06/02 | [
"https://Stackoverflow.com/questions/6213336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/486262/"
] | Quick answer:
```
arrays = []
for line in open(your_file): # no need to use readlines if you don't want to store them
# use a list comprehension to build your array on the fly
new_array = np.array((array.float(i) for i in line.split(' ')))
arrays.append(new_array)
```
If you process often this kind of d... | [If you want a numpy array and each row in the text file has the same number of values](http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html#numpy.loadtxt):
```
a = numpy.loadtxt('data.txt')
```
Without numpy:
```
with open('data.txt') as f:
arrays = list(csv.reader(f, delimiter=' ', quoting=c... |
6,213,336 | I'm reading lines from a file to then work with them. Each line is composed solely by float numbers.
I have pretty much everything sorted up to convert the lines into arrays.
I basically do (pseudopython code)
```
line=file.readlines()
line=line.split(' ') # Or whatever separator
array=np.array(line)
#And then i... | 2011/06/02 | [
"https://Stackoverflow.com/questions/6213336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/486262/"
] | Quick answer:
```
arrays = []
for line in open(your_file): # no need to use readlines if you don't want to store them
# use a list comprehension to build your array on the fly
new_array = np.array((array.float(i) for i in line.split(' ')))
arrays.append(new_array)
```
If you process often this kind of d... | One possible one-liner:
```
a_list = [map(float, line.split(' ')) for line in a_file]
```
Note that I used `map()` here instead of a nested list comprehension to aid readability.
If you want a numpy array:
```
an_array = np.array([map(float, line.split(' ')) for line in a_file])
``` |
6,213,336 | I'm reading lines from a file to then work with them. Each line is composed solely by float numbers.
I have pretty much everything sorted up to convert the lines into arrays.
I basically do (pseudopython code)
```
line=file.readlines()
line=line.split(' ') # Or whatever separator
array=np.array(line)
#And then i... | 2011/06/02 | [
"https://Stackoverflow.com/questions/6213336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/486262/"
] | Quick answer:
```
arrays = []
for line in open(your_file): # no need to use readlines if you don't want to store them
# use a list comprehension to build your array on the fly
new_array = np.array((array.float(i) for i in line.split(' ')))
arrays.append(new_array)
```
If you process often this kind of d... | I would use regular expressions
import re
```
all_lines = ''.join( file.readlines() )
new_array = np.array( re.findall('[\d.E+-]+', all_lines), float)
np.reshape( new_array, (m,n) )
```
First merging the files into one long string, and then extracting only the expressions corresponding to floats ( **'[\d.E+-]'** ... |
6,213,336 | I'm reading lines from a file to then work with them. Each line is composed solely by float numbers.
I have pretty much everything sorted up to convert the lines into arrays.
I basically do (pseudopython code)
```
line=file.readlines()
line=line.split(' ') # Or whatever separator
array=np.array(line)
#And then i... | 2011/06/02 | [
"https://Stackoverflow.com/questions/6213336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/486262/"
] | [If you want a numpy array and each row in the text file has the same number of values](http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html#numpy.loadtxt):
```
a = numpy.loadtxt('data.txt')
```
Without numpy:
```
with open('data.txt') as f:
arrays = list(csv.reader(f, delimiter=' ', quoting=c... | How about the following:
```
import numpy as np
arrays = []
for line in open('data.txt'):
arrays.append(np.array([float(val) for val in line.rstrip('\n').split(' ') if val != '']))
``` |
6,213,336 | I'm reading lines from a file to then work with them. Each line is composed solely by float numbers.
I have pretty much everything sorted up to convert the lines into arrays.
I basically do (pseudopython code)
```
line=file.readlines()
line=line.split(' ') # Or whatever separator
array=np.array(line)
#And then i... | 2011/06/02 | [
"https://Stackoverflow.com/questions/6213336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/486262/"
] | How about the following:
```
import numpy as np
arrays = []
for line in open('data.txt'):
arrays.append(np.array([float(val) for val in line.rstrip('\n').split(' ') if val != '']))
``` | One possible one-liner:
```
a_list = [map(float, line.split(' ')) for line in a_file]
```
Note that I used `map()` here instead of a nested list comprehension to aid readability.
If you want a numpy array:
```
an_array = np.array([map(float, line.split(' ')) for line in a_file])
``` |
6,213,336 | I'm reading lines from a file to then work with them. Each line is composed solely by float numbers.
I have pretty much everything sorted up to convert the lines into arrays.
I basically do (pseudopython code)
```
line=file.readlines()
line=line.split(' ') # Or whatever separator
array=np.array(line)
#And then i... | 2011/06/02 | [
"https://Stackoverflow.com/questions/6213336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/486262/"
] | How about the following:
```
import numpy as np
arrays = []
for line in open('data.txt'):
arrays.append(np.array([float(val) for val in line.rstrip('\n').split(' ') if val != '']))
``` | I would use regular expressions
import re
```
all_lines = ''.join( file.readlines() )
new_array = np.array( re.findall('[\d.E+-]+', all_lines), float)
np.reshape( new_array, (m,n) )
```
First merging the files into one long string, and then extracting only the expressions corresponding to floats ( **'[\d.E+-]'** ... |
6,213,336 | I'm reading lines from a file to then work with them. Each line is composed solely by float numbers.
I have pretty much everything sorted up to convert the lines into arrays.
I basically do (pseudopython code)
```
line=file.readlines()
line=line.split(' ') # Or whatever separator
array=np.array(line)
#And then i... | 2011/06/02 | [
"https://Stackoverflow.com/questions/6213336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/486262/"
] | [If you want a numpy array and each row in the text file has the same number of values](http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html#numpy.loadtxt):
```
a = numpy.loadtxt('data.txt')
```
Without numpy:
```
with open('data.txt') as f:
arrays = list(csv.reader(f, delimiter=' ', quoting=c... | One possible one-liner:
```
a_list = [map(float, line.split(' ')) for line in a_file]
```
Note that I used `map()` here instead of a nested list comprehension to aid readability.
If you want a numpy array:
```
an_array = np.array([map(float, line.split(' ')) for line in a_file])
``` |
6,213,336 | I'm reading lines from a file to then work with them. Each line is composed solely by float numbers.
I have pretty much everything sorted up to convert the lines into arrays.
I basically do (pseudopython code)
```
line=file.readlines()
line=line.split(' ') # Or whatever separator
array=np.array(line)
#And then i... | 2011/06/02 | [
"https://Stackoverflow.com/questions/6213336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/486262/"
] | [If you want a numpy array and each row in the text file has the same number of values](http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html#numpy.loadtxt):
```
a = numpy.loadtxt('data.txt')
```
Without numpy:
```
with open('data.txt') as f:
arrays = list(csv.reader(f, delimiter=' ', quoting=c... | I would use regular expressions
import re
```
all_lines = ''.join( file.readlines() )
new_array = np.array( re.findall('[\d.E+-]+', all_lines), float)
np.reshape( new_array, (m,n) )
```
First merging the files into one long string, and then extracting only the expressions corresponding to floats ( **'[\d.E+-]'** ... |
6,213,336 | I'm reading lines from a file to then work with them. Each line is composed solely by float numbers.
I have pretty much everything sorted up to convert the lines into arrays.
I basically do (pseudopython code)
```
line=file.readlines()
line=line.split(' ') # Or whatever separator
array=np.array(line)
#And then i... | 2011/06/02 | [
"https://Stackoverflow.com/questions/6213336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/486262/"
] | One possible one-liner:
```
a_list = [map(float, line.split(' ')) for line in a_file]
```
Note that I used `map()` here instead of a nested list comprehension to aid readability.
If you want a numpy array:
```
an_array = np.array([map(float, line.split(' ')) for line in a_file])
``` | I would use regular expressions
import re
```
all_lines = ''.join( file.readlines() )
new_array = np.array( re.findall('[\d.E+-]+', all_lines), float)
np.reshape( new_array, (m,n) )
```
First merging the files into one long string, and then extracting only the expressions corresponding to floats ( **'[\d.E+-]'** ... |
47,057,572 | I tried to use pytesseract:
```
import pytesseract
from PIL import Image
pytesseract.pytesseract.tesseract_cmd = 'C:\\Python27\\scripts\\pytesseract.exe'
im = Image.open('Download.png')
print pytesseract.image_to_string(im)
```
But I got this error:
```
Traceback (most recent call last):
... | 2017/11/01 | [
"https://Stackoverflow.com/questions/47057572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8500407/"
] | You need to install tesseract using windows installer available [here](https://github.com/UB-Mannheim/tesseract/wiki). Then you should install the python wrapper as:
```
pip install pytesseract
```
Then you should also set the tesseract path in your script after importing pytesseract library as below (Please do not ... | I think there is something wrong with your path 'C:\Python27\scripts\pytesseract.exe', This seems to point to the pytessaract.py code (hence the error has pytessaract.py on it - the exact error is mentioned in the main function of pytessaract.py which runs only if **name** == "**main**" ).
The path must actually poin... |
65,040,971 | I setup a new Debian 10 (Buster) instance on AWS EC2, and was able to install a pip3 package that depended on netifaces, but when I came back to it the next day the package is breaking reporting an error in netifaces. If I try to run pip3 install netifaces I get the same error:
```
~$ pip3 install netifaces
Collecting... | 2020/11/27 | [
"https://Stackoverflow.com/questions/65040971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/439005/"
] | `HTMLParser().unescape` was removed in Python 3.9. Compare [the code in Python 3.8](https://github.com/python/cpython/blob/v3.8.0/Lib/html/parser.py#L466) vs [Python 3.9](https://github.com/python/cpython/blob/v3.9.0/Lib/html/parser.py).
The error seems to be a bug in `setuptools`. Try to upgrade `setuptools`. Or use ... | I was facing this issue in PyCharm 2018. Apart from upgrading `setuptools` as mentioned above, I also had to upgrade to `PyCharm 2020.3.4` to solve this issue. Related bug on PyCharm issue tracker: <https://youtrack.jetbrains.com/issue/PY-39579>
Hope this helps someone avoid spending hours trying to debug this. |
65,040,971 | I setup a new Debian 10 (Buster) instance on AWS EC2, and was able to install a pip3 package that depended on netifaces, but when I came back to it the next day the package is breaking reporting an error in netifaces. If I try to run pip3 install netifaces I get the same error:
```
~$ pip3 install netifaces
Collecting... | 2020/11/27 | [
"https://Stackoverflow.com/questions/65040971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/439005/"
] | `HTMLParser().unescape` was removed in Python 3.9. Compare [the code in Python 3.8](https://github.com/python/cpython/blob/v3.8.0/Lib/html/parser.py#L466) vs [Python 3.9](https://github.com/python/cpython/blob/v3.9.0/Lib/html/parser.py).
The error seems to be a bug in `setuptools`. Try to upgrade `setuptools`. Or use ... | Downgrading to any older python3 version is not the solution and most of the time upgrading setuptools won't fix the issue. The proper solution that worked for me to work with pip using python3.9 is the following on Ubuntu18:
locate /usr/lib/python3/dist-packages/setuptools/py33compact.py33
and change
```
# unescape =... |
65,040,971 | I setup a new Debian 10 (Buster) instance on AWS EC2, and was able to install a pip3 package that depended on netifaces, but when I came back to it the next day the package is breaking reporting an error in netifaces. If I try to run pip3 install netifaces I get the same error:
```
~$ pip3 install netifaces
Collecting... | 2020/11/27 | [
"https://Stackoverflow.com/questions/65040971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/439005/"
] | `HTMLParser().unescape` was removed in Python 3.9. Compare [the code in Python 3.8](https://github.com/python/cpython/blob/v3.8.0/Lib/html/parser.py#L466) vs [Python 3.9](https://github.com/python/cpython/blob/v3.9.0/Lib/html/parser.py).
The error seems to be a bug in `setuptools`. Try to upgrade `setuptools`. Or use ... | I had python3.6 and related packages through deb management.
Needed python3.9 for side project and the solution to fix pip and `AttributeError: 'HTMLParser' object has no attribute 'unescape'`
was to update pip for python3.9 locally for one user:
```
python3.9 -m pip install --upgrade pip
```
now installing python3.... |
65,040,971 | I setup a new Debian 10 (Buster) instance on AWS EC2, and was able to install a pip3 package that depended on netifaces, but when I came back to it the next day the package is breaking reporting an error in netifaces. If I try to run pip3 install netifaces I get the same error:
```
~$ pip3 install netifaces
Collecting... | 2020/11/27 | [
"https://Stackoverflow.com/questions/65040971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/439005/"
] | I was facing this issue in PyCharm 2018. Apart from upgrading `setuptools` as mentioned above, I also had to upgrade to `PyCharm 2020.3.4` to solve this issue. Related bug on PyCharm issue tracker: <https://youtrack.jetbrains.com/issue/PY-39579>
Hope this helps someone avoid spending hours trying to debug this. | Downgrading to any older python3 version is not the solution and most of the time upgrading setuptools won't fix the issue. The proper solution that worked for me to work with pip using python3.9 is the following on Ubuntu18:
locate /usr/lib/python3/dist-packages/setuptools/py33compact.py33
and change
```
# unescape =... |
65,040,971 | I setup a new Debian 10 (Buster) instance on AWS EC2, and was able to install a pip3 package that depended on netifaces, but when I came back to it the next day the package is breaking reporting an error in netifaces. If I try to run pip3 install netifaces I get the same error:
```
~$ pip3 install netifaces
Collecting... | 2020/11/27 | [
"https://Stackoverflow.com/questions/65040971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/439005/"
] | I had python3.6 and related packages through deb management.
Needed python3.9 for side project and the solution to fix pip and `AttributeError: 'HTMLParser' object has no attribute 'unescape'`
was to update pip for python3.9 locally for one user:
```
python3.9 -m pip install --upgrade pip
```
now installing python3.... | Downgrading to any older python3 version is not the solution and most of the time upgrading setuptools won't fix the issue. The proper solution that worked for me to work with pip using python3.9 is the following on Ubuntu18:
locate /usr/lib/python3/dist-packages/setuptools/py33compact.py33
and change
```
# unescape =... |
8,778,865 | I was writing a program in python
```
import sys
def func(N, M):
if N == M:
return 0.00
else:
if M == 0:
return pow(2, N+1) - 2.00
else :
return 1.00 + (0.5)*func(N, M+1) + 0.5*func(N, 0)
def main(*args):
test_cases = int(raw_input())
while test_cases:
... | 2012/01/08 | [
"https://Stackoverflow.com/questions/8778865",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1032610/"
] | Floats in Python are IEEE doubles: they are not unlimited precision. But if your computation only needs integers, then just use integers: they are unlimited precision. Unfortunately, I think your computation does not stay within the integers.
There are third-party packages built on GMP that provide arbitrary-precision... | Consider using an arbitrary precision floating-point library, for example the [bigfloat](http://packages.python.org/bigfloat/) package, or [mpmath](http://code.google.com/p/mpmath/). |
8,778,865 | I was writing a program in python
```
import sys
def func(N, M):
if N == M:
return 0.00
else:
if M == 0:
return pow(2, N+1) - 2.00
else :
return 1.00 + (0.5)*func(N, M+1) + 0.5*func(N, 0)
def main(*args):
test_cases = int(raw_input())
while test_cases:
... | 2012/01/08 | [
"https://Stackoverflow.com/questions/8778865",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1032610/"
] | I maintain one of the Python to GMP/MPFR libraries and I tested your function. After checking the results and looking at your function, I think your function remains entirely in the integers. The following function returns the same values:
```
def func(N, M):
if M == 0:
return 2**(N+1) - 2
elif N == M:... | Consider using an arbitrary precision floating-point library, for example the [bigfloat](http://packages.python.org/bigfloat/) package, or [mpmath](http://code.google.com/p/mpmath/). |
63,002,403 | Is this as expected? I thought in Python, variables are pointers to objects in memory. If I modify the python list that a variable points to once, the memory reference changes. But if I modify it again, the memory reference is the same?
```
>>> id(mylist)
Traceback (most recent call last):
File "<stdin>", line 1, in... | 2020/07/20 | [
"https://Stackoverflow.com/questions/63002403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3552698/"
] | You are correct in that the memory references should change. Take a careful look at the memory addresses: they're not identical.
Edit: Regarding your edit, the memory address only changes on reassignment of the variable. The memory of the variable stays the same if you mutate the list. | Take a look of the id's you provided . There are completely different. 4338643744 != 4338953744. Look the first 5 numbers: 43386 != 43389. Everything is working as expects due to memory reference is changing properly. |
63,002,403 | Is this as expected? I thought in Python, variables are pointers to objects in memory. If I modify the python list that a variable points to once, the memory reference changes. But if I modify it again, the memory reference is the same?
```
>>> id(mylist)
Traceback (most recent call last):
File "<stdin>", line 1, in... | 2020/07/20 | [
"https://Stackoverflow.com/questions/63002403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3552698/"
] | You are correct in that the memory references should change. Take a careful look at the memory addresses: they're not identical.
Edit: Regarding your edit, the memory address only changes on reassignment of the variable. The memory of the variable stays the same if you mutate the list. | The memory addresses are not identical. It is behaving as expected -
`mylist = ['123']` --> Points to memory address **4338643744** (See 8643 in between)
[](https://i.stack.imgur.com/APDkj.png)
`mylist = ['123','a']` --> Points to memory address **4... |
63,002,403 | Is this as expected? I thought in Python, variables are pointers to objects in memory. If I modify the python list that a variable points to once, the memory reference changes. But if I modify it again, the memory reference is the same?
```
>>> id(mylist)
Traceback (most recent call last):
File "<stdin>", line 1, in... | 2020/07/20 | [
"https://Stackoverflow.com/questions/63002403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3552698/"
] | You are correct in that the memory references should change. Take a careful look at the memory addresses: they're not identical.
Edit: Regarding your edit, the memory address only changes on reassignment of the variable. The memory of the variable stays the same if you mutate the list. | For a mutable object, the `id` which is a `unique identifier for the specified object` will be based on the value itself.
[](https://i.stack.imgur.com/eJqDt.png)refere[](https://i.sta... |
63,002,403 | Is this as expected? I thought in Python, variables are pointers to objects in memory. If I modify the python list that a variable points to once, the memory reference changes. But if I modify it again, the memory reference is the same?
```
>>> id(mylist)
Traceback (most recent call last):
File "<stdin>", line 1, in... | 2020/07/20 | [
"https://Stackoverflow.com/questions/63002403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3552698/"
] | The memory addresses are not identical. It is behaving as expected -
`mylist = ['123']` --> Points to memory address **4338643744** (See 8643 in between)
[](https://i.stack.imgur.com/APDkj.png)
`mylist = ['123','a']` --> Points to memory address **4... | Take a look of the id's you provided . There are completely different. 4338643744 != 4338953744. Look the first 5 numbers: 43386 != 43389. Everything is working as expects due to memory reference is changing properly. |
63,002,403 | Is this as expected? I thought in Python, variables are pointers to objects in memory. If I modify the python list that a variable points to once, the memory reference changes. But if I modify it again, the memory reference is the same?
```
>>> id(mylist)
Traceback (most recent call last):
File "<stdin>", line 1, in... | 2020/07/20 | [
"https://Stackoverflow.com/questions/63002403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3552698/"
] | Take a look of the id's you provided . There are completely different. 4338643744 != 4338953744. Look the first 5 numbers: 43386 != 43389. Everything is working as expects due to memory reference is changing properly. | For a mutable object, the `id` which is a `unique identifier for the specified object` will be based on the value itself.
[](https://i.stack.imgur.com/eJqDt.png)refere[](https://i.sta... |
63,002,403 | Is this as expected? I thought in Python, variables are pointers to objects in memory. If I modify the python list that a variable points to once, the memory reference changes. But if I modify it again, the memory reference is the same?
```
>>> id(mylist)
Traceback (most recent call last):
File "<stdin>", line 1, in... | 2020/07/20 | [
"https://Stackoverflow.com/questions/63002403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3552698/"
] | The memory addresses are not identical. It is behaving as expected -
`mylist = ['123']` --> Points to memory address **4338643744** (See 8643 in between)
[](https://i.stack.imgur.com/APDkj.png)
`mylist = ['123','a']` --> Points to memory address **4... | For a mutable object, the `id` which is a `unique identifier for the specified object` will be based on the value itself.
[](https://i.stack.imgur.com/eJqDt.png)refere[](https://i.sta... |
73,648,264 | I have a json like this but much longer:
```
[
{
"id": "123",
"name": "home network configuration",
"description": "home utilities",
"definedRanges": [
{
"id": "6500b67e",
"name": "100-200",
"beginIPv4Address": "192.168.090.100",
"endIPv4Address": "192.168.090.20... | 2022/09/08 | [
"https://Stackoverflow.com/questions/73648264",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1066865/"
] | Well, you were close. Here's how you put those together:
```
map({name, definedRanges: .definedRanges | map({name, beginIPv4Address, endIPv4Address})})
```
[Online demo](https://jqplay.org/s/tHkRlLUV3K-) | Here's my shot at solutions to produce one or the other desired output:
```
map(
{ name }
+ (.definedRanges[] | {
"definedRanges.name": .name,
"definedRanges.beginIPv4Address": .beginIPv4Address,
"definedRanges.endIPv4Address": .endIPv4Address
}))
```
Output:
```json
[
{
"name": "home ... |
73,648,264 | I have a json like this but much longer:
```
[
{
"id": "123",
"name": "home network configuration",
"description": "home utilities",
"definedRanges": [
{
"id": "6500b67e",
"name": "100-200",
"beginIPv4Address": "192.168.090.100",
"endIPv4Address": "192.168.090.20... | 2022/09/08 | [
"https://Stackoverflow.com/questions/73648264",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1066865/"
] | The '*or even this*' can be achieved using:
```
map(.name as $name | .definedRanges[] | { name, beginIPv4Address, endIPv4Address} | with_entries(.key = "definedRanges." + .key) | .name = $name)
```
Which yields:
```json
[
{
"definedRanges.name": "100-200",
"definedRanges.beginIPv4Address": "192.168.090.10... | Here's my shot at solutions to produce one or the other desired output:
```
map(
{ name }
+ (.definedRanges[] | {
"definedRanges.name": .name,
"definedRanges.beginIPv4Address": .beginIPv4Address,
"definedRanges.endIPv4Address": .endIPv4Address
}))
```
Output:
```json
[
{
"name": "home ... |
295,028 | I have a very tricky situation (for my standards) in hand. I have a script that needs to read a script variable name from [ConfigParser](https://docs.python.org/2/library/configparser.html). For example, I need to read
```
self.post.id
```
from a .cfg file and use it as a variable in the script. How do I achieve thi... | 2008/11/17 | [
"https://Stackoverflow.com/questions/295028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2220518/"
] | test.ini:
```
[head]
var: self.post.id
```
python:
```
import ConfigParser
class Test:
def __init__(self):
self.post = TestPost(5)
def getPost(self):
config = ConfigParser.ConfigParser()
config.read('/path/to/test.ini')
newvar = config.get('head', 'var')
print eval(newvar)
class... | This is a bit silly.
You have a dynamic language, distributed in source form.
You're trying to make what amounts to a change to the source. Which is easy-to-read, plain text Python.
Why not just change the Python source and stop messing about with a configuration file?
It's a lot easier to have a block of code like... |
45,533,019 | I was making a permutation script with python an i looked for how to make a multidimensional array, but the only way i could find was `array3
= [ [ "" for i in range(12) ] for j in range(4) ]` Is there any way i can make it so it's defined as multidimensional but not the size of it? I also found that it's possible to ... | 2017/08/06 | [
"https://Stackoverflow.com/questions/45533019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7848729/"
] | Use `itertools.chain.from_iterable` and `itertools.product`:
```
from itertools import chain, product
for first, second in product(chain.from_iterable(array),
chain.from_iterable(array2)):
print("{}{}".format(first, second))
```
Since `array` and `array2` are lists and not arbitrary... | If I understand you correctly You'll need a 4th degree nesting:
```
array = [["a","b","c","d","e","f"],["7","8","9","0","11","12"]]
array2 = [["1","2","3","4","5","6"],["g","h","i","j","k","l"]]
for row in array: # iterate "rows"
for cell in row: # iterate "cells" in a specific "row"
for row_2 in array2... |
40,032,276 | I have a dataframe similar to:
```
id | date | value
--- | ---------- | ------
1 | 2016-01-07 | 13.90
1 | 2016-01-16 | 14.50
2 | 2016-01-09 | 10.50
2 | 2016-01-28 | 5.50
3 | 2016-01-05 | 1.50
```
I am trying to keep the most recent values for each id, like this:
```
id | date | value
--- | ... | 2016/10/13 | [
"https://Stackoverflow.com/questions/40032276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4641956/"
] | The window operator as suggested works very well to solve this problem:
```
from datetime import date
rdd = sc.parallelize([
[1, date(2016, 1, 7), 13.90],
[1, date(2016, 1, 16), 14.50],
[2, date(2016, 1, 9), 10.50],
[2, date(2016, 1, 28), 5.50],
[3, date(2016, 1, 5), 1.50]
])
df = rdd.toDF(['id',... | If you have items with the same date then you will get duplicates with the dense\_rank. You should use row\_number:
```py
from pyspark.sql.window import Window
from datetime import date
import pyspark.sql.functions as F
rdd = spark.sparkContext.parallelize([
[1, date(2016, 1, 7), 13.90],
[1, date(2016, 1, 7... |
40,032,276 | I have a dataframe similar to:
```
id | date | value
--- | ---------- | ------
1 | 2016-01-07 | 13.90
1 | 2016-01-16 | 14.50
2 | 2016-01-09 | 10.50
2 | 2016-01-28 | 5.50
3 | 2016-01-05 | 1.50
```
I am trying to keep the most recent values for each id, like this:
```
id | date | value
--- | ... | 2016/10/13 | [
"https://Stackoverflow.com/questions/40032276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4641956/"
] | The window operator as suggested works very well to solve this problem:
```
from datetime import date
rdd = sc.parallelize([
[1, date(2016, 1, 7), 13.90],
[1, date(2016, 1, 16), 14.50],
[2, date(2016, 1, 9), 10.50],
[2, date(2016, 1, 28), 5.50],
[3, date(2016, 1, 5), 1.50]
])
df = rdd.toDF(['id',... | You can use row\_number to get the record with latest date:
```
import pyspark.sql.functions as F
from pyspark.sql.window import Window
new_df = df.withColumn("row_number",F.row_number().over(Window.partitionBy(df.id).orderBy(df.date.desc()))).filter(F.col("row_number")==1).drop("row_number")
``` |
40,032,276 | I have a dataframe similar to:
```
id | date | value
--- | ---------- | ------
1 | 2016-01-07 | 13.90
1 | 2016-01-16 | 14.50
2 | 2016-01-09 | 10.50
2 | 2016-01-28 | 5.50
3 | 2016-01-05 | 1.50
```
I am trying to keep the most recent values for each id, like this:
```
id | date | value
--- | ... | 2016/10/13 | [
"https://Stackoverflow.com/questions/40032276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4641956/"
] | If you have items with the same date then you will get duplicates with the dense\_rank. You should use row\_number:
```py
from pyspark.sql.window import Window
from datetime import date
import pyspark.sql.functions as F
rdd = spark.sparkContext.parallelize([
[1, date(2016, 1, 7), 13.90],
[1, date(2016, 1, 7... | You can use row\_number to get the record with latest date:
```
import pyspark.sql.functions as F
from pyspark.sql.window import Window
new_df = df.withColumn("row_number",F.row_number().over(Window.partitionBy(df.id).orderBy(df.date.desc()))).filter(F.col("row_number")==1).drop("row_number")
``` |
36,341,553 | Lets say I want to use `gcc` from the command line in order to compile a C extension of Python. I'd structure the call something like this:
```
gcc -o applesauce.pyd -I C:/Python35/include -L C:/Python35/libs -l python35 applesauce.c
```
I noticed that the `-I`, `-L`, and `-l` options are absolutely necessary, or el... | 2016/03/31 | [
"https://Stackoverflow.com/questions/36341553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3689198/"
] | The easiest way to compile extensions is to use `distutils`, [like this](https://docs.python.org/2/distutils/examples.html);
```
from distutils.core import setup
from distutils.extension import Extension
setup(name='foobar',
version='1.0',
ext_modules=[Extension('foo', ['foo.c'])],
)
```
Keep in mi... | If you look at the source of [`build_ext.py`](http://svn.python.org/projects/python/trunk/Lib/distutils/command/build_ext.py) from `distutils` in the method `finalize_options` you will find code for different platforms used to locate libs. |
65,365,486 | I'm trying to locate an element using python selenium, and have the html below:
```
<input class="form-control" type="text" placeholder="University Search">
```
I couldn't locate where to type what I want to type.
```
from selenium import webdriver
import time
driver = webdriver.Chrome(executable_path=r"D:\Python\... | 2020/12/19 | [
"https://Stackoverflow.com/questions/65365486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11405347/"
] | You are attempting to use [find\_element\_by\_name](https://selenium-python.readthedocs.io/locating-elements.html#locating-by-name) and yet this element has no `name` attribute defined. You need to look for the element with the specific `placeholder` attribute you are interested in - you can use [find\_element\_by\_xpa... | Very close, try the XPath when all else fails:
```
text_area = driver.find_element_by_xpath("//*[@id='qs-rankings']/thead/tr[3]/td[2]/div/input")
```
You can copy the full/relative XPath to clipboard if you're inspecting the webpage's html. |
65,365,486 | I'm trying to locate an element using python selenium, and have the html below:
```
<input class="form-control" type="text" placeholder="University Search">
```
I couldn't locate where to type what I want to type.
```
from selenium import webdriver
import time
driver = webdriver.Chrome(executable_path=r"D:\Python\... | 2020/12/19 | [
"https://Stackoverflow.com/questions/65365486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11405347/"
] | Make sure you wait for the page to load using webdriver waits,click the popup and then proceed to target the element to send keys to.
```
driver.get('https://www.topuniversities.com/university-rankings/university-subject-rankings/2020/engineering-technology')
driver.maximize_window()
wait=WebDriverWait(driver, 10)
wai... | Very close, try the XPath when all else fails:
```
text_area = driver.find_element_by_xpath("//*[@id='qs-rankings']/thead/tr[3]/td[2]/div/input")
```
You can copy the full/relative XPath to clipboard if you're inspecting the webpage's html. |
65,365,486 | I'm trying to locate an element using python selenium, and have the html below:
```
<input class="form-control" type="text" placeholder="University Search">
```
I couldn't locate where to type what I want to type.
```
from selenium import webdriver
import time
driver = webdriver.Chrome(executable_path=r"D:\Python\... | 2020/12/19 | [
"https://Stackoverflow.com/questions/65365486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11405347/"
] | To send a *character sequence* to the element you can use either of the following [Locator Strategies](https://stackoverflow.com/questions/48369043/official-locator-strategies-for-the-webdriver/48376890#48376890):
* Using `css_selector`:
```
driver.find_element_by_css_selector("input.form-control[placeholder='Univers... | Very close, try the XPath when all else fails:
```
text_area = driver.find_element_by_xpath("//*[@id='qs-rankings']/thead/tr[3]/td[2]/div/input")
```
You can copy the full/relative XPath to clipboard if you're inspecting the webpage's html. |
10,264,460 | I am looking for some words in a file in python. After I find each word I need to read the next two words from the file. I've looked for some solution but I could not find reading just the next words.
```
# offsetFile - file pointer
# searchTerms - list of words
for line in offsetFile:
for word in searchTerms:
... | 2012/04/22 | [
"https://Stackoverflow.com/questions/10264460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/776614/"
] | An easy way to deal with this is to read the file using a generator that yields one word at a time from the file.
```
def words(fileobj):
for line in fileobj:
for word in line.split():
yield word
```
Then to find the word you're interested in and read the next two words:
```
with open("offse... | If you need to retrieve only two first words, just do it:
```
offsetFile.readline().split()[:2]
``` |
10,264,460 | I am looking for some words in a file in python. After I find each word I need to read the next two words from the file. I've looked for some solution but I could not find reading just the next words.
```
# offsetFile - file pointer
# searchTerms - list of words
for line in offsetFile:
for word in searchTerms:
... | 2012/04/22 | [
"https://Stackoverflow.com/questions/10264460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/776614/"
] | An easy way to deal with this is to read the file using a generator that yields one word at a time from the file.
```
def words(fileobj):
for line in fileobj:
for word in line.split():
yield word
```
Then to find the word you're interested in and read the next two words:
```
with open("offse... | ```
word = '3' #Your word
delim = ',' #Your delim
with open('test_file.txt') as f:
for line in f:
if word in line:
s_line = line.strip().split(delim)
two_words = (s_line[s_line.index(word) + 1],\
s_line[s_line.index(word) + 2])
break
``` |
10,264,460 | I am looking for some words in a file in python. After I find each word I need to read the next two words from the file. I've looked for some solution but I could not find reading just the next words.
```
# offsetFile - file pointer
# searchTerms - list of words
for line in offsetFile:
for word in searchTerms:
... | 2012/04/22 | [
"https://Stackoverflow.com/questions/10264460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/776614/"
] | An easy way to deal with this is to read the file using a generator that yields one word at a time from the file.
```
def words(fileobj):
for line in fileobj:
for word in line.split():
yield word
```
Then to find the word you're interested in and read the next two words:
```
with open("offse... | ```
def searchTerm(offsetFile, searchTerms):
# remove any found words from this list; if empty we can exit
searchThese = searchTerms[:]
for line in offsetFile:
words_in_line = line.split()
# Use this list comprehension if always two numbers... |
67,167,886 | I have installed `TensorFlow` on an M1 (**ARM**) Mac according to [these instructions](https://github.com/apple/tensorflow_macos/issues/153). Everything works fine.
However, model training is happening on the `CPU`. How do I switch training to the `GPU`?
```
In: tensorflow.config.list_physical_devices()
Out: [Physica... | 2021/04/19 | [
"https://Stackoverflow.com/questions/67167886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/626537/"
] | Update
------
The [tensorflow\_macos tf 2.4](https://github.com/apple/tensorflow_macos) repository has been archived by the owner. For `tf 2.5`, refer to [here](https://developer.apple.com/metal/tensorflow-plugin/).
---
It's probably not useful to disable the eager execution fully but to `tf. functions`. Try this an... | Try with turning off the eager execution...
via following
```
import tensorflow as tf
tf.compat.v1.disable_eager_execution()
```
Let me know if it works. |
59,520,376 | I came across a scenario where i need to run the function parallely for a list of values in python. I learnt executor.map from `concurrent.futures` will do the job. And I was able to parallelize the function using the below syntax `executor.map(func,[values])`.
But now, I came across the same scenario (i.e the functi... | 2019/12/29 | [
"https://Stackoverflow.com/questions/59520376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9452253/"
] | If you have an iterable of `sites` that you want to `map` and you want to pass the same `search_term` and `pages` argument to each call. You can use `zip` to create an iterable that returns tuples of 3 elements where the first is your list of sites and the 2nd and 3rd are the other parameters just repeating using `iter... | Here is a useful way of using kwargs in `executor.map`, by simply using a `lambda` function to pass the kwargs with the `**kwargs` notation:
```py
from concurrent.futures import ProcessPoolExecutor
def func(arg1, arg2, ...):
....
items = [
{ 'arg1': 0, 'arg2': 3 },
{ 'arg1': 1, 'arg2': 4 },
{ 'arg1':... |
1,713,015 | I installed Yahoo BOSS (it's a Python installation that allows you to use their search features). I followed everything perfectly. However, when I run the example to confirm that it works, I get this:
```
$ python ex3.py
Traceback (most recent call last):
File "ex3.py", line 16, in ?
from yos.yql import db
Fil... | 2009/11/11 | [
"https://Stackoverflow.com/questions/1713015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/179736/"
] | Use Python 2.5 or above: xml.etree.ElementTree was added in 2.5.
<http://docs.python.org/library/xml.etree.elementtree.html> | A google search reveals that you need to install the [effbot elementtree](http://effbot.org/downloads/#elementtree) Python module. |
34,804,612 | so im writing a login system with python and i would like to know if i can search a text document for the username you put in then have it output the line it was found on and search a password document. if it matches the password that you put in with the string on that line then it prints that you logged in. any and al... | 2016/01/15 | [
"https://Stackoverflow.com/questions/34804612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5382035/"
] | fucntion to get the line number. You can use this how you want
```
def getLineNumber(fileName, searchString):
with open(fileName) as f:
for i,line in enumerate(f, start=1):
if searchString in line:
return i
raise Exception('string not found')
``` | Pythonic way for your answer
```
f = open(filename)
line_no = [num for num,line in enumerate(f) if 'searchstring' in line][0]
print line_no+1
``` |
45,049,312 | How do I CONSOLIDATE the following using python COMPREHENSION
**FROM (list of dicts)**
```
[
{'server':'serv1','os':'Linux','archive':'/my/folder1'}
,{'server':'serv2','os':'Linux','archive':'/my/folder1'}
,{'server':'serv3','os':'Linux','archive':'/my/folder2'}
,{'server':'serv4','os':'AIX','archive':'/my/folder... | 2017/07/12 | [
"https://Stackoverflow.com/questions/45049312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2288573/"
] | the need to be able to set default values to your dictionary and to have the same key several times may make a dict-comprehension a bit clumsy. i'd prefer something like this:
a [`defaultdict`](https://docs.python.org/3/library/collections.html#collections.defaultdict) may help:
```
from collections import defaultdic... | It's difficult to achieve with list comprehension because of the accumulation effect. However, it's possible using `itertools.groupby` on the list sorted by your keys (use the same `key` function for both sorting and grouping).
Then extract the server info in a list comprehension and prefix by the group key. Pass the ... |
1,091,756 | >
> **Possible Duplicate:**
>
> [How many Python classes should I put in one file?](https://stackoverflow.com/questions/106896/how-many-python-classes-should-i-put-in-one-file)
>
>
>
Coming from a C++ background I've grown accustomed to organizing my classes such that, for the most part, there's a 1:1 ratio be... | 2009/07/07 | [
"https://Stackoverflow.com/questions/1091756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2494/"
] | the book [Expert Python Programming](http://www.packtpub.com/expert-python-programming/book) has something related discussion
Chapter 4: Choosing Good Names:"Building the Namespace Tree" and "Splitting the Code"
My line crude summary: collect some related class to one module(source file),and
collect some related... | There is no specific convention for this - do whatever makes your code the most readable and maintainable. |
1,091,756 | >
> **Possible Duplicate:**
>
> [How many Python classes should I put in one file?](https://stackoverflow.com/questions/106896/how-many-python-classes-should-i-put-in-one-file)
>
>
>
Coming from a C++ background I've grown accustomed to organizing my classes such that, for the most part, there's a 1:1 ratio be... | 2009/07/07 | [
"https://Stackoverflow.com/questions/1091756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2494/"
] | There's a mantra, "flat is better than nested," that generally discourages an overuse of hierarchy. I'm not sure there's any hard and fast rules as to when you want to create a new module -- for the most part, people just use their discretion to group logically related functionality (classes and functions that pertain ... | In python, class can also be used for small tasks (just for grouping etc). maintaining a 1:1 relation would result in having too many files with small or little functionality. |
1,091,756 | >
> **Possible Duplicate:**
>
> [How many Python classes should I put in one file?](https://stackoverflow.com/questions/106896/how-many-python-classes-should-i-put-in-one-file)
>
>
>
Coming from a C++ background I've grown accustomed to organizing my classes such that, for the most part, there's a 1:1 ratio be... | 2009/07/07 | [
"https://Stackoverflow.com/questions/1091756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2494/"
] | Here are some possible reasons:
1. Python is not exclusively class-based - the natural unit of code decomposition in Python is the module. Modules are just as likely to contain functions (which are first-class objects in Python) as classes. In Java, the unit of decomposition is the class. Hence, Python has one module=... | There's a mantra, "flat is better than nested," that generally discourages an overuse of hierarchy. I'm not sure there's any hard and fast rules as to when you want to create a new module -- for the most part, people just use their discretion to group logically related functionality (classes and functions that pertain ... |
1,091,756 | >
> **Possible Duplicate:**
>
> [How many Python classes should I put in one file?](https://stackoverflow.com/questions/106896/how-many-python-classes-should-i-put-in-one-file)
>
>
>
Coming from a C++ background I've grown accustomed to organizing my classes such that, for the most part, there's a 1:1 ratio be... | 2009/07/07 | [
"https://Stackoverflow.com/questions/1091756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2494/"
] | Here are some possible reasons:
1. Python is not exclusively class-based - the natural unit of code decomposition in Python is the module. Modules are just as likely to contain functions (which are first-class objects in Python) as classes. In Java, the unit of decomposition is the class. Hence, Python has one module=... | the book [Expert Python Programming](http://www.packtpub.com/expert-python-programming/book) has something related discussion
Chapter 4: Choosing Good Names:"Building the Namespace Tree" and "Splitting the Code"
My line crude summary: collect some related class to one module(source file),and
collect some related... |
1,091,756 | >
> **Possible Duplicate:**
>
> [How many Python classes should I put in one file?](https://stackoverflow.com/questions/106896/how-many-python-classes-should-i-put-in-one-file)
>
>
>
Coming from a C++ background I've grown accustomed to organizing my classes such that, for the most part, there's a 1:1 ratio be... | 2009/07/07 | [
"https://Stackoverflow.com/questions/1091756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2494/"
] | Here are some possible reasons:
1. Python is not exclusively class-based - the natural unit of code decomposition in Python is the module. Modules are just as likely to contain functions (which are first-class objects in Python) as classes. In Java, the unit of decomposition is the class. Hence, Python has one module=... | A good example of not having seperate files for each class might be the models.py file within a django app. Each django app may have a handful of classes that are related to that app, and putting them into individual files just makes more work.
Similarly, having each view in a different file again is likely to be coun... |
1,091,756 | >
> **Possible Duplicate:**
>
> [How many Python classes should I put in one file?](https://stackoverflow.com/questions/106896/how-many-python-classes-should-i-put-in-one-file)
>
>
>
Coming from a C++ background I've grown accustomed to organizing my classes such that, for the most part, there's a 1:1 ratio be... | 2009/07/07 | [
"https://Stackoverflow.com/questions/1091756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2494/"
] | Here are some possible reasons:
1. Python is not exclusively class-based - the natural unit of code decomposition in Python is the module. Modules are just as likely to contain functions (which are first-class objects in Python) as classes. In Java, the unit of decomposition is the class. Hence, Python has one module=... | There is no specific convention for this - do whatever makes your code the most readable and maintainable. |
1,091,756 | >
> **Possible Duplicate:**
>
> [How many Python classes should I put in one file?](https://stackoverflow.com/questions/106896/how-many-python-classes-should-i-put-in-one-file)
>
>
>
Coming from a C++ background I've grown accustomed to organizing my classes such that, for the most part, there's a 1:1 ratio be... | 2009/07/07 | [
"https://Stackoverflow.com/questions/1091756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2494/"
] | There's a mantra, "flat is better than nested," that generally discourages an overuse of hierarchy. I'm not sure there's any hard and fast rules as to when you want to create a new module -- for the most part, people just use their discretion to group logically related functionality (classes and functions that pertain ... | There is no specific convention for this - do whatever makes your code the most readable and maintainable. |
1,091,756 | >
> **Possible Duplicate:**
>
> [How many Python classes should I put in one file?](https://stackoverflow.com/questions/106896/how-many-python-classes-should-i-put-in-one-file)
>
>
>
Coming from a C++ background I've grown accustomed to organizing my classes such that, for the most part, there's a 1:1 ratio be... | 2009/07/07 | [
"https://Stackoverflow.com/questions/1091756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2494/"
] | There's a mantra, "flat is better than nested," that generally discourages an overuse of hierarchy. I'm not sure there's any hard and fast rules as to when you want to create a new module -- for the most part, people just use their discretion to group logically related functionality (classes and functions that pertain ... | the book [Expert Python Programming](http://www.packtpub.com/expert-python-programming/book) has something related discussion
Chapter 4: Choosing Good Names:"Building the Namespace Tree" and "Splitting the Code"
My line crude summary: collect some related class to one module(source file),and
collect some related... |
1,091,756 | >
> **Possible Duplicate:**
>
> [How many Python classes should I put in one file?](https://stackoverflow.com/questions/106896/how-many-python-classes-should-i-put-in-one-file)
>
>
>
Coming from a C++ background I've grown accustomed to organizing my classes such that, for the most part, there's a 1:1 ratio be... | 2009/07/07 | [
"https://Stackoverflow.com/questions/1091756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2494/"
] | In python, class can also be used for small tasks (just for grouping etc). maintaining a 1:1 relation would result in having too many files with small or little functionality. | A good example of not having seperate files for each class might be the models.py file within a django app. Each django app may have a handful of classes that are related to that app, and putting them into individual files just makes more work.
Similarly, having each view in a different file again is likely to be coun... |
1,091,756 | >
> **Possible Duplicate:**
>
> [How many Python classes should I put in one file?](https://stackoverflow.com/questions/106896/how-many-python-classes-should-i-put-in-one-file)
>
>
>
Coming from a C++ background I've grown accustomed to organizing my classes such that, for the most part, there's a 1:1 ratio be... | 2009/07/07 | [
"https://Stackoverflow.com/questions/1091756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2494/"
] | the book [Expert Python Programming](http://www.packtpub.com/expert-python-programming/book) has something related discussion
Chapter 4: Choosing Good Names:"Building the Namespace Tree" and "Splitting the Code"
My line crude summary: collect some related class to one module(source file),and
collect some related... | A good example of not having seperate files for each class might be the models.py file within a django app. Each django app may have a handful of classes that are related to that app, and putting them into individual files just makes more work.
Similarly, having each view in a different file again is likely to be coun... |
45,043,961 | I'm getting the following error when trying to run
`$ bazel build object_detection/...`
And I'm getting ~20 of the same error (1 for each time it attempts to build that). I think it's something with the way I need to configure bazel to recognize the py\_proto\_library, but I don't know where, or how I would do this.
... | 2017/07/11 | [
"https://Stackoverflow.com/questions/45043961",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2544449/"
] | The solution ended up being running this command, like the instructions say:
```
$ protoc object_detection/protos/*.proto --python_out=.
```
and then running this command, like the instructions say.:
```
$ export PYTHONPATH=$PYTHONPATH:`pwd`:`pwd`/slim
``` | Are you using `load` in the `BUILD` file you're building?
`load("@protobuf//:protobuf.bzl", "py_proto_library")`?
The error seems to indicate the symbol `py_proto_library` isn't loaded into skylark. |
68,630,769 | I have a list of strings in python and want to run a recursive grep on each string in the list. Am using the following code,
```
import subprocess as sp
for python_file in python_files:
out = sp.getoutput("grep -r python_file . | wc -l")
print(out)
```
The output I am getting is the grep of the string "pyth... | 2021/08/03 | [
"https://Stackoverflow.com/questions/68630769",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16582585/"
] | Your code has several issues. The immediate answer to what you seem to be asking was given in a comment, but there are more things to fix here.
If you want to pass in a variable instead of a static string, you have to use some sort of string interpolation.
`grep` already knows how to report how many lines matched; us... | Your intent isn't totally clear from the way you've written your question, but the first argument to `grep` is the **pattern** (`python_file` in your example), and the second is the **file(s)** `.` in your example
You could write this in native Python or just use grep directly, which is probably easier than using both... |
62,295,148 | I am new to lambda functions. I am trying to get the sum of elements in a list, but facing this issue repeatedly.
[](https://i.stack.imgur.com/9k7gu.png)
When following up with tutorials online([Tutorial-link](https://realpython.com/python-lambda/))... | 2020/06/10 | [
"https://Stackoverflow.com/questions/62295148",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2663091/"
] | The [findOne](https://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#findOne) function in the node.js driver has a slightly different definition than the one in the shell.
Try
```
db.collection("inventory").findOne({ _id: 1 }, {projection:{ "size": 0 }}, (err, result) => {
``` | May you should try this
`db.collection("inventory").findOne({ _id: 1 }). select("-size"). exec((err, ``result) => {//body of the fn}) ;` |
67,047,424 | In this code, I am trying to insert a code block using [react-quilljs](https://github.com/gtgalone/react-quilljs#usage)
```
import React, { useState } from 'react';
import hljs from 'highlight.js';
import { useQuill } from 'react-quilljs';
import 'quill/dist/quill.snow.css'; // Add css for snow theme
export default... | 2021/04/11 | [
"https://Stackoverflow.com/questions/67047424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10134463/"
] | Your code *is* getting marked up by `highlight.js` with CSS classes:
```
<span class="hljs-keyword">const</span>
```
You are not seeing the impact of those CSS classes because you don't have a stylesheet loaded to handle them. You need to choose the theme that you want from [the available styles](https://highlightjs... | Look at the css in the editor mode. It depends on two class names ql-snow and ql-editor.
You can fix this issue by wrapping it around one more div with className ql-snow.
```
<div className='ql-snow'>
<div className='ql-editor' dangerouslySetInnerHTML={{ __html: content }}>
<div/>
</div>
```
This should wor... |
67,047,424 | In this code, I am trying to insert a code block using [react-quilljs](https://github.com/gtgalone/react-quilljs#usage)
```
import React, { useState } from 'react';
import hljs from 'highlight.js';
import { useQuill } from 'react-quilljs';
import 'quill/dist/quill.snow.css'; // Add css for snow theme
export default... | 2021/04/11 | [
"https://Stackoverflow.com/questions/67047424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10134463/"
] | Your code *is* getting marked up by `highlight.js` with CSS classes:
```
<span class="hljs-keyword">const</span>
```
You are not seeing the impact of those CSS classes because you don't have a stylesheet loaded to handle them. You need to choose the theme that you want from [the available styles](https://highlightjs... | I got the same issue and when I used `hjls` what happened was that I got syntax highlighting in the editor but not in the value.
If you noticed the syntax gets highlighted some seconds after you write the code block, this means that the value gets set before the syntax gets highlighted.
So, I just set the value after 2... |
10,509,293 | >
> **Possible Duplicate:**
>
> [Why aren't Python's superclass **init** methods automatically invoked?](https://stackoverflow.com/questions/3782827/why-arent-pythons-superclass-init-methods-automatically-invoked)
>
>
>
For example:
```
class Pet(object):
def __init__(self, name, species):
self.na... | 2012/05/09 | [
"https://Stackoverflow.com/questions/10509293",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1241100/"
] | Having the language force the super class to initialize before or after means that you lose functionality. A subclass may depend on a superclass's initialization to be run first, or vice versa.
In addition, it wouldn't have any way of knowing what arguments to pass -- subclasses decide what values are passed to an ini... | You can make species a class attribute like this
```
class Pet(object):
species = None
def __init__(self, name):
self.name = name
def getName(self):
return self.name
def getSpecies(self):
return self.species
def __str__(self):
return "%s is a %s" % (self.name, se... |
67,377,043 | What is the reason why I cannot access a specific line number in the already split string?
```
a = "ABCDEFGHIJKLJMNOPRSTCUFSC"
barcode = "2"
import textwrap
prazno = textwrap.fill(a,width=5)
podeli = prazno.splitlines()
```
Here the output is correct:
```
print(podeli)
ABCDE
FGHI... | 2021/05/03 | [
"https://Stackoverflow.com/questions/67377043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15827381/"
] | You can solve your immediate problem by rebuilding the list, but I fear you have a more general problem that you haven't told us.
```
if barcode[0] == '1':
podeli[1] += ' MATA'
elif barcode[0] == '2':
podeli[1] += ' MATA'
line2 = textwrap.fill(podeli[2], width=3).splitlines()
po... | Try this, it should split a string you specified by a width of 3:
```
n = 3
[((podeli[2])[i:i+n]) for i in range(0, len(podeli[2]), n)]
``` |
40,882,899 | I am using python+bs4+pyside in the code ,please look the part of the code below:
```
enter code here
#coding:gb2312
import urllib2
import sys
import urllib
import urlparse
import random
import time
from datetime import datetime, timedelta
import socket
from bs4 import BeautifulSoup
import lxml.html
from PySide.QtGu... | 2016/11/30 | [
"https://Stackoverflow.com/questions/40882899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7229399/"
] | try changing your foreach loop to this.
```
foreach ($list as $key => $value) {
echo $value->title." || ";
echo $value->link." ";
echo nl2br("\n");
}
```
Hope this Works for you. | What you did is looping the keys and values seperated and than you tried to get the values from the keys of the stdClass, what you need to do is looping it as an object. I also used `json_decode($json_str, true)` to get the result as an array instead of an stdClass.
```
$json_str = '[{"title":"root","link":"one"},{"ti... |
40,882,899 | I am using python+bs4+pyside in the code ,please look the part of the code below:
```
enter code here
#coding:gb2312
import urllib2
import sys
import urllib
import urlparse
import random
import time
from datetime import datetime, timedelta
import socket
from bs4 import BeautifulSoup
import lxml.html
from PySide.QtGu... | 2016/11/30 | [
"https://Stackoverflow.com/questions/40882899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7229399/"
] | try changing your foreach loop to this.
```
foreach ($list as $key => $value) {
echo $value->title." || ";
echo $value->link." ";
echo nl2br("\n");
}
```
Hope this Works for you. | **Code :**
```
$list = json_decode($json);
foreach ($list as $item) {
echo $item->title . ' || ' . $item->link . '<br>';
}
``` |
40,882,899 | I am using python+bs4+pyside in the code ,please look the part of the code below:
```
enter code here
#coding:gb2312
import urllib2
import sys
import urllib
import urlparse
import random
import time
from datetime import datetime, timedelta
import socket
from bs4 import BeautifulSoup
import lxml.html
from PySide.QtGu... | 2016/11/30 | [
"https://Stackoverflow.com/questions/40882899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7229399/"
] | What you did is looping the keys and values seperated and than you tried to get the values from the keys of the stdClass, what you need to do is looping it as an object. I also used `json_decode($json_str, true)` to get the result as an array instead of an stdClass.
```
$json_str = '[{"title":"root","link":"one"},{"ti... | **Code :**
```
$list = json_decode($json);
foreach ($list as $item) {
echo $item->title . ' || ' . $item->link . '<br>';
}
``` |
66,012,040 | Running this DAG in airflow gives error as Task exited with return code Negsignal.SIGABRT.
I am not sure what is wrong I have done
```
from airflow import DAG
from airflow.providers.snowflake.operators.snowflake import SnowflakeOperator
from airflow.utils.dates import days_ago
SNOWFLAKE_CONN_ID = 's... | 2021/02/02 | [
"https://Stackoverflow.com/questions/66012040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10110307/"
] | I ran into the same error on Mac OSX - which looks like the OS you are using based on the local file path.
Adding the following to my Airflow *scheduler* session fixed the problem:
```
export OBJC_DISABLE_INITIALIZE_FORK_SAFETY=YES
```
The cause is described in the [Airflow docs](https://airflow.apache.org/blog/air... | You are executing:
```
snowflake_op_with_params = SnowflakeOperator(
task_id='snowflake_op_with_params',
dag=dag,
snowflake_conn_id=SNOWFLAKE_CONN_ID,
sql=SQL_INSERT_STATEMENT,
parameters={"id": 56},
warehouse=SNOWFLAKE_WAREHOUSE,
database=SNOWFLAKE_DATABASE,
# schema=SNOWFLAKE_SCHEMA,
... |
66,012,040 | Running this DAG in airflow gives error as Task exited with return code Negsignal.SIGABRT.
I am not sure what is wrong I have done
```
from airflow import DAG
from airflow.providers.snowflake.operators.snowflake import SnowflakeOperator
from airflow.utils.dates import days_ago
SNOWFLAKE_CONN_ID = 's... | 2021/02/02 | [
"https://Stackoverflow.com/questions/66012040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10110307/"
] | This helped me too on Mac OSX:
1. Open terminal an open .zshrc (or .bash\_profile) with `nano .zshrc`
2. Add this line to the profile `export OBJC_DISABLE_INITIALIZE_FORK_SAFETY=YES`
3. Restart scheduler & web server. | You are executing:
```
snowflake_op_with_params = SnowflakeOperator(
task_id='snowflake_op_with_params',
dag=dag,
snowflake_conn_id=SNOWFLAKE_CONN_ID,
sql=SQL_INSERT_STATEMENT,
parameters={"id": 56},
warehouse=SNOWFLAKE_WAREHOUSE,
database=SNOWFLAKE_DATABASE,
# schema=SNOWFLAKE_SCHEMA,
... |
66,012,040 | Running this DAG in airflow gives error as Task exited with return code Negsignal.SIGABRT.
I am not sure what is wrong I have done
```
from airflow import DAG
from airflow.providers.snowflake.operators.snowflake import SnowflakeOperator
from airflow.utils.dates import days_ago
SNOWFLAKE_CONN_ID = 's... | 2021/02/02 | [
"https://Stackoverflow.com/questions/66012040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10110307/"
] | You are executing:
```
snowflake_op_with_params = SnowflakeOperator(
task_id='snowflake_op_with_params',
dag=dag,
snowflake_conn_id=SNOWFLAKE_CONN_ID,
sql=SQL_INSERT_STATEMENT,
parameters={"id": 56},
warehouse=SNOWFLAKE_WAREHOUSE,
database=SNOWFLAKE_DATABASE,
# schema=SNOWFLAKE_SCHEMA,
... | I think the issue you are facing has to do with OCSP checking
Add "insecure\_mode=True" in snowflake connector to disable OCSP checking
```py
snowflake.connector.connect(
insecure_mode=True,
)
```
But "insecure\_mode=True" is needed only when running inside Airflow (Running as a pyscript works fine) . I don't kn... |
66,012,040 | Running this DAG in airflow gives error as Task exited with return code Negsignal.SIGABRT.
I am not sure what is wrong I have done
```
from airflow import DAG
from airflow.providers.snowflake.operators.snowflake import SnowflakeOperator
from airflow.utils.dates import days_ago
SNOWFLAKE_CONN_ID = 's... | 2021/02/02 | [
"https://Stackoverflow.com/questions/66012040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10110307/"
] | I ran into the same error on Mac OSX - which looks like the OS you are using based on the local file path.
Adding the following to my Airflow *scheduler* session fixed the problem:
```
export OBJC_DISABLE_INITIALIZE_FORK_SAFETY=YES
```
The cause is described in the [Airflow docs](https://airflow.apache.org/blog/air... | I think the issue you are facing has to do with OCSP checking
Add "insecure\_mode=True" in snowflake connector to disable OCSP checking
```py
snowflake.connector.connect(
insecure_mode=True,
)
```
But "insecure\_mode=True" is needed only when running inside Airflow (Running as a pyscript works fine) . I don't kn... |
66,012,040 | Running this DAG in airflow gives error as Task exited with return code Negsignal.SIGABRT.
I am not sure what is wrong I have done
```
from airflow import DAG
from airflow.providers.snowflake.operators.snowflake import SnowflakeOperator
from airflow.utils.dates import days_ago
SNOWFLAKE_CONN_ID = 's... | 2021/02/02 | [
"https://Stackoverflow.com/questions/66012040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10110307/"
] | This helped me too on Mac OSX:
1. Open terminal an open .zshrc (or .bash\_profile) with `nano .zshrc`
2. Add this line to the profile `export OBJC_DISABLE_INITIALIZE_FORK_SAFETY=YES`
3. Restart scheduler & web server. | I think the issue you are facing has to do with OCSP checking
Add "insecure\_mode=True" in snowflake connector to disable OCSP checking
```py
snowflake.connector.connect(
insecure_mode=True,
)
```
But "insecure\_mode=True" is needed only when running inside Airflow (Running as a pyscript works fine) . I don't kn... |
32,103,424 | Coming from [Python recursively appending list function](https://stackoverflow.com/questions/32102420/python-recursively-appending-list-function)
Trying to recursively get a list of permissions associated with a file structure.
I have this function:
```
def get_child_perms(self, folder, request, perm_list):
... | 2015/08/19 | [
"https://Stackoverflow.com/questions/32103424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4941891/"
] | The basic issue occurs you are only returning the `folder permission` , when folder does not have any children , when it has children, you are not including the `folder.has_read_permission(request)` in your return result , which is most probably causing you issue. You need to do -
```
def get_child_perms(self, folder,... | why not [os.walk](https://docs.python.org/3/library/os.html?highlight=walk#os.walk)
>
> When topdown is True, the caller can modify the dirnames list in-place
> (perhaps using del or slice assignment), and walk() will only recurse
> into the subdirectories whose names remain in dirnames; this can be
> used to pru... |
26,643,903 | I'm trying to use python requests to PUT a .pmml model to a local openscoring server.
This works (from directory containing DecisionTreeIris.pmml):
```
curl -X PUT --data-binary @DecisionTreeIris.pmml -H "Content-type: text/xml" http://localhost:8080/openscoring/model/DecisionTreeIris
```
This doesn't:
```
impor... | 2014/10/30 | [
"https://Stackoverflow.com/questions/26643903",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/829332/"
] | You are trying to store Components in the same variable. This is wrong:
```
var enemy1Clone : Transform = Instantiate(enemy1, transform.position, transform.rotation);
enemy1Clone.GetComponent("enemyscript");
enemy1Clone.GetComponent(Animator);
```
`enemy1Clone` is of type `Transform`, don't try putting `enemyscript... | if the **Animator** is not initialized, you have to re-order the components, put the **Animator** component right below the **Transform** component and you should be fine. |
56,496,458 | The [logging docs](https://docs.python.org/2/library/logging.html) don't mention what the default logger obtained from [`basicConfig`](https://docs.python.org/2/library/logging.html#logging.basicConfig) writes to: stdout or stderr.
What is the default behavior? | 2019/06/07 | [
"https://Stackoverflow.com/questions/56496458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1804173/"
] | If no `filename` argument is passed to [logging.basicconfig](https://docs.python.org/2/library/logging.html#logging.basicConfig) it will configure a `StreamHandler`. If a `stream` argument is passed to `logging.basicconfig` it will pass this on to `StreamHandler` otherwise `StreamHandler` defaults to using `sys.stderr`... | Apparently the default is stderr.
A quick check: Using a minimal example
```py
import logging
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
logger.info("test")
```
and running it with `python test.py 1> /tmp/log_stdout 2> /tmp/log_stderr` results in an empty stdout file, but a non-em... |
9,222,129 | I have three python functions:
```
def decorator_function(func)
def wrapper(..)
return func(*args, **kwargs)
return wrapper
def plain_func(...)
@decorator_func
def wrapped_func(....)
```
inside a module A.
Now I want to get all the functions inside this module A, for which I do:
```
for fname, func in in... | 2012/02/10 | [
"https://Stackoverflow.com/questions/9222129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/334909/"
] | If all you want is to keep the original function name visible from "the outside" I think that you can do that with
```
@functools.wraps
```
as a decorator to your decorator
here's the example from the standard docs
```
>>> from functools import wraps
>>> def my_decorator(f):
... @wraps(f)
... def wrapper(*... | You can access the pre-decorated function with:
```
wrapped_func.func_closure[0].cell_contents()
```
For example,
```
def decorator_function(func):
def wrapper(*args, **kwargs):
print('Bar')
return func(*args, **kwargs)
return wrapper
@decorator_function
def wrapped_func():
print('Foo')
wra... |
13,400,876 | >
> **Possible Duplicate:**
>
> [Python’s most efficient way to choose longest string in list?](https://stackoverflow.com/questions/873327/pythons-most-efficient-way-to-choose-longest-string-in-list)
>
>
>
I have a list L
```
L = [[1,2,3],[5,7],[1,3],[77]]
```
I want to return the length of the longest subli... | 2012/11/15 | [
"https://Stackoverflow.com/questions/13400876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1538364/"
] | `max(L,key=len)` will give you the object with the longest length (`[1,2,3]` in your example) -- To actually get the length (if that's all you care about), you can do `len(max(L,key=len))` which is a bit ugly -- I'd break it up onto 2 lines. Or you can use the version supplied by ecatamur.
All of these answers have lo... | Try a comprehension:
```
max(len(l) for l in L)
``` |
50,506,478 | i am gaurav and i am learning programming. i was reading regular expressions in dive into python 3,so i thought to try myself something so i wrote this code in eclipse but i got a lot of errors.can anyone pls help me
```
import re
def add_shtner(add):
return re.sub(r"\bROAD\b","RD",add)
print(add_shtner("100,BROA... | 2018/05/24 | [
"https://Stackoverflow.com/questions/50506478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5925439/"
] | This is supported from version `@angular/[email protected]`.
---
**Update** (November 2019):
**[The `fileReplacements` solution does not work with
Angular CLI 8.0.0 anymore](https://github.com/angular/angular-cli/issues/14599#issuecomment-527131237)**
Change `angular.json` to set your production `index.html` instea... | I'm using Angular 8 and I don't know why it doesn't work on my side.
But I can specify the location for the `index.html` for any build configuration (and looks like also `serve`) <https://stackoverflow.com/a/57274333/3473303> |
50,506,478 | i am gaurav and i am learning programming. i was reading regular expressions in dive into python 3,so i thought to try myself something so i wrote this code in eclipse but i got a lot of errors.can anyone pls help me
```
import re
def add_shtner(add):
return re.sub(r"\bROAD\b","RD",add)
print(add_shtner("100,BROA... | 2018/05/24 | [
"https://Stackoverflow.com/questions/50506478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5925439/"
] | This is supported from version `@angular/[email protected]`.
---
**Update** (November 2019):
**[The `fileReplacements` solution does not work with
Angular CLI 8.0.0 anymore](https://github.com/angular/angular-cli/issues/14599#issuecomment-527131237)**
Change `angular.json` to set your production `index.html` instea... | In **Angular 8** "fileReplacements" did not work for replacing index.html. This was my solution.
**Current Working Solution**
```
...
"production": {
"index": {
"input": "src/index.prod.html",
"output": "index.html"
},
...
```
***Full Build Configuration**... |
50,506,478 | i am gaurav and i am learning programming. i was reading regular expressions in dive into python 3,so i thought to try myself something so i wrote this code in eclipse but i got a lot of errors.can anyone pls help me
```
import re
def add_shtner(add):
return re.sub(r"\bROAD\b","RD",add)
print(add_shtner("100,BROA... | 2018/05/24 | [
"https://Stackoverflow.com/questions/50506478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5925439/"
] | This is supported from version `@angular/[email protected]`.
---
**Update** (November 2019):
**[The `fileReplacements` solution does not work with
Angular CLI 8.0.0 anymore](https://github.com/angular/angular-cli/issues/14599#issuecomment-527131237)**
Change `angular.json` to set your production `index.html` instea... | As explained [in this github issue](https://github.com/angular/angular-cli/issues/14599#issuecomment-527131237), change `angular.json` to set your production `index.html`:
```
"architect":{
"build": {
"options": {
"index": "src/index.html", //non-prod
},
"configurations": {
"production":{
... |
50,506,478 | i am gaurav and i am learning programming. i was reading regular expressions in dive into python 3,so i thought to try myself something so i wrote this code in eclipse but i got a lot of errors.can anyone pls help me
```
import re
def add_shtner(add):
return re.sub(r"\bROAD\b","RD",add)
print(add_shtner("100,BROA... | 2018/05/24 | [
"https://Stackoverflow.com/questions/50506478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5925439/"
] | This is supported from version `@angular/[email protected]`.
---
**Update** (November 2019):
**[The `fileReplacements` solution does not work with
Angular CLI 8.0.0 anymore](https://github.com/angular/angular-cli/issues/14599#issuecomment-527131237)**
Change `angular.json` to set your production `index.html` instea... | [](https://i.stack.imgur.com/LXtQG.png)
you need to update your angular.json file for production configuration
see image. |
50,506,478 | i am gaurav and i am learning programming. i was reading regular expressions in dive into python 3,so i thought to try myself something so i wrote this code in eclipse but i got a lot of errors.can anyone pls help me
```
import re
def add_shtner(add):
return re.sub(r"\bROAD\b","RD",add)
print(add_shtner("100,BROA... | 2018/05/24 | [
"https://Stackoverflow.com/questions/50506478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5925439/"
] | In **Angular 8** "fileReplacements" did not work for replacing index.html. This was my solution.
**Current Working Solution**
```
...
"production": {
"index": {
"input": "src/index.prod.html",
"output": "index.html"
},
...
```
***Full Build Configuration**... | I'm using Angular 8 and I don't know why it doesn't work on my side.
But I can specify the location for the `index.html` for any build configuration (and looks like also `serve`) <https://stackoverflow.com/a/57274333/3473303> |
50,506,478 | i am gaurav and i am learning programming. i was reading regular expressions in dive into python 3,so i thought to try myself something so i wrote this code in eclipse but i got a lot of errors.can anyone pls help me
```
import re
def add_shtner(add):
return re.sub(r"\bROAD\b","RD",add)
print(add_shtner("100,BROA... | 2018/05/24 | [
"https://Stackoverflow.com/questions/50506478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5925439/"
] | As explained [in this github issue](https://github.com/angular/angular-cli/issues/14599#issuecomment-527131237), change `angular.json` to set your production `index.html`:
```
"architect":{
"build": {
"options": {
"index": "src/index.html", //non-prod
},
"configurations": {
"production":{
... | I'm using Angular 8 and I don't know why it doesn't work on my side.
But I can specify the location for the `index.html` for any build configuration (and looks like also `serve`) <https://stackoverflow.com/a/57274333/3473303> |
50,506,478 | i am gaurav and i am learning programming. i was reading regular expressions in dive into python 3,so i thought to try myself something so i wrote this code in eclipse but i got a lot of errors.can anyone pls help me
```
import re
def add_shtner(add):
return re.sub(r"\bROAD\b","RD",add)
print(add_shtner("100,BROA... | 2018/05/24 | [
"https://Stackoverflow.com/questions/50506478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5925439/"
] | I'm using Angular 8 and I don't know why it doesn't work on my side.
But I can specify the location for the `index.html` for any build configuration (and looks like also `serve`) <https://stackoverflow.com/a/57274333/3473303> | [](https://i.stack.imgur.com/LXtQG.png)
you need to update your angular.json file for production configuration
see image. |
50,506,478 | i am gaurav and i am learning programming. i was reading regular expressions in dive into python 3,so i thought to try myself something so i wrote this code in eclipse but i got a lot of errors.can anyone pls help me
```
import re
def add_shtner(add):
return re.sub(r"\bROAD\b","RD",add)
print(add_shtner("100,BROA... | 2018/05/24 | [
"https://Stackoverflow.com/questions/50506478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5925439/"
] | In **Angular 8** "fileReplacements" did not work for replacing index.html. This was my solution.
**Current Working Solution**
```
...
"production": {
"index": {
"input": "src/index.prod.html",
"output": "index.html"
},
...
```
***Full Build Configuration**... | [](https://i.stack.imgur.com/LXtQG.png)
you need to update your angular.json file for production configuration
see image. |
50,506,478 | i am gaurav and i am learning programming. i was reading regular expressions in dive into python 3,so i thought to try myself something so i wrote this code in eclipse but i got a lot of errors.can anyone pls help me
```
import re
def add_shtner(add):
return re.sub(r"\bROAD\b","RD",add)
print(add_shtner("100,BROA... | 2018/05/24 | [
"https://Stackoverflow.com/questions/50506478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5925439/"
] | As explained [in this github issue](https://github.com/angular/angular-cli/issues/14599#issuecomment-527131237), change `angular.json` to set your production `index.html`:
```
"architect":{
"build": {
"options": {
"index": "src/index.html", //non-prod
},
"configurations": {
"production":{
... | [](https://i.stack.imgur.com/LXtQG.png)
you need to update your angular.json file for production configuration
see image. |
63,997,745 | ```py
string = "This is a test string. It has 44 characters." #Line1
for i in range(len(string) // 10): #Line2
result= string[10 * i:10 * i + 10] #Line3
print(result) #Line4
```
I want to understand the above code so that I can achiev... | 2020/09/21 | [
"https://Stackoverflow.com/questions/63997745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14311349/"
] | You can do:
```
colSums(df) != 0
A B C
TRUE TRUE FALSE
``` | Maybe `apply()` can be useful:
```
#Data
df = data.frame("A" = c("TRUE","FALSE","FALSE","FALSE"),
"B" = c("FALSE","TRUE","TRUE","FALSE"),
"C" = c("FALSE","FALSE","FALSE","FALSE"))
#Apply
apply(df,2,function(x) any(x=='TRUE'))
```
Output:
```
A B C
TRUE TRUE FALSE
```... |
63,997,745 | ```py
string = "This is a test string. It has 44 characters." #Line1
for i in range(len(string) // 10): #Line2
result= string[10 * i:10 * i + 10] #Line3
print(result) #Line4
```
I want to understand the above code so that I can achiev... | 2020/09/21 | [
"https://Stackoverflow.com/questions/63997745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14311349/"
] | You can do:
```
colSums(df) != 0
A B C
TRUE TRUE FALSE
``` | Using `dplyr`
```
library(dplyr)
df %>%
summarise(across(everything(), any))
# A B C
#1 TRUE TRUE FALSE
``` |
63,997,745 | ```py
string = "This is a test string. It has 44 characters." #Line1
for i in range(len(string) // 10): #Line2
result= string[10 * i:10 * i + 10] #Line3
print(result) #Line4
```
I want to understand the above code so that I can achiev... | 2020/09/21 | [
"https://Stackoverflow.com/questions/63997745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14311349/"
] | Maybe `apply()` can be useful:
```
#Data
df = data.frame("A" = c("TRUE","FALSE","FALSE","FALSE"),
"B" = c("FALSE","TRUE","TRUE","FALSE"),
"C" = c("FALSE","FALSE","FALSE","FALSE"))
#Apply
apply(df,2,function(x) any(x=='TRUE'))
```
Output:
```
A B C
TRUE TRUE FALSE
```... | Using `dplyr`
```
library(dplyr)
df %>%
summarise(across(everything(), any))
# A B C
#1 TRUE TRUE FALSE
``` |
1,621,521 | Is there a program which I can run like this:
```
py2py.py < orig.py > smaller.py
```
Where orig.py contains python source code with comments and doc strings, and smaller.py contains identical, runnable source code but without the comments and doc strings?
Code which originally looked like this:
```
#/usr/bin/pyth... | 2009/10/25 | [
"https://Stackoverflow.com/questions/1621521",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/196255/"
] | [This Python minifier](https://pypi.python.org/pypi/pyminifier) looks like it does what you need. | I recommend [minipy](https://github.com/gareth-rees/minipy). The most compelling reason is that it does proper analysis of the source code abstract syntax tree so the minified code is much more accurate. I've found that the more well known [pyminifier](https://pypi.python.org/pypi/pyminifier) tends to generate code wit... |
29,853,907 | I was working with django-1.8.1 and everything was good but when I tried again to run my server with command bellow, I get some errors :
command : `python manage.py runserver`
errors appeared in command-line :
```
> Traceback (most recent call last):
File "C:\Python34\lib\wsgiref\handlers.py", line 137, in run
... | 2015/04/24 | [
"https://Stackoverflow.com/questions/29853907",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4701816/"
] | Looks like a mixed solution for me.
Typically `TcpListener listener = new TcpListener(8888)` awaits for the connection on given port.
Then, when it accepts the connection from client, it establishes connection on different socket `Socket socket = listener.AcceptSocket()` so that listening port remains awaiting for oth... | The term client has two definitions. At the application level you have a client and server application. The client is the master and the server is the slave. At the socket level, both the client application and server application have a client (also called a socket).
The server socket listens at the loopback address 12... |
16,251,016 | Hi all i want to web based GUI Testing tool. I found dogtail is written using python. but i didnot get any good tutorial and examples to move further. Please Guide me weather dogtail is perfect or something better than this in python is there?. and if please share doc and example.
My requirement:
A DVR continuous sho... | 2013/04/27 | [
"https://Stackoverflow.com/questions/16251016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2017556/"
] | [Selenium](https://pypi.python.org/pypi/selenium) is designed exactly for this, it allows you to control the browser in Python, and check if things are as expected (e.g check if a specific element exists, submit a form etc)
There's [some more examples in the documentation](http://selenium-python.readthedocs.org/en/lat... | Selenium provides a python interface rather than just record your mouse movements, see <http://selenium-python.readthedocs.org/en/latest/api.html>
If you need to check your video frames your can record them locally and OCR the frames looking for some expected text or timecode. |
16,251,016 | Hi all i want to web based GUI Testing tool. I found dogtail is written using python. but i didnot get any good tutorial and examples to move further. Please Guide me weather dogtail is perfect or something better than this in python is there?. and if please share doc and example.
My requirement:
A DVR continuous sho... | 2013/04/27 | [
"https://Stackoverflow.com/questions/16251016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2017556/"
] | Selenium provides a python interface rather than just record your mouse movements, see <http://selenium-python.readthedocs.org/en/latest/api.html>
If you need to check your video frames your can record them locally and OCR the frames looking for some expected text or timecode. | For Simple form based UI Testing. I have created a framework using python/selenium/phantomjs although it can do complex stuff too. I am yet to document it. (If you don't need to run firefox you don't need to install phantomjs)
<https://github.com/manav148/PyUIT> |
16,251,016 | Hi all i want to web based GUI Testing tool. I found dogtail is written using python. but i didnot get any good tutorial and examples to move further. Please Guide me weather dogtail is perfect or something better than this in python is there?. and if please share doc and example.
My requirement:
A DVR continuous sho... | 2013/04/27 | [
"https://Stackoverflow.com/questions/16251016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2017556/"
] | [Selenium](https://pypi.python.org/pypi/selenium) is designed exactly for this, it allows you to control the browser in Python, and check if things are as expected (e.g check if a specific element exists, submit a form etc)
There's [some more examples in the documentation](http://selenium-python.readthedocs.org/en/lat... | For Simple form based UI Testing. I have created a framework using python/selenium/phantomjs although it can do complex stuff too. I am yet to document it. (If you don't need to run firefox you don't need to install phantomjs)
<https://github.com/manav148/PyUIT> |
52,928,809 | Hi I am a beginner in python coding!
This is my code:
```
while True:
try:
x=raw_input("Please enter a word: ")
break
except ValueError:
print( "Sorry it is not a word. try again")
```
The main aim of this code is to check the input. If the input is string than OK, but when the input ... | 2018/10/22 | [
"https://Stackoverflow.com/questions/52928809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10540371/"
] | Try using KV0, it works for me:
```
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[[AVAudioSession sharedInstance] setActive:YES error:nil];
[[AVAudioSession sharedInstance] addObserver:self forKeyPath:@"outputVolume" options:0 context:nil];
... | Apparently, my code worked ok. The problem was with my laptop - it had some volume issue, some when I was changing the volume on the simulator, the volume didn't really changed. When I switched to a real device, everything worked properly |
57,745,554 | I am trying to write a script in python so I can find in 1 sec the COM number of the USB serial adapter I have plugged to my laptop.
What I need is to isolate the COMx port so I can display the result and open putty with that specific port. Can you help me with that?
Until now I have already written a script in batch/... | 2019/09/01 | [
"https://Stackoverflow.com/questions/57745554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4964403/"
] | this is a follow up answer from @MacrosG
i tried a minimal example with properties from Device
```
from infi.devicemanager import DeviceManager
dm = DeviceManager()
dm.root.rescan()
devs = dm.all_devices
print ('Size of Devs: ',len(devs))
for d in devs:
if "USB" in d.description :
print(d.description... | If Python says the strings are not the same I dare say it's quite likely they are not.
You can compare with:
```
if "USB Serial Port" in devs[i]:
```
Then you should be able to find not a complete letter by letter match but one that contains a USB port.
There is no need to use numpy, `devs` is already a list and... |
57,745,554 | I am trying to write a script in python so I can find in 1 sec the COM number of the USB serial adapter I have plugged to my laptop.
What I need is to isolate the COMx port so I can display the result and open putty with that specific port. Can you help me with that?
Until now I have already written a script in batch/... | 2019/09/01 | [
"https://Stackoverflow.com/questions/57745554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4964403/"
] | this is a follow up answer from @MacrosG
i tried a minimal example with properties from Device
```
from infi.devicemanager import DeviceManager
dm = DeviceManager()
dm.root.rescan()
devs = dm.all_devices
print ('Size of Devs: ',len(devs))
for d in devs:
if "USB" in d.description :
print(d.description... | If you want to do this with regular-expressions:
```
def main():
from infi.devicemanager import DeviceManager
import re
device_manager = DeviceManager()
device_manager.root.rescan()
pattern = r"USB Serial Port \(COM(\d)\)"
for device in device_manager.all_devices:
try:
m... |
57,745,554 | I am trying to write a script in python so I can find in 1 sec the COM number of the USB serial adapter I have plugged to my laptop.
What I need is to isolate the COMx port so I can display the result and open putty with that specific port. Can you help me with that?
Until now I have already written a script in batch/... | 2019/09/01 | [
"https://Stackoverflow.com/questions/57745554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4964403/"
] | this is a follow up answer from @MacrosG
i tried a minimal example with properties from Device
```
from infi.devicemanager import DeviceManager
dm = DeviceManager()
dm.root.rescan()
devs = dm.all_devices
print ('Size of Devs: ',len(devs))
for d in devs:
if "USB" in d.description :
print(d.description... | Huge thanks to everyone and especially to bigdataolddriver since I went with his solution
Last thing!
```
for d in devs:
if "USB Serial Port" in d.description :
str = d.__str__()
COMport = str.split('(', 1)[1].split(')')[0]
i=1
break
else:
i=0
if i == 1:
print ("I... |
55,007,820 | I've the following problem : I'm actually making a script for an ovirt server to automatically delete virtual machine which include unregister them from the DNS. But for some very specific virtual machine there is multiple FQDN for an IP address example:
```
myfirstfqdn.com IN A 10.10.10.10
mysecondfqdn.com IN A 10.10... | 2019/03/05 | [
"https://Stackoverflow.com/questions/55007820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8919169/"
] | That's outright impossible. If I am in the right mood, I could add an entry to my DNS server pointing to your IP address. Generally, you cannot find it out (except for some hints in some protocols like http(s)). | Given a zone file in the above format, you could do something like...
```
from collections import defaultdict
zone_file = """myfirstfqdn.com IN A 10.10.10.10
mysecondfqdn.com IN A 10.10.10.10"""
# Build mapping for lookups
ip_fqdn_mapping = defaultdict(list)
for record in zone_file.split("\n"):
fqdn, record_cla... |
52,588,535 | I was trying to pass some arguments via PyCharm when I noticed that it's behaving differently that my console. When I pass arguments with no space in between all works fine, but when my arguments contains spaces inside it the behavior diverge.
```
def main():
"""
Main function
"""
for i, arg in enumera... | 2018/10/01 | [
"https://Stackoverflow.com/questions/52588535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3584765/"
] | You can use [`String.prototype.trim()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trim):
```js
const title1 = "DisneyLand-Paris";
const title2 = "DisneyLand-Paris ";
const trimmed = title2.trim();
console.log(title1 === title2); // false
console.log(title1 === trimmed... | You need to use trim() method
```
const string1 = "DisneyLand-Paris";
const string2 = "DisneyLand-Paris ";
const string3 = "";
if(string1 === string2.trim()){
string3 = `it's the same titles ` ; //here you have to use template literals because of it’s
console.log(string3);
}
``` |
11,329,212 | I have started to look into python and am trying to grasp new things in little chunks, the latest goal i set for myself was to read a tab seperate file of floats into memory and compare values in the list and print the values if difference was as large as the user specified. I have written the following code for it so ... | 2012/07/04 | [
"https://Stackoverflow.com/questions/11329212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1093485/"
] | Try this in place of your list comprehension:
```
y = [float(i) for i in line.split()]
```
*Explanation*:
The data you read from the file are strings, to convert them to other types you need to cast them. So in your case you want to cast your values to float via `float()` .. which you tried, but not quite correctly... | The list comprehension isn't doing what you think it's doing. It's simply assigning each string to the variable `float`, and returning it. Instead you actually want to use another name and call float on it:
```
y = [float(x) for x in line.split()]
``` |
11,329,212 | I have started to look into python and am trying to grasp new things in little chunks, the latest goal i set for myself was to read a tab seperate file of floats into memory and compare values in the list and print the values if difference was as large as the user specified. I have written the following code for it so ... | 2012/07/04 | [
"https://Stackoverflow.com/questions/11329212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1093485/"
] | Try this in place of your list comprehension:
```
y = [float(i) for i in line.split()]
```
*Explanation*:
The data you read from the file are strings, to convert them to other types you need to cast them. So in your case you want to cast your values to float via `float()` .. which you tried, but not quite correctly... | **Error 1**: `y = [float(x) for x in line.split()]` or simply `map(float,lines.split())`
**Error 2**: `if x[j][0] - x[i][0] == float(value): #you didn't converted value to a float` |
46,824,700 | With Rebol pick I can only get one element:
```
list: [1 2 3 4 5 6 7 8 9]
pick list 3
```
In python one can get a whole sub-list with
```
list[3:7]
``` | 2017/10/19 | [
"https://Stackoverflow.com/questions/46824700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/310291/"
] | * [**AT**](http://www.rebol.com/docs/words/wat.html) can seek a position at a list.
* [**COPY**](http://www.rebol.com/r3/docs/functions/copy.html) will copy from a position to the end of list, by default
* the **/PART** refinement of COPY lets you add a limit to copying
Passing an integer to /PART assumes how many thi... | ```
>> list: [1 2 3 4 5 6 7 8 9]
== [1 2 3 4 5 6 7 8 9]
>> copy/part skip list 2 5
== [3 4 5 6 7]
```
So, you can skip to the right location in the list, and then copy as many consecutive members as you need.
If you want an equivalent function, you can write your own. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.