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
|
|---|---|---|---|---|---|
60,577,610
|
I have a Post object with comments and I am trying to send ajax requests in a while loop to check if there have been new comments created, and if there were, add them to the DOM.
How can you achieve that in django?
Here are my models:
```py
class Post(models.Model):
name = models.CharField(max_length=255)
date_added = models.DateTimeField(auto_now_add=True)
last_modified = models.DateTimeField(auto_now=True)
class PostComment(models.Model):
comment = models.TextField()
author = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='post', related_query_name='post')
date_added = models.DateTimeField(auto_now_add=True)
last_modified = models.DateTimeField(auto_now=True)
```
I have tried to look into channels and web sockets but all the tutorials that I have found use old versions of django and python. So I decided to simply achieve the same with ajax requests in a while loop.
I am open to any suggestions about how to achieve my outcome!
|
2020/03/07
|
[
"https://Stackoverflow.com/questions/60577610",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11804213/"
] |
The [merge function](https://www.apollographql.com/docs/react/caching/cache-field-behavior/#the-merge-function) in cache type policies is what you are looking for. It allows you to define a custom strategy for writing incoming data into the cache.
When creating the cache you can define how to write specific fields. Let's assume the `date` field belongs to the `Comment` type:
```js
const cache = new InMemoryCache({
typePolicies: {
Comment: {
fields: {
date: {
merge(_, date) {
return new Date(date);
},
},
},
},
},
});
```
|
Try this one:
```
const { loading, error, data } = useQuery(GET_COMMENTS, {
onCompleted: data => {
// Do changes here
}
});
```
You can check it here <https://www.apollographql.com/docs/react/api/react/hooks/>
|
60,577,610
|
I have a Post object with comments and I am trying to send ajax requests in a while loop to check if there have been new comments created, and if there were, add them to the DOM.
How can you achieve that in django?
Here are my models:
```py
class Post(models.Model):
name = models.CharField(max_length=255)
date_added = models.DateTimeField(auto_now_add=True)
last_modified = models.DateTimeField(auto_now=True)
class PostComment(models.Model):
comment = models.TextField()
author = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='post', related_query_name='post')
date_added = models.DateTimeField(auto_now_add=True)
last_modified = models.DateTimeField(auto_now=True)
```
I have tried to look into channels and web sockets but all the tutorials that I have found use old versions of django and python. So I decided to simply achieve the same with ajax requests in a while loop.
I am open to any suggestions about how to achieve my outcome!
|
2020/03/07
|
[
"https://Stackoverflow.com/questions/60577610",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11804213/"
] |
The [merge function](https://www.apollographql.com/docs/react/caching/cache-field-behavior/#the-merge-function) in cache type policies is what you are looking for. It allows you to define a custom strategy for writing incoming data into the cache.
When creating the cache you can define how to write specific fields. Let's assume the `date` field belongs to the `Comment` type:
```js
const cache = new InMemoryCache({
typePolicies: {
Comment: {
fields: {
date: {
merge(_, date) {
return new Date(date);
},
},
},
},
},
});
```
|
You can call your transformer function inside `onCompleted` and use its result as a state variable.
```
const [myData, setMyData] = useState([]);
const { loading } = useQuery(GET_DATA_QUERY, {
variables: {
options: {
limit: 20
}
},
onCompleted: (response) => {
const transformed = tranformData(response)
setMyData(transformed)
}
});
return (
<div style={{ color: "white" }}>
{loading ? <div>Loading..</div> : <div>{myData.length}</div>}
</div>
);
```
|
4,296,570
|
I'm a webdeveloper and I have a django project that I need to work on.
I am running mac OSX 10.6.5 on a macbook pro. I used macports to install django and python 2.6.
I now have some sort of problem, possibly related to my PATH / PYTHONPATH that prevents me from running django.
In terminal echo $PATH gives:
```
echo $PATH
/Library/Python/2.6/site-packages:/opt/local/bin:/opt/local/sbin:/opt/local/bin:/opt/local/sbin:/opt/local/bin:/opt/local/sbin:/opt/local/bin:/opt/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin
```
and echo $PYTHONPATH gives nothing.
sudo port installed gives :
```
sudo port installed
The following ports are currently installed:
autoconf @2.65_1 (active)
automake @1.11.1_0 (active)
bash-completion @1.1_8
bash-completion @1.2_0 (active)
bzip2 @1.0.5_3+darwin
bzip2 @1.0.6_0 (active)
db46 @4.6.21_6 (active)
expat @2.0.1_0
expat @2.0.1_1 (active)
fontconfig @2.8.0_0+macosx (active)
freetype @2.3.12_0+macosx (active)
gdbm @1.8.3_2 (active)
gettext @0.18_0
gettext @0.18.1.1_2 (active)
gperf @3.0.4_0 (active)
help2man @1.38.2_0 (active)
ImageMagick @6.6.2-0_0+q16 (active)
jpeg @8a_0 (active)
lcms @1.19_2 (active)
libiconv @1.13.1_0 (active)
libpng @1.2.43_0 (active)
libtool @2.2.6b_1+darwin (active)
libxml2 @2.7.7_0 (active)
m4 @1.4.14_0 (active)
ncurses @5.7_0+darwin_10
ncurses @5.7_1 (active)
ncursesw @5.7_0+darwin_10
ncursesw @5.7_1 (active)
openssl @1.0.0b_0 (active)
p5-locale-gettext @1.05_2 (active)
p7zip @9.04_0 (active)
perl5 @5.8.9_0 (active)
perl5.8 @5.8.9_3 (active)
pkgconfig @0.25_0 (active)
py26-distribute @0.6.14_0 (active)
py26-django @1.2.3_0+bash_completion (active)
python26 @2.6.6_0+no_tkinter (active)
readline @6.1.002_0 (active)
sqlite3 @3.7.3_0 (active)
tiff @3.9.2_3+macosx (active)
xorg-bigreqsproto @1.1.0_0 (active)
xorg-inputproto @2.0_0 (active)
xorg-kbproto @1.0.4_0 (active)
xorg-libice @1.0.6_0 (active)
xorg-libsm @1.1.1_0 (active)
xorg-libX11 @1.3.3_0 (active)
xorg-libXau @1.0.5_0 (active)
xorg-libXdmcp @1.0.3_0 (active)
xorg-libXext @1.1.1_0 (active)
xorg-libXt @1.0.8_0 (active)
xorg-util-macros @1.7.0_0 (active)
xorg-xcmiscproto @1.2.0_0 (active)
xorg-xextproto @7.1.1_0 (active)
xorg-xf86bigfontproto @1.2.0_0 (active)
xorg-xproto @7.0.16_0 (active)
xorg-xtrans @1.2.5_0 (active)
zlib @1.2.5_0 (active)
```
and when I type python I get:
```
python
Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
```
I'm pretty certain that this is the incorrect version.
When I try and test if django is available to python I get:
```
>>> import django
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named django
>>>
```
Could anyone help me figure out what is going on here? I only need to get django running so that I can view and work on the django project that my colleague sent me.
Thanks for any help in advance!
|
2010/11/28
|
[
"https://Stackoverflow.com/questions/4296570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/522909/"
] |
First, Macports writes the file ~/.profile to set its PATH variables. If you have created a ~/.bash\_profile file then ~/.profile will be **ignored**. You will have to copy the contents over.
To see what python version Macports has selected use:
```
port select --list python
```
which will show you something like this:
```
Available versions for python:
none
python25-apple
python26-apple
python27 (active)
python32
```
To tell Macports to use a specific version use:
```
port select --set python python27
```
That should get your python version correct. You can use the python easy\_install to install Django now or use the Macports distribution of Django.
|
Is that really the Python interpreter installed by macports? 2.6.1 smells like the Apple provided one to me (2.6.1 is quite old).
try,
```
which python
```
As an aside, I wouldn't install Django using macports.
EDIT: Macports installed 2.6.6, the problem is the apple provided python is earlier on your path.
```
python26 @2.6.6_0+no_tkinter (active)
```
EDIT:
I use python from homebrew, which by default goes in /usr/local/bin/python.
To use this, I have a line in my .bashrc, but it could go at the end of your /etc/profile
```
export PATH=/usr/local/bin:/usr/local/sbin:$PATH
```
What that does is prepends my system path with location of my homebrew installs (/usr/local)
In your case, it should be where your macports python (the 2.6.6 one) can be found.
HTH
|
4,296,570
|
I'm a webdeveloper and I have a django project that I need to work on.
I am running mac OSX 10.6.5 on a macbook pro. I used macports to install django and python 2.6.
I now have some sort of problem, possibly related to my PATH / PYTHONPATH that prevents me from running django.
In terminal echo $PATH gives:
```
echo $PATH
/Library/Python/2.6/site-packages:/opt/local/bin:/opt/local/sbin:/opt/local/bin:/opt/local/sbin:/opt/local/bin:/opt/local/sbin:/opt/local/bin:/opt/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin
```
and echo $PYTHONPATH gives nothing.
sudo port installed gives :
```
sudo port installed
The following ports are currently installed:
autoconf @2.65_1 (active)
automake @1.11.1_0 (active)
bash-completion @1.1_8
bash-completion @1.2_0 (active)
bzip2 @1.0.5_3+darwin
bzip2 @1.0.6_0 (active)
db46 @4.6.21_6 (active)
expat @2.0.1_0
expat @2.0.1_1 (active)
fontconfig @2.8.0_0+macosx (active)
freetype @2.3.12_0+macosx (active)
gdbm @1.8.3_2 (active)
gettext @0.18_0
gettext @0.18.1.1_2 (active)
gperf @3.0.4_0 (active)
help2man @1.38.2_0 (active)
ImageMagick @6.6.2-0_0+q16 (active)
jpeg @8a_0 (active)
lcms @1.19_2 (active)
libiconv @1.13.1_0 (active)
libpng @1.2.43_0 (active)
libtool @2.2.6b_1+darwin (active)
libxml2 @2.7.7_0 (active)
m4 @1.4.14_0 (active)
ncurses @5.7_0+darwin_10
ncurses @5.7_1 (active)
ncursesw @5.7_0+darwin_10
ncursesw @5.7_1 (active)
openssl @1.0.0b_0 (active)
p5-locale-gettext @1.05_2 (active)
p7zip @9.04_0 (active)
perl5 @5.8.9_0 (active)
perl5.8 @5.8.9_3 (active)
pkgconfig @0.25_0 (active)
py26-distribute @0.6.14_0 (active)
py26-django @1.2.3_0+bash_completion (active)
python26 @2.6.6_0+no_tkinter (active)
readline @6.1.002_0 (active)
sqlite3 @3.7.3_0 (active)
tiff @3.9.2_3+macosx (active)
xorg-bigreqsproto @1.1.0_0 (active)
xorg-inputproto @2.0_0 (active)
xorg-kbproto @1.0.4_0 (active)
xorg-libice @1.0.6_0 (active)
xorg-libsm @1.1.1_0 (active)
xorg-libX11 @1.3.3_0 (active)
xorg-libXau @1.0.5_0 (active)
xorg-libXdmcp @1.0.3_0 (active)
xorg-libXext @1.1.1_0 (active)
xorg-libXt @1.0.8_0 (active)
xorg-util-macros @1.7.0_0 (active)
xorg-xcmiscproto @1.2.0_0 (active)
xorg-xextproto @7.1.1_0 (active)
xorg-xf86bigfontproto @1.2.0_0 (active)
xorg-xproto @7.0.16_0 (active)
xorg-xtrans @1.2.5_0 (active)
zlib @1.2.5_0 (active)
```
and when I type python I get:
```
python
Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
```
I'm pretty certain that this is the incorrect version.
When I try and test if django is available to python I get:
```
>>> import django
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named django
>>>
```
Could anyone help me figure out what is going on here? I only need to get django running so that I can view and work on the django project that my colleague sent me.
Thanks for any help in advance!
|
2010/11/28
|
[
"https://Stackoverflow.com/questions/4296570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/522909/"
] |
First, Macports writes the file ~/.profile to set its PATH variables. If you have created a ~/.bash\_profile file then ~/.profile will be **ignored**. You will have to copy the contents over.
To see what python version Macports has selected use:
```
port select --list python
```
which will show you something like this:
```
Available versions for python:
none
python25-apple
python26-apple
python27 (active)
python32
```
To tell Macports to use a specific version use:
```
port select --set python python27
```
That should get your python version correct. You can use the python easy\_install to install Django now or use the Macports distribution of Django.
|
Both Python 2.6.1 and 2.6.6 should work fine with django. But if you want to use 2.6.6, just add the location of that to your PATH variable now that you've taken the older python off of your path.
To get Django working, try putting the location of django on your PYTHONPATH. On a mac, if django is installed in /Library/Django-1.2.1 add:
`export PYTHONPATH=$PYTHONPATH:/Library/Django-1.2.1`
to your ~/.bash\_profile file. (then run `source ~/.bash_profile` to refresh it).
If that doesn't work, I would re-install django. I've never used macports, but installing python packages with pip has always worked well for me. Delete your old django files and run `easy-install pip` and then `pip -install django` should do the trick - that will install django in your site-packages directory, so it will be on your path and ready to go.
|
4,296,570
|
I'm a webdeveloper and I have a django project that I need to work on.
I am running mac OSX 10.6.5 on a macbook pro. I used macports to install django and python 2.6.
I now have some sort of problem, possibly related to my PATH / PYTHONPATH that prevents me from running django.
In terminal echo $PATH gives:
```
echo $PATH
/Library/Python/2.6/site-packages:/opt/local/bin:/opt/local/sbin:/opt/local/bin:/opt/local/sbin:/opt/local/bin:/opt/local/sbin:/opt/local/bin:/opt/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin
```
and echo $PYTHONPATH gives nothing.
sudo port installed gives :
```
sudo port installed
The following ports are currently installed:
autoconf @2.65_1 (active)
automake @1.11.1_0 (active)
bash-completion @1.1_8
bash-completion @1.2_0 (active)
bzip2 @1.0.5_3+darwin
bzip2 @1.0.6_0 (active)
db46 @4.6.21_6 (active)
expat @2.0.1_0
expat @2.0.1_1 (active)
fontconfig @2.8.0_0+macosx (active)
freetype @2.3.12_0+macosx (active)
gdbm @1.8.3_2 (active)
gettext @0.18_0
gettext @0.18.1.1_2 (active)
gperf @3.0.4_0 (active)
help2man @1.38.2_0 (active)
ImageMagick @6.6.2-0_0+q16 (active)
jpeg @8a_0 (active)
lcms @1.19_2 (active)
libiconv @1.13.1_0 (active)
libpng @1.2.43_0 (active)
libtool @2.2.6b_1+darwin (active)
libxml2 @2.7.7_0 (active)
m4 @1.4.14_0 (active)
ncurses @5.7_0+darwin_10
ncurses @5.7_1 (active)
ncursesw @5.7_0+darwin_10
ncursesw @5.7_1 (active)
openssl @1.0.0b_0 (active)
p5-locale-gettext @1.05_2 (active)
p7zip @9.04_0 (active)
perl5 @5.8.9_0 (active)
perl5.8 @5.8.9_3 (active)
pkgconfig @0.25_0 (active)
py26-distribute @0.6.14_0 (active)
py26-django @1.2.3_0+bash_completion (active)
python26 @2.6.6_0+no_tkinter (active)
readline @6.1.002_0 (active)
sqlite3 @3.7.3_0 (active)
tiff @3.9.2_3+macosx (active)
xorg-bigreqsproto @1.1.0_0 (active)
xorg-inputproto @2.0_0 (active)
xorg-kbproto @1.0.4_0 (active)
xorg-libice @1.0.6_0 (active)
xorg-libsm @1.1.1_0 (active)
xorg-libX11 @1.3.3_0 (active)
xorg-libXau @1.0.5_0 (active)
xorg-libXdmcp @1.0.3_0 (active)
xorg-libXext @1.1.1_0 (active)
xorg-libXt @1.0.8_0 (active)
xorg-util-macros @1.7.0_0 (active)
xorg-xcmiscproto @1.2.0_0 (active)
xorg-xextproto @7.1.1_0 (active)
xorg-xf86bigfontproto @1.2.0_0 (active)
xorg-xproto @7.0.16_0 (active)
xorg-xtrans @1.2.5_0 (active)
zlib @1.2.5_0 (active)
```
and when I type python I get:
```
python
Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
```
I'm pretty certain that this is the incorrect version.
When I try and test if django is available to python I get:
```
>>> import django
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named django
>>>
```
Could anyone help me figure out what is going on here? I only need to get django running so that I can view and work on the django project that my colleague sent me.
Thanks for any help in advance!
|
2010/11/28
|
[
"https://Stackoverflow.com/questions/4296570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/522909/"
] |
First, Macports writes the file ~/.profile to set its PATH variables. If you have created a ~/.bash\_profile file then ~/.profile will be **ignored**. You will have to copy the contents over.
To see what python version Macports has selected use:
```
port select --list python
```
which will show you something like this:
```
Available versions for python:
none
python25-apple
python26-apple
python27 (active)
python32
```
To tell Macports to use a specific version use:
```
port select --set python python27
```
That should get your python version correct. You can use the python easy\_install to install Django now or use the Macports distribution of Django.
|
I had the same problem. Turns out, after running
```
sudo port install py26-django
```
You have two different python environments.
You end up python2.6 installed and symlinked from /opt/local/bin/python2.6, but this directory doesn't have "python", just "python2.6". So when you run "python", you still pick up the default python installation.
To fix the issue, do
```
cd /opt/local/bin
sudo ln -s python2.6 python
```
Since /opt/local/bin is first on your PATH, running "python" would pick-up the environment installed by macport.
|
64,698,542
|
The Nvidia model is showing error for strides, even if I initialize them to the default value of (1,1)
I am using 'strides' as a replacement for the 'subsample' argument in previous versions of keras can someone explain the new syntax of using them.
```
def nvidia_model():
model = Sequential()
model.add(Conv2D(24,5,5, strides = (2,2), input_shape= (66,200,3), activation='relu'))
model.add(Conv2D(36,5,5, strides = (2,2), activation = 'relu'))
model.add(Conv2D(48,5,5, strides = (2,2), activation = 'relu'))
model.add(Conv2D(64,3,3, activation = 'relu'))
model.add(Conv2D(64,3,3, activation = 'relu'))
model.add(Dropout(0.5)) #50% nodes turned to zero
model.add( Flatten())
model.add(Dense(100, activation ='relu'))
model.add(Dropout(0.5))
model.add(Dense(50, activation ='relu'))
model.add(Dense(10, activation ='relu'))
model.add(Dense(1))
optimizer = Adam(lr = 1e-3)
model.compile(loss = 'mse' , optimizer = optimizer)
return model
model = nvidia_model()
print(model.summary)
```
```
Error:
TypeError Traceback (most recent call last)
<ipython-input-83-aff2a2709b79> in <module>()
----> 1 model = nvidia_model()
2 print(model.summary)
<ipython-input-82-7942ade664af> in nvidia_model()
1 def nvidia_model():
2 model = Sequential()
----> 3 model.add(Conv2D(24,5,5, strides = (2,2), input_shape= (66,200,3), activation='relu'))
4 model.add(Conv2D(36,5,5, strides = (2,2), activation = 'relu'))
5 model.add(Conv2D(48,5,5, strides = (2,2), activation = 'relu'))
TypeError: __init__() got multiple values for argument 'strides'
```
|
2020/11/05
|
[
"https://Stackoverflow.com/questions/64698542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13301154/"
] |
I never worked with `tensorflow`, but according to the documentation of [`Conv2D`](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Conv2D) it's defined as
```
tf.keras.layers.Conv2D(
filters, kernel_size, strides=(1, 1), padding='valid', data_format=None,
dilation_rate=(1, 1), groups=1, activation=None, use_bias=True,
kernel_initializer='glorot_uniform', bias_initializer='zeros',
kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None,
kernel_constraint=None, bias_constraint=None, **kwargs
)
```
As you can see `strides` is the third parameter.
Now you use `Conv2D(24,5,5, strides = (2,2), input_shape= (66,200,3), activation='relu')` where the third parameter is `5` and then you try to set `strides` again with the keyword parameter. It seems there is one parameter too much in your call.
Imagine the little Python gnome handling your code: "OK, the boss wants an instance of `Conv2D`. He sets the first argument `filters` to `4`, the second argument `kernel_size` to `2` and the third argument `strides`to `2`. Done with the positional arguments. Now let's continue with the keyword arguments. Here we have `strides` and ... oh, I already have `strides`, so I don't know what to do. The boss might be angry so I'll tell him exactly what happenend: `TypeError: __init__() got multiple values for argument 'strides'`"
|
```
model.add(Conv2D(24,5,5, strides = (2,2), input_shape= (66,200,3), activation='relu'))
model.add(Conv2D(36,5,5, strides = (2,2), activation = 'relu'))
model.add(Conv2D(48,5,5, strides = (2,2), activation = 'relu'))
```
For these lines use parentheses like the following example
```
model.add(Conv2D(24,(5,5), strides = (2,2), input_shape= (66,200,3), activation='relu'))
model.add(Conv2D(36,(5,5), strides = (2,2), activation = 'relu'))
model.add(Conv2D(48,(5,5), strides = (2,2), activation = 'relu'))
```
|
74,416,745
|
I have been successfully using Google Build for continuous integration with Google Cloud Run for the Django Application.
However recently psycop2-binary started giving errors as below
```
Step #0 - "Buildpack": ββββββββββββββββββββββββββββββββββββββ 202.7/202.7 kB
28.3 MB/s eta 0:00:00
Step #0 - "Buildpack": Collecting google-cloud-build==3.9.0
Step #0 - "Buildpack": Downloading google_cloud_build-3.9.0-py2.py3-none-any.whl (88 kB)
Step #0 - "Buildpack": ββββββββββββββββββββββββββββββββββββββββ 88.2/88.2 kB 13.0 MB/s eta 0:00:00
Step #0 - "Buildpack": Collecting psycopg2-binary==2.9.3
Step #0 - "Buildpack": Downloading psycopg2-binary-2.9.3.tar.gz (380 kB)
Step #0 - "Buildpack": ββββββββββββββββββββββββββββββββββββββ 380.6/380.6 kB 39.3 MB/s eta 0:00:00
Step #0 - "Buildpack": Preparing metadata (setup.py): started
Step #0 - "Buildpack": Preparing metadata (setup.py): finished with status 'error'
Step #0 - "Buildpack": error: subprocess-exited-with-error
Step #0 - "Buildpack":
Step #0 - "Buildpack": Γ python setup.py egg_info did not run successfully.
Step #0 - "Buildpack": β exit code: 1
Step #0 - "Buildpack": β°β> [25 lines of output]
Step #0 - "Buildpack": /layers/google.python.runtime/python/lib/python3.11/site-packages/setuptools/config/setupcfg.py:508: SetuptoolsDeprecationWarning: The license_file parameter is deprecated, use license_files instead.
Step #0 - "Buildpack": warnings.warn(msg, warning_class)
Step #0 - "Buildpack": running egg_info
Step #0 - "Buildpack": creating /tmp/pip-pip-egg-info-a97zvtp4/psycopg2_binary.egg-info
Step #0 - "Buildpack": writing /tmp/pip-pip-egg-info-a97zvtp4/psycopg2_binary.egg-info/PKG-INFO
Step #0 - "Buildpack": writing dependency_links to /tmp/pip-pip-egg-info-a97zvtp4/psycopg2_binary.egg-info/dependency_links.txt
Step #0 - "Buildpack": writing top-level names to /tmp/pip-pip-egg-info-a97zvtp4/psycopg2_binary.egg-info/top_level.txt
Step #0 - "Buildpack": writing manifest file '/tmp/pip-pip-egg-info-a97zvtp4/psycopg2_binary.egg-info/SOURCES.txt'
Step #0 - "Buildpack":
Step #0 - "Buildpack": Error: pg_config executable not found.
Step #0 - "Buildpack":
Step #0 - "Buildpack": pg_config is required to build psycopg2 from source. Please add the directory
Step #0 - "Buildpack": containing pg_config to the $PATH or specify the full executable path with the
Step #0 - "Buildpack": option:
Step #0 - "Buildpack":
Step #0 - "Buildpack": python setup.py build_ext --pg-config /path/to/pg_config build ...
Step #0 - "Buildpack":
Step #0 - "Buildpack": or with the pg_config option in 'setup.cfg'.
Step #0 - "Buildpack":
Step #0 - "Buildpack": If you prefer to avoid building psycopg2 from source, please install the PyPI
Step #0 - "Buildpack": 'psycopg2-binary' package instead.
Step #0 - "Buildpack":
Step #0 - "Buildpack": For further information please check the 'doc/src/install.rst' file (also at
Step #0 - "Buildpack": <https://www.psycopg.org/docs/install.html>).
Step #0 - "Buildpack":
Step #0 - "Buildpack": [end of output]
Step #0 - "Buildpack":
Step #0 - "Buildpack": note: This error originates from a subprocess, and is likely not a problem with pip.
Step #0 - "Buildpack": error: metadata-generation-failed
Step #0 - "Buildpack":
Step #0 - "Buildpack": Γ Encountered error while generating package metadata.
Step #0 - "Buildpack": β°β> See above for output.
Step #0 - "Buildpack":
Step #0 - "Buildpack": note: This is an issue with the package mentioned above, not pip.
Step #0 - "Buildpack": hint: See above for details.
Step #0 - "Buildpack": Done "python3 -m pip install --requirement requirements.txt --upgr..." (5.263140792s)
Step #0 - "Buildpack": Failure: (ID: c84b3231) ...bernetes==24.2.0
Step #0 - "Buildpack": Downloading kubernetes-24.2.0-py2.py3-none-any.whl (1.5 MB)
Step #0 - "Buildpack": ββββββββββββββββββββββββββββββββββββββββ 1.5/1.5 MB 72.6 MB/s eta 0:00:00
Step #0 - "Buildpack": Collecting google-cloud-container==2.11.0
Step #0 - "Buildpack": Downloading google_cloud_container-2.11.0-py2.py3-none-any.whl (202 kB)
Step #0 - "Buildpack": ββββββββββββββββββββββββββββββββββββββ 202.7/202.7 kB 28.3 MB/s eta 0:00:00
Step #0 - "Buildpack": Collecting google-cloud-build==3.9.0
Step #0 - "Buildpack": Downloading google_cloud_build-3.9.0-py2.py3-none-any.whl (88 kB)
Step #0 - "Buildpack": ββββββββββββββββββββββββββββββββββββββββ 88.2/88.2 kB 13.0 MB/s eta 0:00:00
Step #0 - "Buildpack": Collecting psycopg2-binary==2.9.3
Step #0 - "Buildpack": Downloading psycopg2-binary-2.9.3.tar.gz (380 kB)
Step #0 - "Buildpack": ββββββββββββββββββββββββββββββββββββββ 380.6/380.6 kB 39.3 MB/s eta 0:00:00
Step #0 - "Buildpack": Preparing metadata (setup.py): started
Step #0 - "Buildpack": Preparing metadata (setup.py): finished with status 'error'
Step #0 - "Buildpack": error: subprocess-exited-with-error
Step #0 - "Buildpack":
Step #0 - "Buildpack": Γ python setup.py egg_info did not run successfully.
Step #0 - "Buildpack": β exit code: 1
Step #0 - "Buildpack": β°β> [25 lines of output]
Step #0 - "Buildpack": /layers/google.python.runtime/python/lib/python3.11/site-packages/setuptools/config/setupcfg.py:508: SetuptoolsDeprecationWarning: The license_file parameter is deprecated, use license_files instead.
Step #0 - "Buildpack": warnings.warn(msg, warning_class)
Step #0 - "Buildpack": running egg_info
Step #0 - "Buildpack": creating /tmp/pip-pip-egg-info-a97zvtp4/psycopg2_binary.egg-info
Step #0 - "Buildpack": writing /tmp/pip-pip-egg-info-a97zvtp4/psycopg2_binary.egg-info/PKG-INFO
Step #0 - "Buildpack": writing dependency_links to /tmp/pip-pip-egg-info-a97zvtp4/psycopg2_binary.egg-info/dependency_links.txt
Step #0 - "Buildpack": writing top-level names to /tmp/pip-pip-egg-info-a97zvtp4/psycopg2_binary.egg-info/top_level.txt
Step #0 - "Buildpack": writing manifest file '/tmp/pip-pip-egg-info-a97zvtp4/psycopg2_binary.egg-info/SOURCES.txt'
Step #0 - "Buildpack":
Step #0 - "Buildpack": Error: pg_config executable not found.
Step #0 - "Buildpack":
Step #0 - "Buildpack": pg_config is required to build psycopg2 from source. Please add the directory
Step #0 - "Buildpack": containing pg_config to the $PATH or specify the full executable path with the
Step #0 - "Buildpack": option:
Step #0 - "Buildpack":
Step #0 - "Buildpack": python setup.py build_ext --pg-config /path/to/pg_config build ...
Step #0 - "Buildpack":
Step #0 - "Buildpack": or with the pg_config option in 'setup.cfg'.
Step #0 - "Buildpack":
Step #0 - "Buildpack": If you prefer to avoid building psycopg2 from source, please install the PyPI
Step #0 - "Buildpack": 'psycopg2-binary' package instead.
Step #0 - "Buildpack":
Step #0 - "Buildpack": For further information please check the 'doc/src/install.rst' file (also at
Step #0 - "Buildpack": <https://www.psycopg.org/docs/install.html>).
Step #0 - "Buildpack":
Step #0 - "Buildpack": [end of output]
Step #0 - "Buildpack":
Step #0 - "Buildpack": note: This error originates from a subprocess, and is likely not a problem with pip.
Step #0 - "Buildpack": error: metadata-generation-failed
Step #0 - "Buildpack":
Step #0 - "Buildpack": Γ Encountered error while generating package metadata.
Step #0 - "Buildpack": β°β> See above for output.
Step #0 - "Buildpack":
Step #0 - "Buildpack": note: This is an issue with the package mentioned above, not pip.
Step #0 - "Buildpack": hint: See above for details.
Step #0 - "Buildpack": --------------------------------------------------------------------------------
Step #0 - "Buildpack": Sorry your project couldn't be built.
Step #0 - "Buildpack": Our documentation explains ways to configure Buildpacks to better recognise your project:
Step #0 - "Buildpack": -> https://github.com/GoogleCloudPlatform/buildpacks/blob/main/README.md
Step #0 - "Buildpack": If you think you've found an issue, please report it:
Step #0 - "Buildpack": -> https://github.com/GoogleCloudPlatform/buildpacks/issues/new
Step #0 - "Buildpack": --------------------------------------------------------------------------------
Step #0 - "Buildpack": ERROR: failed to build: exit status 1
Step #0 - "Buildpack": ERROR: failed to build: executing lifecycle: failed with status code: 51
Finished Step #0 - "Buildpack"
ERROR
ERROR: build step 0 "gcr.io/k8s-skaffold/pack" failed: step exited with non-zero status: 1
```
You can find the requirements information as below as well :
```
Django==3.1.0
google-auth
google-cloud
google-cloud-pubsub==2.5.0
google-cloud-storage==1.25.0
google-cloud-secret-manager==0.1.1
django-sitemap-generate==0.5.0
django-cors-headers==3.2.1
djangorestframework==3.11.1
django-storages==1.9.1
django-anymail[mailgun]
django-robots==4.0
python-dateutil==2.8.1
gunicorn==20.0.4
requests==2.23.0
stripe==2.43.0
six==1.14.0
google-api-python-client==1.8.3
pyparsing==2.4.7
protobuf==3.20.*
djangorestframework-jwt==1.10.0
djangorestframework-simplejwt==5.2.0
django-filter==21.1
google-cloud-logging>=3.0.0
kubernetes==24.2.0
google-cloud-container==2.11.0
google-cloud-build==3.9.0
psycopg2-binary==2.9.3
```
How can I fix this issue ?
Update :
Pip version is already 22.3.1.
```
Step #0 - "Buildpack": Running "sed -i s|/opt/python3.11|/layers/google.python.runtime/python|g /layers/google.python.runtime/python/bin/2to3-3.11"
Step #0 - "Buildpack": Done "sed -i s|/opt/python3.11|/layers/google.python.runtime/pytho..." (1.28464ms)
Step #0 - "Buildpack": Upgrading pip to the latest version and installing build tools
Step #0 - "Buildpack": --------------------------------------------------------------------------------
Step #0 - "Buildpack": Running "/layers/google.python.runtime/python/bin/python3 -m pip install --upgrade pip setuptools==v64.0.0 wheel"
Step #0 - "Buildpack": Requirement already satisfied: pip in /layers/google.python.runtime/python/lib/python3.11/site-packages (22.3)
Step #0 - "Buildpack": Collecting pip
Step #0 - "Buildpack": Downloading pip-22.3.1-py3-none-any.whl (2.1 MB)
Step #0 - "Buildpack": ββββββββββββββββββββββββββββββββββββββββ 2.1/2.1 MB 25.2 MB/s eta 0:00:00
Step #0 - "Buildpack": Collecting setuptools==v64.0.0
Step #0 - "Buildpack": Downloading setuptools-64.0.0-py3-none-any.whl (1.2 MB)
Step #0 - "Buildpack": ββββββββββββββββββββββββββββββββββββββββ 1.2/1.2 MB 80.9 MB/s eta 0:00:00
```
|
2022/11/12
|
[
"https://Stackoverflow.com/questions/74416745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5342009/"
] |
In addition to your answer @london\_utku for new feature in psycopg 2.9.5
* Add support for Python 3.11.
* Add support for rowcount in MERGE statements in binary packages
(ticket #1497).
* Wheel package compiled against OpenSSL 1.1.1r and PostgreSQL 15
libpq.
You can also review all the Release notes for [Psycopg 2.9.5 documentation](https://www.psycopg.org/docs/news.html#what-s-new-in-psycopg-2-9-5)
|
Updated psycopg2-binary to 2.9.5, and the situation is resolved.
|
34,357,513
|
I love python one liners:
```
u = payload.get("actor", {}).get("username", "")
```
Problem I face is, I have no control over what 'payload' contains, other than knowing it is a dictionary. So, if 'payload' does not have "actor", or it does and actor does or doesn't have "username", this one-liner is fine.
Problem of course arises when payload DOES have actor, but actor is not a dictionary.
Is there as pretty a way to do this comprehensively as a one liner, *and consider the possibility that 'actor' may not be a dictionary?*
Of course I can check the type using 'isinstance', but that's not as nice.
I'm not requiring a one liner per se, just asking for the most efficient way to ensure 'u' gets populated, without exception, and without prior knowledge of what exactly is in 'payload'.
|
2015/12/18
|
[
"https://Stackoverflow.com/questions/34357513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1222167/"
] |
Why not use an Exception:
```
try:
u = payload.get("actor", {}).get("username", "")
except AttributeError:
u = ""
```
|
If you really need to do it in 1 line, you'll have to implement the functionality yourself. Which is worth doing if you use this semantics many times in your program.
There are two ways to do it: function or custom dictionary-like object for `payload`.
1) Function handles the case of `actor` being not a `dict`. It can check for `isinstance` or do the `try` or whatever else -- it's not essential. The usage would look something like `u = get("username", "", payload.get("actor", {}))` or `u = get("", payload, 'actor', 'username')` (with arbitrary amount of nested calls for items in `payload`).
2) A class of custom objects is a powerful thing -- do it if you can and really need this abstraction in the program. A descendant of `dict` or `UserDict` (in Python3) can check for what it stores or outputs on `__getitem__` calls.
|
34,357,513
|
I love python one liners:
```
u = payload.get("actor", {}).get("username", "")
```
Problem I face is, I have no control over what 'payload' contains, other than knowing it is a dictionary. So, if 'payload' does not have "actor", or it does and actor does or doesn't have "username", this one-liner is fine.
Problem of course arises when payload DOES have actor, but actor is not a dictionary.
Is there as pretty a way to do this comprehensively as a one liner, *and consider the possibility that 'actor' may not be a dictionary?*
Of course I can check the type using 'isinstance', but that's not as nice.
I'm not requiring a one liner per se, just asking for the most efficient way to ensure 'u' gets populated, without exception, and without prior knowledge of what exactly is in 'payload'.
|
2015/12/18
|
[
"https://Stackoverflow.com/questions/34357513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1222167/"
] |
### Using EAFP
As xnx suggested, you can take advantage of the following python paradigm:
>
> [Easier to ask for forgiveness than permission](https://docs.python.org/3/glossary.html#term-eafp)
>
>
>
you can use it on `KeyError`s as well:
```
try:
u = payload["actor"]["username"]
except (AttributeError, KeyError):
u = ""
```
### Using a wrapper with forgiving indexing
Sometimes it would be nice to have something like null-conditional operators in Python. With some helper class this can be compressed into a one-liner expression:
```
class Forgive:
def __init__(self, value = None):
self.value = value
def __getitem__(self, name):
if self.value is None:
return Forgive()
try:
return Forgive(self.value.__getitem__(name))
except (KeyError, AttributeError):
return Forgive()
def get(self, default = None):
return default if self.value is None else self.value
data = {'actor':{'username': 'Joe'}}
print(Forgive(data)['actor']['username'].get('default1'))
print(Forgive(data)['actor']['address'].get('default2'))
```
ps: one could redefine `__getattr__` as well besides `__getitem__`, so you could even write `Forgive(data)['actor'].username.get('default1')`.
|
Why not use an Exception:
```
try:
u = payload.get("actor", {}).get("username", "")
except AttributeError:
u = ""
```
|
34,357,513
|
I love python one liners:
```
u = payload.get("actor", {}).get("username", "")
```
Problem I face is, I have no control over what 'payload' contains, other than knowing it is a dictionary. So, if 'payload' does not have "actor", or it does and actor does or doesn't have "username", this one-liner is fine.
Problem of course arises when payload DOES have actor, but actor is not a dictionary.
Is there as pretty a way to do this comprehensively as a one liner, *and consider the possibility that 'actor' may not be a dictionary?*
Of course I can check the type using 'isinstance', but that's not as nice.
I'm not requiring a one liner per se, just asking for the most efficient way to ensure 'u' gets populated, without exception, and without prior knowledge of what exactly is in 'payload'.
|
2015/12/18
|
[
"https://Stackoverflow.com/questions/34357513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1222167/"
] |
Why not use an Exception:
```
try:
u = payload.get("actor", {}).get("username", "")
except AttributeError:
u = ""
```
|
The answer hege\_hegedus gave is correct, however there's one caveat in that exception handling is a lot slower than going through if..else statement.
For example if you're iterating over thousands of `payload` object and an actor entry is only occasionally not a dictionary, this code is perfectly valid.
However if you're iterating over thousands of `payload` objects and every other `actor` entry is not a dictionary then you'd be better off with this code.
```
u = ''
if 'actor' in payload and isinstance(payload['actor'], dict):
u = payload['actor'].get('username', '')
```
For more discussion go here -- <https://mail.python.org/pipermail/tutor/2011-January/081143.html>
UPDATE
Also the code statement can be re-written as a one-liner albeit not nearly as legible as two-line statement
```
u = payload['actor'].get('username', '') if 'actor' in payload and isinstance(payload['actor'], dict) else ''
```
|
34,357,513
|
I love python one liners:
```
u = payload.get("actor", {}).get("username", "")
```
Problem I face is, I have no control over what 'payload' contains, other than knowing it is a dictionary. So, if 'payload' does not have "actor", or it does and actor does or doesn't have "username", this one-liner is fine.
Problem of course arises when payload DOES have actor, but actor is not a dictionary.
Is there as pretty a way to do this comprehensively as a one liner, *and consider the possibility that 'actor' may not be a dictionary?*
Of course I can check the type using 'isinstance', but that's not as nice.
I'm not requiring a one liner per se, just asking for the most efficient way to ensure 'u' gets populated, without exception, and without prior knowledge of what exactly is in 'payload'.
|
2015/12/18
|
[
"https://Stackoverflow.com/questions/34357513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1222167/"
] |
### Using EAFP
As xnx suggested, you can take advantage of the following python paradigm:
>
> [Easier to ask for forgiveness than permission](https://docs.python.org/3/glossary.html#term-eafp)
>
>
>
you can use it on `KeyError`s as well:
```
try:
u = payload["actor"]["username"]
except (AttributeError, KeyError):
u = ""
```
### Using a wrapper with forgiving indexing
Sometimes it would be nice to have something like null-conditional operators in Python. With some helper class this can be compressed into a one-liner expression:
```
class Forgive:
def __init__(self, value = None):
self.value = value
def __getitem__(self, name):
if self.value is None:
return Forgive()
try:
return Forgive(self.value.__getitem__(name))
except (KeyError, AttributeError):
return Forgive()
def get(self, default = None):
return default if self.value is None else self.value
data = {'actor':{'username': 'Joe'}}
print(Forgive(data)['actor']['username'].get('default1'))
print(Forgive(data)['actor']['address'].get('default2'))
```
ps: one could redefine `__getattr__` as well besides `__getitem__`, so you could even write `Forgive(data)['actor'].username.get('default1')`.
|
If you really need to do it in 1 line, you'll have to implement the functionality yourself. Which is worth doing if you use this semantics many times in your program.
There are two ways to do it: function or custom dictionary-like object for `payload`.
1) Function handles the case of `actor` being not a `dict`. It can check for `isinstance` or do the `try` or whatever else -- it's not essential. The usage would look something like `u = get("username", "", payload.get("actor", {}))` or `u = get("", payload, 'actor', 'username')` (with arbitrary amount of nested calls for items in `payload`).
2) A class of custom objects is a powerful thing -- do it if you can and really need this abstraction in the program. A descendant of `dict` or `UserDict` (in Python3) can check for what it stores or outputs on `__getitem__` calls.
|
34,357,513
|
I love python one liners:
```
u = payload.get("actor", {}).get("username", "")
```
Problem I face is, I have no control over what 'payload' contains, other than knowing it is a dictionary. So, if 'payload' does not have "actor", or it does and actor does or doesn't have "username", this one-liner is fine.
Problem of course arises when payload DOES have actor, but actor is not a dictionary.
Is there as pretty a way to do this comprehensively as a one liner, *and consider the possibility that 'actor' may not be a dictionary?*
Of course I can check the type using 'isinstance', but that's not as nice.
I'm not requiring a one liner per se, just asking for the most efficient way to ensure 'u' gets populated, without exception, and without prior knowledge of what exactly is in 'payload'.
|
2015/12/18
|
[
"https://Stackoverflow.com/questions/34357513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1222167/"
] |
The answer hege\_hegedus gave is correct, however there's one caveat in that exception handling is a lot slower than going through if..else statement.
For example if you're iterating over thousands of `payload` object and an actor entry is only occasionally not a dictionary, this code is perfectly valid.
However if you're iterating over thousands of `payload` objects and every other `actor` entry is not a dictionary then you'd be better off with this code.
```
u = ''
if 'actor' in payload and isinstance(payload['actor'], dict):
u = payload['actor'].get('username', '')
```
For more discussion go here -- <https://mail.python.org/pipermail/tutor/2011-January/081143.html>
UPDATE
Also the code statement can be re-written as a one-liner albeit not nearly as legible as two-line statement
```
u = payload['actor'].get('username', '') if 'actor' in payload and isinstance(payload['actor'], dict) else ''
```
|
If you really need to do it in 1 line, you'll have to implement the functionality yourself. Which is worth doing if you use this semantics many times in your program.
There are two ways to do it: function or custom dictionary-like object for `payload`.
1) Function handles the case of `actor` being not a `dict`. It can check for `isinstance` or do the `try` or whatever else -- it's not essential. The usage would look something like `u = get("username", "", payload.get("actor", {}))` or `u = get("", payload, 'actor', 'username')` (with arbitrary amount of nested calls for items in `payload`).
2) A class of custom objects is a powerful thing -- do it if you can and really need this abstraction in the program. A descendant of `dict` or `UserDict` (in Python3) can check for what it stores or outputs on `__getitem__` calls.
|
34,357,513
|
I love python one liners:
```
u = payload.get("actor", {}).get("username", "")
```
Problem I face is, I have no control over what 'payload' contains, other than knowing it is a dictionary. So, if 'payload' does not have "actor", or it does and actor does or doesn't have "username", this one-liner is fine.
Problem of course arises when payload DOES have actor, but actor is not a dictionary.
Is there as pretty a way to do this comprehensively as a one liner, *and consider the possibility that 'actor' may not be a dictionary?*
Of course I can check the type using 'isinstance', but that's not as nice.
I'm not requiring a one liner per se, just asking for the most efficient way to ensure 'u' gets populated, without exception, and without prior knowledge of what exactly is in 'payload'.
|
2015/12/18
|
[
"https://Stackoverflow.com/questions/34357513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1222167/"
] |
### Using EAFP
As xnx suggested, you can take advantage of the following python paradigm:
>
> [Easier to ask for forgiveness than permission](https://docs.python.org/3/glossary.html#term-eafp)
>
>
>
you can use it on `KeyError`s as well:
```
try:
u = payload["actor"]["username"]
except (AttributeError, KeyError):
u = ""
```
### Using a wrapper with forgiving indexing
Sometimes it would be nice to have something like null-conditional operators in Python. With some helper class this can be compressed into a one-liner expression:
```
class Forgive:
def __init__(self, value = None):
self.value = value
def __getitem__(self, name):
if self.value is None:
return Forgive()
try:
return Forgive(self.value.__getitem__(name))
except (KeyError, AttributeError):
return Forgive()
def get(self, default = None):
return default if self.value is None else self.value
data = {'actor':{'username': 'Joe'}}
print(Forgive(data)['actor']['username'].get('default1'))
print(Forgive(data)['actor']['address'].get('default2'))
```
ps: one could redefine `__getattr__` as well besides `__getitem__`, so you could even write `Forgive(data)['actor'].username.get('default1')`.
|
The answer hege\_hegedus gave is correct, however there's one caveat in that exception handling is a lot slower than going through if..else statement.
For example if you're iterating over thousands of `payload` object and an actor entry is only occasionally not a dictionary, this code is perfectly valid.
However if you're iterating over thousands of `payload` objects and every other `actor` entry is not a dictionary then you'd be better off with this code.
```
u = ''
if 'actor' in payload and isinstance(payload['actor'], dict):
u = payload['actor'].get('username', '')
```
For more discussion go here -- <https://mail.python.org/pipermail/tutor/2011-January/081143.html>
UPDATE
Also the code statement can be re-written as a one-liner albeit not nearly as legible as two-line statement
```
u = payload['actor'].get('username', '') if 'actor' in payload and isinstance(payload['actor'], dict) else ''
```
|
71,998,895
|
I'm trying to setup Pipenv on Ubuntu 22.04 LTS and I used:
```
sudo apt install pipenv
```
but I get an error:
```
FileNotFoundError: [Errno 2] No such file or directory: '/home/foo/.local/share/virtualenvs/hello-JDpq8NmY/bin/python'
```
I tried to update pip with:
```
curl -sS https://bootstrap.pypa.io/get-pip.py | python3.10
```
Still no use.
I tried the solution suggested [here](https://github.com/pypa/pipenv/issues/5075#issuecomment-1107460002) and nothing changed.
The environment is there but the bin folder is missing.
|
2022/04/25
|
[
"https://Stackoverflow.com/questions/71998895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12009223/"
] |
Finally, I have caught the issue. You are editing in admin panel and I was sharing code for front end. Please try below steps for admin:
Step 1 - file classes/Address.php
```
'lastname' => ['type' => self::TYPE_STRING, 'validate' => 'isAnything', 'required' => true, 'size' => 255],
```
Change this to **isAnything**
Step 2 - src\PrestaShopBundle\Form\Admin\Sell\Address/CustomerAddressType.php
Change your code to below code:
```
line 209: add('last_name', TextType::class, [
'label' => $this->trans('Last name', 'Admin.Global'),
'help' => $genericInvalidCharsMessage,
'required' => true,
'constraints' => [
new NotBlank([
'message' => $this->trans(
'This field cannot be empty.', 'Admin.Notifications.Error'
),
]),
new CleanHtml(),
new TypedRegex([
'type' => TypedRegex::TYPE_GENERIC_NAME,
]),
new Length([
'max' => AddressConstraint::MAX_LAST_NAME_LENGTH,
'maxMessage' => $this->trans(
'This field cannot be longer than %limit% characters',
'Admin.Notifications.Error',
['%limit%' => AddressConstraint::MAX_LAST_NAME_LENGTH]
),
]),
],
])
```
Now, you are ready to go and check.
|
Go to the file **classes/Address.php** file:
```
'lastname' =>array('type' => self::TYPE_STRING, 'validate' => 'isCustomerName', 'required' => true, 'size' => 32),
```
to :
```
'lastname' =>array('type' => self::TYPE_STRING, 'validate' => 'isAnything', 'required' => true, 'size' => 32),
```
validate to **isAnything**.
I think you were modifying in customer class. Please try with Address.php.
|
71,998,895
|
I'm trying to setup Pipenv on Ubuntu 22.04 LTS and I used:
```
sudo apt install pipenv
```
but I get an error:
```
FileNotFoundError: [Errno 2] No such file or directory: '/home/foo/.local/share/virtualenvs/hello-JDpq8NmY/bin/python'
```
I tried to update pip with:
```
curl -sS https://bootstrap.pypa.io/get-pip.py | python3.10
```
Still no use.
I tried the solution suggested [here](https://github.com/pypa/pipenv/issues/5075#issuecomment-1107460002) and nothing changed.
The environment is there but the bin folder is missing.
|
2022/04/25
|
[
"https://Stackoverflow.com/questions/71998895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12009223/"
] |
Finally, I have caught the issue. You are editing in admin panel and I was sharing code for front end. Please try below steps for admin:
Step 1 - file classes/Address.php
```
'lastname' => ['type' => self::TYPE_STRING, 'validate' => 'isAnything', 'required' => true, 'size' => 255],
```
Change this to **isAnything**
Step 2 - src\PrestaShopBundle\Form\Admin\Sell\Address/CustomerAddressType.php
Change your code to below code:
```
line 209: add('last_name', TextType::class, [
'label' => $this->trans('Last name', 'Admin.Global'),
'help' => $genericInvalidCharsMessage,
'required' => true,
'constraints' => [
new NotBlank([
'message' => $this->trans(
'This field cannot be empty.', 'Admin.Notifications.Error'
),
]),
new CleanHtml(),
new TypedRegex([
'type' => TypedRegex::TYPE_GENERIC_NAME,
]),
new Length([
'max' => AddressConstraint::MAX_LAST_NAME_LENGTH,
'maxMessage' => $this->trans(
'This field cannot be longer than %limit% characters',
'Admin.Notifications.Error',
['%limit%' => AddressConstraint::MAX_LAST_NAME_LENGTH]
),
]),
],
])
```
Now, you are ready to go and check.
|
Thanks for sharing the files.
I have resolved the case. You need to modify the classes/form/CustomerAddressForm.php
line 229
```
$isValid &= $this->validateField('lastname', 'isName', $this->translator->trans(
'Invalid name',
[],
'Shop.Forms.Errors'
));
```
Change to:
```
$isValid &= $this->validateField('lastname', 'isAnything', $this->translator->trans(
'Invalid name',
[],
'Shop.Forms.Errors'
));
```
|
71,998,895
|
I'm trying to setup Pipenv on Ubuntu 22.04 LTS and I used:
```
sudo apt install pipenv
```
but I get an error:
```
FileNotFoundError: [Errno 2] No such file or directory: '/home/foo/.local/share/virtualenvs/hello-JDpq8NmY/bin/python'
```
I tried to update pip with:
```
curl -sS https://bootstrap.pypa.io/get-pip.py | python3.10
```
Still no use.
I tried the solution suggested [here](https://github.com/pypa/pipenv/issues/5075#issuecomment-1107460002) and nothing changed.
The environment is there but the bin folder is missing.
|
2022/04/25
|
[
"https://Stackoverflow.com/questions/71998895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12009223/"
] |
Finally, I have caught the issue. You are editing in admin panel and I was sharing code for front end. Please try below steps for admin:
Step 1 - file classes/Address.php
```
'lastname' => ['type' => self::TYPE_STRING, 'validate' => 'isAnything', 'required' => true, 'size' => 255],
```
Change this to **isAnything**
Step 2 - src\PrestaShopBundle\Form\Admin\Sell\Address/CustomerAddressType.php
Change your code to below code:
```
line 209: add('last_name', TextType::class, [
'label' => $this->trans('Last name', 'Admin.Global'),
'help' => $genericInvalidCharsMessage,
'required' => true,
'constraints' => [
new NotBlank([
'message' => $this->trans(
'This field cannot be empty.', 'Admin.Notifications.Error'
),
]),
new CleanHtml(),
new TypedRegex([
'type' => TypedRegex::TYPE_GENERIC_NAME,
]),
new Length([
'max' => AddressConstraint::MAX_LAST_NAME_LENGTH,
'maxMessage' => $this->trans(
'This field cannot be longer than %limit% characters',
'Admin.Notifications.Error',
['%limit%' => AddressConstraint::MAX_LAST_NAME_LENGTH]
),
]),
],
])
```
Now, you are ready to go and check.
|
I want to do this good with override. I have an issue with override this class. I have created module to override but it is not working. There is a way to override this without editing core files?
```
services:
_defaults:
public: true
form.type.customer_address:
class: 'Playdev\PrestaShopBundle\Form\Admin\Sell\Address\CustomCustomerAddressType'
public: true
arguments:
- '@prestashop.adapter.form.choice_provider.country_state_by_id'
- '@=service("prestashop.adapter.legacy.context").getContext().country.id'
- '@router'
tags:
- { name: form.type }
```
<https://ibb.co/VVjnJYr>
There is a file class override:
\modules\pd\_overridemodule\src\PrestaShopBundle\Form\Admin\Sell\Address\CustomCustomerAddressType.php
<https://ibb.co/7QPHrqx>
And I have an error when I am inside Edit Address Form Backoffice
Type error: Too few arguments to function PrestaShopBundle\Form\Admin\Sell\Address\CustomerAddressType::\_\_construct(), 0 passed in C:\laragon\www\prestabiolab\vendor\symfony\symfony\src\Symfony\Component\Form\FormRegistry.php on line 92 and exactly 5 expected
[Symfony\Component\Debug\Exception\FatalThrowableError 0]
<https://ibb.co/YfwhtKq>
---
**I have found a solution**
Need to create module and call hookactionCustomerAddressFormBuilderModifier.
```
public function hookactionCustomerAddressFormBuilderModifier(array $params)
{
/** @var $formBuilder \Symfony\Component\Form */
$formBuilder = $params['form_builder'];
// remove lastname field
$formBuilder->remove('last_name');
// get all fields without removed
$allFields = $formBuilder->all();
// remove all fields
foreach ($allFields as $inputField => $input) {
$formBuilder->remove($inputField);
}
foreach ($allFields as $inputField => $input) {
// normally add fields
$formBuilder->add($input);
// add fields after firstname
if ($inputField == 'first_name') {
$formBuilder->add('last_name', TextType::class, [
'label' => $this->trans('Last name', [], 'Admin.Global'),
'help' => $this->trans(
'Invalid characters:',
[],
'Admin.Notifications.Info'
) . ' ' . TypedRegexValidator::GENERIC_NAME_CHARS,
'required' => true,
'constraints' => [
new NotBlank([
'message' => $this->trans(
'This field cannot be empty.', [], 'Admin.Notifications.Error'
),
]),
new CleanHtml(),
new TypedRegex([
'type' => TypedRegex::TYPE_GENERIC_NAME,
]),
new Length([
'max' => AddressConstraint::MAX_LAST_NAME_LENGTH,
'maxMessage' => $this->trans(
'This field cannot be longer than %limit% characters',
['%limit%' => AddressConstraint::MAX_LAST_NAME_LENGTH],
'Admin.Notifications.Error',
),
]),
],
]);
}
}
}
```
Now I think it works okey with override :)
|
2,014,767
|
I've got a python function that should loop through a tuple of coordinates and print their contents:
```
def do(coordList):
for element in coordList:
print element
y=((5,5),(4,4))
x=((5,5))
```
When y is run through the function, it outputs (5,5) and (4,4), the desired result. However, running x through the function outputs 5 and 5.
Is there a way to force x to be defined as a tuple within a tuple, and if not, what is the easiest way to resolve this problem?
|
2010/01/06
|
[
"https://Stackoverflow.com/questions/2014767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/211791/"
] |
Use a trailing comma for singleton tuples.
```
x = ((5, 5),)
```
|
```
x=((5,5),)
```
(*x*) is an expression (*x*,) is a singleton tuple.
|
2,014,767
|
I've got a python function that should loop through a tuple of coordinates and print their contents:
```
def do(coordList):
for element in coordList:
print element
y=((5,5),(4,4))
x=((5,5))
```
When y is run through the function, it outputs (5,5) and (4,4), the desired result. However, running x through the function outputs 5 and 5.
Is there a way to force x to be defined as a tuple within a tuple, and if not, what is the easiest way to resolve this problem?
|
2010/01/06
|
[
"https://Stackoverflow.com/questions/2014767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/211791/"
] |
Use a trailing comma for singleton tuples.
```
x = ((5, 5),)
```
|
This is an old and infuriating quirk of python syntax. You have to include a trailing comma to make Python see a tuple:
```
x = ((5,5),)
```
|
2,014,767
|
I've got a python function that should loop through a tuple of coordinates and print their contents:
```
def do(coordList):
for element in coordList:
print element
y=((5,5),(4,4))
x=((5,5))
```
When y is run through the function, it outputs (5,5) and (4,4), the desired result. However, running x through the function outputs 5 and 5.
Is there a way to force x to be defined as a tuple within a tuple, and if not, what is the easiest way to resolve this problem?
|
2010/01/06
|
[
"https://Stackoverflow.com/questions/2014767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/211791/"
] |
Use a trailing comma for singleton tuples.
```
x = ((5, 5),)
```
|
You need to add a comma after your first tuple.
`((5,5),)` should work.
|
2,014,767
|
I've got a python function that should loop through a tuple of coordinates and print their contents:
```
def do(coordList):
for element in coordList:
print element
y=((5,5),(4,4))
x=((5,5))
```
When y is run through the function, it outputs (5,5) and (4,4), the desired result. However, running x through the function outputs 5 and 5.
Is there a way to force x to be defined as a tuple within a tuple, and if not, what is the easiest way to resolve this problem?
|
2010/01/06
|
[
"https://Stackoverflow.com/questions/2014767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/211791/"
] |
Use a trailing comma for singleton tuples.
```
x = ((5, 5),)
```
|
Simply add a comma:
```
x=((5,5),)
```
|
2,014,767
|
I've got a python function that should loop through a tuple of coordinates and print their contents:
```
def do(coordList):
for element in coordList:
print element
y=((5,5),(4,4))
x=((5,5))
```
When y is run through the function, it outputs (5,5) and (4,4), the desired result. However, running x through the function outputs 5 and 5.
Is there a way to force x to be defined as a tuple within a tuple, and if not, what is the easiest way to resolve this problem?
|
2010/01/06
|
[
"https://Stackoverflow.com/questions/2014767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/211791/"
] |
```
x=((5,5),)
```
(*x*) is an expression (*x*,) is a singleton tuple.
|
This is an old and infuriating quirk of python syntax. You have to include a trailing comma to make Python see a tuple:
```
x = ((5,5),)
```
|
2,014,767
|
I've got a python function that should loop through a tuple of coordinates and print their contents:
```
def do(coordList):
for element in coordList:
print element
y=((5,5),(4,4))
x=((5,5))
```
When y is run through the function, it outputs (5,5) and (4,4), the desired result. However, running x through the function outputs 5 and 5.
Is there a way to force x to be defined as a tuple within a tuple, and if not, what is the easiest way to resolve this problem?
|
2010/01/06
|
[
"https://Stackoverflow.com/questions/2014767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/211791/"
] |
```
x=((5,5),)
```
(*x*) is an expression (*x*,) is a singleton tuple.
|
You need to add a comma after your first tuple.
`((5,5),)` should work.
|
2,014,767
|
I've got a python function that should loop through a tuple of coordinates and print their contents:
```
def do(coordList):
for element in coordList:
print element
y=((5,5),(4,4))
x=((5,5))
```
When y is run through the function, it outputs (5,5) and (4,4), the desired result. However, running x through the function outputs 5 and 5.
Is there a way to force x to be defined as a tuple within a tuple, and if not, what is the easiest way to resolve this problem?
|
2010/01/06
|
[
"https://Stackoverflow.com/questions/2014767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/211791/"
] |
```
x=((5,5),)
```
(*x*) is an expression (*x*,) is a singleton tuple.
|
Simply add a comma:
```
x=((5,5),)
```
|
13,276,847
|
I'm trying to add commas to floats for display to end users of my application on GAE. The numbers come from json and are part of a 10 item query with 2 times each (aka 20 numbers per page view). For eg.
```
"total_reach": 276160.0, "total_reach": 500160.0
```
I'm using the python GAE SDK 1.7.3 template system and simply want to display the numbers to the end user with commas e.g.: 276,160 and 500,160. Note, I am using the default webbapp2 and standard templates (from google.appengine.ext.webapp import template) which, as I understand it, is based on Django.
The Django floatformat works great to get rid of the decimal, but now I need to add the comma. Django's humanize looks perfect with its intcomma filter. However, I simply can't figure out how to enable it. I suspect its crazy simple and I'm being dense (and am noob to python) - but I'm out of ideas.
While I tried a range of things, the most recent and promising was (based on my understanding of [the source](http://code.google.com/p/googleappengine/source/browse/trunk/lib/django/django/contrib/humanize/templatetags/humanize.py?r=41)):
```
from google.appengine.ext.webapp.template import register_template_library
register_template_library('django.contrib.humanize.templatetags.humanize')
```
which gave me the following 500:
```
No module named django.contrib.humanize.templatetags
```
but it seems to be there in the source.
I'm very much at a loss. I've searched around and found items like [this](https://stackoverflow.com/questions/901121/how-to-use-inbulit-django-templatetags-in-google-app-engine) which just didn't work and seemed to be aimed at webapp (as opposed to webapp2). Help and thanks!
UPDATE:
Couldn't get it going using the settings.py approach. In the end, I solved it on my own. See below for my functional but not ideal solution.
|
2012/11/07
|
[
"https://Stackoverflow.com/questions/13276847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1807085/"
] |
```
ids = $("tr.selectON td[id]").map(function() { return this.id; }).get();
```
Documentations :
**To get elements with `id` attribute** <http://api.jquery.com/attribute-contains-prefix-selector/>
**To filter id attribute** <http://api.jquery.com/map/>
**To convert result into array** <http://api.jquery.com/get/>
|
You can make it simpler, cant speak to the JQuery performance though:
```
ids =[]
$('tr.selectON td[id^=""]').each( function() {
ids.push( this.id )
});
```
"this" in the function is already a dom object, so you have direct access to its id.
|
49,561,543
|
I'm interested in getting a mapping of country codes to international phone number prefixes, like so:
```
{'US': '+1', 'GB': '+44', 'DE': '+49', ...}
```
One library that probably contains this information is [`python-phonenumbers`](https://github.com/daviddrysdale/python-phonenumbers). However, after a quick perusal of the source code I wasn't able to find where this information is stored. For example, the `shortdata/region_DE.py` module looks like this:
```
"""Auto-generated file, do not edit by hand. DE metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_DE = PhoneMetadata(id='DE', country_code=None, international_prefix=None,
general_desc=PhoneNumberDesc(national_number_pattern='1\\d{2,5}', possible_length=(3, 6)),
toll_free=PhoneNumberDesc(national_number_pattern='116\\d{3}', example_number='116000', possible_length=(6,)),
emergency=PhoneNumberDesc(national_number_pattern='11[02]', example_number='112', possible_length=(3,)),
short_code=PhoneNumberDesc(national_number_pattern='11(?:[025]|6(?:00[06]|1(?:1[17]|23)))', example_number='115', possible_length=(3, 6)),
short_data=True)
```
It seems like the `country_code` and `international_prefix` fields are `None`. How can I get such a mapping (possibly with a different library)?
|
2018/03/29
|
[
"https://Stackoverflow.com/questions/49561543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/995862/"
] |
You can get the mapping you want using [`pycountry`](https://pypi.python.org/pypi/pycountry) and [`phonenumbers`](https://pypi.python.org/pypi/phonenumbers), along with a simple dictionary comprehension:
```
import phonenumbers as pn
import pycountry
dct = {c.alpha_2: pn.country_code_for_region(c.alpha_2) for c in pycountry.countries}
print(dct)
```
Output:
```
{'SK': 421, 'KI': 686, 'LV': 371, 'GH': 233, 'JP': 81, 'SA': 966, 'TD': 235, 'SX': 1, 'CY': 357, 'CH': 41, 'EG': 20, 'PA': 507, 'KP': 850, 'CO': 57, 'GW': 245, 'KG': 996, 'AW': 297, 'FM': 691, 'SB': 677, 'HR': 385, 'PY': 595, 'BG': 359, 'IQ': 964, 'ID': 62, 'GQ': 240, 'CA': 1, 'CG': 242, 'MO': 853, 'SL': 232, 'LA': 856, 'OM': 968, 'MP': 1, 'DK': 45, 'FI': 358, 'DO': 1, 'BM': 1, 'GN': 224, 'NE': 227, 'ER': 291, 'DE': 49, 'UM': 0, 'CM': 237, 'PR': 1, 'RO': 40, 'AZ': 994, 'DZ': 213, 'BW': 267, 'MK': 389, 'HN': 504, 'IS': 354, 'SJ': 47, 'ME': 382, 'NR': 674, 'AD': 376, 'BY': 375, 'RE': 262, 'PG': 675, 'SO': 252, 'NO': 47, 'CC': 61, 'EE': 372, 'BN': 673, 'AU': 61, 'HM': 0, 'ML': 223, 'BD': 880, 'GE': 995, 'US': 1, 'UY': 598, 'SM': 378, 'NG': 234, 'BE': 32, 'KY': 1, 'AR': 54, 'CR': 506, 'VA': 39, 'YE': 967, 'TR': 90, 'CV': 238, 'DM': 1, 'ZM': 260, 'BR': 55, 'MG': 261, 'BL': 590, 'FJ': 679, 'SH': 290, 'KN': 1, 'ZA': 27, 'CF': 236, 'ZW': 263, 'PL': 48, 'SV': 503, 'QA': 974, 'MN': 976, 'SE': 46, 'JE': 44, 'PS': 970, 'MZ': 258, 'TK': 690, 'PM': 508, 'CW': 599, 'HK': 852, 'LB': 961, 'SY': 963, 'LC': 1, 'IE': 353, 'RW': 250, 'NL': 31, 'MA': 212, 'GM': 220, 'IR': 98, 'AT': 43, 'SZ': 268, 'GT': 502, 'MT': 356, 'BQ': 599, 'MX': 52, 'NC': 687, 'CK': 682, 'SI': 386, 'VE': 58, 'IM': 44, 'AM': 374, 'SD': 249, 'LY': 218, 'LI': 423, 'TN': 216, 'UG': 256, 'RU': 7, 'DJ': 253, 'IL': 972, 'TM': 993, 'BF': 226, 'GF': 594, 'TO': 676, 'GI': 350, 'MH': 692, 'UZ': 998, 'PF': 689, 'KZ': 7, 'GA': 241, 'PE': 51, 'TV': 688, 'BT': 975, 'MQ': 596, 'MF': 590, 'AF': 93, 'IN': 91, 'AX': 358, 'BH': 973, 'JM': 1, 'MY': 60, 'BO': 591, 'AI': 1, 'SR': 597, 'ET': 251, 'ES': 34, 'TF': 0, 'GU': 1, 'BJ': 229, 'SS': 211, 'KE': 254, 'BZ': 501, 'IO': 246, 'MU': 230, 'CL': 56, 'MD': 373, 'LU': 352, 'TJ': 992, 'EC': 593, 'VG': 1, 'NZ': 64, 'VU': 678, 'FO': 298, 'LR': 231, 'AL': 355, 'GB': 44, 'AS': 1, 'IT': 39, 'TC': 1, 'TW': 886, 'BI': 257, 'HU': 36, 'TL': 670, 'GG': 44, 'PN': 0, 'SG': 65, 'LS': 266, 'KH': 855, 'FR': 33, 'BV': 0, 'CX': 61, 'AE': 971, 'LT': 370, 'PT': 351, 'KR': 82, 'BB': 1, 'TG': 228, 'AQ': 0, 'EH': 212, 'AG': 1, 'VN': 84, 'CI': 225, 'BS': 1, 'GL': 299, 'MW': 265, 'NU': 683, 'NF': 672, 'LK': 94, 'MS': 1, 'GP': 590, 'NP': 977, 'PW': 680, 'PK': 92, 'WF': 681, 'BA': 387, 'KM': 269, 'JO': 962, 'CU': 53, 'GR': 30, 'YT': 262, 'RS': 381, 'NA': 264, 'ST': 239, 'SC': 248, 'CN': 86, 'CD': 243, 'GS': 0, 'KW': 965, 'MM': 95, 'AO': 244, 'MV': 960, 'UA': 380, 'TT': 1, 'FK': 500, 'WS': 685, 'CZ': 420, 'PH': 63, 'VI': 1, 'TZ': 255, 'MR': 222, 'MC': 377, 'SN': 221, 'HT': 509, 'VC': 1, 'NI': 505, 'GD': 1, 'GY': 592, 'TH': 66}
```
|
I have just found a python library that must be perfect for your problem.
It's called PhoneISO3166.
This is the github link: [GitHub phoneiso3166](https://github.com/onlinecity/phone-iso3166/)
|
47,271,662
|
I would like to compute an RBF or "Gaussian" kernel for a data matrix `X` with `n` rows and `d` columns. The resulting square kernel matrix is given by:
```
K[i,j] = var * exp(-gamma * ||X[i] - X[j]||^2)
```
`var` and `gamma` are scalars.
What is the fastest way to do this in python?
|
2017/11/13
|
[
"https://Stackoverflow.com/questions/47271662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3475712/"
] |
I am going to present four different methods for computing such a kernel, followed by a comparison of their run-time.
Using pure numpy
================
Here, I use the fact that `||x-y||^2 = ||x||^2 + ||y||^2 - 2 * x^T * y`.
```py
import numpy as np
X_norm = np.sum(X ** 2, axis = -1)
K = var * np.exp(-gamma * (X_norm[:,None] + X_norm[None,:] - 2 * np.dot(X, X.T)))
```
Using numexpr
=============
[`numexpr`](http://numexpr.readthedocs.io/en/latest/user_guide.html) is a python package that allows for efficient and parallelized array operations on numpy arrays. We can use it as follows to perform the same computation as above:
```py
import numpy as np
import numexpr as ne
X_norm = np.sum(X ** 2, axis = -1)
K = ne.evaluate('v * exp(-g * (A + B - 2 * C))', {
'A' : X_norm[:,None],
'B' : X_norm[None,:],
'C' : np.dot(X, X.T),
'g' : gamma,
'v' : var
})
```
Using `scipy.spatial.distance.pdist`
====================================
We could also use [`scipy.spatial.distance.pdist`](https://docs.scipy.org/doc/scipy-0.19.1/reference/generated/scipy.spatial.distance.pdist.html) to compute a non-redundant array of pairwise squared euclidean distances, compute the kernel on that array and then transform it to a square matrix:
```py
import numpy as np
from scipy.spatial.distance import pdist, squareform
K = squareform(var * np.exp(-gamma * pdist(X, 'sqeuclidean')))
K[np.arange(K.shape[0]), np.arange(K.shape[1])] = var
```
Using `sklearn.metrics.pairwise.rbf_kernel`
===========================================
`sklearn` provides a [built-in method](http://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.rbf_kernel.html) for direct computation of an RBF kernel:
```py
import numpy as np
from sklearn.metrics.pairwise import rbf_kernel
K = var * rbf_kernel(X, gamma = gamma)
```
Run-time comparison
===================
I use 25,000 random samples of 512 dimensions for testing and perform experiments on an Intel Core i7-7700HQ (4 cores @ 2.8 GHz). More precisely:
```py
X = np.random.randn(25000, 512)
gamma = 0.01
var = 5.0
```
Each method is run 7 times and the mean and standard deviation of the time per execution is reported.
```none
| Method | Time |
|-------------------------------------|-------------------|
| numpy | 24.2 s Β± 1.06 s |
| numexpr | 8.89 s Β± 314 ms |
| scipy.spatial.distance.pdist | 2min 59s Β± 312 ms |
| sklearn.metrics.pairwise.rbf_kernel | 13.9 s Β± 757 ms |
```
First of all, `scipy.spatial.distance.pdist` is surprisingly slow.
`numexpr` is almost 3 times faster than the pure `numpy` method, but this speed-up factor will vary with the number of available CPUs.
`sklearn.metrics.pairwise.rbf_kernel` is not the fastest way, but only a bit slower than `numexpr`.
|
In the case that you are evaluating X against a high number of gammas, it is useful to save the negative pairwise distances matrix using the tricks done by @Callidior and @Divakar.
```
from numpy import exp, matmul, power, einsum, dot
from scipy.linalg.blas import sgemm
from numexpr import evaluate
def pdist2(X):
X_norm = - einsum('ij,ij->i', X, X)
return evaluate('A + B + C', {
'A' : X_norm[:,None],
'B' : X_norm[None,:],
'C' : sgemm(alpha=2.0, a=X, b=X, trans_b=True),
})
pairwise_distance_matrix = pdist2(X)
```
Then, the best solution would be to use `numexpr` to compute the exponential.
```
def rbf_kernel2(gamma, p_matrix):
return evaluate('exp(g * m)', {
'm' : p_matrix,
'g' : gamma,
})
```
Example:
```
import numpy as np
np.random.seed(1001)
X= np.random.rand(1001, 5).astype('float32')
p_matrix_test = pdist2(X)
gamma_test_list = (10 ** np.linspace(-2, 1, 11)).astype('float32')
def app2(gamma, X):
X_norm = - gamma * einsum('ij,ij->i', X, X)
return evaluate('exp(A + B + C)', {\
'A' : X_norm[:, None],\
'B' : X_norm[None, :],\
'C' : sgemm(alpha=2.0*gamma, a=X, b=X, trans_b=True),\
'g' : gamma,
})
```
I have the results:
```
%timeit y = [app2(gamma_test, x_test) for gamma_test in gamma_test_list]
```
>
> 70.8 ms Β± 5.06 ms per loop (mean Β± std. dev. of 7 runs, 10 loops each)
>
>
>
```
%timeit y = [rbf_kernel2(gamma_test, p_matrix_test) for gamma_test in gamma_test_list]
```
>
> 33.6 ms Β± 2.33 ms per loop (mean Β± std. dev. of 7 runs, 10 loops each)
>
>
>
Note that you need to add the overhead to compute the pairwise distance matrix before but it shouldn't be much if you are evaluating against a large number of gammas.
|
47,271,662
|
I would like to compute an RBF or "Gaussian" kernel for a data matrix `X` with `n` rows and `d` columns. The resulting square kernel matrix is given by:
```
K[i,j] = var * exp(-gamma * ||X[i] - X[j]||^2)
```
`var` and `gamma` are scalars.
What is the fastest way to do this in python?
|
2017/11/13
|
[
"https://Stackoverflow.com/questions/47271662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3475712/"
] |
I am going to present four different methods for computing such a kernel, followed by a comparison of their run-time.
Using pure numpy
================
Here, I use the fact that `||x-y||^2 = ||x||^2 + ||y||^2 - 2 * x^T * y`.
```py
import numpy as np
X_norm = np.sum(X ** 2, axis = -1)
K = var * np.exp(-gamma * (X_norm[:,None] + X_norm[None,:] - 2 * np.dot(X, X.T)))
```
Using numexpr
=============
[`numexpr`](http://numexpr.readthedocs.io/en/latest/user_guide.html) is a python package that allows for efficient and parallelized array operations on numpy arrays. We can use it as follows to perform the same computation as above:
```py
import numpy as np
import numexpr as ne
X_norm = np.sum(X ** 2, axis = -1)
K = ne.evaluate('v * exp(-g * (A + B - 2 * C))', {
'A' : X_norm[:,None],
'B' : X_norm[None,:],
'C' : np.dot(X, X.T),
'g' : gamma,
'v' : var
})
```
Using `scipy.spatial.distance.pdist`
====================================
We could also use [`scipy.spatial.distance.pdist`](https://docs.scipy.org/doc/scipy-0.19.1/reference/generated/scipy.spatial.distance.pdist.html) to compute a non-redundant array of pairwise squared euclidean distances, compute the kernel on that array and then transform it to a square matrix:
```py
import numpy as np
from scipy.spatial.distance import pdist, squareform
K = squareform(var * np.exp(-gamma * pdist(X, 'sqeuclidean')))
K[np.arange(K.shape[0]), np.arange(K.shape[1])] = var
```
Using `sklearn.metrics.pairwise.rbf_kernel`
===========================================
`sklearn` provides a [built-in method](http://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.rbf_kernel.html) for direct computation of an RBF kernel:
```py
import numpy as np
from sklearn.metrics.pairwise import rbf_kernel
K = var * rbf_kernel(X, gamma = gamma)
```
Run-time comparison
===================
I use 25,000 random samples of 512 dimensions for testing and perform experiments on an Intel Core i7-7700HQ (4 cores @ 2.8 GHz). More precisely:
```py
X = np.random.randn(25000, 512)
gamma = 0.01
var = 5.0
```
Each method is run 7 times and the mean and standard deviation of the time per execution is reported.
```none
| Method | Time |
|-------------------------------------|-------------------|
| numpy | 24.2 s Β± 1.06 s |
| numexpr | 8.89 s Β± 314 ms |
| scipy.spatial.distance.pdist | 2min 59s Β± 312 ms |
| sklearn.metrics.pairwise.rbf_kernel | 13.9 s Β± 757 ms |
```
First of all, `scipy.spatial.distance.pdist` is surprisingly slow.
`numexpr` is almost 3 times faster than the pure `numpy` method, but this speed-up factor will vary with the number of available CPUs.
`sklearn.metrics.pairwise.rbf_kernel` is not the fastest way, but only a bit slower than `numexpr`.
|
The NumPy solution with a given X, Y and gamma would be:
```
import numpy as np
def rbf_kernel(X, Y, gamma):
X_norm = np.sum(X ** 2, axis=-1)
Y_norm = np.sum(Y ** 2, axis=-1)
K = np.exp(-gamma * (X_norm[:, None] + Y_norm[None, :] - 2 * np.dot(X, Y.T)))
return K
```
|
47,271,662
|
I would like to compute an RBF or "Gaussian" kernel for a data matrix `X` with `n` rows and `d` columns. The resulting square kernel matrix is given by:
```
K[i,j] = var * exp(-gamma * ||X[i] - X[j]||^2)
```
`var` and `gamma` are scalars.
What is the fastest way to do this in python?
|
2017/11/13
|
[
"https://Stackoverflow.com/questions/47271662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3475712/"
] |
Well you are doing a lot of optimizations in your [`answer post`](https://stackoverflow.com/a/47271663/3293881). I would like to add few more (mostly tweaks). I would build upon the winner from the answer post, which seems to be `numexpr` based on.
### Tweak #1
First off, `np.sum(X ** 2, axis = -1)` could be optimized with `np.einsum`. Though this part isn't the biggest overhead, but optimization of any sort won't hurt. So, that summation could be expressed as -
```
X_norm = np.einsum('ij,ij->i',X,X)
```
### Tweak #2
Secondly, we could leverage Scipy supported blas functions and if allowed use single-precision dtype for noticeable performance improvement over its double precision one. Hence, `np.dot(X, X.T)` could be computed with [`SciPy's sgemm`](https://docs.scipy.org/doc/scipy-0.19.1/reference/generated/scipy.linalg.blas.sgemm.html) like so -
```
sgemm(alpha=1.0, a=X, b=X, trans_b=True)
```
Few more tweaks on rearranging the negative sign with `gamma` lets us feed more to `sgemm`. Also, we would push in `gamma` into the `alpha` term.
### Tweaked implementations
Thus, with these two optimizations, we would have two more *variants* (if I could put it that way) of the `numexpr` method, listed below -
```
from scipy.linalg.blas import sgemm
def app1(X, gamma, var):
X_norm = -np.einsum('ij,ij->i',X,X)
return ne.evaluate('v * exp(g * (A + B + 2 * C))', {\
'A' : X_norm[:,None],\
'B' : X_norm[None,:],\
'C' : np.dot(X, X.T),\
'g' : gamma,\
'v' : var\
})
def app2(X, gamma, var):
X_norm = -gamma*np.einsum('ij,ij->i',X,X)
return ne.evaluate('v * exp(A + B + C)', {\
'A' : X_norm[:,None],\
'B' : X_norm[None,:],\
'C' : sgemm(alpha=2.0*gamma, a=X, b=X, trans_b=True),\
'g' : gamma,\
'v' : var\
})
```
### Runtime test
Numexpr based one from your answer post -
```
def app0(X, gamma, var):
X_norm = np.sum(X ** 2, axis = -1)
return ne.evaluate('v * exp(-g * (A + B - 2 * C))', {
'A' : X_norm[:,None],
'B' : X_norm[None,:],
'C' : np.dot(X, X.T),
'g' : gamma,
'v' : var
})
```
Timings and verification -
```
In [165]: # Setup
...: X = np.random.randn(10000, 512)
...: gamma = 0.01
...: var = 5.0
In [166]: %timeit app0(X, gamma, var)
...: %timeit app1(X, gamma, var)
...: %timeit app2(X, gamma, var)
1 loop, best of 3: 1.25 s per loop
1 loop, best of 3: 1.24 s per loop
1 loop, best of 3: 973 ms per loop
In [167]: np.allclose(app0(X, gamma, var), app1(X, gamma, var))
Out[167]: True
In [168]: np.allclose(app0(X, gamma, var), app2(X, gamma, var))
Out[168]: True
```
|
In the case that you are evaluating X against a high number of gammas, it is useful to save the negative pairwise distances matrix using the tricks done by @Callidior and @Divakar.
```
from numpy import exp, matmul, power, einsum, dot
from scipy.linalg.blas import sgemm
from numexpr import evaluate
def pdist2(X):
X_norm = - einsum('ij,ij->i', X, X)
return evaluate('A + B + C', {
'A' : X_norm[:,None],
'B' : X_norm[None,:],
'C' : sgemm(alpha=2.0, a=X, b=X, trans_b=True),
})
pairwise_distance_matrix = pdist2(X)
```
Then, the best solution would be to use `numexpr` to compute the exponential.
```
def rbf_kernel2(gamma, p_matrix):
return evaluate('exp(g * m)', {
'm' : p_matrix,
'g' : gamma,
})
```
Example:
```
import numpy as np
np.random.seed(1001)
X= np.random.rand(1001, 5).astype('float32')
p_matrix_test = pdist2(X)
gamma_test_list = (10 ** np.linspace(-2, 1, 11)).astype('float32')
def app2(gamma, X):
X_norm = - gamma * einsum('ij,ij->i', X, X)
return evaluate('exp(A + B + C)', {\
'A' : X_norm[:, None],\
'B' : X_norm[None, :],\
'C' : sgemm(alpha=2.0*gamma, a=X, b=X, trans_b=True),\
'g' : gamma,
})
```
I have the results:
```
%timeit y = [app2(gamma_test, x_test) for gamma_test in gamma_test_list]
```
>
> 70.8 ms Β± 5.06 ms per loop (mean Β± std. dev. of 7 runs, 10 loops each)
>
>
>
```
%timeit y = [rbf_kernel2(gamma_test, p_matrix_test) for gamma_test in gamma_test_list]
```
>
> 33.6 ms Β± 2.33 ms per loop (mean Β± std. dev. of 7 runs, 10 loops each)
>
>
>
Note that you need to add the overhead to compute the pairwise distance matrix before but it shouldn't be much if you are evaluating against a large number of gammas.
|
47,271,662
|
I would like to compute an RBF or "Gaussian" kernel for a data matrix `X` with `n` rows and `d` columns. The resulting square kernel matrix is given by:
```
K[i,j] = var * exp(-gamma * ||X[i] - X[j]||^2)
```
`var` and `gamma` are scalars.
What is the fastest way to do this in python?
|
2017/11/13
|
[
"https://Stackoverflow.com/questions/47271662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3475712/"
] |
Well you are doing a lot of optimizations in your [`answer post`](https://stackoverflow.com/a/47271663/3293881). I would like to add few more (mostly tweaks). I would build upon the winner from the answer post, which seems to be `numexpr` based on.
### Tweak #1
First off, `np.sum(X ** 2, axis = -1)` could be optimized with `np.einsum`. Though this part isn't the biggest overhead, but optimization of any sort won't hurt. So, that summation could be expressed as -
```
X_norm = np.einsum('ij,ij->i',X,X)
```
### Tweak #2
Secondly, we could leverage Scipy supported blas functions and if allowed use single-precision dtype for noticeable performance improvement over its double precision one. Hence, `np.dot(X, X.T)` could be computed with [`SciPy's sgemm`](https://docs.scipy.org/doc/scipy-0.19.1/reference/generated/scipy.linalg.blas.sgemm.html) like so -
```
sgemm(alpha=1.0, a=X, b=X, trans_b=True)
```
Few more tweaks on rearranging the negative sign with `gamma` lets us feed more to `sgemm`. Also, we would push in `gamma` into the `alpha` term.
### Tweaked implementations
Thus, with these two optimizations, we would have two more *variants* (if I could put it that way) of the `numexpr` method, listed below -
```
from scipy.linalg.blas import sgemm
def app1(X, gamma, var):
X_norm = -np.einsum('ij,ij->i',X,X)
return ne.evaluate('v * exp(g * (A + B + 2 * C))', {\
'A' : X_norm[:,None],\
'B' : X_norm[None,:],\
'C' : np.dot(X, X.T),\
'g' : gamma,\
'v' : var\
})
def app2(X, gamma, var):
X_norm = -gamma*np.einsum('ij,ij->i',X,X)
return ne.evaluate('v * exp(A + B + C)', {\
'A' : X_norm[:,None],\
'B' : X_norm[None,:],\
'C' : sgemm(alpha=2.0*gamma, a=X, b=X, trans_b=True),\
'g' : gamma,\
'v' : var\
})
```
### Runtime test
Numexpr based one from your answer post -
```
def app0(X, gamma, var):
X_norm = np.sum(X ** 2, axis = -1)
return ne.evaluate('v * exp(-g * (A + B - 2 * C))', {
'A' : X_norm[:,None],
'B' : X_norm[None,:],
'C' : np.dot(X, X.T),
'g' : gamma,
'v' : var
})
```
Timings and verification -
```
In [165]: # Setup
...: X = np.random.randn(10000, 512)
...: gamma = 0.01
...: var = 5.0
In [166]: %timeit app0(X, gamma, var)
...: %timeit app1(X, gamma, var)
...: %timeit app2(X, gamma, var)
1 loop, best of 3: 1.25 s per loop
1 loop, best of 3: 1.24 s per loop
1 loop, best of 3: 973 ms per loop
In [167]: np.allclose(app0(X, gamma, var), app1(X, gamma, var))
Out[167]: True
In [168]: np.allclose(app0(X, gamma, var), app2(X, gamma, var))
Out[168]: True
```
|
The NumPy solution with a given X, Y and gamma would be:
```
import numpy as np
def rbf_kernel(X, Y, gamma):
X_norm = np.sum(X ** 2, axis=-1)
Y_norm = np.sum(Y ** 2, axis=-1)
K = np.exp(-gamma * (X_norm[:, None] + Y_norm[None, :] - 2 * np.dot(X, Y.T)))
return K
```
|
17,890,896
|
I have 15 lines in a log file and i want to read the 4th and 10 th line for example through python and display them on output saying this string is found :
```
abc
def
aaa
aaa
aasd
dsfsfs
dssfsd
sdfsds
sfdsf
ssddfs
sdsf
f
dsf
s
d
```
please suggest through code how to achieve this in python .
just to elaborate more on this example the first (string or line is unique) and can be found easily in logfile the next String B comes within 40 lines of the first one but this one occurs at lots of places in the log file so i need to read this string withing the first 40 lines after reading string A and print the same that these strings were found.
Also I cant use `with` command of python as this gives me errors like 'with' will become a reserved keyword in Python 2.6. **I am using Python 2.5**
|
2013/07/26
|
[
"https://Stackoverflow.com/questions/17890896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2615729/"
] |
Here you go (untested):
```
- (int)getRank:(NSString *passedString) {
if([passedString isEqualToString:@"randomcard"]){
return YES;
} else {
return NO;
}
}
```
I suggest you learn Objective-C first. This is a very basic question.
|
To begin, NSString (the iOS implementation of String) goes something like this:
```
NSString str = @"Some STR";
```
or
```
NSString = [NSString initWithFormat:@"Hello %@", "Hi there"]];
```
|
17,890,896
|
I have 15 lines in a log file and i want to read the 4th and 10 th line for example through python and display them on output saying this string is found :
```
abc
def
aaa
aaa
aasd
dsfsfs
dssfsd
sdfsds
sfdsf
ssddfs
sdsf
f
dsf
s
d
```
please suggest through code how to achieve this in python .
just to elaborate more on this example the first (string or line is unique) and can be found easily in logfile the next String B comes within 40 lines of the first one but this one occurs at lots of places in the log file so i need to read this string withing the first 40 lines after reading string A and print the same that these strings were found.
Also I cant use `with` command of python as this gives me errors like 'with' will become a reserved keyword in Python 2.6. **I am using Python 2.5**
|
2013/07/26
|
[
"https://Stackoverflow.com/questions/17890896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2615729/"
] |
```
+ (int)getRank:(NSString *)passedString
{
return [passedString isEqualToString:@"randomcard"] ? 1 : 0;
}
```
I use the "+" symbol because you had it defined as "static" in your Java code and the equivalent in Objective-C are class methods.
So, if you call in Java:
`int rank = Class.getRank("some string");`
here in Objective-C you would do:
`int rank = [Class getRank:@"some string"];`
If you need to call this from an instance (an actual object), you could do:
```
int rank = [self.class getRank:@"some string"];
```
|
To begin, NSString (the iOS implementation of String) goes something like this:
```
NSString str = @"Some STR";
```
or
```
NSString = [NSString initWithFormat:@"Hello %@", "Hi there"]];
```
|
17,890,896
|
I have 15 lines in a log file and i want to read the 4th and 10 th line for example through python and display them on output saying this string is found :
```
abc
def
aaa
aaa
aasd
dsfsfs
dssfsd
sdfsds
sfdsf
ssddfs
sdsf
f
dsf
s
d
```
please suggest through code how to achieve this in python .
just to elaborate more on this example the first (string or line is unique) and can be found easily in logfile the next String B comes within 40 lines of the first one but this one occurs at lots of places in the log file so i need to read this string withing the first 40 lines after reading string A and print the same that these strings were found.
Also I cant use `with` command of python as this gives me errors like 'with' will become a reserved keyword in Python 2.6. **I am using Python 2.5**
|
2013/07/26
|
[
"https://Stackoverflow.com/questions/17890896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2615729/"
] |
Here you go (untested):
```
- (int)getRank:(NSString *passedString) {
if([passedString isEqualToString:@"randomcard"]){
return YES;
} else {
return NO;
}
}
```
I suggest you learn Objective-C first. This is a very basic question.
|
```
+ (int)getRank:(NSString *)passedString
{
return [passedString isEqualToString:@"randomcard"] ? 1 : 0;
}
```
I use the "+" symbol because you had it defined as "static" in your Java code and the equivalent in Objective-C are class methods.
So, if you call in Java:
`int rank = Class.getRank("some string");`
here in Objective-C you would do:
`int rank = [Class getRank:@"some string"];`
If you need to call this from an instance (an actual object), you could do:
```
int rank = [self.class getRank:@"some string"];
```
|
67,241,815
|
I tried writing a simple merge and sort function in python and got stuck after getting the following error-
```
List out of range.
```
I would appreciate if you could help me fix it and figure out how to avoid it. I have added the code below-
```
def merge(lst1, lst2):
# Gets two sorted lists and returns one merged and sorted list
merge_sorted = []
i = 0
j = 0
len1 = len(lst1) - 1
len2 = len(lst2) - 1
while i < len1 or j < len2:
if lst1[i] < lst2[j]:
merge_sorted.append(lst1[i])
i += 1
elif lst1[i] > lst2[j]:
merge_sorted.append(lst2[j])
j += 1
else:
merge_sorted.append(lst1[i])
merge_sorted.append(lst2[j])
i += 1
j += 1
return merge_sorted
lst1 = [2, 4, 5, 6, 8]
lst2 = [1, 3, 7, 9, 0]
merge(lst1, lst2)
```
What I got:
```
IndexError Traceback (most recent call last)
<ipython-input-13-572aad47097b> in <module>()
22 lst1 = [2, 4, 5, 6, 8]
23 lst2 = [1, 3, 7, 9, 0]
---> 24 merge(lst1, lst2)
<ipython-input-13-572aad47097b> in merge(lst1, lst2)
7 len2 = len(lst2) - 1
8 while i < len1 or j < len2:
----> 9 if lst1[i] < lst2[j]:
10 merge_sorted.append(lst1[i])
11 i += 1
IndexError: list index out of range
```
|
2021/04/24
|
[
"https://Stackoverflow.com/questions/67241815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15753999/"
] |
Your problem is the while condition:
```
while i < len1 or j < len2:
```
it should be `and` - if either of the conditoins are not true, you simple append the remainder of the non-empty list to your result and you are done.
Your current code still enters the while-body and checks `if lst1[i] < lst2[j]:` if one of the `i` / `j` is bigger then the list you get the error you have.
---
The full fixed code:
```
def merge(lst1, lst2):
# Gets two sorted lists and returns one merged and sorted list
merge_sorted = []
i = 0
j = 0
len1 = len(lst1) - 1
len2 = len(lst2) - 1
while i < len1 and j < len2: # use and
if lst1[i] < lst2[j]:
merge_sorted.append(lst1[i])
i += 1
elif lst1[i] > lst2[j]:
merge_sorted.append(lst2[j])
j += 1
else:
merge_sorted.append(lst1[i])
merge_sorted.append(lst2[j])
i += 1
j += 1
# add remainder lists - the slices evaluate to [] if behind the list lengths
merge_sorted.extend(lst1[i:]) # if i is aready out of the list this is []
merge_sorted.extend(lst2[j:]) # if j is aready out of the list this is []
return merge_sorted
lst1 = [2, 4, 5, 6, 8]
lst2 = [0, 1, 3, 7, 9] # fixed input, needs to be sorted, yours was not
print(merge(lst1, lst2))
```
Output:
```
[0, 1, 2, 3, 4, 5, 6, 8, 7, 9]
```
|
Here are the values for i, j just before that `if` condition-
```
0 0
0 1
1 1
1 2
2 2
3 2
4 2
4 3
5 3
```
When any of the lists is traversed till the end, it throws `index out of range error`.
**Solution-**
Instead of using `or` condition, use `and` condition and append the remaining list elements at the end of the sorted list.
|
67,241,815
|
I tried writing a simple merge and sort function in python and got stuck after getting the following error-
```
List out of range.
```
I would appreciate if you could help me fix it and figure out how to avoid it. I have added the code below-
```
def merge(lst1, lst2):
# Gets two sorted lists and returns one merged and sorted list
merge_sorted = []
i = 0
j = 0
len1 = len(lst1) - 1
len2 = len(lst2) - 1
while i < len1 or j < len2:
if lst1[i] < lst2[j]:
merge_sorted.append(lst1[i])
i += 1
elif lst1[i] > lst2[j]:
merge_sorted.append(lst2[j])
j += 1
else:
merge_sorted.append(lst1[i])
merge_sorted.append(lst2[j])
i += 1
j += 1
return merge_sorted
lst1 = [2, 4, 5, 6, 8]
lst2 = [1, 3, 7, 9, 0]
merge(lst1, lst2)
```
What I got:
```
IndexError Traceback (most recent call last)
<ipython-input-13-572aad47097b> in <module>()
22 lst1 = [2, 4, 5, 6, 8]
23 lst2 = [1, 3, 7, 9, 0]
---> 24 merge(lst1, lst2)
<ipython-input-13-572aad47097b> in merge(lst1, lst2)
7 len2 = len(lst2) - 1
8 while i < len1 or j < len2:
----> 9 if lst1[i] < lst2[j]:
10 merge_sorted.append(lst1[i])
11 i += 1
IndexError: list index out of range
```
|
2021/04/24
|
[
"https://Stackoverflow.com/questions/67241815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15753999/"
] |
Your problem is the while condition:
```
while i < len1 or j < len2:
```
it should be `and` - if either of the conditoins are not true, you simple append the remainder of the non-empty list to your result and you are done.
Your current code still enters the while-body and checks `if lst1[i] < lst2[j]:` if one of the `i` / `j` is bigger then the list you get the error you have.
---
The full fixed code:
```
def merge(lst1, lst2):
# Gets two sorted lists and returns one merged and sorted list
merge_sorted = []
i = 0
j = 0
len1 = len(lst1) - 1
len2 = len(lst2) - 1
while i < len1 and j < len2: # use and
if lst1[i] < lst2[j]:
merge_sorted.append(lst1[i])
i += 1
elif lst1[i] > lst2[j]:
merge_sorted.append(lst2[j])
j += 1
else:
merge_sorted.append(lst1[i])
merge_sorted.append(lst2[j])
i += 1
j += 1
# add remainder lists - the slices evaluate to [] if behind the list lengths
merge_sorted.extend(lst1[i:]) # if i is aready out of the list this is []
merge_sorted.extend(lst2[j:]) # if j is aready out of the list this is []
return merge_sorted
lst1 = [2, 4, 5, 6, 8]
lst2 = [0, 1, 3, 7, 9] # fixed input, needs to be sorted, yours was not
print(merge(lst1, lst2))
```
Output:
```
[0, 1, 2, 3, 4, 5, 6, 8, 7, 9]
```
|
As suggested by other techies you can modify and run the program but you are simply increasing the time complexity of your program which you could have done in two lines.
* Just extend the list1 elements like
```
list1.extend(list2)
```
* once the elements are into the list1
```
print(set(sorted(list1)))
```
|
67,241,815
|
I tried writing a simple merge and sort function in python and got stuck after getting the following error-
```
List out of range.
```
I would appreciate if you could help me fix it and figure out how to avoid it. I have added the code below-
```
def merge(lst1, lst2):
# Gets two sorted lists and returns one merged and sorted list
merge_sorted = []
i = 0
j = 0
len1 = len(lst1) - 1
len2 = len(lst2) - 1
while i < len1 or j < len2:
if lst1[i] < lst2[j]:
merge_sorted.append(lst1[i])
i += 1
elif lst1[i] > lst2[j]:
merge_sorted.append(lst2[j])
j += 1
else:
merge_sorted.append(lst1[i])
merge_sorted.append(lst2[j])
i += 1
j += 1
return merge_sorted
lst1 = [2, 4, 5, 6, 8]
lst2 = [1, 3, 7, 9, 0]
merge(lst1, lst2)
```
What I got:
```
IndexError Traceback (most recent call last)
<ipython-input-13-572aad47097b> in <module>()
22 lst1 = [2, 4, 5, 6, 8]
23 lst2 = [1, 3, 7, 9, 0]
---> 24 merge(lst1, lst2)
<ipython-input-13-572aad47097b> in merge(lst1, lst2)
7 len2 = len(lst2) - 1
8 while i < len1 or j < len2:
----> 9 if lst1[i] < lst2[j]:
10 merge_sorted.append(lst1[i])
11 i += 1
IndexError: list index out of range
```
|
2021/04/24
|
[
"https://Stackoverflow.com/questions/67241815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15753999/"
] |
Your problem is the while condition:
```
while i < len1 or j < len2:
```
it should be `and` - if either of the conditoins are not true, you simple append the remainder of the non-empty list to your result and you are done.
Your current code still enters the while-body and checks `if lst1[i] < lst2[j]:` if one of the `i` / `j` is bigger then the list you get the error you have.
---
The full fixed code:
```
def merge(lst1, lst2):
# Gets two sorted lists and returns one merged and sorted list
merge_sorted = []
i = 0
j = 0
len1 = len(lst1) - 1
len2 = len(lst2) - 1
while i < len1 and j < len2: # use and
if lst1[i] < lst2[j]:
merge_sorted.append(lst1[i])
i += 1
elif lst1[i] > lst2[j]:
merge_sorted.append(lst2[j])
j += 1
else:
merge_sorted.append(lst1[i])
merge_sorted.append(lst2[j])
i += 1
j += 1
# add remainder lists - the slices evaluate to [] if behind the list lengths
merge_sorted.extend(lst1[i:]) # if i is aready out of the list this is []
merge_sorted.extend(lst2[j:]) # if j is aready out of the list this is []
return merge_sorted
lst1 = [2, 4, 5, 6, 8]
lst2 = [0, 1, 3, 7, 9] # fixed input, needs to be sorted, yours was not
print(merge(lst1, lst2))
```
Output:
```
[0, 1, 2, 3, 4, 5, 6, 8, 7, 9]
```
|
First of all, Your logic is wrong! You are picking the lower numbers and putting them into the list. but what about the biggest number of all? You will be stuck there! Because you will never pick the last one!
I changed the logic. Instead of counting up the iterators, I removed the picked ones! and when one list got empty the rest of the other one will join the final list.
and secondly, don't use the "merge" name for your function! It's occupied!
```
def merger(l1, l2):
merge_sorted = []
t1, t2 = sorted(l1), sorted(l2)
while len(t1) != 0 and len(t2) != 0:
if t1[0] <= t2[0]:
merge_sorted.append(t1[0])
t1 = t1[1:]
else:
merge_sorted.append(t2[0])
t2 = t2[1:]
return merge_sorted + (t1 if len(t1) != 0 else t2)
lst2 = [2, 4, 5, 6, 8]
lst1 = [1, 3, 7, 9, 0, 10]
print(merger(lst1, lst2))
```
|
67,241,815
|
I tried writing a simple merge and sort function in python and got stuck after getting the following error-
```
List out of range.
```
I would appreciate if you could help me fix it and figure out how to avoid it. I have added the code below-
```
def merge(lst1, lst2):
# Gets two sorted lists and returns one merged and sorted list
merge_sorted = []
i = 0
j = 0
len1 = len(lst1) - 1
len2 = len(lst2) - 1
while i < len1 or j < len2:
if lst1[i] < lst2[j]:
merge_sorted.append(lst1[i])
i += 1
elif lst1[i] > lst2[j]:
merge_sorted.append(lst2[j])
j += 1
else:
merge_sorted.append(lst1[i])
merge_sorted.append(lst2[j])
i += 1
j += 1
return merge_sorted
lst1 = [2, 4, 5, 6, 8]
lst2 = [1, 3, 7, 9, 0]
merge(lst1, lst2)
```
What I got:
```
IndexError Traceback (most recent call last)
<ipython-input-13-572aad47097b> in <module>()
22 lst1 = [2, 4, 5, 6, 8]
23 lst2 = [1, 3, 7, 9, 0]
---> 24 merge(lst1, lst2)
<ipython-input-13-572aad47097b> in merge(lst1, lst2)
7 len2 = len(lst2) - 1
8 while i < len1 or j < len2:
----> 9 if lst1[i] < lst2[j]:
10 merge_sorted.append(lst1[i])
11 i += 1
IndexError: list index out of range
```
|
2021/04/24
|
[
"https://Stackoverflow.com/questions/67241815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15753999/"
] |
As suggested by other techies you can modify and run the program but you are simply increasing the time complexity of your program which you could have done in two lines.
* Just extend the list1 elements like
```
list1.extend(list2)
```
* once the elements are into the list1
```
print(set(sorted(list1)))
```
|
Here are the values for i, j just before that `if` condition-
```
0 0
0 1
1 1
1 2
2 2
3 2
4 2
4 3
5 3
```
When any of the lists is traversed till the end, it throws `index out of range error`.
**Solution-**
Instead of using `or` condition, use `and` condition and append the remaining list elements at the end of the sorted list.
|
67,241,815
|
I tried writing a simple merge and sort function in python and got stuck after getting the following error-
```
List out of range.
```
I would appreciate if you could help me fix it and figure out how to avoid it. I have added the code below-
```
def merge(lst1, lst2):
# Gets two sorted lists and returns one merged and sorted list
merge_sorted = []
i = 0
j = 0
len1 = len(lst1) - 1
len2 = len(lst2) - 1
while i < len1 or j < len2:
if lst1[i] < lst2[j]:
merge_sorted.append(lst1[i])
i += 1
elif lst1[i] > lst2[j]:
merge_sorted.append(lst2[j])
j += 1
else:
merge_sorted.append(lst1[i])
merge_sorted.append(lst2[j])
i += 1
j += 1
return merge_sorted
lst1 = [2, 4, 5, 6, 8]
lst2 = [1, 3, 7, 9, 0]
merge(lst1, lst2)
```
What I got:
```
IndexError Traceback (most recent call last)
<ipython-input-13-572aad47097b> in <module>()
22 lst1 = [2, 4, 5, 6, 8]
23 lst2 = [1, 3, 7, 9, 0]
---> 24 merge(lst1, lst2)
<ipython-input-13-572aad47097b> in merge(lst1, lst2)
7 len2 = len(lst2) - 1
8 while i < len1 or j < len2:
----> 9 if lst1[i] < lst2[j]:
10 merge_sorted.append(lst1[i])
11 i += 1
IndexError: list index out of range
```
|
2021/04/24
|
[
"https://Stackoverflow.com/questions/67241815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15753999/"
] |
First of all, Your logic is wrong! You are picking the lower numbers and putting them into the list. but what about the biggest number of all? You will be stuck there! Because you will never pick the last one!
I changed the logic. Instead of counting up the iterators, I removed the picked ones! and when one list got empty the rest of the other one will join the final list.
and secondly, don't use the "merge" name for your function! It's occupied!
```
def merger(l1, l2):
merge_sorted = []
t1, t2 = sorted(l1), sorted(l2)
while len(t1) != 0 and len(t2) != 0:
if t1[0] <= t2[0]:
merge_sorted.append(t1[0])
t1 = t1[1:]
else:
merge_sorted.append(t2[0])
t2 = t2[1:]
return merge_sorted + (t1 if len(t1) != 0 else t2)
lst2 = [2, 4, 5, 6, 8]
lst1 = [1, 3, 7, 9, 0, 10]
print(merger(lst1, lst2))
```
|
Here are the values for i, j just before that `if` condition-
```
0 0
0 1
1 1
1 2
2 2
3 2
4 2
4 3
5 3
```
When any of the lists is traversed till the end, it throws `index out of range error`.
**Solution-**
Instead of using `or` condition, use `and` condition and append the remaining list elements at the end of the sorted list.
|
43,753,657
|
I am a beginner in python and I am using an older version of anaconda which has the 3.5.2 version of python, because I would like to use tensorflow with it. I have some outdated packages that I would like to update with "conda update all". Is there a way to do this without updating python from 3.5 to 3.6, which is incompatible with tensorflow?
|
2017/05/03
|
[
"https://Stackoverflow.com/questions/43753657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7955849/"
] |
You can either update them all manually `conda update yourpackage`
...or you could update them all `conda update --all`, and then downgrade python again with `conda install python=3.5.2`.
|
Another simple method: `conda update --all python=3.5.2`
Replace the python version with your currently installed version. This will update all packages, and since the target version for `python` is already installed, it will not be updated. This also works with multiple packages: `conda update all python=3.5.2 spyder=3.3.6`.
|
43,753,657
|
I am a beginner in python and I am using an older version of anaconda which has the 3.5.2 version of python, because I would like to use tensorflow with it. I have some outdated packages that I would like to update with "conda update all". Is there a way to do this without updating python from 3.5 to 3.6, which is incompatible with tensorflow?
|
2017/05/03
|
[
"https://Stackoverflow.com/questions/43753657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7955849/"
] |
Short Answer
============
```sh
conda update --all --dry-run 2>/dev/null |
grep -Fe '-->' |
cut -d' ' -f3 |
grep -ve 'python' |
xargs conda update
```
---
Long Answer
===========
Step 1: Dry run to check packages to be updated
-----------------------------------------------
**Command**
```sh
conda update --all --dry-run
```
**Result**
```
Collecting package metadata (current_repodata.json): done
Solving environment: done
## Package Plan ##
environment location: //anaconda3/envs/general
The following packages will be UPDATED:
astroid 2.3.1-py37_0 --> 2.3.2-py37_0
ca-certificates 2019.8.28-0 --> 2019.10.16-0
openssl 1.0.2t-h1de35cc_1 --> 1.1.1d-h1de35cc_3
pip 19.2.3-py37_0 --> 19.3.1-py37_0
pylint 2.4.2-py37_0 --> 2.4.3-py37_0
python 3.7.0-hc167b69_0 --> 3.7.4-h359304d_1
sqlite 3.30.0-ha441bb4_0 --> 3.30.1-ha441bb4_0
DryRunExit: Dry run. Exiting.
```
---
Step 2: Get rid of messages from stderr (optional, but clearer)
---------------------------------------------------------------
**Command**
```sh
conda update --all --dry-run 2>/dev/null
```
**Result**
```
Collecting package metadata (current_repodata.json): done
Solving environment: done
## Package Plan ##
environment location: //anaconda3/envs/general
The following packages will be UPDATED:
astroid 2.3.1-py37_0 --> 2.3.2-py37_0
ca-certificates 2019.8.28-0 --> 2019.10.16-0
openssl 1.0.2t-h1de35cc_1 --> 1.1.1d-h1de35cc_3
pip 19.2.3-py37_0 --> 19.3.1-py37_0
pylint 2.4.2-py37_0 --> 2.4.3-py37_0
python 3.7.0-hc167b69_0 --> 3.7.4-h359304d_1
sqlite 3.30.0-ha441bb4_0 --> 3.30.1-ha441bb4_0
```
---
Step 3: Extract the lines with package names
--------------------------------------------
**Command**
```sh
conda update --all --dry-run 2>/dev/null |
grep -Fe '-->'
```
**Result**
```
astroid 2.3.1-py37_0 --> 2.3.2-py37_0
ca-certificates 2019.8.28-0 --> 2019.10.16-0
openssl 1.0.2t-h1de35cc_1 --> 1.1.1d-h1de35cc_3
pip 19.2.3-py37_0 --> 19.3.1-py37_0
pylint 2.4.2-py37_0 --> 2.4.3-py37_0
python 3.7.0-hc167b69_0 --> 3.7.4-h359304d_1
sqlite 3.30.0-ha441bb4_0 --> 3.30.1-ha441bb4_0
```
---
Step 4: Produce a list of package names
---------------------------------------
**Command**
```sh
conda update --all --dry-run 2>/dev/null |
grep -Fe '-->' |
cut -d' ' -f3
```
Note: Since there are 2 spaces in front of each package name, the package name is the 3rd field of the line. This leads to the argument `-f3`.
**Result**
```
astroid
ca-certificates
openssl
pip
pylint
python
sqlite
```
---
Step 5: Remove the package(s) not requiring update from the list
----------------------------------------------------------------
**Command**
```sh
conda update --all --dry-run 2>/dev/null |
grep -Fe '-->' |
cut -d' ' -f3 |
grep -ve 'python'
```
**Result**
```
astroid
ca-certificates
openssl
pip
pylint
sqlite
```
---
Step 6: Update the packages from the list
-----------------------------------------
**Command**
```sh
conda update --all --dry-run 2>/dev/null |
grep -Fe '-->' |
cut -d' ' -f3 |
grep -ve 'python' |
xargs conda update
```
|
Another simple method: `conda update --all python=3.5.2`
Replace the python version with your currently installed version. This will update all packages, and since the target version for `python` is already installed, it will not be updated. This also works with multiple packages: `conda update all python=3.5.2 spyder=3.3.6`.
|
33,582,766
|
I'm running a python script and it used to work (it even does on my other laptop right now) but not on my current computer - I just get the error code:
```
Process finished with exit code -1073741515 (0xC0000135)
```
I don't get any other results - not even from "print" commands at the beginning of the file.
I haven't found anything specific to that.
I re-installed python (2.7.9), pygame (1.9.1) and even pycharm (tried 4.5 first, now with 5.0 - same result)
Does anyone know what that error code means? I couldn't find anything about it.
|
2015/11/07
|
[
"https://Stackoverflow.com/questions/33582766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3909896/"
] |
I encountered the same error when running .py in PyCharm on Windows. Inspired by <https://thenewboston.com/forum/topic.php?id=10088>, I uninstalled and reinstalled Python. When reinstalling, I checked the `ADD PYTHON TO THE PATH` Option. After recreating the virtual environment in PyCharm, the error was gone.
**Update**: On another Windows PC (64-bit), I encountered the same error where reinstalling Python was not enough. I tried two things.
1. Uninstalling 32-bit Python and installing 64-bit Python. Namely downloading `python-3.6.4-amd64.exe` instead of `python-3.6.4.exe`
2. Recreating the Pycharm project from github.
Between the two actions, the error was gone.
|
I encountered this error in my code as well, in my case the problem was sharing `pickle` which produced in Unix machine one a Windows one.
|
33,582,766
|
I'm running a python script and it used to work (it even does on my other laptop right now) but not on my current computer - I just get the error code:
```
Process finished with exit code -1073741515 (0xC0000135)
```
I don't get any other results - not even from "print" commands at the beginning of the file.
I haven't found anything specific to that.
I re-installed python (2.7.9), pygame (1.9.1) and even pycharm (tried 4.5 first, now with 5.0 - same result)
Does anyone know what that error code means? I couldn't find anything about it.
|
2015/11/07
|
[
"https://Stackoverflow.com/questions/33582766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3909896/"
] |
I encountered the same error when running .py in PyCharm on Windows. Inspired by <https://thenewboston.com/forum/topic.php?id=10088>, I uninstalled and reinstalled Python. When reinstalling, I checked the `ADD PYTHON TO THE PATH` Option. After recreating the virtual environment in PyCharm, the error was gone.
**Update**: On another Windows PC (64-bit), I encountered the same error where reinstalling Python was not enough. I tried two things.
1. Uninstalling 32-bit Python and installing 64-bit Python. Namely downloading `python-3.6.4-amd64.exe` instead of `python-3.6.4.exe`
2. Recreating the Pycharm project from github.
Between the two actions, the error was gone.
|
\*\*I faced the same situation and the malfunction stems from trying to run both terminal processor and graphical user interfaces. When I clicked the button program stopped running \*\*
Solution: I disabled terminal inputs and work with graphics.
For example:
if you do this
```
entry1=Entry(root,width=10).pack()
variable= str(input("Whats your name?"))
```
You will see the error.
if you delete either entry1 or variable, you will not see the problem.
|
33,582,766
|
I'm running a python script and it used to work (it even does on my other laptop right now) but not on my current computer - I just get the error code:
```
Process finished with exit code -1073741515 (0xC0000135)
```
I don't get any other results - not even from "print" commands at the beginning of the file.
I haven't found anything specific to that.
I re-installed python (2.7.9), pygame (1.9.1) and even pycharm (tried 4.5 first, now with 5.0 - same result)
Does anyone know what that error code means? I couldn't find anything about it.
|
2015/11/07
|
[
"https://Stackoverflow.com/questions/33582766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3909896/"
] |
reinstall python β you don't have python33.dll in c:\WINDOWS\system32\
Maybe you have different python versions β look at folders in root of c:
If yes, then point to your version of python.exe in pyCharm > Settings > Project Interpreter
|
I solved it by disabling "**PyQt compatible**" checkbox in the Settings under **Build, Execution, Deployment --> Python Debugger**.
After that, it should debug properly.
|
33,582,766
|
I'm running a python script and it used to work (it even does on my other laptop right now) but not on my current computer - I just get the error code:
```
Process finished with exit code -1073741515 (0xC0000135)
```
I don't get any other results - not even from "print" commands at the beginning of the file.
I haven't found anything specific to that.
I re-installed python (2.7.9), pygame (1.9.1) and even pycharm (tried 4.5 first, now with 5.0 - same result)
Does anyone know what that error code means? I couldn't find anything about it.
|
2015/11/07
|
[
"https://Stackoverflow.com/questions/33582766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3909896/"
] |
reinstall python β you don't have python33.dll in c:\WINDOWS\system32\
Maybe you have different python versions β look at folders in root of c:
If yes, then point to your version of python.exe in pyCharm > Settings > Project Interpreter
|
I got this error in PyCharm after upgrading pyarrow to the most recent version -- 0.16 --- using pip, running the same code I had ran before this update which used pandas read\_parquet specifying the engine="pyarrow" triggering use of this library. After uninstalling and installing the previous version with
>
> pip install pyarrow=="0.15"
>
>
>
the problem resolved.
|
33,582,766
|
I'm running a python script and it used to work (it even does on my other laptop right now) but not on my current computer - I just get the error code:
```
Process finished with exit code -1073741515 (0xC0000135)
```
I don't get any other results - not even from "print" commands at the beginning of the file.
I haven't found anything specific to that.
I re-installed python (2.7.9), pygame (1.9.1) and even pycharm (tried 4.5 first, now with 5.0 - same result)
Does anyone know what that error code means? I couldn't find anything about it.
|
2015/11/07
|
[
"https://Stackoverflow.com/questions/33582766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3909896/"
] |
I encountered the same error when running .py in PyCharm on Windows. Inspired by <https://thenewboston.com/forum/topic.php?id=10088>, I uninstalled and reinstalled Python. When reinstalling, I checked the `ADD PYTHON TO THE PATH` Option. After recreating the virtual environment in PyCharm, the error was gone.
**Update**: On another Windows PC (64-bit), I encountered the same error where reinstalling Python was not enough. I tried two things.
1. Uninstalling 32-bit Python and installing 64-bit Python. Namely downloading `python-3.6.4-amd64.exe` instead of `python-3.6.4.exe`
2. Recreating the Pycharm project from github.
Between the two actions, the error was gone.
|
Here is caused it and solution:
The computer had two physical processors. The code uses Numba for parallel computations. Upon disabling and re-enabling hyperthreading this issue started. To solve it clear **pycache** folder and run the program.
|
33,582,766
|
I'm running a python script and it used to work (it even does on my other laptop right now) but not on my current computer - I just get the error code:
```
Process finished with exit code -1073741515 (0xC0000135)
```
I don't get any other results - not even from "print" commands at the beginning of the file.
I haven't found anything specific to that.
I re-installed python (2.7.9), pygame (1.9.1) and even pycharm (tried 4.5 first, now with 5.0 - same result)
Does anyone know what that error code means? I couldn't find anything about it.
|
2015/11/07
|
[
"https://Stackoverflow.com/questions/33582766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3909896/"
] |
reinstall python β you don't have python33.dll in c:\WINDOWS\system32\
Maybe you have different python versions β look at folders in root of c:
If yes, then point to your version of python.exe in pyCharm > Settings > Project Interpreter
|
\*\*I faced the same situation and the malfunction stems from trying to run both terminal processor and graphical user interfaces. When I clicked the button program stopped running \*\*
Solution: I disabled terminal inputs and work with graphics.
For example:
if you do this
```
entry1=Entry(root,width=10).pack()
variable= str(input("Whats your name?"))
```
You will see the error.
if you delete either entry1 or variable, you will not see the problem.
|
33,582,766
|
I'm running a python script and it used to work (it even does on my other laptop right now) but not on my current computer - I just get the error code:
```
Process finished with exit code -1073741515 (0xC0000135)
```
I don't get any other results - not even from "print" commands at the beginning of the file.
I haven't found anything specific to that.
I re-installed python (2.7.9), pygame (1.9.1) and even pycharm (tried 4.5 first, now with 5.0 - same result)
Does anyone know what that error code means? I couldn't find anything about it.
|
2015/11/07
|
[
"https://Stackoverflow.com/questions/33582766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3909896/"
] |
I encountered this error in my code as well, in my case the problem was sharing `pickle` which produced in Unix machine one a Windows one.
|
If you're trying create a .svm use dlib probably the problem is in .xml, some image that you use is cause the problem. Try to create a new .xml putting out a image(any image) or remove that your .xml and test, try this even you find out the image problem.
For exemple, the image "treinamento3.jpg" was the problem. I removed this command line:
```
< image file='delirium\treinamento3.jpg'>
< box top='213' left='86' width='46' height='49'/ >
< box top='531' left='47' width='125' height='123'/ >
< /image >
```
from my .xml for solve my problem.
|
33,582,766
|
I'm running a python script and it used to work (it even does on my other laptop right now) but not on my current computer - I just get the error code:
```
Process finished with exit code -1073741515 (0xC0000135)
```
I don't get any other results - not even from "print" commands at the beginning of the file.
I haven't found anything specific to that.
I re-installed python (2.7.9), pygame (1.9.1) and even pycharm (tried 4.5 first, now with 5.0 - same result)
Does anyone know what that error code means? I couldn't find anything about it.
|
2015/11/07
|
[
"https://Stackoverflow.com/questions/33582766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3909896/"
] |
I got this error in PyCharm after upgrading pyarrow to the most recent version -- 0.16 --- using pip, running the same code I had ran before this update which used pandas read\_parquet specifying the engine="pyarrow" triggering use of this library. After uninstalling and installing the previous version with
>
> pip install pyarrow=="0.15"
>
>
>
the problem resolved.
|
Here is caused it and solution:
The computer had two physical processors. The code uses Numba for parallel computations. Upon disabling and re-enabling hyperthreading this issue started. To solve it clear **pycache** folder and run the program.
|
33,582,766
|
I'm running a python script and it used to work (it even does on my other laptop right now) but not on my current computer - I just get the error code:
```
Process finished with exit code -1073741515 (0xC0000135)
```
I don't get any other results - not even from "print" commands at the beginning of the file.
I haven't found anything specific to that.
I re-installed python (2.7.9), pygame (1.9.1) and even pycharm (tried 4.5 first, now with 5.0 - same result)
Does anyone know what that error code means? I couldn't find anything about it.
|
2015/11/07
|
[
"https://Stackoverflow.com/questions/33582766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3909896/"
] |
reinstall python β you don't have python33.dll in c:\WINDOWS\system32\
Maybe you have different python versions β look at folders in root of c:
If yes, then point to your version of python.exe in pyCharm > Settings > Project Interpreter
|
I encountered this error in my code as well, in my case the problem was sharing `pickle` which produced in Unix machine one a Windows one.
|
33,582,766
|
I'm running a python script and it used to work (it even does on my other laptop right now) but not on my current computer - I just get the error code:
```
Process finished with exit code -1073741515 (0xC0000135)
```
I don't get any other results - not even from "print" commands at the beginning of the file.
I haven't found anything specific to that.
I re-installed python (2.7.9), pygame (1.9.1) and even pycharm (tried 4.5 first, now with 5.0 - same result)
Does anyone know what that error code means? I couldn't find anything about it.
|
2015/11/07
|
[
"https://Stackoverflow.com/questions/33582766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3909896/"
] |
The error seems to be related to issues in native code (e.g. C/C++) and might be related to issues in loading some dll file. To know which file, the Windows "Event Viewer" is your friend.
The "Event Viewer" -> "Windows Logs" -> "Application" feed usually shows one or more rows for each crashed application and one of them should list the problematic filename.
Personally I observed similar issue with matplotlib on Python 3.9 (installed using Anaconda on Windows 10). I could see this kind of error when the code was executed using PyCharm. The same code just crashed with no visible errors when starting from Anaconda console.
The Event viewer then showed issue with freetype.dll. In this case, the problem was fixed by downgrading the packege from 2.11.0 to 2.10.4:
```
conda install freetype=2.10.4
```
Depending on the exact issue, I could imagine that removing pycache folder might help (like mentioned in other answers). Also, sometimes it might make sense to look at the PATH environment variable to actually understand why certain dll file is loaded from such a location.
|
Here is caused it and solution:
The computer had two physical processors. The code uses Numba for parallel computations. Upon disabling and re-enabling hyperthreading this issue started. To solve it clear **pycache** folder and run the program.
|
12,737,121
|
This bit is being troublesome....
```
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
//1
NSString *urlString = @"http://zaphod_beeblebrox.pythonanywhere.com/";
//2
NSURL *url = [NSURL URLWithString:urlString];
//3
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//4
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
//5
[NSURLConnection sendAsynchronousRequest:request queue:queue
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if ([data length] > 0 && error == nil) (UIWebView)
else if ((error != nil) NSLog(@"Error: %@", error))}];
}@end
```
I can't seem to figure out what is causing else if to have problems. I have googled the crap out of this and have checked my code over and over, but I cant seem to figure this out!
please help.
|
2012/10/04
|
[
"https://Stackoverflow.com/questions/12737121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1718637/"
] |
You asked this same question before, which [I answered](https://stackoverflow.com/a/12720171/1271826). I repeat the relevant portions of that answer below. If there's something that didn't make sense, just leave a comment below.
---
I'm guessing you're trying to load a html page in a `UIWebView`? You obviously need an `IBOutlet` for your `UIWebView`. (If you're not familiar with `IBOutlet`, check out the Apple tutorial [Your First iOS App](http://developer.apple.com/library/ios/referencelibrary/GettingStarted/RoadMapiOS/chapters/RM_YourFirstApp_iOS/Articles/00_Introduction.html).)
Anyway, in my examples below, I'm going to assume your `IBOutlet` is called `webview`, and thus I might advise getting rid of the `NSOperationQueue` and `NSUrlConnection` and just have the `UIWebView` load the html for you:
```
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *urlString = @"http://zaphod_beeblebrox.pythonanywhere.com/";
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webview loadRequest:request];
}
```
It might be worth going through a few iPhone programming tutorials (just google it and you'll get tons of hits), too or look at the Apple [App Programming Guide](http://developer.apple.com/library/ios/#referencelibrary/GettingStarted/RoadMapiOS/chapters/Introduction.html) or check out the wonderful resources at <http://developer.apple.com>.
---
**Update:**
By the way, if you insist on using `NSOperationQueue` and `NSUrlConnection`, you still need an `IBOutlet` for your webview. But the revised code would look like:
```
NSString *urlString = @"http://zaphod_beeblebrox.pythonanywhere.com/";
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request
queue:queue
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if ([data length] > 0 && error == nil)
{
NSString *htmlString = [NSString stringWithUTF8String:data.bytes];
[self.webview loadHTMLString:htmlString baseURL:url];
}
else if (error != nil)
{
NSLog(@"Error: %@", error);
}
else
{
NSLog(@"No data returned");
}
}];
```
I think `loadRequest` is much simpler, but if you really want to do it this way, here you go.
|
' I am trying to use a uiwebview to bring up a web app. If you know of any better way, please let me know!'
```
[theWebView loadRequest:[NSURLRequest requestWithURL:theURL]];
```
|
12,737,121
|
This bit is being troublesome....
```
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
//1
NSString *urlString = @"http://zaphod_beeblebrox.pythonanywhere.com/";
//2
NSURL *url = [NSURL URLWithString:urlString];
//3
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//4
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
//5
[NSURLConnection sendAsynchronousRequest:request queue:queue
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if ([data length] > 0 && error == nil) (UIWebView)
else if ((error != nil) NSLog(@"Error: %@", error))}];
}@end
```
I can't seem to figure out what is causing else if to have problems. I have googled the crap out of this and have checked my code over and over, but I cant seem to figure this out!
please help.
|
2012/10/04
|
[
"https://Stackoverflow.com/questions/12737121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1718637/"
] |
You asked this same question before, which [I answered](https://stackoverflow.com/a/12720171/1271826). I repeat the relevant portions of that answer below. If there's something that didn't make sense, just leave a comment below.
---
I'm guessing you're trying to load a html page in a `UIWebView`? You obviously need an `IBOutlet` for your `UIWebView`. (If you're not familiar with `IBOutlet`, check out the Apple tutorial [Your First iOS App](http://developer.apple.com/library/ios/referencelibrary/GettingStarted/RoadMapiOS/chapters/RM_YourFirstApp_iOS/Articles/00_Introduction.html).)
Anyway, in my examples below, I'm going to assume your `IBOutlet` is called `webview`, and thus I might advise getting rid of the `NSOperationQueue` and `NSUrlConnection` and just have the `UIWebView` load the html for you:
```
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *urlString = @"http://zaphod_beeblebrox.pythonanywhere.com/";
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webview loadRequest:request];
}
```
It might be worth going through a few iPhone programming tutorials (just google it and you'll get tons of hits), too or look at the Apple [App Programming Guide](http://developer.apple.com/library/ios/#referencelibrary/GettingStarted/RoadMapiOS/chapters/Introduction.html) or check out the wonderful resources at <http://developer.apple.com>.
---
**Update:**
By the way, if you insist on using `NSOperationQueue` and `NSUrlConnection`, you still need an `IBOutlet` for your webview. But the revised code would look like:
```
NSString *urlString = @"http://zaphod_beeblebrox.pythonanywhere.com/";
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request
queue:queue
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if ([data length] > 0 && error == nil)
{
NSString *htmlString = [NSString stringWithUTF8String:data.bytes];
[self.webview loadHTMLString:htmlString baseURL:url];
}
else if (error != nil)
{
NSLog(@"Error: %@", error);
}
else
{
NSLog(@"No data returned");
}
}];
```
I think `loadRequest` is much simpler, but if you really want to do it this way, here you go.
|
You have 3 different errors. First "(UIWebView)" doesn't mean anything, and secondly, if you had a statement there that did mean something it would need a semicolon after it. Thirdly, there should be a semicolon after NSLog(@"Error: %@", error). It would be better to put some of the code on separate lines for readability -- it should look like this:
```
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if ([data length] > 0 && error == nil)
;//a valid expression here with a semicolon at the end
else if (error != nil)
NSLog(@"Error: %@", error);
}];
```
That being said, you should use the method that @Rob posted to make your code work.
|
27,949,520
|
how can I do this:
in python, how can I do a loop or an if statment, that to get in the loop/ the if statment, you need a function to be called.
I mean something like this:
```
if function() *is called*:
print('function() is called')
```
thanks
|
2015/01/14
|
[
"https://Stackoverflow.com/questions/27949520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4454553/"
] |
You should use booleans to handle that:
```
def function():
function.has_been_called = True
pass
function.has_been_called = False
#Actual Code!:
if function.has_been_called:
print('function()is called')
```
The boolean will now store whether or not the fucntion has been called.
|
Use a decorator to wrap the function, so that any time the function is called, you get a print, without having to alter your original function
```
def is_called(func):
def wrap():
func()
print func, "is called"
return wrap
@is_called
def function():
pass
if function():
pass #do
```
would print 'function is called'
|
58,932,201
|
I moved my Gem5 simulations from my system to a server. My system does not have HDF5 libraries, but the server has, and I am met with this error:
>
>
> ```
> /usr/local/lib/python2.7/config/libpython2.7.a(posixmodule.o): In function `posix_tmpnam':
> /space/src/Python-2.7/./Modules/posixmodule.c:7275: warning: the use of `tmpnam_r' is dangerous, better use `mkstemp'
> /usr/local/lib/python2.7/config/libpython2.7.a(posixmodule.o): In function `posix_tempnam':
> /space/src/Python-2.7/./Modules/posixmodule.c:7230: warning: the use of `tempnam' is dangerous, better use `mkstemp'
> build/X86/base/lib.o.partial: In function `Stats::Hdf5::addMetaData(H5::DataSet&, char const*, double)':
> /net/nasstore/students/GRAD/ECE/febinps/home/Paper3/gem5/build/X86/base/stats/hdf5.cc:312: undefined reference to `H5::H5Object::createAttribute(char const*, H5::DataType const&, H5::DataSpace const&, H5::PropList const&) const'
> build/X86/base/lib.o.partial: In function `Stats::Hdf5::addMetaData(H5::DataSet&, char const*, std::vector<char const*, std::allocator<char const*> > const&)':
> /net/nasstore/students/GRAD/ECE/febinps/home/Paper3/gem5/build/X86/base/stats/hdf5.cc:280: undefined reference to `H5::H5Object::createAttribute(char const*, H5::DataType const&, H5::DataSpace const&, H5::PropList const&) const'
> build/X86/base/lib.o.partial: In function `Stats::Hdf5::addMetaData(H5::DataSet&, char const*, std::string const&)':
> /net/nasstore/students/GRAD/ECE/febinps/home/Paper3/gem5/build/X86/base/stats/hdf5.cc:302: undefined reference to `H5::H5Object::createAttribute(char const*, H5::DataType const&, H5::DataSpace const&, H5::PropList const&) const'
> collect2: error: ld returned 1 exit status
> scons: *** [build/X86/gem5.opt] Error 1
> scons: building terminated because of errors.
>
> ```
>
>
How can I fix this? Is there an yway I can avoid the build from using HDF5? I cannot do much at the server as I do not have admin access.
|
2019/11/19
|
[
"https://Stackoverflow.com/questions/58932201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6346849/"
] |
I don't know the root cause of this issue, some one who is working on Gem5 could possibly answer that.
But as a workaround, since I have no admin access to the server ,and even then removing a library just for the sake of one build doesn't feel right, I edited the SConstruct file in gem5/, where the environment variables are gathered and passed:
```
have_hdf5 = 0 #check_hdf5() #line number 951 in the SConstruct file
```
This seems to work for the build.
|
In case you run on older system like Debian 10 or Ubuntu 16.04, the errors are due to the fact that the `hdf5` library path is not in default system library path. I solved it by manually (brutally) linking gem5 ...
The link flags added are:
`-L/usr/lib/x86_64-linux-gnu/hdf5/serial/ -lhdf5_cpp -lhdf5`
```sh
g++ -o /gem5/default/build/X86/gem5.opt \
-Wl,--as-needed -fuse-ld=gold -L/usr/lib/python2.7/config-x86_64-linux-gnu -L/usr/lib \
-Xlinker -export-dynamic \
-Wl,-O1 -Wl,-Bsymbolic-functions -z origin -O3 \
/gem5/default/build/X86/sim/main.o \
/gem5/default/build/X86/dev/net/lib.o.partial \
/gem5/default/build/X86/base/lib.o.partial \
/gem5/default/build/X86/dev/i2c/lib.o.partial \
/gem5/default/build/X86/cpu/testers/traffic_gen/lib.o.partial \
/gem5/default/build/X86/mem/cache/tags/indexing_policies/lib.o.partial \
/gem5/default/build/X86/mem/ruby/slicc_interface/lib.o.partial \
/gem5/default/build/X86/mem/probes/lib.o.partial \
/gem5/default/build/X86/mem/ruby/network/simple/lib.o.partial \
/gem5/default/build/X86/dev/x86/lib.o.partial \
/gem5/default/build/X86/mem/ruby/network/fault_model/lib.o.partial \
/gem5/default/build/X86/systemc/utils/lib.o.partial \
/gem5/default/build/X86/systemc/dt/int/lib.o.partial \
/gem5/default/build/X86/cpu/kvm/lib.o.partial \
/gem5/default/build/X86/cpu/simple/probes/lib.o.partial \
/gem5/default/build/X86/base/filters/lib.o.partial \
/gem5/default/build/X86/dev/serial/lib.o.partial \
/gem5/default/build/X86/sim/power/lib.o.partial \
/gem5/default/build/X86/mem/cache/tags/lib.o.partial \
/gem5/default/build/X86/arch/x86/bios/lib.o.partial \
/gem5/default/build/X86/systemc/dt/fx/lib.o.partial \
/gem5/default/build/X86/mem/ruby/common/lib.o.partial \
/gem5/default/build/X86/mem/ruby/network/garnet2.0/lib.o.partial \
/gem5/default/build/X86/mem/ruby/structures/lib.o.partial \
/gem5/default/build/X86/cpu/testers/garnet_synthetic_traffic/lib.o.partial \
/gem5/default/build/X86/mem/cache/prefetch/lib.o.partial \
/gem5/default/build/X86/cpu/trace/lib.o.partial \
/gem5/default/build/X86/sim/probe/lib.o.partial \
/gem5/default/build/X86/sim/lib.o.partial \
/gem5/default/build/X86/mem/ruby/protocol/lib.o.partial \
/gem5/default/build/X86/systemc/tlm_core/2/quantum/lib.o.partial \
/gem5/default/build/X86/cpu/simple/lib.o.partial \
/gem5/default/build/X86/base/vnc/lib.o.partial \
/gem5/default/build/X86/mem/ruby/system/lib.o.partial \
/gem5/default/build/X86/mem/cache/lib.o.partial \
/gem5/default/build/X86/arch/x86/lib.o.partial \
/gem5/default/build/X86/dev/storage/lib.o.partial \
/gem5/default/build/X86/mem/protocol/lib.o.partial \
/gem5/default/build/X86/systemc/core/lib.o.partial \
/gem5/default/build/X86/systemc/tlm_core/2/generic_payload/lib.o.partial \
/gem5/default/build/X86/cpu/testers/directedtest/lib.o.partial \
/gem5/default/build/X86/mem/ruby/profiler/lib.o.partial \
/gem5/default/build/X86/arch/x86/regs/lib.o.partial \
/gem5/default/build/X86/dev/pci/lib.o.partial \
/gem5/default/build/X86/cpu/o3/probe/lib.o.partial \
/gem5/default/build/X86/mem/cache/compressors/lib.o.partial \
/gem5/default/build/X86/cpu/lib.o.partial \
/gem5/default/build/X86/learning_gem5/part2/lib.o.partial \
/gem5/default/build/X86/mem/cache/replacement_policies/lib.o.partial \
/gem5/default/build/X86/dev/virtio/lib.o.partial \
/gem5/default/build/X86/proto/lib.o.partial \
/gem5/default/build/X86/cpu/testers/rubytest/lib.o.partial \
/gem5/default/build/X86/mem/qos/lib.o.partial \
/gem5/default/build/X86/cpu/pred/lib.o.partial \
/gem5/default/build/X86/python/lib.o.partial \
/gem5/default/build/X86/arch/generic/lib.o.partial \
/gem5/default/build/X86/systemc/tlm_bridge/lib.o.partial \
/gem5/default/build/X86/dev/lib.o.partial \
/gem5/default/build/X86/kern/lib.o.partial \
/gem5/default/build/X86/mem/lib.o.partial \
/gem5/default/build/X86/cpu/testers/memtest/lib.o.partial \
/gem5/default/build/X86/systemc/dt/misc/lib.o.partial \
/gem5/default/build/X86/systemc/tlm_utils/lib.o.partial \
/gem5/default/build/X86/cpu/o3/lib.o.partial \
/gem5/default/build/X86/mem/ruby/network/lib.o.partial \
/gem5/default/build/X86/systemc/dt/bit/lib.o.partial \
/gem5/default/build/X86/dev/ps2/lib.o.partial \
/gem5/default/build/X86/unittest/lib.o.partial \
/gem5/default/build/X86/systemc/channel/lib.o.partial \
/gem5/default/build/X86/systemc/dt/lib.o.partial \
/gem5/default/build/X86/base/date.o \
-L/gem5/default/build/libelf -L/gem5/default/build/fputils -L/gem5/default/build/libfdt -L/gem5/default/build/drampower -L/gem5/default/build/iostream3 -L/gem5/default/build/nomali -L/gem5/default/build/googletest -L/usr/lib/x86_64-linux-gnu/hdf5/serial/ \
-lpython2.7 -lpthread -ldl -lutil -lm -lz -lprotobuf -lrt -ltcmalloc -lnomali -liostream3 \
-ldrampower -lfdt -lfputils -lelf -lhdf5_cpp -lhdf5
```
|
58,932,201
|
I moved my Gem5 simulations from my system to a server. My system does not have HDF5 libraries, but the server has, and I am met with this error:
>
>
> ```
> /usr/local/lib/python2.7/config/libpython2.7.a(posixmodule.o): In function `posix_tmpnam':
> /space/src/Python-2.7/./Modules/posixmodule.c:7275: warning: the use of `tmpnam_r' is dangerous, better use `mkstemp'
> /usr/local/lib/python2.7/config/libpython2.7.a(posixmodule.o): In function `posix_tempnam':
> /space/src/Python-2.7/./Modules/posixmodule.c:7230: warning: the use of `tempnam' is dangerous, better use `mkstemp'
> build/X86/base/lib.o.partial: In function `Stats::Hdf5::addMetaData(H5::DataSet&, char const*, double)':
> /net/nasstore/students/GRAD/ECE/febinps/home/Paper3/gem5/build/X86/base/stats/hdf5.cc:312: undefined reference to `H5::H5Object::createAttribute(char const*, H5::DataType const&, H5::DataSpace const&, H5::PropList const&) const'
> build/X86/base/lib.o.partial: In function `Stats::Hdf5::addMetaData(H5::DataSet&, char const*, std::vector<char const*, std::allocator<char const*> > const&)':
> /net/nasstore/students/GRAD/ECE/febinps/home/Paper3/gem5/build/X86/base/stats/hdf5.cc:280: undefined reference to `H5::H5Object::createAttribute(char const*, H5::DataType const&, H5::DataSpace const&, H5::PropList const&) const'
> build/X86/base/lib.o.partial: In function `Stats::Hdf5::addMetaData(H5::DataSet&, char const*, std::string const&)':
> /net/nasstore/students/GRAD/ECE/febinps/home/Paper3/gem5/build/X86/base/stats/hdf5.cc:302: undefined reference to `H5::H5Object::createAttribute(char const*, H5::DataType const&, H5::DataSpace const&, H5::PropList const&) const'
> collect2: error: ld returned 1 exit status
> scons: *** [build/X86/gem5.opt] Error 1
> scons: building terminated because of errors.
>
> ```
>
>
How can I fix this? Is there an yway I can avoid the build from using HDF5? I cannot do much at the server as I do not have admin access.
|
2019/11/19
|
[
"https://Stackoverflow.com/questions/58932201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6346849/"
] |
After the resolution of: <https://askubuntu.com/questions/1187343/installation-of-gem5-on-ubuntu-19-10-on-my-laptop-i5-cpu-m520-64bit> in gem5 b383997d4a9c642dd4356bfc4554ac7ae183ae62 (March 2020) the Ubuntu 19.10 (GCC 9) build is working for me:
```
scons -j `nproc` build/ARM/gem5.opt
```
If you find any further build bugs, do open an issue on the Jira issue tracker.
After <https://gem5-review.googlesource.com/c/public/gem5/+/34777> gem5 should be building every time with HDF5 on the [upstream testing system](https://stackoverflow.com/questions/52279971/how-to-run-the-gem5-unit-tests) see also <https://askubuntu.com/questions/350475/how-can-i-install-gem5/1275773#1275773> so I don't think it will break again easily.
|
In case you run on older system like Debian 10 or Ubuntu 16.04, the errors are due to the fact that the `hdf5` library path is not in default system library path. I solved it by manually (brutally) linking gem5 ...
The link flags added are:
`-L/usr/lib/x86_64-linux-gnu/hdf5/serial/ -lhdf5_cpp -lhdf5`
```sh
g++ -o /gem5/default/build/X86/gem5.opt \
-Wl,--as-needed -fuse-ld=gold -L/usr/lib/python2.7/config-x86_64-linux-gnu -L/usr/lib \
-Xlinker -export-dynamic \
-Wl,-O1 -Wl,-Bsymbolic-functions -z origin -O3 \
/gem5/default/build/X86/sim/main.o \
/gem5/default/build/X86/dev/net/lib.o.partial \
/gem5/default/build/X86/base/lib.o.partial \
/gem5/default/build/X86/dev/i2c/lib.o.partial \
/gem5/default/build/X86/cpu/testers/traffic_gen/lib.o.partial \
/gem5/default/build/X86/mem/cache/tags/indexing_policies/lib.o.partial \
/gem5/default/build/X86/mem/ruby/slicc_interface/lib.o.partial \
/gem5/default/build/X86/mem/probes/lib.o.partial \
/gem5/default/build/X86/mem/ruby/network/simple/lib.o.partial \
/gem5/default/build/X86/dev/x86/lib.o.partial \
/gem5/default/build/X86/mem/ruby/network/fault_model/lib.o.partial \
/gem5/default/build/X86/systemc/utils/lib.o.partial \
/gem5/default/build/X86/systemc/dt/int/lib.o.partial \
/gem5/default/build/X86/cpu/kvm/lib.o.partial \
/gem5/default/build/X86/cpu/simple/probes/lib.o.partial \
/gem5/default/build/X86/base/filters/lib.o.partial \
/gem5/default/build/X86/dev/serial/lib.o.partial \
/gem5/default/build/X86/sim/power/lib.o.partial \
/gem5/default/build/X86/mem/cache/tags/lib.o.partial \
/gem5/default/build/X86/arch/x86/bios/lib.o.partial \
/gem5/default/build/X86/systemc/dt/fx/lib.o.partial \
/gem5/default/build/X86/mem/ruby/common/lib.o.partial \
/gem5/default/build/X86/mem/ruby/network/garnet2.0/lib.o.partial \
/gem5/default/build/X86/mem/ruby/structures/lib.o.partial \
/gem5/default/build/X86/cpu/testers/garnet_synthetic_traffic/lib.o.partial \
/gem5/default/build/X86/mem/cache/prefetch/lib.o.partial \
/gem5/default/build/X86/cpu/trace/lib.o.partial \
/gem5/default/build/X86/sim/probe/lib.o.partial \
/gem5/default/build/X86/sim/lib.o.partial \
/gem5/default/build/X86/mem/ruby/protocol/lib.o.partial \
/gem5/default/build/X86/systemc/tlm_core/2/quantum/lib.o.partial \
/gem5/default/build/X86/cpu/simple/lib.o.partial \
/gem5/default/build/X86/base/vnc/lib.o.partial \
/gem5/default/build/X86/mem/ruby/system/lib.o.partial \
/gem5/default/build/X86/mem/cache/lib.o.partial \
/gem5/default/build/X86/arch/x86/lib.o.partial \
/gem5/default/build/X86/dev/storage/lib.o.partial \
/gem5/default/build/X86/mem/protocol/lib.o.partial \
/gem5/default/build/X86/systemc/core/lib.o.partial \
/gem5/default/build/X86/systemc/tlm_core/2/generic_payload/lib.o.partial \
/gem5/default/build/X86/cpu/testers/directedtest/lib.o.partial \
/gem5/default/build/X86/mem/ruby/profiler/lib.o.partial \
/gem5/default/build/X86/arch/x86/regs/lib.o.partial \
/gem5/default/build/X86/dev/pci/lib.o.partial \
/gem5/default/build/X86/cpu/o3/probe/lib.o.partial \
/gem5/default/build/X86/mem/cache/compressors/lib.o.partial \
/gem5/default/build/X86/cpu/lib.o.partial \
/gem5/default/build/X86/learning_gem5/part2/lib.o.partial \
/gem5/default/build/X86/mem/cache/replacement_policies/lib.o.partial \
/gem5/default/build/X86/dev/virtio/lib.o.partial \
/gem5/default/build/X86/proto/lib.o.partial \
/gem5/default/build/X86/cpu/testers/rubytest/lib.o.partial \
/gem5/default/build/X86/mem/qos/lib.o.partial \
/gem5/default/build/X86/cpu/pred/lib.o.partial \
/gem5/default/build/X86/python/lib.o.partial \
/gem5/default/build/X86/arch/generic/lib.o.partial \
/gem5/default/build/X86/systemc/tlm_bridge/lib.o.partial \
/gem5/default/build/X86/dev/lib.o.partial \
/gem5/default/build/X86/kern/lib.o.partial \
/gem5/default/build/X86/mem/lib.o.partial \
/gem5/default/build/X86/cpu/testers/memtest/lib.o.partial \
/gem5/default/build/X86/systemc/dt/misc/lib.o.partial \
/gem5/default/build/X86/systemc/tlm_utils/lib.o.partial \
/gem5/default/build/X86/cpu/o3/lib.o.partial \
/gem5/default/build/X86/mem/ruby/network/lib.o.partial \
/gem5/default/build/X86/systemc/dt/bit/lib.o.partial \
/gem5/default/build/X86/dev/ps2/lib.o.partial \
/gem5/default/build/X86/unittest/lib.o.partial \
/gem5/default/build/X86/systemc/channel/lib.o.partial \
/gem5/default/build/X86/systemc/dt/lib.o.partial \
/gem5/default/build/X86/base/date.o \
-L/gem5/default/build/libelf -L/gem5/default/build/fputils -L/gem5/default/build/libfdt -L/gem5/default/build/drampower -L/gem5/default/build/iostream3 -L/gem5/default/build/nomali -L/gem5/default/build/googletest -L/usr/lib/x86_64-linux-gnu/hdf5/serial/ \
-lpython2.7 -lpthread -ldl -lutil -lm -lz -lprotobuf -lrt -ltcmalloc -lnomali -liostream3 \
-ldrampower -lfdt -lfputils -lelf -lhdf5_cpp -lhdf5
```
|
63,056,197
|
I'm writing some python code where I need to use generators inside recursive functions. Here is some code I wrote to mimic what I am trying to do. This is attempt 1.
```
def f():
def f2(i):
if i > 0:
yield i
f2(i - 1)
yield f2(10)
for x in f():
for y in x:
print(y)
```
This only prints 10, attempt 2 using this `yield from` construct I found online.
```
def f():
def f2(i):
if i > 0:
yield i
yield from f2(i - 1)
yield from f2(10)
for x in f():
print(x)
```
This does what I want, but I don't understand what is happening, what is `yield from` doing behind the scenes and why doesn't my first attempt work?
|
2020/07/23
|
[
"https://Stackoverflow.com/questions/63056197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5927758/"
] |
You can think of `yield from` as a for loop which yields every item:
```
for i in f(10):
yield i
```
is the same as `yield from f(10)`. In other words, it *yields* the items *from* the given iteratable which in this case is another generator.
|
`yield from g()` will recurse inside a new generator `g` yielding from each `yield` statement at that generator
so
```
def g1():
yield from g2()
def g2()
for i in range(10):
yield i * 2
```
You can think as if `yield from` in g1 was unrolling `g2` inside of it, expanding to something like this
```
def g1():
for i in range(10):
yield i * 2
```
This not what is happening because you have scopes and etc, but during the execution of `yield from g2()` in `g1` then interpreter recurse in `g2` yield each value that it yields, possibly recursing to another generator.
Now consider this generator
```
def flatten(maybe_it):
try:
for i0 in maybe_it:
for i1 in flatten(i0):
yield i1
except TypeError:
yield maybe_it
```
with `yield from` it can be rewrite as
```
def flatten(maybe_it):
try:
for i0 in maybe_it:
yield from flatten(i0):
except TypeError:
yield maybe_it
```
|
10,989,297
|
I have the following PHP code, and for the life of me I can't think of a simple & elegant way to implement around the empty() function in python to check if the index is defined in a list.
```
$counter = 0;
$a = array();
for ($i=0;$i<100;$i++){
$i = ($i > 4) ? 0 : $i;
if empty($a[$i]){
$a[$i]=array();
}
$a[$i][] = $counter;
$counter++;
}
```
if I do
```
if a[i] is None
```
then I get index out of range. However I am aware of ways to do it in multiple steps, but that's not what I wanted.
|
2012/06/12
|
[
"https://Stackoverflow.com/questions/10989297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/342553/"
] |
PHP Arrays and Python lists are not equivalent. PHP Arrays are actually [associative containers](http://php.net/manual/en/language.types.array.php):
>
> An array in PHP is actually an ordered map. A map is a type that
> associates values to keys. This type is optimized for several
> different uses; it can be treated as an array, list (vector), hash
> table (an implementation of a map), dictionary, collection, stack,
> queue, and probably more.
>
>
>
In Python, the map data structure is defined as a [dictionary](http://docs.python.org/library/stdtypes.html#typesmapping):
>
> A mapping object maps hashable values to arbitrary objects. Mappings
> are mutable objects. There is currently only one standard mapping
> type, the dictionary.
>
>
>
The `empty()` function [serve many purposes](http://php.net/manual/en/function.empty.php). In your use context, it is equivalent to the Python `in` operator:
```
>>> a = {}
>>> a[1] = "x"
>>> a[3] = "y"
>>> a[5] = "z"
>>> i = 3
>>> i in a
True
>>> i = 2
>>> i in a
False
```
|
In the event you were trying to do it with a list, you would have to actually set that index to none, otherwise the element wouldn't be there you'd possibly be trying to check an index past the end of the list.
```
>>> i = [None]
>>> i
[None]
>>> i = [None, None]
>>> i
[None, None]
>>> i[1] is None
True
```
|
10,989,297
|
I have the following PHP code, and for the life of me I can't think of a simple & elegant way to implement around the empty() function in python to check if the index is defined in a list.
```
$counter = 0;
$a = array();
for ($i=0;$i<100;$i++){
$i = ($i > 4) ? 0 : $i;
if empty($a[$i]){
$a[$i]=array();
}
$a[$i][] = $counter;
$counter++;
}
```
if I do
```
if a[i] is None
```
then I get index out of range. However I am aware of ways to do it in multiple steps, but that's not what I wanted.
|
2012/06/12
|
[
"https://Stackoverflow.com/questions/10989297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/342553/"
] |
PHP Arrays and Python lists are not equivalent. PHP Arrays are actually [associative containers](http://php.net/manual/en/language.types.array.php):
>
> An array in PHP is actually an ordered map. A map is a type that
> associates values to keys. This type is optimized for several
> different uses; it can be treated as an array, list (vector), hash
> table (an implementation of a map), dictionary, collection, stack,
> queue, and probably more.
>
>
>
In Python, the map data structure is defined as a [dictionary](http://docs.python.org/library/stdtypes.html#typesmapping):
>
> A mapping object maps hashable values to arbitrary objects. Mappings
> are mutable objects. There is currently only one standard mapping
> type, the dictionary.
>
>
>
The `empty()` function [serve many purposes](http://php.net/manual/en/function.empty.php). In your use context, it is equivalent to the Python `in` operator:
```
>>> a = {}
>>> a[1] = "x"
>>> a[3] = "y"
>>> a[5] = "z"
>>> i = 3
>>> i in a
True
>>> i = 2
>>> i in a
False
```
|
```
# variable may not exsists
if (variable in vars() or variable in globals()) and variable != "" and variable == False:
pass
```
|
14,049,983
|
I am trying to search for an element in a sub-element with Selenium (Version 2.28.0), but selenium des not seem to limit its search to the sub-element. Am I doing this wrong or is there a way to use element.find to search a sub-element?
For an example I created a simple test webpage with this code:
```
<!DOCTYPE html>
<html>
<body>
<div class=div title=div1>
<h1>My First Heading</h1>
<p class='test'>My first paragraph.</p>
</div>
<div class=div title=div2>
<h1>My Second Heading</h1>
<p class='test'>My second paragraph.</p>
</div>
<div class=div title=div3>
<h1>My Third Heading</h1>
<p class='test'>My third paragraph.</p>
</div>
</body>
</html>
```
My python (Version 2.6) code looks like this:
```
from selenium import webdriver
driver = webdriver.Firefox()
# Open the test page with this instance of Firefox
# element2 gets the second division as a web element
element2 = driver.find_element_by_xpath("//div[@title='div2']")
# Search second division for a paragraph with a class of 'test' and print the content
print element2.find_element_by_xpath("//p[@class='test']").text
# expected output: "My second paragraph."
# actual output: "My first paragraph."
```
If I run:
```
print element2.get_attribute('innerHTML')
```
It returns the html from the second division. So selenium is not limiting its search to element2.
I would like to be able to find a sub-element of element2. This post suggests my code should work [Selenium WebDriver access a sub element](https://stackoverflow.com/questions/8836712/selenium-webdriver-access-a-sub-element) but his problem was caused by a time-out issue.
Can anyone help me understand what is happening here?
|
2012/12/27
|
[
"https://Stackoverflow.com/questions/14049983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1529981/"
] |
If you start an XPath expression with `//`, it begins searching from the root of document. To search relative to a particular element, you should prepend the expression with `.` instead:
```
element2 = driver.find_element_by_xpath("//div[@title='div2']")
element2.find_element_by_xpath(".//p[@class='test']").text
```
|
***Find The Child of any Elements***
```
parent = browser.find_element(by=By.XPATH,value='value of XPATH of Parents')
child=parent.find_elements(by=By.TAG_NAME,value='value of child path')
```
|
14,049,983
|
I am trying to search for an element in a sub-element with Selenium (Version 2.28.0), but selenium des not seem to limit its search to the sub-element. Am I doing this wrong or is there a way to use element.find to search a sub-element?
For an example I created a simple test webpage with this code:
```
<!DOCTYPE html>
<html>
<body>
<div class=div title=div1>
<h1>My First Heading</h1>
<p class='test'>My first paragraph.</p>
</div>
<div class=div title=div2>
<h1>My Second Heading</h1>
<p class='test'>My second paragraph.</p>
</div>
<div class=div title=div3>
<h1>My Third Heading</h1>
<p class='test'>My third paragraph.</p>
</div>
</body>
</html>
```
My python (Version 2.6) code looks like this:
```
from selenium import webdriver
driver = webdriver.Firefox()
# Open the test page with this instance of Firefox
# element2 gets the second division as a web element
element2 = driver.find_element_by_xpath("//div[@title='div2']")
# Search second division for a paragraph with a class of 'test' and print the content
print element2.find_element_by_xpath("//p[@class='test']").text
# expected output: "My second paragraph."
# actual output: "My first paragraph."
```
If I run:
```
print element2.get_attribute('innerHTML')
```
It returns the html from the second division. So selenium is not limiting its search to element2.
I would like to be able to find a sub-element of element2. This post suggests my code should work [Selenium WebDriver access a sub element](https://stackoverflow.com/questions/8836712/selenium-webdriver-access-a-sub-element) but his problem was caused by a time-out issue.
Can anyone help me understand what is happening here?
|
2012/12/27
|
[
"https://Stackoverflow.com/questions/14049983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1529981/"
] |
If you start an XPath expression with `//`, it begins searching from the root of document. To search relative to a particular element, you should prepend the expression with `.` instead:
```
element2 = driver.find_element_by_xpath("//div[@title='div2']")
element2.find_element_by_xpath(".//p[@class='test']").text
```
|
This is how you search for element or tag in CSS subclass and I believe that it works for multilevel situation as well:
Sample HTML:
```html
<li class="meta-item">
<span class="label">Posted:</span>
<time class="value" datetime="2019-03-22T09:46:24+01:00" pubdate="pubdate">22.03.2019 u 09:46</time>
</li>
```
This is how you would get `pubdate` tag value for example.
```
published = driver.find_element_by_css_selector('li>time').get_attribute('datetime')
```
|
14,049,983
|
I am trying to search for an element in a sub-element with Selenium (Version 2.28.0), but selenium des not seem to limit its search to the sub-element. Am I doing this wrong or is there a way to use element.find to search a sub-element?
For an example I created a simple test webpage with this code:
```
<!DOCTYPE html>
<html>
<body>
<div class=div title=div1>
<h1>My First Heading</h1>
<p class='test'>My first paragraph.</p>
</div>
<div class=div title=div2>
<h1>My Second Heading</h1>
<p class='test'>My second paragraph.</p>
</div>
<div class=div title=div3>
<h1>My Third Heading</h1>
<p class='test'>My third paragraph.</p>
</div>
</body>
</html>
```
My python (Version 2.6) code looks like this:
```
from selenium import webdriver
driver = webdriver.Firefox()
# Open the test page with this instance of Firefox
# element2 gets the second division as a web element
element2 = driver.find_element_by_xpath("//div[@title='div2']")
# Search second division for a paragraph with a class of 'test' and print the content
print element2.find_element_by_xpath("//p[@class='test']").text
# expected output: "My second paragraph."
# actual output: "My first paragraph."
```
If I run:
```
print element2.get_attribute('innerHTML')
```
It returns the html from the second division. So selenium is not limiting its search to element2.
I would like to be able to find a sub-element of element2. This post suggests my code should work [Selenium WebDriver access a sub element](https://stackoverflow.com/questions/8836712/selenium-webdriver-access-a-sub-element) but his problem was caused by a time-out issue.
Can anyone help me understand what is happening here?
|
2012/12/27
|
[
"https://Stackoverflow.com/questions/14049983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1529981/"
] |
Use the following:
```
element2 = driver.find_element_by_cssselector("css=div[title='div2']")
element2.find_element_by_cssselector("p[@class='test']").text
```
Please let me know if you have any problems.
|
***Find The Child of any Elements***
```
parent = browser.find_element(by=By.XPATH,value='value of XPATH of Parents')
child=parent.find_elements(by=By.TAG_NAME,value='value of child path')
```
|
14,049,983
|
I am trying to search for an element in a sub-element with Selenium (Version 2.28.0), but selenium des not seem to limit its search to the sub-element. Am I doing this wrong or is there a way to use element.find to search a sub-element?
For an example I created a simple test webpage with this code:
```
<!DOCTYPE html>
<html>
<body>
<div class=div title=div1>
<h1>My First Heading</h1>
<p class='test'>My first paragraph.</p>
</div>
<div class=div title=div2>
<h1>My Second Heading</h1>
<p class='test'>My second paragraph.</p>
</div>
<div class=div title=div3>
<h1>My Third Heading</h1>
<p class='test'>My third paragraph.</p>
</div>
</body>
</html>
```
My python (Version 2.6) code looks like this:
```
from selenium import webdriver
driver = webdriver.Firefox()
# Open the test page with this instance of Firefox
# element2 gets the second division as a web element
element2 = driver.find_element_by_xpath("//div[@title='div2']")
# Search second division for a paragraph with a class of 'test' and print the content
print element2.find_element_by_xpath("//p[@class='test']").text
# expected output: "My second paragraph."
# actual output: "My first paragraph."
```
If I run:
```
print element2.get_attribute('innerHTML')
```
It returns the html from the second division. So selenium is not limiting its search to element2.
I would like to be able to find a sub-element of element2. This post suggests my code should work [Selenium WebDriver access a sub element](https://stackoverflow.com/questions/8836712/selenium-webdriver-access-a-sub-element) but his problem was caused by a time-out issue.
Can anyone help me understand what is happening here?
|
2012/12/27
|
[
"https://Stackoverflow.com/questions/14049983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1529981/"
] |
Use the following:
```
element2 = driver.find_element_by_cssselector("css=div[title='div2']")
element2.find_element_by_cssselector("p[@class='test']").text
```
Please let me know if you have any problems.
|
This is how you search for element or tag in CSS subclass and I believe that it works for multilevel situation as well:
Sample HTML:
```html
<li class="meta-item">
<span class="label">Posted:</span>
<time class="value" datetime="2019-03-22T09:46:24+01:00" pubdate="pubdate">22.03.2019 u 09:46</time>
</li>
```
This is how you would get `pubdate` tag value for example.
```
published = driver.find_element_by_css_selector('li>time').get_attribute('datetime')
```
|
14,049,983
|
I am trying to search for an element in a sub-element with Selenium (Version 2.28.0), but selenium des not seem to limit its search to the sub-element. Am I doing this wrong or is there a way to use element.find to search a sub-element?
For an example I created a simple test webpage with this code:
```
<!DOCTYPE html>
<html>
<body>
<div class=div title=div1>
<h1>My First Heading</h1>
<p class='test'>My first paragraph.</p>
</div>
<div class=div title=div2>
<h1>My Second Heading</h1>
<p class='test'>My second paragraph.</p>
</div>
<div class=div title=div3>
<h1>My Third Heading</h1>
<p class='test'>My third paragraph.</p>
</div>
</body>
</html>
```
My python (Version 2.6) code looks like this:
```
from selenium import webdriver
driver = webdriver.Firefox()
# Open the test page with this instance of Firefox
# element2 gets the second division as a web element
element2 = driver.find_element_by_xpath("//div[@title='div2']")
# Search second division for a paragraph with a class of 'test' and print the content
print element2.find_element_by_xpath("//p[@class='test']").text
# expected output: "My second paragraph."
# actual output: "My first paragraph."
```
If I run:
```
print element2.get_attribute('innerHTML')
```
It returns the html from the second division. So selenium is not limiting its search to element2.
I would like to be able to find a sub-element of element2. This post suggests my code should work [Selenium WebDriver access a sub element](https://stackoverflow.com/questions/8836712/selenium-webdriver-access-a-sub-element) but his problem was caused by a time-out issue.
Can anyone help me understand what is happening here?
|
2012/12/27
|
[
"https://Stackoverflow.com/questions/14049983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1529981/"
] |
If you start an XPath expression with `//`, it begins searching from the root of document. To search relative to a particular element, you should prepend the expression with `.` instead:
```
element2 = driver.find_element_by_xpath("//div[@title='div2']")
element2.find_element_by_xpath(".//p[@class='test']").text
```
|
Use the following:
```
element2 = driver.find_element_by_cssselector("css=div[title='div2']")
element2.find_element_by_cssselector("p[@class='test']").text
```
Please let me know if you have any problems.
|
14,049,983
|
I am trying to search for an element in a sub-element with Selenium (Version 2.28.0), but selenium des not seem to limit its search to the sub-element. Am I doing this wrong or is there a way to use element.find to search a sub-element?
For an example I created a simple test webpage with this code:
```
<!DOCTYPE html>
<html>
<body>
<div class=div title=div1>
<h1>My First Heading</h1>
<p class='test'>My first paragraph.</p>
</div>
<div class=div title=div2>
<h1>My Second Heading</h1>
<p class='test'>My second paragraph.</p>
</div>
<div class=div title=div3>
<h1>My Third Heading</h1>
<p class='test'>My third paragraph.</p>
</div>
</body>
</html>
```
My python (Version 2.6) code looks like this:
```
from selenium import webdriver
driver = webdriver.Firefox()
# Open the test page with this instance of Firefox
# element2 gets the second division as a web element
element2 = driver.find_element_by_xpath("//div[@title='div2']")
# Search second division for a paragraph with a class of 'test' and print the content
print element2.find_element_by_xpath("//p[@class='test']").text
# expected output: "My second paragraph."
# actual output: "My first paragraph."
```
If I run:
```
print element2.get_attribute('innerHTML')
```
It returns the html from the second division. So selenium is not limiting its search to element2.
I would like to be able to find a sub-element of element2. This post suggests my code should work [Selenium WebDriver access a sub element](https://stackoverflow.com/questions/8836712/selenium-webdriver-access-a-sub-element) but his problem was caused by a time-out issue.
Can anyone help me understand what is happening here?
|
2012/12/27
|
[
"https://Stackoverflow.com/questions/14049983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1529981/"
] |
This is how you search for element or tag in CSS subclass and I believe that it works for multilevel situation as well:
Sample HTML:
```html
<li class="meta-item">
<span class="label">Posted:</span>
<time class="value" datetime="2019-03-22T09:46:24+01:00" pubdate="pubdate">22.03.2019 u 09:46</time>
</li>
```
This is how you would get `pubdate` tag value for example.
```
published = driver.find_element_by_css_selector('li>time').get_attribute('datetime')
```
|
***Find The Child of any Elements***
```
parent = browser.find_element(by=By.XPATH,value='value of XPATH of Parents')
child=parent.find_elements(by=By.TAG_NAME,value='value of child path')
```
|
14,049,983
|
I am trying to search for an element in a sub-element with Selenium (Version 2.28.0), but selenium des not seem to limit its search to the sub-element. Am I doing this wrong or is there a way to use element.find to search a sub-element?
For an example I created a simple test webpage with this code:
```
<!DOCTYPE html>
<html>
<body>
<div class=div title=div1>
<h1>My First Heading</h1>
<p class='test'>My first paragraph.</p>
</div>
<div class=div title=div2>
<h1>My Second Heading</h1>
<p class='test'>My second paragraph.</p>
</div>
<div class=div title=div3>
<h1>My Third Heading</h1>
<p class='test'>My third paragraph.</p>
</div>
</body>
</html>
```
My python (Version 2.6) code looks like this:
```
from selenium import webdriver
driver = webdriver.Firefox()
# Open the test page with this instance of Firefox
# element2 gets the second division as a web element
element2 = driver.find_element_by_xpath("//div[@title='div2']")
# Search second division for a paragraph with a class of 'test' and print the content
print element2.find_element_by_xpath("//p[@class='test']").text
# expected output: "My second paragraph."
# actual output: "My first paragraph."
```
If I run:
```
print element2.get_attribute('innerHTML')
```
It returns the html from the second division. So selenium is not limiting its search to element2.
I would like to be able to find a sub-element of element2. This post suggests my code should work [Selenium WebDriver access a sub element](https://stackoverflow.com/questions/8836712/selenium-webdriver-access-a-sub-element) but his problem was caused by a time-out issue.
Can anyone help me understand what is happening here?
|
2012/12/27
|
[
"https://Stackoverflow.com/questions/14049983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1529981/"
] |
If you start an XPath expression with `//`, it begins searching from the root of document. To search relative to a particular element, you should prepend the expression with `.` instead:
```
element2 = driver.find_element_by_xpath("//div[@title='div2']")
element2.find_element_by_xpath(".//p[@class='test']").text
```
|
Chrome Webdriver :
```
element = driver.find_element_by_id("ParentElement")
localElement = element.find_element_by_id("ChildElement")
print(localElement.text)
```
|
14,049,983
|
I am trying to search for an element in a sub-element with Selenium (Version 2.28.0), but selenium des not seem to limit its search to the sub-element. Am I doing this wrong or is there a way to use element.find to search a sub-element?
For an example I created a simple test webpage with this code:
```
<!DOCTYPE html>
<html>
<body>
<div class=div title=div1>
<h1>My First Heading</h1>
<p class='test'>My first paragraph.</p>
</div>
<div class=div title=div2>
<h1>My Second Heading</h1>
<p class='test'>My second paragraph.</p>
</div>
<div class=div title=div3>
<h1>My Third Heading</h1>
<p class='test'>My third paragraph.</p>
</div>
</body>
</html>
```
My python (Version 2.6) code looks like this:
```
from selenium import webdriver
driver = webdriver.Firefox()
# Open the test page with this instance of Firefox
# element2 gets the second division as a web element
element2 = driver.find_element_by_xpath("//div[@title='div2']")
# Search second division for a paragraph with a class of 'test' and print the content
print element2.find_element_by_xpath("//p[@class='test']").text
# expected output: "My second paragraph."
# actual output: "My first paragraph."
```
If I run:
```
print element2.get_attribute('innerHTML')
```
It returns the html from the second division. So selenium is not limiting its search to element2.
I would like to be able to find a sub-element of element2. This post suggests my code should work [Selenium WebDriver access a sub element](https://stackoverflow.com/questions/8836712/selenium-webdriver-access-a-sub-element) but his problem was caused by a time-out issue.
Can anyone help me understand what is happening here?
|
2012/12/27
|
[
"https://Stackoverflow.com/questions/14049983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1529981/"
] |
Use the following:
```
element2 = driver.find_element_by_cssselector("css=div[title='div2']")
element2.find_element_by_cssselector("p[@class='test']").text
```
Please let me know if you have any problems.
|
I guess,we need use method "By" from webdriver.common.by when use "driver.find\_element".
So...the code must be:
```
from selenium import webdriver
driver = webdriver.Firefox()
from selenium.webdriver.common.by import By
element2 = driver.find_element(By.XPATH, "//div[@title='div2']")
element2.find_element(By.XPATH, ".//p[@class='test']").text
```
|
14,049,983
|
I am trying to search for an element in a sub-element with Selenium (Version 2.28.0), but selenium des not seem to limit its search to the sub-element. Am I doing this wrong or is there a way to use element.find to search a sub-element?
For an example I created a simple test webpage with this code:
```
<!DOCTYPE html>
<html>
<body>
<div class=div title=div1>
<h1>My First Heading</h1>
<p class='test'>My first paragraph.</p>
</div>
<div class=div title=div2>
<h1>My Second Heading</h1>
<p class='test'>My second paragraph.</p>
</div>
<div class=div title=div3>
<h1>My Third Heading</h1>
<p class='test'>My third paragraph.</p>
</div>
</body>
</html>
```
My python (Version 2.6) code looks like this:
```
from selenium import webdriver
driver = webdriver.Firefox()
# Open the test page with this instance of Firefox
# element2 gets the second division as a web element
element2 = driver.find_element_by_xpath("//div[@title='div2']")
# Search second division for a paragraph with a class of 'test' and print the content
print element2.find_element_by_xpath("//p[@class='test']").text
# expected output: "My second paragraph."
# actual output: "My first paragraph."
```
If I run:
```
print element2.get_attribute('innerHTML')
```
It returns the html from the second division. So selenium is not limiting its search to element2.
I would like to be able to find a sub-element of element2. This post suggests my code should work [Selenium WebDriver access a sub element](https://stackoverflow.com/questions/8836712/selenium-webdriver-access-a-sub-element) but his problem was caused by a time-out issue.
Can anyone help me understand what is happening here?
|
2012/12/27
|
[
"https://Stackoverflow.com/questions/14049983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1529981/"
] |
I guess,we need use method "By" from webdriver.common.by when use "driver.find\_element".
So...the code must be:
```
from selenium import webdriver
driver = webdriver.Firefox()
from selenium.webdriver.common.by import By
element2 = driver.find_element(By.XPATH, "//div[@title='div2']")
element2.find_element(By.XPATH, ".//p[@class='test']").text
```
|
Chrome Webdriver :
```
element = driver.find_element_by_id("ParentElement")
localElement = element.find_element_by_id("ChildElement")
print(localElement.text)
```
|
14,049,983
|
I am trying to search for an element in a sub-element with Selenium (Version 2.28.0), but selenium des not seem to limit its search to the sub-element. Am I doing this wrong or is there a way to use element.find to search a sub-element?
For an example I created a simple test webpage with this code:
```
<!DOCTYPE html>
<html>
<body>
<div class=div title=div1>
<h1>My First Heading</h1>
<p class='test'>My first paragraph.</p>
</div>
<div class=div title=div2>
<h1>My Second Heading</h1>
<p class='test'>My second paragraph.</p>
</div>
<div class=div title=div3>
<h1>My Third Heading</h1>
<p class='test'>My third paragraph.</p>
</div>
</body>
</html>
```
My python (Version 2.6) code looks like this:
```
from selenium import webdriver
driver = webdriver.Firefox()
# Open the test page with this instance of Firefox
# element2 gets the second division as a web element
element2 = driver.find_element_by_xpath("//div[@title='div2']")
# Search second division for a paragraph with a class of 'test' and print the content
print element2.find_element_by_xpath("//p[@class='test']").text
# expected output: "My second paragraph."
# actual output: "My first paragraph."
```
If I run:
```
print element2.get_attribute('innerHTML')
```
It returns the html from the second division. So selenium is not limiting its search to element2.
I would like to be able to find a sub-element of element2. This post suggests my code should work [Selenium WebDriver access a sub element](https://stackoverflow.com/questions/8836712/selenium-webdriver-access-a-sub-element) but his problem was caused by a time-out issue.
Can anyone help me understand what is happening here?
|
2012/12/27
|
[
"https://Stackoverflow.com/questions/14049983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1529981/"
] |
This is how you search for element or tag in CSS subclass and I believe that it works for multilevel situation as well:
Sample HTML:
```html
<li class="meta-item">
<span class="label">Posted:</span>
<time class="value" datetime="2019-03-22T09:46:24+01:00" pubdate="pubdate">22.03.2019 u 09:46</time>
</li>
```
This is how you would get `pubdate` tag value for example.
```
published = driver.find_element_by_css_selector('li>time').get_attribute('datetime')
```
|
Chrome Webdriver :
```
element = driver.find_element_by_id("ParentElement")
localElement = element.find_element_by_id("ChildElement")
print(localElement.text)
```
|
37,371,992
|
I am trying to split the integers in a series by forward slash by using `rsplit` function of python but it does not work.
Original Data
=============
```
date
1/30/2015
1/30/2015
1/30/2015
1/30/2015
1/30/2015
1/30/2015
1/30/2015
1/30/2015
1/30/2015
1/30/2015
```
expected Data
=============
I want to split by '/'
```
date
'1' '30' '2015'
'1' '30' '2015'
'1' '30' '2015'
'1' '30' '2015'
'1' '30' '2015'
'1' '30' '2015'
'1' '30' '2015'
```
purpose of doing this is to take the year in separate column. i was trying to use below code before.
```
date = df['date']
split = date.rsplit("/")
OutputData['Year']=split[2]
```
split[2]-> is year in date series - purpose to take year in separate columns
many thanks in advance
this is the error i get every time 'this is a series of objects'
================================================================
AttributeError: 'Series' object has no attribute 'split'
|
2016/05/22
|
[
"https://Stackoverflow.com/questions/37371992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5157772/"
] |
You can use the `str` accessor to use string methods on the series:
```
df["date"].str.rsplit("/")
```
Or to have them in different columns:
```
df["date"].str.rsplit("/", expand = True)
```
With a series, it might be better to work on datetime data:
```
import pandas as pd
pd.to_datetime(df["date"]).dt.year
Out[10]:
0 2015
1 2015
2 2015
3 2015
4 2015
5 2015
6 2015
7 2015
8 2015
9 2015
Name: date, dtype: int64
```
|
IMO it would be more useful to just convert the string to a `datetime` using [`to_datetime`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html) so you can perform arithmetic operations on it and if you want the year or any other date/time component you can use the vectorised [`dt`](http://pandas.pydata.org/pandas-docs/stable/api.html#datetimelike-properties) accessor:
```
In [23]:
df['date'] = pd.to_datetime(df['date'])
df
Out[23]:
date
0 2015-01-30
1 2015-01-30
2 2015-01-30
3 2015-01-30
4 2015-01-30
5 2015-01-30
6 2015-01-30
7 2015-01-30
8 2015-01-30
9 2015-01-30
In [24]:
df['year'] = df['date'].dt.year
df
Out[24]:
date year
0 2015-01-30 2015
1 2015-01-30 2015
2 2015-01-30 2015
3 2015-01-30 2015
4 2015-01-30 2015
5 2015-01-30 2015
6 2015-01-30 2015
7 2015-01-30 2015
8 2015-01-30 2015
9 2015-01-30 2015
```
|
72,542,852
|
I'm trying to make a discord bot that can read dates from a txt file on my device.
----------------------------------------------------------------------------------
I've read the documentation and looked over similar posts, but I keep running into the same error. Just starting to learn python so please excuse any obvious mistakes/ strange formatting.
---
```
list = open("dates.txt","r")
list.seek(0)
var firstLine = file1.readline()
file1.close()
bot.sendMessage({
to: channelID,
message: firstLine
})
```
---
The error:
```
C:\Users\My Laptop\Desktop\Discord Bots\HeadzUp\bot.js:241
list = open("dates.txt","r")
^
ReferenceError: open is not defined
at DiscordClient.<anonymous> (C:\Users\My Laptop\Desktop\Discord Bots\HeadzUp\bot.js:241:13)
at DiscordClient.emit (node:events:527:28)
at DiscordClient.handleWSMessage (C:\Users\My Laptop\Desktop\Discord Bots\HeadzUp\node_modules\discord.io\lib\index.js:1854:11)
at WebSocket.emit (node:events:527:28)
at Receiver.ontext (C:\Users\My Laptop\Desktop\Discord Bots\HeadzUp\node_modules\ws\lib\WebSocket.js:841:10)
at C:\Users\My Laptop\Desktop\Discord Bots\HeadzUp\node_modules\ws\lib\Receiver.js:536:18
at Receiver.applyExtensions (C:\Users\My Laptop\Desktop\Discord Bots\HeadzUp\node_modules\ws\lib\Receiver.js:371:5)
at C:\Users\My Laptop\Desktop\Discord Bots\HeadzUp\node_modules\ws\lib\Receiver.js:508:14
at Receiver.flush (C:\Users\My Laptop\Desktop\Discord Bots\HeadzUp\node_modules\ws\lib\Receiver.js:347:3)
at Receiver.finish (C:\Users\My Laptop\Desktop\Discord Bots\HeadzUp\node_modules\ws\lib\Receiver.js:541:12)
PS C:\Users\My Laptop\Desktop\Discord Bots\HeadzUp>
```
---
Might be useful to know
* This bot is able to do other things like respond to commands
* dates.txt exists in the same folder at C:\Users\My Laptop\Desktop\Discord Bots\HeadzUp
|
2022/06/08
|
[
"https://Stackoverflow.com/questions/72542852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19296877/"
] |
So it seems like I completely mashed up python and nodejs on accident.
Not quite sure what I was thinking but that was the issue.
---
Simple answer β don't mix nodejs and Python.
|
First of all you should avoid to redefine "list" as this is python keyword.
Second, the command is correct and the "open" keyword is built in in native python. So it should work.
This exact line works in my python environment (even when overwriting "list").
When you look at the end of the lines of the error message you can see the ".js" endings. This is hinting, that you somehow try to interpret python code with a javascript interpreter.
Maybe you should post some more information about your system and setup.
If you use a proper python3 interpreter your code should work.
|
64,726,961
|
given a function, like split(" ",1) whats the most pythonic way to take the first element of its output only, for example given:
```
x= "a sequence of words"
x.split(" ",1)
```
I would like to get the string "a"
|
2020/11/07
|
[
"https://Stackoverflow.com/questions/64726961",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4792022/"
] |
After the split a list is returned, so use indexing to get the first element:
```
x= "a sequence of words"
print(x.split(" ",1)[0])
```
|
The most "pythonic" method is an opinion. However any method like split which returns a list you can simply index the list at 0 to get the first item.
`a = x.split(" ", 1)[0]`
|
64,726,961
|
given a function, like split(" ",1) whats the most pythonic way to take the first element of its output only, for example given:
```
x= "a sequence of words"
x.split(" ",1)
```
I would like to get the string "a"
|
2020/11/07
|
[
"https://Stackoverflow.com/questions/64726961",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4792022/"
] |
After the split a list is returned, so use indexing to get the first element:
```
x= "a sequence of words"
print(x.split(" ",1)[0])
```
|
You can use the first index
Example:
```py
x.split(" ",1)[0]
```
|
64,726,961
|
given a function, like split(" ",1) whats the most pythonic way to take the first element of its output only, for example given:
```
x= "a sequence of words"
x.split(" ",1)
```
I would like to get the string "a"
|
2020/11/07
|
[
"https://Stackoverflow.com/questions/64726961",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4792022/"
] |
After the split a list is returned, so use indexing to get the first element:
```
x= "a sequence of words"
print(x.split(" ",1)[0])
```
|
Wouldnβt this work as well?
```
x.split()[0]
```
|
64,726,961
|
given a function, like split(" ",1) whats the most pythonic way to take the first element of its output only, for example given:
```
x= "a sequence of words"
x.split(" ",1)
```
I would like to get the string "a"
|
2020/11/07
|
[
"https://Stackoverflow.com/questions/64726961",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4792022/"
] |
Do you mean? where 0 is the index
```
x = "a sequence of words"
print(x[0])
```
|
The most "pythonic" method is an opinion. However any method like split which returns a list you can simply index the list at 0 to get the first item.
`a = x.split(" ", 1)[0]`
|
64,726,961
|
given a function, like split(" ",1) whats the most pythonic way to take the first element of its output only, for example given:
```
x= "a sequence of words"
x.split(" ",1)
```
I would like to get the string "a"
|
2020/11/07
|
[
"https://Stackoverflow.com/questions/64726961",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4792022/"
] |
Do you mean? where 0 is the index
```
x = "a sequence of words"
print(x[0])
```
|
You can use the first index
Example:
```py
x.split(" ",1)[0]
```
|
64,726,961
|
given a function, like split(" ",1) whats the most pythonic way to take the first element of its output only, for example given:
```
x= "a sequence of words"
x.split(" ",1)
```
I would like to get the string "a"
|
2020/11/07
|
[
"https://Stackoverflow.com/questions/64726961",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4792022/"
] |
Do you mean? where 0 is the index
```
x = "a sequence of words"
print(x[0])
```
|
Wouldnβt this work as well?
```
x.split()[0]
```
|
64,726,961
|
given a function, like split(" ",1) whats the most pythonic way to take the first element of its output only, for example given:
```
x= "a sequence of words"
x.split(" ",1)
```
I would like to get the string "a"
|
2020/11/07
|
[
"https://Stackoverflow.com/questions/64726961",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4792022/"
] |
Let's use the variable x you stated, and input the first character from x into another variable y:
```
x = "a sequence of words"
y = x[0]
```
If you print y, you'll get the output 'a'. This is because the characters in a string can be indexed just like the items in a list. 0 is the first index, 1 is the second, and so on and so forth. You could also use the knowledge of indexing to print out a range of characters(For example, `'a sequence'`).
```
z = x[0:10]
```
It's important to note that you have to count the spaces, and that this is upper-bound exclusive(i.e It won't print the last number), so add one to the character index where you want to stop.
|
The most "pythonic" method is an opinion. However any method like split which returns a list you can simply index the list at 0 to get the first item.
`a = x.split(" ", 1)[0]`
|
64,726,961
|
given a function, like split(" ",1) whats the most pythonic way to take the first element of its output only, for example given:
```
x= "a sequence of words"
x.split(" ",1)
```
I would like to get the string "a"
|
2020/11/07
|
[
"https://Stackoverflow.com/questions/64726961",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4792022/"
] |
Let's use the variable x you stated, and input the first character from x into another variable y:
```
x = "a sequence of words"
y = x[0]
```
If you print y, you'll get the output 'a'. This is because the characters in a string can be indexed just like the items in a list. 0 is the first index, 1 is the second, and so on and so forth. You could also use the knowledge of indexing to print out a range of characters(For example, `'a sequence'`).
```
z = x[0:10]
```
It's important to note that you have to count the spaces, and that this is upper-bound exclusive(i.e It won't print the last number), so add one to the character index where you want to stop.
|
You can use the first index
Example:
```py
x.split(" ",1)[0]
```
|
64,726,961
|
given a function, like split(" ",1) whats the most pythonic way to take the first element of its output only, for example given:
```
x= "a sequence of words"
x.split(" ",1)
```
I would like to get the string "a"
|
2020/11/07
|
[
"https://Stackoverflow.com/questions/64726961",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4792022/"
] |
Let's use the variable x you stated, and input the first character from x into another variable y:
```
x = "a sequence of words"
y = x[0]
```
If you print y, you'll get the output 'a'. This is because the characters in a string can be indexed just like the items in a list. 0 is the first index, 1 is the second, and so on and so forth. You could also use the knowledge of indexing to print out a range of characters(For example, `'a sequence'`).
```
z = x[0:10]
```
It's important to note that you have to count the spaces, and that this is upper-bound exclusive(i.e It won't print the last number), so add one to the character index where you want to stop.
|
Wouldnβt this work as well?
```
x.split()[0]
```
|
58,638,534
|
I am very new to python 3(and python in general), and I have decided to try to make a cypher and decypher in my own way as a personal project. The cypher works by generating a random number and multiplying the letters number value by it. It adds all of these multiplied values into a list and then adding the random number at the end.
Let's say that the list is [1976, 1995, 19]. The user would copy and paste this into the input and press enter
```py
dlist = list(input('Text to be Decyphered:'))
```
The function would then take the last value in the list and give the variable rnd the value. It would then delete this value from the list. After this it would divide the other values by rnd. The problem is that
```py
dlist[-1]
```
comes back with ']'
```py
import string
import random
from random import randrange
def cypher():
rinput = input('Write Text to be Cyphered: ')
rnd = randrange(0, 100)
rinput = rinput.lower()
output = []
for character in rinput:
number = ord(character) * rnd
output.append(number)
output.append(rnd)
print(output)
def decypher():
dlist = list(input('Text to be Decyphered:'))
rnd = dlist[-2]
rnd = int(rnd)
dlist.pop()
a = 1
out = ""
for number in dlist:
vlc = int(dlist[a])
vnum = vlc/rnd
valf = chr(vnum)
out + valf
a=a+1
print(out)
```
I think that the program is treating the list as a string because it is coming from an input() code.
|
2019/10/31
|
[
"https://Stackoverflow.com/questions/58638534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12301586/"
] |
When you use `list` function, it converts the string to `['[', '1', '9', '7', '6', ',', ' ', '1', '9', '9', '5', ',', ' ', '1', '9', ']']`
Use instead:
```py
dlist = eval(input('Text to be Decyphered:'))
```
`eval` function will convert it to an actual list. You can cross check it:
```py
>>>print(type(eval('[1976, 1995, 19]')))
<class 'list'>
>>>print(eval('[1976, 1995, 19]'))
[1976, 1995, 19]
>>>for i in eval('[1976, 1995, 19]')
print(i)
1976
1995
19
```
|
Try json on your input:
```
import json
data = json.loads(the_string)
```
|
58,638,534
|
I am very new to python 3(and python in general), and I have decided to try to make a cypher and decypher in my own way as a personal project. The cypher works by generating a random number and multiplying the letters number value by it. It adds all of these multiplied values into a list and then adding the random number at the end.
Let's say that the list is [1976, 1995, 19]. The user would copy and paste this into the input and press enter
```py
dlist = list(input('Text to be Decyphered:'))
```
The function would then take the last value in the list and give the variable rnd the value. It would then delete this value from the list. After this it would divide the other values by rnd. The problem is that
```py
dlist[-1]
```
comes back with ']'
```py
import string
import random
from random import randrange
def cypher():
rinput = input('Write Text to be Cyphered: ')
rnd = randrange(0, 100)
rinput = rinput.lower()
output = []
for character in rinput:
number = ord(character) * rnd
output.append(number)
output.append(rnd)
print(output)
def decypher():
dlist = list(input('Text to be Decyphered:'))
rnd = dlist[-2]
rnd = int(rnd)
dlist.pop()
a = 1
out = ""
for number in dlist:
vlc = int(dlist[a])
vnum = vlc/rnd
valf = chr(vnum)
out + valf
a=a+1
print(out)
```
I think that the program is treating the list as a string because it is coming from an input() code.
|
2019/10/31
|
[
"https://Stackoverflow.com/questions/58638534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12301586/"
] |
When you use `list` function, it converts the string to `['[', '1', '9', '7', '6', ',', ' ', '1', '9', '9', '5', ',', ' ', '1', '9', ']']`
Use instead:
```py
dlist = eval(input('Text to be Decyphered:'))
```
`eval` function will convert it to an actual list. You can cross check it:
```py
>>>print(type(eval('[1976, 1995, 19]')))
<class 'list'>
>>>print(eval('[1976, 1995, 19]'))
[1976, 1995, 19]
>>>for i in eval('[1976, 1995, 19]')
print(i)
1976
1995
19
```
|
You have a few problems on your code:
1. randrange(0, 100) -> if you get 0 then your result will all be 0 and won't work
2. Characters are Integers, Multiplication and division you will not always get an integer back so you man need to handle rounding
3. Your input to cypher is a String but the input of decypher is a list so you need to convert a list back to a string in a way you can parse it. maybe remove "[" and "]" the split the string
To convert a string to a list you can use something like
```
valToDecode = "[464, 404, 460, 464, 4]"
cleanedVal = valToDecode.strip("][").split(","))
```
|
58,638,534
|
I am very new to python 3(and python in general), and I have decided to try to make a cypher and decypher in my own way as a personal project. The cypher works by generating a random number and multiplying the letters number value by it. It adds all of these multiplied values into a list and then adding the random number at the end.
Let's say that the list is [1976, 1995, 19]. The user would copy and paste this into the input and press enter
```py
dlist = list(input('Text to be Decyphered:'))
```
The function would then take the last value in the list and give the variable rnd the value. It would then delete this value from the list. After this it would divide the other values by rnd. The problem is that
```py
dlist[-1]
```
comes back with ']'
```py
import string
import random
from random import randrange
def cypher():
rinput = input('Write Text to be Cyphered: ')
rnd = randrange(0, 100)
rinput = rinput.lower()
output = []
for character in rinput:
number = ord(character) * rnd
output.append(number)
output.append(rnd)
print(output)
def decypher():
dlist = list(input('Text to be Decyphered:'))
rnd = dlist[-2]
rnd = int(rnd)
dlist.pop()
a = 1
out = ""
for number in dlist:
vlc = int(dlist[a])
vnum = vlc/rnd
valf = chr(vnum)
out + valf
a=a+1
print(out)
```
I think that the program is treating the list as a string because it is coming from an input() code.
|
2019/10/31
|
[
"https://Stackoverflow.com/questions/58638534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12301586/"
] |
You have a few problems on your code:
1. randrange(0, 100) -> if you get 0 then your result will all be 0 and won't work
2. Characters are Integers, Multiplication and division you will not always get an integer back so you man need to handle rounding
3. Your input to cypher is a String but the input of decypher is a list so you need to convert a list back to a string in a way you can parse it. maybe remove "[" and "]" the split the string
To convert a string to a list you can use something like
```
valToDecode = "[464, 404, 460, 464, 4]"
cleanedVal = valToDecode.strip("][").split(","))
```
|
Try json on your input:
```
import json
data = json.loads(the_string)
```
|
48,957,624
|
I am very to new to python and trying to translate a bunch of keywords using google API. I have an excel file with 3000 keywords which are mix of english, spanish, german etc. Trying to translate everything to English.
However, every time I run my code, I get error at different values. Sometimes, my code give error at 810th keyword while sometime it gives error at 1038 keyword.
And I am not even editing the layout of the file.
**JSONDecodeError: Expecting value: line 1 column 1 (char 0)**
Below is my code:
```
from googletrans import Translator
import pandas
import math
import time
df = pandas.read_excel(r'Desktop/python_keywords.xlsx')
keywords = df['Keywords']
Translate = []
translator = Translator()
for i in range(0,len(keywords)):
word = translator.translate(str(keywords[j])).text
Translate.append(word)
```
|
2018/02/23
|
[
"https://Stackoverflow.com/questions/48957624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5695920/"
] |
Normally this error is due to the character limit of 15K in Googletrans API.
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Consider reducing the number of characters.
|
Which line of your code gives you this error? Look at error trace
Let's start with your iterators: it is declared as `i`, but then you use `j`. Then check length of your request. It shouldn't be longer than 5k symbols according to [JSONDecodeError using Google Translate API with Python3](https://stackoverflow.com/questions/48021371/jsondecodeerror-using-google-translate-api-with-python3).
Anyway, it looks like api responds with empty json and you have to add at least `try .. except` to avoid this error, smth like this:
```
try:
word = translator.translate(str(keywords[j])).text
except JSONDecodeError as err:
print(err) # if you want to see when error happens
else:
Translate.append(word)
```
|
62,719,063
|
Using beautiful soup and python, I have undertaken some webscraping of the shown website to isolate: the rank, company name and revenue.
I would like to show, in an html table that I am rendering using flask and jinja2, the results of the top ten companies in the table, however, the code I have written is just displaying the first record five times.
**Code in file: webscraper.py**
```
url = 'https://en.m.wikipedia.org/wiki/List_of_largest_Internet_companies'
req = requests.get(url)
bsObj = BeautifulSoup(req.text, 'html.parser')
data = bsObj.find('table',{'class':'wikitable sortable mw-collapsible'})
table_data=[]
trs = bsObj.select('table tr')
for tr in trs[1:6]: #first element is empty
row = []
for t in tr.select('td')[:3]: #td is referring to the columns
row.extend([t.text.strip()])
table_data.append(row)
data=table_data
rank=data[0][0]
name=data[0][1]
revenue=data[0][2]
```
**Relevant code in home.html**
```
<p>{{data}}</p>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Rank</th>
<th scope="col">Name</th>
<th scope="col">Revenue</th>
</tr>
</thead>
<tbody>
{% for element in data %}
<tr>
<th scope="row"></th>
<td>{{rank}}</td>
<td>{{name}}</td>
<td>{{revenue}}</td>
</tr>
{% endfor %}
</tbody>
```
**The HTML output is:** Note: The variable {{data}} is showing all five records correctly..but I am not isolating the data correctly.
[['1', 'Amazon', '$280.5'], ['2', 'Google', '$161.8'], ['3', 'JD.com', '$82.8'], ['4', 'Facebook', '$70.69'], ['5', 'Alibaba', '$56.152']]
Rank Name Revenue
=================
1 Amazon $280.5
1 Amazon $280.5
1 Amazon $280.5
1 Amazon $280.5
1 Amazon $280.5
As mentioned, I want 1 - 10, all the companies listed up to 10, not just Amazon.
Any suggestions as to what I've done wrong in my code - I'd like the most elegant solution that pertains to my own code, not a completely new idea or solution.
Explanation of the for loop and theory behind it please too.
I know this is wrong:
```
rank=data[0][0]
name=data[0][1]
revenue=data[0][2]
```
but don't understand why and how to go about constructing it in the most elegant way such that I have the variables rank, name and revenue contain the respective data elements.
|
2020/07/03
|
[
"https://Stackoverflow.com/questions/62719063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5074035/"
] |
```
rank=data[0][0]
name=data[0][1]
revenue=data[0][2]
```
You're setting the rank, name and revenue from a single element (first element of data)
I suggest that you try getting changing rank, name and revenue in your html to `{{element[0]}}` and so on, to access the respective data from each element you loop on
|
Thank you to @mmfallacy above who suggested this answer that I am just fleshing out.
It works, but will accept the answer above as he suggested it.
Here it is for reference:
```
{% for element in data %}
<tr>
<th scope="row"></th>
<td>{{element[0]}}</td>
<td>{{element[1]}}</td>
<td>{{element[2]}}</td>
</tr>
{% endfor %}
```
I simply deleted any tries to generate variables rank, revenue in the .py file.
|
68,603,298
|
i am following the django instructions to build a web application hello
i have done everthing after the document but this happens
Page not found (404)
Request Method: GET
Request URL: <http://127.0.0.1:8000/hello>
Using the URLconf defined in PythonWeb.urls, Django tried these URL patterns, in this order:
admin/
The current path, hello, didnβt match any of these.
there must be another path as hello/
this is my code:
views.py/hello:
```
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
return HttpResponse("Hello.")
```
urls.py/pythonweb(my app):
```
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('hello/', include('hello.urls'))
]
```
urls.py/hello:
```
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name =('index'))
]
```
settings.py:
```
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'hello',
]
```
|
2021/07/31
|
[
"https://Stackoverflow.com/questions/68603298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16567727/"
] |
You have made a silly mistake in `settings.py` file:
Remove `/` after `hello`.
```
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'hello',
]
```
|
I tried your code and it worked for me. I did two edits which are:
**settings.py:**
```py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'hello.apps.HelloConfig',
]
```
Please note that your problem is not with `settings.py`, my edit will not make any difference. However, it is recommended to write it this way `hello.apps.HelloConfig`.
Also, I edited `hello/urls.py`, I removed the redundant parenthesis
**hello/urls.py:**
```py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
]
```
Please let me know if it still doesn't work for you.
|
39,489,089
|
This is more or less a follow up question to [Two dimensional color ramp (256x256 matrix) interpolated from 4 corner colors](https://stackoverflow.com/questions/39485178/two-dimensional-color-ramp-256x256-matrix-interpolated-from-4-corner-colors?noredirect=1#comment66289716_39485178) that was profoundly answered by jadsq today.
For linear gradients the previous answer works very well. However, if one wants to have better control of the stop colors of the gradient, this method seems not to be very practical. What might help in this situation is to have some reference color points in a matrix (lookup table) which are used to interpolate color values for the empty position in the look-up table. What I mean might be easier read out of the below image.
[](https://i.stack.imgur.com/AwPYk.png)
The whole idea is taken from <http://cartography.oregonstate.edu/pdf/2006_JennyHurni_SwissStyleShading.pdf> page 4 to 6. I've read through the paper, I understand theoretically what is going on but failing miserably because of my low experience with interpolation methods and to be honest, general math skills. What might also be of interest is, that they use a sigmoid Gaussian bell as interpolation method (page 6). They argue that Gaussian weighting yielded the visually best results and was simple to compute (equation 1, with k=0.0002 for a table of 256 per 256 cells).
---
Edit (better illustrations):
[](https://i.stack.imgur.com/cQVW1.png)
[](https://i.stack.imgur.com/hGXfz.png)
---
I have the other parts of their presented methods in place but filling the empty values in the matrix really is a key part and keeps me from continuing. Once again, thank you for your help!
What I have right now:
```
#!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
# the matrix with the reference color elements
ref=np.full([7, 7, 3], [255,255,255], dtype=np.uint8)
ref[0][6] = (239,238,185)
ref[1][1] = (120,131,125)
ref[4][6] = (184,191,171)
ref[6][2] = (150,168,158)
ref[6][5] = (166,180,166)
# s = ref.shape
#
# from scipy.ndimage.interpolation import zoom
# zooming as in https://stackoverflow.com/a/39485650/1230358 doesn't seem to work here anymore, because we have no corner point as reference but randomly distributed points within the matrix. As far as I know ...
# zoomed=zoom(ref,(256/s[0],256/s[1],1),order=1)
plt.subplot(211)
plt.imshow(ref,interpolation='nearest')
# plt.subplot(212)
# plt.imshow(zoomed,interpolation='nearest')
plt.show()
```
|
2016/09/14
|
[
"https://Stackoverflow.com/questions/39489089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1230358/"
] |
First some questions to better clarify your problem:
* what kind of interpolation you want: linear/cubic/other ?
* What are the points constrains? for example will there be alway just single region encapsulated by these control points or there could be also points inside?
For the simple linear interpolation and arbitrary (but at least 3 points not on a single line) I would try this:
1. **Triangulate control points area**
To non overlapping triangles covering whole defined area.
2. **render triangles**
So just rasterize see [Algorithm to fill triangle](https://stackoverflow.com/a/39062479/2521214) and all the sublinks. You should interpolate also the `R,G,B` along with the coordinates.
3. **Create a 2 copies of gradient and extrapolate one with H and second with V lines**
So scan all the H-horizontal lines of the gradient and if found 2 known pixels far enough from each other (for example quarter or half of gradient size) then extrapolate the whole line unknown colors. So if found known endpoints (Red) are `(x0,y,r0,g0,b0),(x1,y,r1,g1,b1)` then set all unknown colors in the same line as:
```
r = r0+(r1-r0)*(x-x0)/(x1-x0)
g = g0+(g1-g0)*(x-x0)/(x1-x0)
b = b0+(b1-b0)*(x-x0)/(x1-x0)
```
Similarly do the same in the copy of gradient for V-vertical lines now. So the points are now (x,y0,r0,g0,b0),(x,y1,r1,g1,b1)` and extrapolation:
```
r = r0+(r1-r0)*(y-y0)/(y1-y0)
g = g0+(g1-g0)*(y-y0)/(y1-y0)
b = b0+(b1-b0)*(y-y0)/(y1-y0)
```
After this compare both copies and if unknown point is computed in both set it as average of both colors in the target gradient image. Loop this whole process (**#3**) until no new gradient pixel is added.
4. **use single extrapolated color for the rest**
depending on how you define the control points some areas will have only 1 extrapolated color (either from H or V lines but not both) so use only the single computed color for those (after **#3** is done).
Here an example of what I mean by all this:
[](https://i.stack.imgur.com/l6zBg.png)
If you want something simple instead (but not exact) then you can bleed the known control points colors (with smooth filters) to neighboring pixels until the whole gradient is filled and saturated.
1. **fill unknown gradient pixels with predefined color meaning not computed**
2. **set each pixel to average of its computed neighbors**
you may do this in separate image to avoid shifting.
3. **set control points back to original color**
4. **loop #2 until area filled/saturated/or predefined number of iterations**
**[Edit1] second solution**
Ok I put it together in **C++** with your points/colors and gradient size here is how it looks (I bleed 100 times with 4-neighbors bleeding without weights):
[](https://i.stack.imgur.com/lYYyu.png)
The image on the left is input matrix where I encoded into alpha channel (highest 8 bits) if the pixel is reference point, computed or yet undefined. The image on the right is after applying the bleeding 100 times. The bleed is simple just take any non reference point and recompute it as average of all usable pixels around and itself (ignoring any undefined colors).
Here the **C++** code you can ignore the **GDI** stuff for rendering (beware my gradient map has `x` coordinate first you got `y` !)
```cpp
//---------------------------------------------------------------------------
const int mxs=7,mys=7,msz=16; // gradient resolution x,y and square size for render
DWORD map[mxs][mys]; // gradient matrix ... undefined color is >= 0xFF000000
// 0x00?????? - reference color
// 0xFF?????? - uncomputed color
// 0xFE?????? - bleeded color
//---------------------------------------------------------------------------
void map_clear() // set all pixels as uncomputed (white with alpha=255)
{
int x,y;
for (x=0;x<mxs;x++)
for (y=0;y<mys;y++)
map[x][y]=0xFFFFFFFF;
}
void map_bleed() // bleed computed colors
{
int x,y,r,g,b,n;
DWORD tmp[mxs][mys],c;
for (x=0;x<mxs;x++)
for (y=0;y<mys;y++)
{
c=map[x][y];
n=0; r=0; g=0; b=0; if (DWORD(c&0xFF000000)==0) { tmp[x][y]=c; continue; } if (DWORD(c&0xFF000000)!=0xFF000000) { r+=c&255; g+=(c>>8)&255; b+=(c>>16)&255; n++; }
x++; if ((x>=0)&&(x<mxs)&&(y>=0)&&(y<mys)) c=map[x][y]; else c=0xFF000000; if (DWORD(c&0xFF000000)!=0xFF000000) { r+=c&255; g+=(c>>8)&255; b+=(c>>16)&255; n++; }
x--; y--; if ((x>=0)&&(x<mxs)&&(y>=0)&&(y<mys)) c=map[x][y]; else c=0xFF000000; if (DWORD(c&0xFF000000)!=0xFF000000) { r+=c&255; g+=(c>>8)&255; b+=(c>>16)&255; n++; }
x--; y++; if ((x>=0)&&(x<mxs)&&(y>=0)&&(y<mys)) c=map[x][y]; else c=0xFF000000; if (DWORD(c&0xFF000000)!=0xFF000000) { r+=c&255; g+=(c>>8)&255; b+=(c>>16)&255; n++; }
x++; y++; if ((x>=0)&&(x<mxs)&&(y>=0)&&(y<mys)) c=map[x][y]; else c=0xFF000000; if (DWORD(c&0xFF000000)!=0xFF000000) { r+=c&255; g+=(c>>8)&255; b+=(c>>16)&255; n++; }
y--; if (!n) { tmp[x][y]=0xFFFFFFFF; continue; }
c=((r/n)|((g/n)<<8)|((b/n)<<16))&0x00FFFFFF;
tmp[x][y]=c;
}
// copy tmp back to map
for (x=0;x<mxs;x++)
for (y=0;y<mys;y++)
map[x][y]=tmp[x][y];
}
void map_draw(TCanvas *can,int x0,int y0) // just renders actual gradient map onto canvas (can ignore this)
{
int x,y,xx,yy;
for (x=0,xx=x0;x<mxs;x++,xx+=msz)
for (y=0,yy=y0;y<mys;y++,yy+=msz)
{
can->Pen->Color=clBlack;
can->Brush->Color=map[x][y]&0x00FFFFFF;
can->Rectangle(xx,yy,xx+msz,yy+msz);
}
}
//---------------------------------------------------------------------------
```
And here the usage (your example):
```cpp
// clear backbuffer
bmp->Canvas->Brush->Color=clBlack;
bmp->Canvas->FillRect(TRect(0,0,xs,ys));
// init your gradient with reference points
map_clear();
// x y R G B
map[6][0] = (239)|(238<<8)|(185<<16);
map[1][1] = (120)|(131<<8)|(125<<16);
map[6][4] = (184)|(191<<8)|(171<<16);
map[2][6] = (150)|(168<<8)|(158<<16);
map[5][6] = (166)|(180<<8)|(166<<16);
map_draw(bmp->Canvas,msz,msz); // render result (left)
// bleed
for (int i=0;i<100;i++) map_bleed();
map_draw(bmp->Canvas,(mxs+2)*msz,msz); // render result (right)
// refresh window with backbufer (anti-flickering)
Main->Canvas->Draw(0,0,bmp);
```
Again you can ignore all the rendering stuff. The number of bleeds should be 2x bigger then pixels in diagonal so bleeding covers all the pixels. The more iterations the more saturated result I try `100` just for example and the result looks good .. so I did not play with it anymore...
**[Edit2] and here the algorithm for the second approach**
1. **add flags to interpolated matrix**
You need to know if the pixel is `reference,undefined` or `interpolated`. You can encode this to alpha channel, or use mask (separate 2D matrix).
2. **bleed/smooth matrix**
basically for each non `reference` pixel compute its new value as average of all non `undefined` pixels around (4/8 neighbors) and at its position. Do not use `undefined` pixels and store the computed value to temporary matrix (not messing up next pixels otherwise the bleeding/smoothing would shift the pixels usually diagonally). This way undefined pixels areas will shrink by 1 pixel. After whole matrix is done copy the content of temporary matrix to the original one (or swap pointers).
3. **loop #2 until result is saturated or specific count of iterations**
Number of counts should be at leas 2x bigger then the number of diagonal pixels to propagate reference pixel into whole matrix. The saturation check can be done in **#2** while copying the temp array into original one (can do abs difference between frames and if zero or near it stop).
|
I'm here again (a bit late, sorry,I just found the question) with a fairly short solution using `griddata` from `scipy.interpolate`. That function is meant to do precisely what you want : interpolate values on a grid from just a few points. The issues being the following : with that you won't be able to use fancy weights only the predefined interpolation method, and the holes around the border can't be directly interpolated either, so here I completed them with nearest values.
Here's the demo code :
```
# the matrix with the reference color elements
ref=np.full([7, 7, 3], 0 , dtype=np.uint8)
#Note I fill with 0 instead of 255
ref[0][6] = (239,238,185)
ref[1][1] = (120,131,125)
ref[4][6] = (184,191,171)
ref[6][2] = (150,168,158)
ref[6][5] = (166,180,166)
from scipy.interpolate import griddata
#we format the data to feed in griddata
points=np.where(ref != 0)
values=ref[points]
grid_x,grid_y,grid_z=np.mgrid[0:7,0:7,0:3]
#we compute the inperpolation
filled_grid=griddata(points, values, (grid_x, grid_y, grid_z), method='linear')
filled_grid=np.array(filled_grid,dtype=np.uint8) #we convert the float64 to uint8
#filled_grid still has holes around the border
#here i'll complete the holes with the nearest value
points=np.where(filled_grid != 0)
values=filled_grid[points]
near_grid=griddata(points, values, (grid_x, grid_y, grid_z), method='nearest')
completed_grid=(near_grid*(filled_grid == 0))+filled_grid
plt.subplot(131)
plt.imshow(ref,interpolation='nearest')
plt.subplot(132)
plt.imshow(filled_grid,interpolation='nearest')
plt.subplot(133)
plt.imshow(completed_grid,interpolation='nearest')
plt.show()
```
**Output:**
[](https://i.stack.imgur.com/ZTSrr.png)
|
21,582,358
|
Trying to find how to execute ipdb (or pdb) commands such as `disable`.
Calling the `h` command on `disable` says
>
> disable bpnumber [bpnumber ...]
> Disables the breakpoints given as a space separated list of
> bp numbers.
>
>
>
So how whould I get those bp numbers? was looking through the list of commands and couldn't get any to display the bp numbers
**[EDIT]**
The `break`, `b` and `info breakpoints` commands don't do anything, although in my module i clearly have 1 breakpoint set like this `import pdb; pdb.set_trace( )` - same for `ipdb`. Moreover `info` is not defined.
The output of `help` in `pdb`:
>
> Documented commands (type help ):
> ======================================== EOF bt cont enable jump pp run unt a c continue
> exit l q s until alias cl d h
>
> list quit step up args clear debug help n
>
> r tbreak w b commands disable ignore next
> restart u whatis break condition down j p
>
> return unalias where
>
>
> Miscellaneous help topics:
> ========================== exec pdb
>
>
> Undocumented commands:
> ====================== retval rv
>
>
>
And for `ipdb`:
>
> Documented commands (type help ):
> ======================================== EOF bt cont enable jump pdef psource run unt a c
>
> continue exit l pdoc q s until alias cl
>
> d h list pfile quit step up args clear
> debug help n pinfo r tbreak w b
>
> commands disable ignore next pinfo2 restart u whatis
> break condition down j p pp return unalias
> where
>
>
> Miscellaneous help topics:
> ========================== exec pdb
>
>
> Undocumented commands:
> ====================== retval rv
>
>
>
I have saved my module as pb3.py and am executing it within the command line like this
>
> python -m pb3
> The execution does indeed stop at the breakpoint, but within di pdb (ipdb) console, the commands indicated don't display anything - or display a NameError
>
>
>
If more info is needed, i will provide it.
|
2014/02/05
|
[
"https://Stackoverflow.com/questions/21582358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1037251/"
] |
Use the `break` command. Don't add any line numbers and it will list all instead of adding them.
|
>
> info breakpoints
>
>
>
or just
>
> info b
>
>
>
lists all breakpoints.
|
5,214,814
|
I have a bunch of numbers that are tab-delimited with new line characters that looks something like this:
```
104 109 105 110 126 119 97 103\n
114 129 119 130 122 106 117 128\n
```
and so on. How can I use python to write all these numbers to a file in one column? i.e.
```
104\n
109\n
105\n
110\n
126\n
```
and so on. Fairly new to python so any help is appreciated, thanks!
|
2011/03/07
|
[
"https://Stackoverflow.com/questions/5214814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/647475/"
] |
```
"\n".join("104 109 105 110 126 119 97 103\n 114 129 119 130 122 106 117 128\n".split())
```
|
Replace input\_filename and output\_filename with appropriate values.
```
f = open('input_filename','r')
nums = f.read().split()
f.close()
f = open('output_filename', 'w')
f.write('\n'.join(nums))
f.close()
```
[Edit] Reworked example that doesn't load the whole file into memory. It is now very similar to Chinmay Kanchi's example. But I use split where he uses replace.
```
with open('input_filename','r') as input:
with open('output_filename', 'w') as output:
for line in input:
output.write('\n'.join(line.split()))
output.write('\n')
```
|
5,214,814
|
I have a bunch of numbers that are tab-delimited with new line characters that looks something like this:
```
104 109 105 110 126 119 97 103\n
114 129 119 130 122 106 117 128\n
```
and so on. How can I use python to write all these numbers to a file in one column? i.e.
```
104\n
109\n
105\n
110\n
126\n
```
and so on. Fairly new to python so any help is appreciated, thanks!
|
2011/03/07
|
[
"https://Stackoverflow.com/questions/5214814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/647475/"
] |
The easiest way to do this is probably to use `sed`. But if you must use Python, you need to replace all tab characters with newlines. Try something like this:
```
with open('input_file', 'rb') as infile:
with open('output_file', 'wb') as outfile:
for line in infile:
outfile.write(line.replace('\t', '\n'))
```
|
Replace input\_filename and output\_filename with appropriate values.
```
f = open('input_filename','r')
nums = f.read().split()
f.close()
f = open('output_filename', 'w')
f.write('\n'.join(nums))
f.close()
```
[Edit] Reworked example that doesn't load the whole file into memory. It is now very similar to Chinmay Kanchi's example. But I use split where he uses replace.
```
with open('input_filename','r') as input:
with open('output_filename', 'w') as output:
for line in input:
output.write('\n'.join(line.split()))
output.write('\n')
```
|
5,214,814
|
I have a bunch of numbers that are tab-delimited with new line characters that looks something like this:
```
104 109 105 110 126 119 97 103\n
114 129 119 130 122 106 117 128\n
```
and so on. How can I use python to write all these numbers to a file in one column? i.e.
```
104\n
109\n
105\n
110\n
126\n
```
and so on. Fairly new to python so any help is appreciated, thanks!
|
2011/03/07
|
[
"https://Stackoverflow.com/questions/5214814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/647475/"
] |
The easiest way to do this is probably to use `sed`. But if you must use Python, you need to replace all tab characters with newlines. Try something like this:
```
with open('input_file', 'rb') as infile:
with open('output_file', 'wb') as outfile:
for line in infile:
outfile.write(line.replace('\t', '\n'))
```
|
```
"\n".join("104 109 105 110 126 119 97 103\n 114 129 119 130 122 106 117 128\n".split())
```
|
5,214,814
|
I have a bunch of numbers that are tab-delimited with new line characters that looks something like this:
```
104 109 105 110 126 119 97 103\n
114 129 119 130 122 106 117 128\n
```
and so on. How can I use python to write all these numbers to a file in one column? i.e.
```
104\n
109\n
105\n
110\n
126\n
```
and so on. Fairly new to python so any help is appreciated, thanks!
|
2011/03/07
|
[
"https://Stackoverflow.com/questions/5214814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/647475/"
] |
```
"\n".join("104 109 105 110 126 119 97 103\n 114 129 119 130 122 106 117 128\n".split())
```
|
There are multiple ways of tackling this problem. You could use `string.split` and `string.join`, but that seems inefficient, since you'd be converting a string into a tuple and back into a string.
Using regex, we replace one or more whitespace characters with a newline. The metacharacter `\s` represents any whitespace character), which in Python 2.7.1 is equivalent to `[ \t\n\r\f\v]` (and possibly additional whitespace characters, if UNICODE is set).
```
import re
input_file = open('input_filename','r')
output_file = open('output_filename', 'w')
for line in input_file:
output_file.write(re.sub('[\s]+','\n', line))
input_file.close()
output_file.close()
```
|
5,214,814
|
I have a bunch of numbers that are tab-delimited with new line characters that looks something like this:
```
104 109 105 110 126 119 97 103\n
114 129 119 130 122 106 117 128\n
```
and so on. How can I use python to write all these numbers to a file in one column? i.e.
```
104\n
109\n
105\n
110\n
126\n
```
and so on. Fairly new to python so any help is appreciated, thanks!
|
2011/03/07
|
[
"https://Stackoverflow.com/questions/5214814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/647475/"
] |
```
"\n".join("104 109 105 110 126 119 97 103\n 114 129 119 130 122 106 117 128\n".split())
```
|
If your file is small, you can use `file.readlines()` to read all the lines into memory:
```
with open('input.txt', 'r') as fin:
for row in [l.split() for l in fin.readlines()]:
for col in row:
print col
```
If the file is very large, read the lines into memory one at a time (I like to use a generator):
```
for row in open('input.txt'):
for col in row.split():
print col
```
In either case you can pipe the output to a new file:
```
python myscript.py >output.txt
```
|
5,214,814
|
I have a bunch of numbers that are tab-delimited with new line characters that looks something like this:
```
104 109 105 110 126 119 97 103\n
114 129 119 130 122 106 117 128\n
```
and so on. How can I use python to write all these numbers to a file in one column? i.e.
```
104\n
109\n
105\n
110\n
126\n
```
and so on. Fairly new to python so any help is appreciated, thanks!
|
2011/03/07
|
[
"https://Stackoverflow.com/questions/5214814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/647475/"
] |
The easiest way to do this is probably to use `sed`. But if you must use Python, you need to replace all tab characters with newlines. Try something like this:
```
with open('input_file', 'rb') as infile:
with open('output_file', 'wb') as outfile:
for line in infile:
outfile.write(line.replace('\t', '\n'))
```
|
There are multiple ways of tackling this problem. You could use `string.split` and `string.join`, but that seems inefficient, since you'd be converting a string into a tuple and back into a string.
Using regex, we replace one or more whitespace characters with a newline. The metacharacter `\s` represents any whitespace character), which in Python 2.7.1 is equivalent to `[ \t\n\r\f\v]` (and possibly additional whitespace characters, if UNICODE is set).
```
import re
input_file = open('input_filename','r')
output_file = open('output_filename', 'w')
for line in input_file:
output_file.write(re.sub('[\s]+','\n', line))
input_file.close()
output_file.close()
```
|
5,214,814
|
I have a bunch of numbers that are tab-delimited with new line characters that looks something like this:
```
104 109 105 110 126 119 97 103\n
114 129 119 130 122 106 117 128\n
```
and so on. How can I use python to write all these numbers to a file in one column? i.e.
```
104\n
109\n
105\n
110\n
126\n
```
and so on. Fairly new to python so any help is appreciated, thanks!
|
2011/03/07
|
[
"https://Stackoverflow.com/questions/5214814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/647475/"
] |
The easiest way to do this is probably to use `sed`. But if you must use Python, you need to replace all tab characters with newlines. Try something like this:
```
with open('input_file', 'rb') as infile:
with open('output_file', 'wb') as outfile:
for line in infile:
outfile.write(line.replace('\t', '\n'))
```
|
If your file is small, you can use `file.readlines()` to read all the lines into memory:
```
with open('input.txt', 'r') as fin:
for row in [l.split() for l in fin.readlines()]:
for col in row:
print col
```
If the file is very large, read the lines into memory one at a time (I like to use a generator):
```
for row in open('input.txt'):
for col in row.split():
print col
```
In either case you can pipe the output to a new file:
```
python myscript.py >output.txt
```
|
40,443,759
|
I am trying to count the word fizz using python. However it is giving me an error.
```
def fizz_count(x):
count =0
for item in x :
if item== "fizz":
count=count+1
return count
item= ["fizz","cat", "fizz", "Dog", "fizz"]
example= fizz_count(item)
print example
```
i checked with indentation but still it does not work. Where i am doing wrong?
|
2016/11/05
|
[
"https://Stackoverflow.com/questions/40443759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4186243/"
] |
Your indentation seems to be incorrect, and you should not have the first `return count` (why would you return `count` as soon as you define it??).
```
def fizz_count(x):
count = 0
for item in x:
if item == "fizz":
count += 1 # equivalent to count = count + 1
return count
item = ["fizz", "cat", "fizz", "Dog", "fizz"]
example = fizz_count(item)
print example
```
|
Well i am new to python world. What i learned is return statement should be some thing like this.
Example one :-
```
def split_train_test(data, test_ratio):
shuffled_indices = np.random.permutation(len(data))
test_set_size = int(len(data) * test_ratio)
test_indices = shuffled_indices[:test_set_size]
train_indices = shuffled_indices[test_set_size:]
return data.iloc[train_indices],data.iloc[test_indices]
```
Example two :-
```
def load_housing_data(housing_path=HOUSING_PATH):
csv_path = os.path.join(housing_path, "housing.csv")
return pd.read_csv(csv_path)
```
|
40,443,759
|
I am trying to count the word fizz using python. However it is giving me an error.
```
def fizz_count(x):
count =0
for item in x :
if item== "fizz":
count=count+1
return count
item= ["fizz","cat", "fizz", "Dog", "fizz"]
example= fizz_count(item)
print example
```
i checked with indentation but still it does not work. Where i am doing wrong?
|
2016/11/05
|
[
"https://Stackoverflow.com/questions/40443759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4186243/"
] |
Please try the following code: remove `return count` right after `count = 0`
There are also a few indentation changes.
```
def fizz_count(x):
count = 0
for item in x:
if item== "fizz":
count=count+1
return count
item = ["fizz","cat", "fizz", "Dog", "fizz"]
example = fizz_count(item)
print example
```
|
Well i am new to python world. What i learned is return statement should be some thing like this.
Example one :-
```
def split_train_test(data, test_ratio):
shuffled_indices = np.random.permutation(len(data))
test_set_size = int(len(data) * test_ratio)
test_indices = shuffled_indices[:test_set_size]
train_indices = shuffled_indices[test_set_size:]
return data.iloc[train_indices],data.iloc[test_indices]
```
Example two :-
```
def load_housing_data(housing_path=HOUSING_PATH):
csv_path = os.path.join(housing_path, "housing.csv")
return pd.read_csv(csv_path)
```
|
40,443,759
|
I am trying to count the word fizz using python. However it is giving me an error.
```
def fizz_count(x):
count =0
for item in x :
if item== "fizz":
count=count+1
return count
item= ["fizz","cat", "fizz", "Dog", "fizz"]
example= fizz_count(item)
print example
```
i checked with indentation but still it does not work. Where i am doing wrong?
|
2016/11/05
|
[
"https://Stackoverflow.com/questions/40443759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4186243/"
] |
the problem is the identation in your line return
Try with this:
```
def fizz_count(x):
count =0
for item in x :
if item == "fizz":
count += 1
return count
```
|
Well i am new to python world. What i learned is return statement should be some thing like this.
Example one :-
```
def split_train_test(data, test_ratio):
shuffled_indices = np.random.permutation(len(data))
test_set_size = int(len(data) * test_ratio)
test_indices = shuffled_indices[:test_set_size]
train_indices = shuffled_indices[test_set_size:]
return data.iloc[train_indices],data.iloc[test_indices]
```
Example two :-
```
def load_housing_data(housing_path=HOUSING_PATH):
csv_path = os.path.join(housing_path, "housing.csv")
return pd.read_csv(csv_path)
```
|
40,443,759
|
I am trying to count the word fizz using python. However it is giving me an error.
```
def fizz_count(x):
count =0
for item in x :
if item== "fizz":
count=count+1
return count
item= ["fizz","cat", "fizz", "Dog", "fizz"]
example= fizz_count(item)
print example
```
i checked with indentation but still it does not work. Where i am doing wrong?
|
2016/11/05
|
[
"https://Stackoverflow.com/questions/40443759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4186243/"
] |
You do not need the first 'return' statement in your code. It works as follows, with indentation and spacing fixed:
```
def fizz_count(x):
count = 0
for item in x:
if item == "fizz":
count = count + 1
return count
item= ["fizz","cat", "fizz", "Dog", "fizz"]
example = fizz_count(item)
print example
```
|
Well i am new to python world. What i learned is return statement should be some thing like this.
Example one :-
```
def split_train_test(data, test_ratio):
shuffled_indices = np.random.permutation(len(data))
test_set_size = int(len(data) * test_ratio)
test_indices = shuffled_indices[:test_set_size]
train_indices = shuffled_indices[test_set_size:]
return data.iloc[train_indices],data.iloc[test_indices]
```
Example two :-
```
def load_housing_data(housing_path=HOUSING_PATH):
csv_path = os.path.join(housing_path, "housing.csv")
return pd.read_csv(csv_path)
```
|
8,437,964
|
I was wondering if we can print like row-wise in python.
Basically I have a loop which might go on million times and I am printing out some strategic counts in that loop.. so it would be really cool if I can print like row-wise
```
print x
# currently gives
# 3
# 4
#.. and so on
```
and i am looking something like
```
print x
# 3 4
```
|
2011/12/08
|
[
"https://Stackoverflow.com/questions/8437964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/902885/"
] |
In Python2:
```
data = [3, 4]
for x in data:
print x, # notice the comma at the end of the line
```
or in Python3:
```
for x in data:
print(x, end=' ')
```
prints
```
3 4
```
|
Just add a `,` at the end of the item(s) you're printing.
```
print(x,)
# 3 4
```
Or in Python 2:
```
print x,
# 3 4
```
|
8,437,964
|
I was wondering if we can print like row-wise in python.
Basically I have a loop which might go on million times and I am printing out some strategic counts in that loop.. so it would be really cool if I can print like row-wise
```
print x
# currently gives
# 3
# 4
#.. and so on
```
and i am looking something like
```
print x
# 3 4
```
|
2011/12/08
|
[
"https://Stackoverflow.com/questions/8437964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/902885/"
] |
```
my_list = ['keyboard', 'mouse', 'led', 'monitor', 'headphones', 'dvd']
for i in xrange(0, len(my_list), 4):
print '\t'.join(my_list[i:i+4])
```
|
For python 2:
```
for x in num:
print x,
```
For python 3:
```
for x in num:
print(x, end = ' ')
```
|
8,437,964
|
I was wondering if we can print like row-wise in python.
Basically I have a loop which might go on million times and I am printing out some strategic counts in that loop.. so it would be really cool if I can print like row-wise
```
print x
# currently gives
# 3
# 4
#.. and so on
```
and i am looking something like
```
print x
# 3 4
```
|
2011/12/08
|
[
"https://Stackoverflow.com/questions/8437964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/902885/"
] |
If you add comma at the end it should work for you.
```
>>> def test():
... print 1,
... print 2,
...
>>> test()
1 2
```
|
Python 3:
```
l = [3.14, 'string', ('tuple', 'of', 'items')]
print(', '.join(map(repr, l)))
```
Output:
>
>
> ```
> 3.14, 'string', ('tuple', 'of', 'items')
>
> ```
>
>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.