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
405,282
I am trying to write a life simulation in python with a variety of animals. It is impossible to name each instance of the classes I am going to use because I have no way of knowing how many there will be. So, my question: How can I automatically give a name to an object? I was thinking of creating a "Herd" class which could be all the animals of that type alive at the same time...
2009/01/01
[ "https://Stackoverflow.com/questions/405282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
you could make an 'animal' class with a name attribute. Or you could programmically define the class like so: ``` from new import classobj my_class=classobj('Foo',(object,),{}) ``` Found this: <http://www.gamedev.net/community/forums/topic.asp?topic_id=445037>
Any instance could have a name attribute. So it sounds like you may be asking how to dynamically name a *class*, not an *instance*. If that's the case, you can explicitly set the \_\_name\_\_ attribute of a class, or better yet just create the class with the builtin [type](http://docs.python.org/library/functions.html#type) (with 3 args). ``` class Ungulate(Mammal): hoofed = True ``` would be equivalent to ``` cls = type('Ungulate', (Mammal,), {'hoofed': True}) ```
405,282
I am trying to write a life simulation in python with a variety of animals. It is impossible to name each instance of the classes I am going to use because I have no way of knowing how many there will be. So, my question: How can I automatically give a name to an object? I was thinking of creating a "Herd" class which could be all the animals of that type alive at the same time...
2009/01/01
[ "https://Stackoverflow.com/questions/405282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Like this? ``` class Animal( object ): pass # lots of details omitted herd= [ Animal() for i in range(10000) ] ``` At this point, herd will have 10,000 distinct instances of the `Animal` class.
If you need a way to refer to them individually, it's relatively common to have the class give each instance a unique identifier on initialization: ``` >>> import itertools >>> class Animal(object): ... id_iter = itertools.count(1) ... def __init__(self): ... self.id = self.id_iter.next() ... >>> print(Animal().id) 1 >>> print(Animal().id) 2 >>> print(Animal().id) 3 ```
405,282
I am trying to write a life simulation in python with a variety of animals. It is impossible to name each instance of the classes I am going to use because I have no way of knowing how many there will be. So, my question: How can I automatically give a name to an object? I was thinking of creating a "Herd" class which could be all the animals of that type alive at the same time...
2009/01/01
[ "https://Stackoverflow.com/questions/405282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Like this? ``` class Animal( object ): pass # lots of details omitted herd= [ Animal() for i in range(10000) ] ``` At this point, herd will have 10,000 distinct instances of the `Animal` class.
Any instance could have a name attribute. So it sounds like you may be asking how to dynamically name a *class*, not an *instance*. If that's the case, you can explicitly set the \_\_name\_\_ attribute of a class, or better yet just create the class with the builtin [type](http://docs.python.org/library/functions.html#type) (with 3 args). ``` class Ungulate(Mammal): hoofed = True ``` would be equivalent to ``` cls = type('Ungulate', (Mammal,), {'hoofed': True}) ```
405,282
I am trying to write a life simulation in python with a variety of animals. It is impossible to name each instance of the classes I am going to use because I have no way of knowing how many there will be. So, my question: How can I automatically give a name to an object? I was thinking of creating a "Herd" class which could be all the animals of that type alive at the same time...
2009/01/01
[ "https://Stackoverflow.com/questions/405282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
If you need a way to refer to them individually, it's relatively common to have the class give each instance a unique identifier on initialization: ``` >>> import itertools >>> class Animal(object): ... id_iter = itertools.count(1) ... def __init__(self): ... self.id = self.id_iter.next() ... >>> print(Animal().id) 1 >>> print(Animal().id) 2 >>> print(Animal().id) 3 ```
Any instance could have a name attribute. So it sounds like you may be asking how to dynamically name a *class*, not an *instance*. If that's the case, you can explicitly set the \_\_name\_\_ attribute of a class, or better yet just create the class with the builtin [type](http://docs.python.org/library/functions.html#type) (with 3 args). ``` class Ungulate(Mammal): hoofed = True ``` would be equivalent to ``` cls = type('Ungulate', (Mammal,), {'hoofed': True}) ```
57,814,535
I figured out this is a popular question, but still I couldn't find a solution for that. I'm trying to run a simple repo [Here](https://github.com/swathikirans/violence-recognition-pytorch) which uses `PyTorch`. Although I just upgraded my Pytorch to the latest CUDA version from pytorch.org (`1.2.0`), it still throws the same error. I'm on Windows 10 and use conda with python 3.7. ``` raise AssertionError("Torch not compiled with CUDA enabled") AssertionError: Torch not compiled with CUDA enabled ``` How to fix the problem? Here is my `conda list`: ``` # Name Version Build Channel _ipyw_jlab_nb_ext_conf 0.1.0 py37_0 anaconda _pytorch_select 1.1.0 cpu anaconda _tflow_select 2.3.0 mkl anaconda absl-py 0.7.1 pypi_0 pypi alabaster 0.7.12 py37_0 anaconda anaconda 2019.07 py37_0 anaconda anaconda-client 1.7.2 py37_0 anaconda anaconda-navigator 1.9.7 py37_0 anaconda anaconda-project 0.8.3 py_0 anaconda argparse 1.4.0 pypi_0 pypi asn1crypto 0.24.0 py37_0 anaconda astor 0.8.0 pypi_0 pypi astroid 2.2.5 py37_0 anaconda astropy 3.2.1 py37he774522_0 anaconda atomicwrites 1.3.0 py37_1 anaconda attrs 19.1.0 py37_1 anaconda babel 2.7.0 py_0 anaconda backcall 0.1.0 py37_0 anaconda backports 1.0 py_2 anaconda backports-csv 1.0.7 pypi_0 pypi backports-functools-lru-cache 1.5 pypi_0 pypi backports.functools_lru_cache 1.5 py_2 anaconda backports.os 0.1.1 py37_0 anaconda backports.shutil_get_terminal_size 1.0.0 py37_2 anaconda backports.tempfile 1.0 py_1 anaconda backports.weakref 1.0.post1 py_1 anaconda beautifulsoup4 4.7.1 py37_1 anaconda bitarray 0.9.3 py37he774522_0 anaconda bkcharts 0.2 py37_0 anaconda blas 1.0 mkl anaconda bleach 3.1.0 py37_0 anaconda blosc 1.16.3 h7bd577a_0 anaconda bokeh 1.2.0 py37_0 anaconda boto 2.49.0 py37_0 anaconda bottleneck 1.2.1 py37h452e1ab_1 anaconda bzip2 1.0.8 he774522_0 anaconda ca-certificates 2019.5.15 0 anaconda certifi 2019.6.16 py37_0 anaconda cffi 1.12.3 py37h7a1dbc1_0 anaconda chainer 6.2.0 pypi_0 pypi chardet 3.0.4 py37_1 anaconda cheroot 6.5.5 pypi_0 pypi cherrypy 18.1.2 pypi_0 pypi click 7.0 py37_0 anaconda cloudpickle 1.2.1 py_0 anaconda clyent 1.2.2 py37_1 anaconda colorama 0.4.1 py37_0 anaconda comtypes 1.1.7 py37_0 anaconda conda 4.7.11 py37_0 anaconda conda-build 3.18.9 py37_3 anaconda conda-env 2.6.0 1 anaconda conda-package-handling 1.3.11 py37_0 anaconda conda-verify 3.4.2 py_1 anaconda console_shortcut 0.1.1 3 anaconda constants 0.6.0 pypi_0 pypi contextlib2 0.5.5 py37_0 anaconda cpuonly 1.0 0 pytorch cryptography 2.7 py37h7a1dbc1_0 anaconda cudatoolkit 10.0.130 0 anaconda curl 7.65.2 h2a8f88b_0 anaconda cycler 0.10.0 py37_0 anaconda cython 0.29.12 py37ha925a31_0 anaconda cytoolz 0.10.0 py37he774522_0 anaconda dask 2.1.0 py_0 anaconda dask-core 2.1.0 py_0 anaconda decorator 4.4.0 py37_1 anaconda defusedxml 0.6.0 py_0 anaconda distributed 2.1.0 py_0 anaconda docutils 0.14 py37_0 anaconda entrypoints 0.3 py37_0 anaconda et_xmlfile 1.0.1 py37_0 anaconda ez-setup 0.9 pypi_0 pypi fastcache 1.1.0 py37he774522_0 anaconda fasttext 0.9.1 pypi_0 pypi feedparser 5.2.1 pypi_0 pypi ffmpeg 4.1.3 h6538335_0 conda-forge filelock 3.0.12 py_0 anaconda first 2.0.2 pypi_0 pypi flask 1.1.1 py_0 anaconda freetype 2.9.1 ha9979f8_1 anaconda future 0.17.1 py37_0 anaconda gast 0.2.2 py37_0 anaconda get 2019.4.13 pypi_0 pypi get_terminal_size 1.0.0 h38e98db_0 anaconda gevent 1.4.0 py37he774522_0 anaconda glob2 0.7 py_0 anaconda google-pasta 0.1.7 pypi_0 pypi graphviz 2.38.0 4 anaconda greenlet 0.4.15 py37hfa6e2cd_0 anaconda grpcio 1.22.0 pypi_0 pypi h5py 2.9.0 py37h5e291fa_0 anaconda hdf5 1.10.4 h7ebc959_0 anaconda heapdict 1.0.0 py37_2 anaconda html5lib 1.0.1 py37_0 anaconda http-client 0.1.22 pypi_0 pypi hypothesis 4.34.0 pypi_0 pypi icc_rt 2019.0.0 h0cc432a_1 anaconda icu 58.2 ha66f8fd_1 anaconda idna 2.8 py37_0 anaconda imageio 2.4.1 pypi_0 pypi imageio-ffmpeg 0.3.0 pypi_0 pypi imagesize 1.1.0 py37_0 anaconda importlib_metadata 0.17 py37_1 anaconda imutils 0.5.2 pypi_0 pypi intel-openmp 2019.0 pypi_0 pypi ipykernel 5.1.1 py37h39e3cac_0 anaconda ipython 7.6.1 py37h39e3cac_0 anaconda ipython_genutils 0.2.0 py37_0 anaconda ipywidgets 7.5.0 py_0 anaconda isort 4.3.21 py37_0 anaconda itsdangerous 1.1.0 py37_0 anaconda jaraco-functools 2.0 pypi_0 pypi jdcal 1.4.1 py_0 anaconda jedi 0.13.3 py37_0 anaconda jinja2 2.10.1 py37_0 anaconda joblib 0.13.2 py37_0 anaconda jpeg 9b hb83a4c4_2 anaconda json5 0.8.4 py_0 anaconda jsonschema 3.0.1 py37_0 anaconda jupyter 1.0.0 py37_7 anaconda jupyter_client 5.3.1 py_0 anaconda jupyter_console 6.0.0 py37_0 anaconda jupyter_core 4.5.0 py_0 anaconda jupyterlab 1.0.2 py37hf63ae98_0 anaconda jupyterlab_server 1.0.0 py_0 anaconda keras 2.2.4 0 anaconda keras-applications 1.0.8 py_0 anaconda keras-base 2.2.4 py37_0 anaconda keras-preprocessing 1.1.0 py_1 anaconda keyring 18.0.0 py37_0 anaconda kiwisolver 1.1.0 py37ha925a31_0 anaconda krb5 1.16.1 hc04afaa_7 lazy-object-proxy 1.4.1 py37he774522_0 anaconda libarchive 3.3.3 h0643e63_5 anaconda libcurl 7.65.2 h2a8f88b_0 anaconda libiconv 1.15 h1df5818_7 anaconda liblief 0.9.0 ha925a31_2 anaconda libmklml 2019.0.5 0 anaconda libpng 1.6.37 h2a8f88b_0 anaconda libprotobuf 3.8.0 h7bd577a_0 anaconda libsodium 1.0.16 h9d3ae62_0 anaconda libssh2 1.8.2 h7a1dbc1_0 anaconda libtiff 4.0.10 hb898794_2 anaconda libxml2 2.9.9 h464c3ec_0 anaconda libxslt 1.1.33 h579f668_0 anaconda llvmlite 0.29.0 py37ha925a31_0 anaconda locket 0.2.0 py37_1 anaconda lxml 4.3.4 py37h1350720_0 anaconda lz4-c 1.8.1.2 h2fa13f4_0 anaconda lzo 2.10 h6df0209_2 anaconda m2w64-gcc-libgfortran 5.3.0 6 m2w64-gcc-libs 5.3.0 7 m2w64-gcc-libs-core 5.3.0 7 m2w64-gmp 6.1.0 2 m2w64-libwinpthread-git 5.0.0.4634.697f757 2 make-dataset 1.0 pypi_0 pypi markdown 3.1.1 py37_0 anaconda markupsafe 1.1.1 py37he774522_0 anaconda matplotlib 3.1.0 py37hc8f65d3_0 anaconda mccabe 0.6.1 py37_1 anaconda menuinst 1.4.16 py37he774522_0 anaconda mistune 0.8.4 py37he774522_0 anaconda mkl 2019.0 pypi_0 pypi mkl-service 2.0.2 py37he774522_0 anaconda mkl_fft 1.0.12 py37h14836fe_0 anaconda mkl_random 1.0.2 py37h343c172_0 anaconda mock 3.0.5 py37_0 anaconda more-itertools 7.0.0 py37_0 anaconda moviepy 1.0.0 pypi_0 pypi mpmath 1.1.0 py37_0 anaconda msgpack-python 0.6.1 py37h74a9793_1 anaconda msys2-conda-epoch 20160418 1 multipledispatch 0.6.0 py37_0 anaconda mysqlclient 1.4.2.post1 pypi_0 pypi navigator-updater 0.2.1 py37_0 anaconda nbconvert 5.5.0 py_0 anaconda nbformat 4.4.0 py37_0 anaconda networkx 2.3 py_0 anaconda ninja 1.9.0 py37h74a9793_0 anaconda nltk 3.4.4 py37_0 anaconda nose 1.3.7 py37_2 anaconda notebook 6.0.0 py37_0 anaconda numba 0.44.1 py37hf9181ef_0 anaconda numexpr 2.6.9 py37hdce8814_0 anaconda numpy 1.16.4 pypi_0 pypi numpy-base 1.16.4 py37hc3f5095_0 anaconda numpydoc 0.9.1 py_0 anaconda olefile 0.46 py37_0 anaconda opencv-contrib-python 4.1.0.25 pypi_0 pypi opencv-python 4.1.0.25 pypi_0 pypi openpyxl 2.6.2 py_0 anaconda openssl 1.1.1c he774522_1 anaconda packaging 19.0 py37_0 anaconda pandas 0.24.2 py37ha925a31_0 anaconda pandoc 2.2.3.2 0 anaconda pandocfilters 1.4.2 py37_1 anaconda parso 0.5.0 py_0 anaconda partd 1.0.0 py_0 anaconda path.py 12.0.1 py_0 anaconda pathlib2 2.3.4 py37_0 anaconda patsy 0.5.1 py37_0 anaconda pattern 3.6 pypi_0 pypi pdfminer-six 20181108 pypi_0 pypi pep8 1.7.1 py37_0 anaconda pickleshare 0.7.5 py37_0 anaconda pillow 6.1.0 py37hdc69c19_0 anaconda pip 19.1.1 py37_0 anaconda pkginfo 1.5.0.1 py37_0 anaconda pluggy 0.12.0 py_0 anaconda ply 3.11 py37_0 anaconda portend 2.5 pypi_0 pypi post 2019.4.13 pypi_0 pypi powershell_shortcut 0.0.1 2 anaconda proglog 0.1.9 pypi_0 pypi prometheus_client 0.7.1 py_0 anaconda prompt_toolkit 2.0.9 py37_0 anaconda protobuf 3.7.1 pypi_0 pypi psutil 5.6.3 py37he774522_0 anaconda public 2019.4.13 pypi_0 pypi py 1.8.0 py37_0 anaconda py-lief 0.9.0 py37ha925a31_2 anaconda pybind11 2.3.0 pypi_0 pypi pycodestyle 2.5.0 py37_0 anaconda pycosat 0.6.3 py37hfa6e2cd_0 anaconda pycparser 2.19 py37_0 anaconda pycrypto 2.6.1 py37hfa6e2cd_9 anaconda pycryptodome 3.8.2 pypi_0 pypi pycurl 7.43.0.3 py37h7a1dbc1_0 anaconda pydot 1.4.1 pypi_0 pypi pyflakes 2.1.1 py37_0 anaconda pygments 2.4.2 py_0 anaconda pylint 2.3.1 py37_0 anaconda pyodbc 4.0.26 py37ha925a31_0 anaconda pyopenssl 19.0.0 py37_0 anaconda pyparsing 2.4.0 py_0 anaconda pyqt 5.9.2 py37h6538335_2 anaconda pyreadline 2.1 py37_1 anaconda pyrsistent 0.14.11 py37he774522_0 anaconda pysocks 1.7.0 py37_0 anaconda pytables 3.5.2 py37h1da0976_1 anaconda pytest 5.0.1 py37_0 anaconda pytest-arraydiff 0.3 py37h39e3cac_0 anaconda pytest-astropy 0.5.0 py37_0 anaconda pytest-doctestplus 0.3.0 py37_0 anaconda pytest-openfiles 0.3.2 py37_0 anaconda pytest-remotedata 0.3.1 py37_0 anaconda python 3.7.3 h8c8aaf0_1 anaconda python-dateutil 2.8.0 py37_0 anaconda python-docx 0.8.10 pypi_0 pypi python-graphviz 0.11.1 pypi_0 pypi python-libarchive-c 2.8 py37_11 anaconda pytorch 1.2.0 py3.7_cpu_1 [cpuonly] pytorch pytube 9.5.1 pypi_0 pypi pytz 2019.1 py_0 anaconda pywavelets 1.0.3 py37h8c2d366_1 anaconda pywin32 223 py37hfa6e2cd_1 anaconda pywinpty 0.5.5 py37_1000 anaconda pyyaml 5.1.1 py37he774522_0 anaconda pyzmq 18.0.0 py37ha925a31_0 anaconda qt 5.9.7 vc14h73c81de_0 [vc14] anaconda qtawesome 0.5.7 py37_1 anaconda qtconsole 4.5.1 py_0 anaconda qtpy 1.8.0 py_0 anaconda query-string 2019.4.13 pypi_0 pypi request 2019.4.13 pypi_0 pypi requests 2.22.0 py37_0 anaconda rope 0.14.0 py_0 anaconda ruamel_yaml 0.15.46 py37hfa6e2cd_0 anaconda scikit-image 0.15.0 py37ha925a31_0 anaconda scikit-learn 0.21.2 py37h6288b17_0 anaconda scipy 1.3.0 pypi_0 pypi scipy-stack 0.0.5 pypi_0 pypi seaborn 0.9.0 py37_0 anaconda send2trash 1.5.0 py37_0 anaconda setuptools 41.1.0 pypi_0 pypi simplegeneric 0.8.1 py37_2 anaconda singledispatch 3.4.0.3 py37_0 anaconda sip 4.19.8 py37h6538335_0 anaconda six 1.12.0 py37_0 anaconda snappy 1.1.7 h777316e_3 anaconda snowballstemmer 1.9.0 py_0 anaconda sortedcollections 1.1.2 py37_0 anaconda sortedcontainers 2.1.0 py37_0 anaconda soupsieve 1.8 py37_0 anaconda sphinx 2.1.2 py_0 anaconda sphinxcontrib 1.0 py37_1 anaconda sphinxcontrib-applehelp 1.0.1 py_0 anaconda sphinxcontrib-devhelp 1.0.1 py_0 anaconda sphinxcontrib-htmlhelp 1.0.2 py_0 anaconda sphinxcontrib-jsmath 1.0.1 py_0 anaconda sphinxcontrib-qthelp 1.0.2 py_0 anaconda sphinxcontrib-serializinghtml 1.1.3 py_0 anaconda sphinxcontrib-websupport 1.1.2 py_0 anaconda spyder 3.3.6 py37_0 anaconda spyder-kernels 0.5.1 py37_0 anaconda sqlalchemy 1.3.5 py37he774522_0 anaconda sqlite 3.29.0 he774522_0 anaconda statsmodels 0.10.0 py37h8c2d366_0 anaconda summa 1.2.0 pypi_0 pypi sympy 1.4 py37_0 anaconda tbb 2019.4 h74a9793_0 anaconda tblib 1.4.0 py_0 anaconda tempora 1.14.1 pypi_0 pypi tensorboard 1.14.0 py37he3c9ec2_0 anaconda tensorboardx 1.8 pypi_0 pypi tensorflow 1.14.0 mkl_py37h7908ca0_0 anaconda tensorflow-base 1.14.0 mkl_py37ha978198_0 anaconda tensorflow-estimator 1.14.0 py_0 anaconda tensorflow-mkl 1.14.0 h4fcabd2_0 anaconda termcolor 1.1.0 pypi_0 pypi terminado 0.8.2 py37_0 anaconda testpath 0.4.2 py37_0 anaconda tk 8.6.8 hfa6e2cd_0 anaconda toolz 0.10.0 py_0 anaconda torchvision 0.4.0 py37_cpu [cpuonly] pytorch tornado 6.0.3 py37he774522_0 anaconda tqdm 4.32.1 py_0 anaconda traitlets 4.3.2 py37_0 anaconda typing 3.6.6 pypi_0 pypi typing-extensions 3.6.6 pypi_0 pypi unicodecsv 0.14.1 py37_0 anaconda urllib3 1.24.2 py37_0 anaconda validators 0.13.0 pypi_0 pypi vc 14.1 h0510ff6_4 anaconda vs2015_runtime 14.15.26706 h3a45250_4 anaconda wcwidth 0.1.7 py37_0 anaconda webencodings 0.5.1 py37_1 anaconda werkzeug 0.15.4 py_0 anaconda wheel 0.33.4 py37_0 anaconda widgetsnbextension 3.5.0 py37_0 anaconda win_inet_pton 1.1.0 py37_0 anaconda win_unicode_console 0.5 py37_0 anaconda wincertstore 0.2 py37_0 anaconda winpty 0.4.3 4 anaconda wrapt 1.11.2 py37he774522_0 anaconda xlrd 1.2.0 py37_0 anaconda xlsxwriter 1.1.8 py_0 anaconda xlwings 0.15.8 py37_0 anaconda xlwt 1.3.0 py37_0 anaconda xz 5.2.4 h2fa13f4_4 anaconda yaml 0.1.7 hc54c509_2 anaconda youtube-dl 2019.8.2 pypi_0 pypi zc-lockfile 1.4 pypi_0 pypi zeromq 4.3.1 h33f27b4_3 anaconda zict 1.0.0 py_0 anaconda zipp 0.5.1 py_0 anaconda zlib 1.2.11 h62dcd97_3 anaconda zstd 1.3.7 h508b16e_0 anaconda ```
2019/09/06
[ "https://Stackoverflow.com/questions/57814535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3204706/" ]
try this: ``` conda install pytorch torchvision cudatoolkit=10.2 -c pytorch ```
Uninstalling the packages and reinstalling it with pip instead solved it for me. 1.`conda remove pytorch torchvision torchaudio cudatoolkit` 2.`pip3 install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu116`
57,814,535
I figured out this is a popular question, but still I couldn't find a solution for that. I'm trying to run a simple repo [Here](https://github.com/swathikirans/violence-recognition-pytorch) which uses `PyTorch`. Although I just upgraded my Pytorch to the latest CUDA version from pytorch.org (`1.2.0`), it still throws the same error. I'm on Windows 10 and use conda with python 3.7. ``` raise AssertionError("Torch not compiled with CUDA enabled") AssertionError: Torch not compiled with CUDA enabled ``` How to fix the problem? Here is my `conda list`: ``` # Name Version Build Channel _ipyw_jlab_nb_ext_conf 0.1.0 py37_0 anaconda _pytorch_select 1.1.0 cpu anaconda _tflow_select 2.3.0 mkl anaconda absl-py 0.7.1 pypi_0 pypi alabaster 0.7.12 py37_0 anaconda anaconda 2019.07 py37_0 anaconda anaconda-client 1.7.2 py37_0 anaconda anaconda-navigator 1.9.7 py37_0 anaconda anaconda-project 0.8.3 py_0 anaconda argparse 1.4.0 pypi_0 pypi asn1crypto 0.24.0 py37_0 anaconda astor 0.8.0 pypi_0 pypi astroid 2.2.5 py37_0 anaconda astropy 3.2.1 py37he774522_0 anaconda atomicwrites 1.3.0 py37_1 anaconda attrs 19.1.0 py37_1 anaconda babel 2.7.0 py_0 anaconda backcall 0.1.0 py37_0 anaconda backports 1.0 py_2 anaconda backports-csv 1.0.7 pypi_0 pypi backports-functools-lru-cache 1.5 pypi_0 pypi backports.functools_lru_cache 1.5 py_2 anaconda backports.os 0.1.1 py37_0 anaconda backports.shutil_get_terminal_size 1.0.0 py37_2 anaconda backports.tempfile 1.0 py_1 anaconda backports.weakref 1.0.post1 py_1 anaconda beautifulsoup4 4.7.1 py37_1 anaconda bitarray 0.9.3 py37he774522_0 anaconda bkcharts 0.2 py37_0 anaconda blas 1.0 mkl anaconda bleach 3.1.0 py37_0 anaconda blosc 1.16.3 h7bd577a_0 anaconda bokeh 1.2.0 py37_0 anaconda boto 2.49.0 py37_0 anaconda bottleneck 1.2.1 py37h452e1ab_1 anaconda bzip2 1.0.8 he774522_0 anaconda ca-certificates 2019.5.15 0 anaconda certifi 2019.6.16 py37_0 anaconda cffi 1.12.3 py37h7a1dbc1_0 anaconda chainer 6.2.0 pypi_0 pypi chardet 3.0.4 py37_1 anaconda cheroot 6.5.5 pypi_0 pypi cherrypy 18.1.2 pypi_0 pypi click 7.0 py37_0 anaconda cloudpickle 1.2.1 py_0 anaconda clyent 1.2.2 py37_1 anaconda colorama 0.4.1 py37_0 anaconda comtypes 1.1.7 py37_0 anaconda conda 4.7.11 py37_0 anaconda conda-build 3.18.9 py37_3 anaconda conda-env 2.6.0 1 anaconda conda-package-handling 1.3.11 py37_0 anaconda conda-verify 3.4.2 py_1 anaconda console_shortcut 0.1.1 3 anaconda constants 0.6.0 pypi_0 pypi contextlib2 0.5.5 py37_0 anaconda cpuonly 1.0 0 pytorch cryptography 2.7 py37h7a1dbc1_0 anaconda cudatoolkit 10.0.130 0 anaconda curl 7.65.2 h2a8f88b_0 anaconda cycler 0.10.0 py37_0 anaconda cython 0.29.12 py37ha925a31_0 anaconda cytoolz 0.10.0 py37he774522_0 anaconda dask 2.1.0 py_0 anaconda dask-core 2.1.0 py_0 anaconda decorator 4.4.0 py37_1 anaconda defusedxml 0.6.0 py_0 anaconda distributed 2.1.0 py_0 anaconda docutils 0.14 py37_0 anaconda entrypoints 0.3 py37_0 anaconda et_xmlfile 1.0.1 py37_0 anaconda ez-setup 0.9 pypi_0 pypi fastcache 1.1.0 py37he774522_0 anaconda fasttext 0.9.1 pypi_0 pypi feedparser 5.2.1 pypi_0 pypi ffmpeg 4.1.3 h6538335_0 conda-forge filelock 3.0.12 py_0 anaconda first 2.0.2 pypi_0 pypi flask 1.1.1 py_0 anaconda freetype 2.9.1 ha9979f8_1 anaconda future 0.17.1 py37_0 anaconda gast 0.2.2 py37_0 anaconda get 2019.4.13 pypi_0 pypi get_terminal_size 1.0.0 h38e98db_0 anaconda gevent 1.4.0 py37he774522_0 anaconda glob2 0.7 py_0 anaconda google-pasta 0.1.7 pypi_0 pypi graphviz 2.38.0 4 anaconda greenlet 0.4.15 py37hfa6e2cd_0 anaconda grpcio 1.22.0 pypi_0 pypi h5py 2.9.0 py37h5e291fa_0 anaconda hdf5 1.10.4 h7ebc959_0 anaconda heapdict 1.0.0 py37_2 anaconda html5lib 1.0.1 py37_0 anaconda http-client 0.1.22 pypi_0 pypi hypothesis 4.34.0 pypi_0 pypi icc_rt 2019.0.0 h0cc432a_1 anaconda icu 58.2 ha66f8fd_1 anaconda idna 2.8 py37_0 anaconda imageio 2.4.1 pypi_0 pypi imageio-ffmpeg 0.3.0 pypi_0 pypi imagesize 1.1.0 py37_0 anaconda importlib_metadata 0.17 py37_1 anaconda imutils 0.5.2 pypi_0 pypi intel-openmp 2019.0 pypi_0 pypi ipykernel 5.1.1 py37h39e3cac_0 anaconda ipython 7.6.1 py37h39e3cac_0 anaconda ipython_genutils 0.2.0 py37_0 anaconda ipywidgets 7.5.0 py_0 anaconda isort 4.3.21 py37_0 anaconda itsdangerous 1.1.0 py37_0 anaconda jaraco-functools 2.0 pypi_0 pypi jdcal 1.4.1 py_0 anaconda jedi 0.13.3 py37_0 anaconda jinja2 2.10.1 py37_0 anaconda joblib 0.13.2 py37_0 anaconda jpeg 9b hb83a4c4_2 anaconda json5 0.8.4 py_0 anaconda jsonschema 3.0.1 py37_0 anaconda jupyter 1.0.0 py37_7 anaconda jupyter_client 5.3.1 py_0 anaconda jupyter_console 6.0.0 py37_0 anaconda jupyter_core 4.5.0 py_0 anaconda jupyterlab 1.0.2 py37hf63ae98_0 anaconda jupyterlab_server 1.0.0 py_0 anaconda keras 2.2.4 0 anaconda keras-applications 1.0.8 py_0 anaconda keras-base 2.2.4 py37_0 anaconda keras-preprocessing 1.1.0 py_1 anaconda keyring 18.0.0 py37_0 anaconda kiwisolver 1.1.0 py37ha925a31_0 anaconda krb5 1.16.1 hc04afaa_7 lazy-object-proxy 1.4.1 py37he774522_0 anaconda libarchive 3.3.3 h0643e63_5 anaconda libcurl 7.65.2 h2a8f88b_0 anaconda libiconv 1.15 h1df5818_7 anaconda liblief 0.9.0 ha925a31_2 anaconda libmklml 2019.0.5 0 anaconda libpng 1.6.37 h2a8f88b_0 anaconda libprotobuf 3.8.0 h7bd577a_0 anaconda libsodium 1.0.16 h9d3ae62_0 anaconda libssh2 1.8.2 h7a1dbc1_0 anaconda libtiff 4.0.10 hb898794_2 anaconda libxml2 2.9.9 h464c3ec_0 anaconda libxslt 1.1.33 h579f668_0 anaconda llvmlite 0.29.0 py37ha925a31_0 anaconda locket 0.2.0 py37_1 anaconda lxml 4.3.4 py37h1350720_0 anaconda lz4-c 1.8.1.2 h2fa13f4_0 anaconda lzo 2.10 h6df0209_2 anaconda m2w64-gcc-libgfortran 5.3.0 6 m2w64-gcc-libs 5.3.0 7 m2w64-gcc-libs-core 5.3.0 7 m2w64-gmp 6.1.0 2 m2w64-libwinpthread-git 5.0.0.4634.697f757 2 make-dataset 1.0 pypi_0 pypi markdown 3.1.1 py37_0 anaconda markupsafe 1.1.1 py37he774522_0 anaconda matplotlib 3.1.0 py37hc8f65d3_0 anaconda mccabe 0.6.1 py37_1 anaconda menuinst 1.4.16 py37he774522_0 anaconda mistune 0.8.4 py37he774522_0 anaconda mkl 2019.0 pypi_0 pypi mkl-service 2.0.2 py37he774522_0 anaconda mkl_fft 1.0.12 py37h14836fe_0 anaconda mkl_random 1.0.2 py37h343c172_0 anaconda mock 3.0.5 py37_0 anaconda more-itertools 7.0.0 py37_0 anaconda moviepy 1.0.0 pypi_0 pypi mpmath 1.1.0 py37_0 anaconda msgpack-python 0.6.1 py37h74a9793_1 anaconda msys2-conda-epoch 20160418 1 multipledispatch 0.6.0 py37_0 anaconda mysqlclient 1.4.2.post1 pypi_0 pypi navigator-updater 0.2.1 py37_0 anaconda nbconvert 5.5.0 py_0 anaconda nbformat 4.4.0 py37_0 anaconda networkx 2.3 py_0 anaconda ninja 1.9.0 py37h74a9793_0 anaconda nltk 3.4.4 py37_0 anaconda nose 1.3.7 py37_2 anaconda notebook 6.0.0 py37_0 anaconda numba 0.44.1 py37hf9181ef_0 anaconda numexpr 2.6.9 py37hdce8814_0 anaconda numpy 1.16.4 pypi_0 pypi numpy-base 1.16.4 py37hc3f5095_0 anaconda numpydoc 0.9.1 py_0 anaconda olefile 0.46 py37_0 anaconda opencv-contrib-python 4.1.0.25 pypi_0 pypi opencv-python 4.1.0.25 pypi_0 pypi openpyxl 2.6.2 py_0 anaconda openssl 1.1.1c he774522_1 anaconda packaging 19.0 py37_0 anaconda pandas 0.24.2 py37ha925a31_0 anaconda pandoc 2.2.3.2 0 anaconda pandocfilters 1.4.2 py37_1 anaconda parso 0.5.0 py_0 anaconda partd 1.0.0 py_0 anaconda path.py 12.0.1 py_0 anaconda pathlib2 2.3.4 py37_0 anaconda patsy 0.5.1 py37_0 anaconda pattern 3.6 pypi_0 pypi pdfminer-six 20181108 pypi_0 pypi pep8 1.7.1 py37_0 anaconda pickleshare 0.7.5 py37_0 anaconda pillow 6.1.0 py37hdc69c19_0 anaconda pip 19.1.1 py37_0 anaconda pkginfo 1.5.0.1 py37_0 anaconda pluggy 0.12.0 py_0 anaconda ply 3.11 py37_0 anaconda portend 2.5 pypi_0 pypi post 2019.4.13 pypi_0 pypi powershell_shortcut 0.0.1 2 anaconda proglog 0.1.9 pypi_0 pypi prometheus_client 0.7.1 py_0 anaconda prompt_toolkit 2.0.9 py37_0 anaconda protobuf 3.7.1 pypi_0 pypi psutil 5.6.3 py37he774522_0 anaconda public 2019.4.13 pypi_0 pypi py 1.8.0 py37_0 anaconda py-lief 0.9.0 py37ha925a31_2 anaconda pybind11 2.3.0 pypi_0 pypi pycodestyle 2.5.0 py37_0 anaconda pycosat 0.6.3 py37hfa6e2cd_0 anaconda pycparser 2.19 py37_0 anaconda pycrypto 2.6.1 py37hfa6e2cd_9 anaconda pycryptodome 3.8.2 pypi_0 pypi pycurl 7.43.0.3 py37h7a1dbc1_0 anaconda pydot 1.4.1 pypi_0 pypi pyflakes 2.1.1 py37_0 anaconda pygments 2.4.2 py_0 anaconda pylint 2.3.1 py37_0 anaconda pyodbc 4.0.26 py37ha925a31_0 anaconda pyopenssl 19.0.0 py37_0 anaconda pyparsing 2.4.0 py_0 anaconda pyqt 5.9.2 py37h6538335_2 anaconda pyreadline 2.1 py37_1 anaconda pyrsistent 0.14.11 py37he774522_0 anaconda pysocks 1.7.0 py37_0 anaconda pytables 3.5.2 py37h1da0976_1 anaconda pytest 5.0.1 py37_0 anaconda pytest-arraydiff 0.3 py37h39e3cac_0 anaconda pytest-astropy 0.5.0 py37_0 anaconda pytest-doctestplus 0.3.0 py37_0 anaconda pytest-openfiles 0.3.2 py37_0 anaconda pytest-remotedata 0.3.1 py37_0 anaconda python 3.7.3 h8c8aaf0_1 anaconda python-dateutil 2.8.0 py37_0 anaconda python-docx 0.8.10 pypi_0 pypi python-graphviz 0.11.1 pypi_0 pypi python-libarchive-c 2.8 py37_11 anaconda pytorch 1.2.0 py3.7_cpu_1 [cpuonly] pytorch pytube 9.5.1 pypi_0 pypi pytz 2019.1 py_0 anaconda pywavelets 1.0.3 py37h8c2d366_1 anaconda pywin32 223 py37hfa6e2cd_1 anaconda pywinpty 0.5.5 py37_1000 anaconda pyyaml 5.1.1 py37he774522_0 anaconda pyzmq 18.0.0 py37ha925a31_0 anaconda qt 5.9.7 vc14h73c81de_0 [vc14] anaconda qtawesome 0.5.7 py37_1 anaconda qtconsole 4.5.1 py_0 anaconda qtpy 1.8.0 py_0 anaconda query-string 2019.4.13 pypi_0 pypi request 2019.4.13 pypi_0 pypi requests 2.22.0 py37_0 anaconda rope 0.14.0 py_0 anaconda ruamel_yaml 0.15.46 py37hfa6e2cd_0 anaconda scikit-image 0.15.0 py37ha925a31_0 anaconda scikit-learn 0.21.2 py37h6288b17_0 anaconda scipy 1.3.0 pypi_0 pypi scipy-stack 0.0.5 pypi_0 pypi seaborn 0.9.0 py37_0 anaconda send2trash 1.5.0 py37_0 anaconda setuptools 41.1.0 pypi_0 pypi simplegeneric 0.8.1 py37_2 anaconda singledispatch 3.4.0.3 py37_0 anaconda sip 4.19.8 py37h6538335_0 anaconda six 1.12.0 py37_0 anaconda snappy 1.1.7 h777316e_3 anaconda snowballstemmer 1.9.0 py_0 anaconda sortedcollections 1.1.2 py37_0 anaconda sortedcontainers 2.1.0 py37_0 anaconda soupsieve 1.8 py37_0 anaconda sphinx 2.1.2 py_0 anaconda sphinxcontrib 1.0 py37_1 anaconda sphinxcontrib-applehelp 1.0.1 py_0 anaconda sphinxcontrib-devhelp 1.0.1 py_0 anaconda sphinxcontrib-htmlhelp 1.0.2 py_0 anaconda sphinxcontrib-jsmath 1.0.1 py_0 anaconda sphinxcontrib-qthelp 1.0.2 py_0 anaconda sphinxcontrib-serializinghtml 1.1.3 py_0 anaconda sphinxcontrib-websupport 1.1.2 py_0 anaconda spyder 3.3.6 py37_0 anaconda spyder-kernels 0.5.1 py37_0 anaconda sqlalchemy 1.3.5 py37he774522_0 anaconda sqlite 3.29.0 he774522_0 anaconda statsmodels 0.10.0 py37h8c2d366_0 anaconda summa 1.2.0 pypi_0 pypi sympy 1.4 py37_0 anaconda tbb 2019.4 h74a9793_0 anaconda tblib 1.4.0 py_0 anaconda tempora 1.14.1 pypi_0 pypi tensorboard 1.14.0 py37he3c9ec2_0 anaconda tensorboardx 1.8 pypi_0 pypi tensorflow 1.14.0 mkl_py37h7908ca0_0 anaconda tensorflow-base 1.14.0 mkl_py37ha978198_0 anaconda tensorflow-estimator 1.14.0 py_0 anaconda tensorflow-mkl 1.14.0 h4fcabd2_0 anaconda termcolor 1.1.0 pypi_0 pypi terminado 0.8.2 py37_0 anaconda testpath 0.4.2 py37_0 anaconda tk 8.6.8 hfa6e2cd_0 anaconda toolz 0.10.0 py_0 anaconda torchvision 0.4.0 py37_cpu [cpuonly] pytorch tornado 6.0.3 py37he774522_0 anaconda tqdm 4.32.1 py_0 anaconda traitlets 4.3.2 py37_0 anaconda typing 3.6.6 pypi_0 pypi typing-extensions 3.6.6 pypi_0 pypi unicodecsv 0.14.1 py37_0 anaconda urllib3 1.24.2 py37_0 anaconda validators 0.13.0 pypi_0 pypi vc 14.1 h0510ff6_4 anaconda vs2015_runtime 14.15.26706 h3a45250_4 anaconda wcwidth 0.1.7 py37_0 anaconda webencodings 0.5.1 py37_1 anaconda werkzeug 0.15.4 py_0 anaconda wheel 0.33.4 py37_0 anaconda widgetsnbextension 3.5.0 py37_0 anaconda win_inet_pton 1.1.0 py37_0 anaconda win_unicode_console 0.5 py37_0 anaconda wincertstore 0.2 py37_0 anaconda winpty 0.4.3 4 anaconda wrapt 1.11.2 py37he774522_0 anaconda xlrd 1.2.0 py37_0 anaconda xlsxwriter 1.1.8 py_0 anaconda xlwings 0.15.8 py37_0 anaconda xlwt 1.3.0 py37_0 anaconda xz 5.2.4 h2fa13f4_4 anaconda yaml 0.1.7 hc54c509_2 anaconda youtube-dl 2019.8.2 pypi_0 pypi zc-lockfile 1.4 pypi_0 pypi zeromq 4.3.1 h33f27b4_3 anaconda zict 1.0.0 py_0 anaconda zipp 0.5.1 py_0 anaconda zlib 1.2.11 h62dcd97_3 anaconda zstd 1.3.7 h508b16e_0 anaconda ```
2019/09/06
[ "https://Stackoverflow.com/questions/57814535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3204706/" ]
you dont have to install it via anaconda, you could install cuda from their [website](https://developer.nvidia.com/cuda-downloads). after install ends open a new terminal and check your cuda version with: ``` >>> nvcc --version nvcc: NVIDIA (R) Cuda compiler driver Copyright (c) 2005-2021 NVIDIA Corporation Built on Thu_Nov_18_09:52:33_Pacific_Standard_Time_2021 Cuda compilation tools, release 11.5, V11.5.119 Build cuda_11.5.r11.5/compiler.30672275_0 ``` my is V11.5 after, go [here](https://pytorch.org/get-started/locally/) and select your os and preferred package manager(pip or anaconda), and the cuda version you installed, and copy the generated install command, I got: ``` pip3 install torch==1.10.1+cu113 torchvision==0.11.2+cu113 torchaudio===0.10.1+cu113 -f https://download.pytorch.org/whl/cu113/torch_stable.html ``` notice that for me I had python 3.10 installed but my project run over 3.9 so either use virtual environment or run pip of your wanted base interpreter explicitly (for example `C:\Software\Python\Python39\python.exe -m pip install .....`) else you will be stuck with `Could not find a version that satisfies the requirement torch` errors after, open python console and check for cuda availability ```py >>> import torch >>> torch.cuda.is_available() True ```
First activate your environment. Replace <name> with your environment name. ``` conda activate <name> ``` Then see cuda version in your machine. To see cuda version: ``` nvcc --version ``` Now for CUDA 10.1 use: ``` conda install pytorch==1.4.0 torchvision==0.5.0 cudatoolkit=10.1 -c pytorch ``` For CUDA 10.0 use: ``` conda install pytorch==1.4.0 torchvision==0.5.0 cudatoolkit=10.0 -c pytorch ``` For CUDA 9.2 use: ``` conda install pytorch==1.4.0 torchvision==0.5.0 cudatoolkit=9.2 -c pytorch ```
57,814,535
I figured out this is a popular question, but still I couldn't find a solution for that. I'm trying to run a simple repo [Here](https://github.com/swathikirans/violence-recognition-pytorch) which uses `PyTorch`. Although I just upgraded my Pytorch to the latest CUDA version from pytorch.org (`1.2.0`), it still throws the same error. I'm on Windows 10 and use conda with python 3.7. ``` raise AssertionError("Torch not compiled with CUDA enabled") AssertionError: Torch not compiled with CUDA enabled ``` How to fix the problem? Here is my `conda list`: ``` # Name Version Build Channel _ipyw_jlab_nb_ext_conf 0.1.0 py37_0 anaconda _pytorch_select 1.1.0 cpu anaconda _tflow_select 2.3.0 mkl anaconda absl-py 0.7.1 pypi_0 pypi alabaster 0.7.12 py37_0 anaconda anaconda 2019.07 py37_0 anaconda anaconda-client 1.7.2 py37_0 anaconda anaconda-navigator 1.9.7 py37_0 anaconda anaconda-project 0.8.3 py_0 anaconda argparse 1.4.0 pypi_0 pypi asn1crypto 0.24.0 py37_0 anaconda astor 0.8.0 pypi_0 pypi astroid 2.2.5 py37_0 anaconda astropy 3.2.1 py37he774522_0 anaconda atomicwrites 1.3.0 py37_1 anaconda attrs 19.1.0 py37_1 anaconda babel 2.7.0 py_0 anaconda backcall 0.1.0 py37_0 anaconda backports 1.0 py_2 anaconda backports-csv 1.0.7 pypi_0 pypi backports-functools-lru-cache 1.5 pypi_0 pypi backports.functools_lru_cache 1.5 py_2 anaconda backports.os 0.1.1 py37_0 anaconda backports.shutil_get_terminal_size 1.0.0 py37_2 anaconda backports.tempfile 1.0 py_1 anaconda backports.weakref 1.0.post1 py_1 anaconda beautifulsoup4 4.7.1 py37_1 anaconda bitarray 0.9.3 py37he774522_0 anaconda bkcharts 0.2 py37_0 anaconda blas 1.0 mkl anaconda bleach 3.1.0 py37_0 anaconda blosc 1.16.3 h7bd577a_0 anaconda bokeh 1.2.0 py37_0 anaconda boto 2.49.0 py37_0 anaconda bottleneck 1.2.1 py37h452e1ab_1 anaconda bzip2 1.0.8 he774522_0 anaconda ca-certificates 2019.5.15 0 anaconda certifi 2019.6.16 py37_0 anaconda cffi 1.12.3 py37h7a1dbc1_0 anaconda chainer 6.2.0 pypi_0 pypi chardet 3.0.4 py37_1 anaconda cheroot 6.5.5 pypi_0 pypi cherrypy 18.1.2 pypi_0 pypi click 7.0 py37_0 anaconda cloudpickle 1.2.1 py_0 anaconda clyent 1.2.2 py37_1 anaconda colorama 0.4.1 py37_0 anaconda comtypes 1.1.7 py37_0 anaconda conda 4.7.11 py37_0 anaconda conda-build 3.18.9 py37_3 anaconda conda-env 2.6.0 1 anaconda conda-package-handling 1.3.11 py37_0 anaconda conda-verify 3.4.2 py_1 anaconda console_shortcut 0.1.1 3 anaconda constants 0.6.0 pypi_0 pypi contextlib2 0.5.5 py37_0 anaconda cpuonly 1.0 0 pytorch cryptography 2.7 py37h7a1dbc1_0 anaconda cudatoolkit 10.0.130 0 anaconda curl 7.65.2 h2a8f88b_0 anaconda cycler 0.10.0 py37_0 anaconda cython 0.29.12 py37ha925a31_0 anaconda cytoolz 0.10.0 py37he774522_0 anaconda dask 2.1.0 py_0 anaconda dask-core 2.1.0 py_0 anaconda decorator 4.4.0 py37_1 anaconda defusedxml 0.6.0 py_0 anaconda distributed 2.1.0 py_0 anaconda docutils 0.14 py37_0 anaconda entrypoints 0.3 py37_0 anaconda et_xmlfile 1.0.1 py37_0 anaconda ez-setup 0.9 pypi_0 pypi fastcache 1.1.0 py37he774522_0 anaconda fasttext 0.9.1 pypi_0 pypi feedparser 5.2.1 pypi_0 pypi ffmpeg 4.1.3 h6538335_0 conda-forge filelock 3.0.12 py_0 anaconda first 2.0.2 pypi_0 pypi flask 1.1.1 py_0 anaconda freetype 2.9.1 ha9979f8_1 anaconda future 0.17.1 py37_0 anaconda gast 0.2.2 py37_0 anaconda get 2019.4.13 pypi_0 pypi get_terminal_size 1.0.0 h38e98db_0 anaconda gevent 1.4.0 py37he774522_0 anaconda glob2 0.7 py_0 anaconda google-pasta 0.1.7 pypi_0 pypi graphviz 2.38.0 4 anaconda greenlet 0.4.15 py37hfa6e2cd_0 anaconda grpcio 1.22.0 pypi_0 pypi h5py 2.9.0 py37h5e291fa_0 anaconda hdf5 1.10.4 h7ebc959_0 anaconda heapdict 1.0.0 py37_2 anaconda html5lib 1.0.1 py37_0 anaconda http-client 0.1.22 pypi_0 pypi hypothesis 4.34.0 pypi_0 pypi icc_rt 2019.0.0 h0cc432a_1 anaconda icu 58.2 ha66f8fd_1 anaconda idna 2.8 py37_0 anaconda imageio 2.4.1 pypi_0 pypi imageio-ffmpeg 0.3.0 pypi_0 pypi imagesize 1.1.0 py37_0 anaconda importlib_metadata 0.17 py37_1 anaconda imutils 0.5.2 pypi_0 pypi intel-openmp 2019.0 pypi_0 pypi ipykernel 5.1.1 py37h39e3cac_0 anaconda ipython 7.6.1 py37h39e3cac_0 anaconda ipython_genutils 0.2.0 py37_0 anaconda ipywidgets 7.5.0 py_0 anaconda isort 4.3.21 py37_0 anaconda itsdangerous 1.1.0 py37_0 anaconda jaraco-functools 2.0 pypi_0 pypi jdcal 1.4.1 py_0 anaconda jedi 0.13.3 py37_0 anaconda jinja2 2.10.1 py37_0 anaconda joblib 0.13.2 py37_0 anaconda jpeg 9b hb83a4c4_2 anaconda json5 0.8.4 py_0 anaconda jsonschema 3.0.1 py37_0 anaconda jupyter 1.0.0 py37_7 anaconda jupyter_client 5.3.1 py_0 anaconda jupyter_console 6.0.0 py37_0 anaconda jupyter_core 4.5.0 py_0 anaconda jupyterlab 1.0.2 py37hf63ae98_0 anaconda jupyterlab_server 1.0.0 py_0 anaconda keras 2.2.4 0 anaconda keras-applications 1.0.8 py_0 anaconda keras-base 2.2.4 py37_0 anaconda keras-preprocessing 1.1.0 py_1 anaconda keyring 18.0.0 py37_0 anaconda kiwisolver 1.1.0 py37ha925a31_0 anaconda krb5 1.16.1 hc04afaa_7 lazy-object-proxy 1.4.1 py37he774522_0 anaconda libarchive 3.3.3 h0643e63_5 anaconda libcurl 7.65.2 h2a8f88b_0 anaconda libiconv 1.15 h1df5818_7 anaconda liblief 0.9.0 ha925a31_2 anaconda libmklml 2019.0.5 0 anaconda libpng 1.6.37 h2a8f88b_0 anaconda libprotobuf 3.8.0 h7bd577a_0 anaconda libsodium 1.0.16 h9d3ae62_0 anaconda libssh2 1.8.2 h7a1dbc1_0 anaconda libtiff 4.0.10 hb898794_2 anaconda libxml2 2.9.9 h464c3ec_0 anaconda libxslt 1.1.33 h579f668_0 anaconda llvmlite 0.29.0 py37ha925a31_0 anaconda locket 0.2.0 py37_1 anaconda lxml 4.3.4 py37h1350720_0 anaconda lz4-c 1.8.1.2 h2fa13f4_0 anaconda lzo 2.10 h6df0209_2 anaconda m2w64-gcc-libgfortran 5.3.0 6 m2w64-gcc-libs 5.3.0 7 m2w64-gcc-libs-core 5.3.0 7 m2w64-gmp 6.1.0 2 m2w64-libwinpthread-git 5.0.0.4634.697f757 2 make-dataset 1.0 pypi_0 pypi markdown 3.1.1 py37_0 anaconda markupsafe 1.1.1 py37he774522_0 anaconda matplotlib 3.1.0 py37hc8f65d3_0 anaconda mccabe 0.6.1 py37_1 anaconda menuinst 1.4.16 py37he774522_0 anaconda mistune 0.8.4 py37he774522_0 anaconda mkl 2019.0 pypi_0 pypi mkl-service 2.0.2 py37he774522_0 anaconda mkl_fft 1.0.12 py37h14836fe_0 anaconda mkl_random 1.0.2 py37h343c172_0 anaconda mock 3.0.5 py37_0 anaconda more-itertools 7.0.0 py37_0 anaconda moviepy 1.0.0 pypi_0 pypi mpmath 1.1.0 py37_0 anaconda msgpack-python 0.6.1 py37h74a9793_1 anaconda msys2-conda-epoch 20160418 1 multipledispatch 0.6.0 py37_0 anaconda mysqlclient 1.4.2.post1 pypi_0 pypi navigator-updater 0.2.1 py37_0 anaconda nbconvert 5.5.0 py_0 anaconda nbformat 4.4.0 py37_0 anaconda networkx 2.3 py_0 anaconda ninja 1.9.0 py37h74a9793_0 anaconda nltk 3.4.4 py37_0 anaconda nose 1.3.7 py37_2 anaconda notebook 6.0.0 py37_0 anaconda numba 0.44.1 py37hf9181ef_0 anaconda numexpr 2.6.9 py37hdce8814_0 anaconda numpy 1.16.4 pypi_0 pypi numpy-base 1.16.4 py37hc3f5095_0 anaconda numpydoc 0.9.1 py_0 anaconda olefile 0.46 py37_0 anaconda opencv-contrib-python 4.1.0.25 pypi_0 pypi opencv-python 4.1.0.25 pypi_0 pypi openpyxl 2.6.2 py_0 anaconda openssl 1.1.1c he774522_1 anaconda packaging 19.0 py37_0 anaconda pandas 0.24.2 py37ha925a31_0 anaconda pandoc 2.2.3.2 0 anaconda pandocfilters 1.4.2 py37_1 anaconda parso 0.5.0 py_0 anaconda partd 1.0.0 py_0 anaconda path.py 12.0.1 py_0 anaconda pathlib2 2.3.4 py37_0 anaconda patsy 0.5.1 py37_0 anaconda pattern 3.6 pypi_0 pypi pdfminer-six 20181108 pypi_0 pypi pep8 1.7.1 py37_0 anaconda pickleshare 0.7.5 py37_0 anaconda pillow 6.1.0 py37hdc69c19_0 anaconda pip 19.1.1 py37_0 anaconda pkginfo 1.5.0.1 py37_0 anaconda pluggy 0.12.0 py_0 anaconda ply 3.11 py37_0 anaconda portend 2.5 pypi_0 pypi post 2019.4.13 pypi_0 pypi powershell_shortcut 0.0.1 2 anaconda proglog 0.1.9 pypi_0 pypi prometheus_client 0.7.1 py_0 anaconda prompt_toolkit 2.0.9 py37_0 anaconda protobuf 3.7.1 pypi_0 pypi psutil 5.6.3 py37he774522_0 anaconda public 2019.4.13 pypi_0 pypi py 1.8.0 py37_0 anaconda py-lief 0.9.0 py37ha925a31_2 anaconda pybind11 2.3.0 pypi_0 pypi pycodestyle 2.5.0 py37_0 anaconda pycosat 0.6.3 py37hfa6e2cd_0 anaconda pycparser 2.19 py37_0 anaconda pycrypto 2.6.1 py37hfa6e2cd_9 anaconda pycryptodome 3.8.2 pypi_0 pypi pycurl 7.43.0.3 py37h7a1dbc1_0 anaconda pydot 1.4.1 pypi_0 pypi pyflakes 2.1.1 py37_0 anaconda pygments 2.4.2 py_0 anaconda pylint 2.3.1 py37_0 anaconda pyodbc 4.0.26 py37ha925a31_0 anaconda pyopenssl 19.0.0 py37_0 anaconda pyparsing 2.4.0 py_0 anaconda pyqt 5.9.2 py37h6538335_2 anaconda pyreadline 2.1 py37_1 anaconda pyrsistent 0.14.11 py37he774522_0 anaconda pysocks 1.7.0 py37_0 anaconda pytables 3.5.2 py37h1da0976_1 anaconda pytest 5.0.1 py37_0 anaconda pytest-arraydiff 0.3 py37h39e3cac_0 anaconda pytest-astropy 0.5.0 py37_0 anaconda pytest-doctestplus 0.3.0 py37_0 anaconda pytest-openfiles 0.3.2 py37_0 anaconda pytest-remotedata 0.3.1 py37_0 anaconda python 3.7.3 h8c8aaf0_1 anaconda python-dateutil 2.8.0 py37_0 anaconda python-docx 0.8.10 pypi_0 pypi python-graphviz 0.11.1 pypi_0 pypi python-libarchive-c 2.8 py37_11 anaconda pytorch 1.2.0 py3.7_cpu_1 [cpuonly] pytorch pytube 9.5.1 pypi_0 pypi pytz 2019.1 py_0 anaconda pywavelets 1.0.3 py37h8c2d366_1 anaconda pywin32 223 py37hfa6e2cd_1 anaconda pywinpty 0.5.5 py37_1000 anaconda pyyaml 5.1.1 py37he774522_0 anaconda pyzmq 18.0.0 py37ha925a31_0 anaconda qt 5.9.7 vc14h73c81de_0 [vc14] anaconda qtawesome 0.5.7 py37_1 anaconda qtconsole 4.5.1 py_0 anaconda qtpy 1.8.0 py_0 anaconda query-string 2019.4.13 pypi_0 pypi request 2019.4.13 pypi_0 pypi requests 2.22.0 py37_0 anaconda rope 0.14.0 py_0 anaconda ruamel_yaml 0.15.46 py37hfa6e2cd_0 anaconda scikit-image 0.15.0 py37ha925a31_0 anaconda scikit-learn 0.21.2 py37h6288b17_0 anaconda scipy 1.3.0 pypi_0 pypi scipy-stack 0.0.5 pypi_0 pypi seaborn 0.9.0 py37_0 anaconda send2trash 1.5.0 py37_0 anaconda setuptools 41.1.0 pypi_0 pypi simplegeneric 0.8.1 py37_2 anaconda singledispatch 3.4.0.3 py37_0 anaconda sip 4.19.8 py37h6538335_0 anaconda six 1.12.0 py37_0 anaconda snappy 1.1.7 h777316e_3 anaconda snowballstemmer 1.9.0 py_0 anaconda sortedcollections 1.1.2 py37_0 anaconda sortedcontainers 2.1.0 py37_0 anaconda soupsieve 1.8 py37_0 anaconda sphinx 2.1.2 py_0 anaconda sphinxcontrib 1.0 py37_1 anaconda sphinxcontrib-applehelp 1.0.1 py_0 anaconda sphinxcontrib-devhelp 1.0.1 py_0 anaconda sphinxcontrib-htmlhelp 1.0.2 py_0 anaconda sphinxcontrib-jsmath 1.0.1 py_0 anaconda sphinxcontrib-qthelp 1.0.2 py_0 anaconda sphinxcontrib-serializinghtml 1.1.3 py_0 anaconda sphinxcontrib-websupport 1.1.2 py_0 anaconda spyder 3.3.6 py37_0 anaconda spyder-kernels 0.5.1 py37_0 anaconda sqlalchemy 1.3.5 py37he774522_0 anaconda sqlite 3.29.0 he774522_0 anaconda statsmodels 0.10.0 py37h8c2d366_0 anaconda summa 1.2.0 pypi_0 pypi sympy 1.4 py37_0 anaconda tbb 2019.4 h74a9793_0 anaconda tblib 1.4.0 py_0 anaconda tempora 1.14.1 pypi_0 pypi tensorboard 1.14.0 py37he3c9ec2_0 anaconda tensorboardx 1.8 pypi_0 pypi tensorflow 1.14.0 mkl_py37h7908ca0_0 anaconda tensorflow-base 1.14.0 mkl_py37ha978198_0 anaconda tensorflow-estimator 1.14.0 py_0 anaconda tensorflow-mkl 1.14.0 h4fcabd2_0 anaconda termcolor 1.1.0 pypi_0 pypi terminado 0.8.2 py37_0 anaconda testpath 0.4.2 py37_0 anaconda tk 8.6.8 hfa6e2cd_0 anaconda toolz 0.10.0 py_0 anaconda torchvision 0.4.0 py37_cpu [cpuonly] pytorch tornado 6.0.3 py37he774522_0 anaconda tqdm 4.32.1 py_0 anaconda traitlets 4.3.2 py37_0 anaconda typing 3.6.6 pypi_0 pypi typing-extensions 3.6.6 pypi_0 pypi unicodecsv 0.14.1 py37_0 anaconda urllib3 1.24.2 py37_0 anaconda validators 0.13.0 pypi_0 pypi vc 14.1 h0510ff6_4 anaconda vs2015_runtime 14.15.26706 h3a45250_4 anaconda wcwidth 0.1.7 py37_0 anaconda webencodings 0.5.1 py37_1 anaconda werkzeug 0.15.4 py_0 anaconda wheel 0.33.4 py37_0 anaconda widgetsnbextension 3.5.0 py37_0 anaconda win_inet_pton 1.1.0 py37_0 anaconda win_unicode_console 0.5 py37_0 anaconda wincertstore 0.2 py37_0 anaconda winpty 0.4.3 4 anaconda wrapt 1.11.2 py37he774522_0 anaconda xlrd 1.2.0 py37_0 anaconda xlsxwriter 1.1.8 py_0 anaconda xlwings 0.15.8 py37_0 anaconda xlwt 1.3.0 py37_0 anaconda xz 5.2.4 h2fa13f4_4 anaconda yaml 0.1.7 hc54c509_2 anaconda youtube-dl 2019.8.2 pypi_0 pypi zc-lockfile 1.4 pypi_0 pypi zeromq 4.3.1 h33f27b4_3 anaconda zict 1.0.0 py_0 anaconda zipp 0.5.1 py_0 anaconda zlib 1.2.11 h62dcd97_3 anaconda zstd 1.3.7 h508b16e_0 anaconda ```
2019/09/06
[ "https://Stackoverflow.com/questions/57814535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3204706/" ]
First activate your environment. Replace <name> with your environment name. ``` conda activate <name> ``` Then see cuda version in your machine. To see cuda version: ``` nvcc --version ``` Now for CUDA 10.1 use: ``` conda install pytorch==1.4.0 torchvision==0.5.0 cudatoolkit=10.1 -c pytorch ``` For CUDA 10.0 use: ``` conda install pytorch==1.4.0 torchvision==0.5.0 cudatoolkit=10.0 -c pytorch ``` For CUDA 9.2 use: ``` conda install pytorch==1.4.0 torchvision==0.5.0 cudatoolkit=9.2 -c pytorch ```
Uninstalling the packages and reinstalling it with pip instead solved it for me. 1.`conda remove pytorch torchvision torchaudio cudatoolkit` 2.`pip3 install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu116`
57,814,535
I figured out this is a popular question, but still I couldn't find a solution for that. I'm trying to run a simple repo [Here](https://github.com/swathikirans/violence-recognition-pytorch) which uses `PyTorch`. Although I just upgraded my Pytorch to the latest CUDA version from pytorch.org (`1.2.0`), it still throws the same error. I'm on Windows 10 and use conda with python 3.7. ``` raise AssertionError("Torch not compiled with CUDA enabled") AssertionError: Torch not compiled with CUDA enabled ``` How to fix the problem? Here is my `conda list`: ``` # Name Version Build Channel _ipyw_jlab_nb_ext_conf 0.1.0 py37_0 anaconda _pytorch_select 1.1.0 cpu anaconda _tflow_select 2.3.0 mkl anaconda absl-py 0.7.1 pypi_0 pypi alabaster 0.7.12 py37_0 anaconda anaconda 2019.07 py37_0 anaconda anaconda-client 1.7.2 py37_0 anaconda anaconda-navigator 1.9.7 py37_0 anaconda anaconda-project 0.8.3 py_0 anaconda argparse 1.4.0 pypi_0 pypi asn1crypto 0.24.0 py37_0 anaconda astor 0.8.0 pypi_0 pypi astroid 2.2.5 py37_0 anaconda astropy 3.2.1 py37he774522_0 anaconda atomicwrites 1.3.0 py37_1 anaconda attrs 19.1.0 py37_1 anaconda babel 2.7.0 py_0 anaconda backcall 0.1.0 py37_0 anaconda backports 1.0 py_2 anaconda backports-csv 1.0.7 pypi_0 pypi backports-functools-lru-cache 1.5 pypi_0 pypi backports.functools_lru_cache 1.5 py_2 anaconda backports.os 0.1.1 py37_0 anaconda backports.shutil_get_terminal_size 1.0.0 py37_2 anaconda backports.tempfile 1.0 py_1 anaconda backports.weakref 1.0.post1 py_1 anaconda beautifulsoup4 4.7.1 py37_1 anaconda bitarray 0.9.3 py37he774522_0 anaconda bkcharts 0.2 py37_0 anaconda blas 1.0 mkl anaconda bleach 3.1.0 py37_0 anaconda blosc 1.16.3 h7bd577a_0 anaconda bokeh 1.2.0 py37_0 anaconda boto 2.49.0 py37_0 anaconda bottleneck 1.2.1 py37h452e1ab_1 anaconda bzip2 1.0.8 he774522_0 anaconda ca-certificates 2019.5.15 0 anaconda certifi 2019.6.16 py37_0 anaconda cffi 1.12.3 py37h7a1dbc1_0 anaconda chainer 6.2.0 pypi_0 pypi chardet 3.0.4 py37_1 anaconda cheroot 6.5.5 pypi_0 pypi cherrypy 18.1.2 pypi_0 pypi click 7.0 py37_0 anaconda cloudpickle 1.2.1 py_0 anaconda clyent 1.2.2 py37_1 anaconda colorama 0.4.1 py37_0 anaconda comtypes 1.1.7 py37_0 anaconda conda 4.7.11 py37_0 anaconda conda-build 3.18.9 py37_3 anaconda conda-env 2.6.0 1 anaconda conda-package-handling 1.3.11 py37_0 anaconda conda-verify 3.4.2 py_1 anaconda console_shortcut 0.1.1 3 anaconda constants 0.6.0 pypi_0 pypi contextlib2 0.5.5 py37_0 anaconda cpuonly 1.0 0 pytorch cryptography 2.7 py37h7a1dbc1_0 anaconda cudatoolkit 10.0.130 0 anaconda curl 7.65.2 h2a8f88b_0 anaconda cycler 0.10.0 py37_0 anaconda cython 0.29.12 py37ha925a31_0 anaconda cytoolz 0.10.0 py37he774522_0 anaconda dask 2.1.0 py_0 anaconda dask-core 2.1.0 py_0 anaconda decorator 4.4.0 py37_1 anaconda defusedxml 0.6.0 py_0 anaconda distributed 2.1.0 py_0 anaconda docutils 0.14 py37_0 anaconda entrypoints 0.3 py37_0 anaconda et_xmlfile 1.0.1 py37_0 anaconda ez-setup 0.9 pypi_0 pypi fastcache 1.1.0 py37he774522_0 anaconda fasttext 0.9.1 pypi_0 pypi feedparser 5.2.1 pypi_0 pypi ffmpeg 4.1.3 h6538335_0 conda-forge filelock 3.0.12 py_0 anaconda first 2.0.2 pypi_0 pypi flask 1.1.1 py_0 anaconda freetype 2.9.1 ha9979f8_1 anaconda future 0.17.1 py37_0 anaconda gast 0.2.2 py37_0 anaconda get 2019.4.13 pypi_0 pypi get_terminal_size 1.0.0 h38e98db_0 anaconda gevent 1.4.0 py37he774522_0 anaconda glob2 0.7 py_0 anaconda google-pasta 0.1.7 pypi_0 pypi graphviz 2.38.0 4 anaconda greenlet 0.4.15 py37hfa6e2cd_0 anaconda grpcio 1.22.0 pypi_0 pypi h5py 2.9.0 py37h5e291fa_0 anaconda hdf5 1.10.4 h7ebc959_0 anaconda heapdict 1.0.0 py37_2 anaconda html5lib 1.0.1 py37_0 anaconda http-client 0.1.22 pypi_0 pypi hypothesis 4.34.0 pypi_0 pypi icc_rt 2019.0.0 h0cc432a_1 anaconda icu 58.2 ha66f8fd_1 anaconda idna 2.8 py37_0 anaconda imageio 2.4.1 pypi_0 pypi imageio-ffmpeg 0.3.0 pypi_0 pypi imagesize 1.1.0 py37_0 anaconda importlib_metadata 0.17 py37_1 anaconda imutils 0.5.2 pypi_0 pypi intel-openmp 2019.0 pypi_0 pypi ipykernel 5.1.1 py37h39e3cac_0 anaconda ipython 7.6.1 py37h39e3cac_0 anaconda ipython_genutils 0.2.0 py37_0 anaconda ipywidgets 7.5.0 py_0 anaconda isort 4.3.21 py37_0 anaconda itsdangerous 1.1.0 py37_0 anaconda jaraco-functools 2.0 pypi_0 pypi jdcal 1.4.1 py_0 anaconda jedi 0.13.3 py37_0 anaconda jinja2 2.10.1 py37_0 anaconda joblib 0.13.2 py37_0 anaconda jpeg 9b hb83a4c4_2 anaconda json5 0.8.4 py_0 anaconda jsonschema 3.0.1 py37_0 anaconda jupyter 1.0.0 py37_7 anaconda jupyter_client 5.3.1 py_0 anaconda jupyter_console 6.0.0 py37_0 anaconda jupyter_core 4.5.0 py_0 anaconda jupyterlab 1.0.2 py37hf63ae98_0 anaconda jupyterlab_server 1.0.0 py_0 anaconda keras 2.2.4 0 anaconda keras-applications 1.0.8 py_0 anaconda keras-base 2.2.4 py37_0 anaconda keras-preprocessing 1.1.0 py_1 anaconda keyring 18.0.0 py37_0 anaconda kiwisolver 1.1.0 py37ha925a31_0 anaconda krb5 1.16.1 hc04afaa_7 lazy-object-proxy 1.4.1 py37he774522_0 anaconda libarchive 3.3.3 h0643e63_5 anaconda libcurl 7.65.2 h2a8f88b_0 anaconda libiconv 1.15 h1df5818_7 anaconda liblief 0.9.0 ha925a31_2 anaconda libmklml 2019.0.5 0 anaconda libpng 1.6.37 h2a8f88b_0 anaconda libprotobuf 3.8.0 h7bd577a_0 anaconda libsodium 1.0.16 h9d3ae62_0 anaconda libssh2 1.8.2 h7a1dbc1_0 anaconda libtiff 4.0.10 hb898794_2 anaconda libxml2 2.9.9 h464c3ec_0 anaconda libxslt 1.1.33 h579f668_0 anaconda llvmlite 0.29.0 py37ha925a31_0 anaconda locket 0.2.0 py37_1 anaconda lxml 4.3.4 py37h1350720_0 anaconda lz4-c 1.8.1.2 h2fa13f4_0 anaconda lzo 2.10 h6df0209_2 anaconda m2w64-gcc-libgfortran 5.3.0 6 m2w64-gcc-libs 5.3.0 7 m2w64-gcc-libs-core 5.3.0 7 m2w64-gmp 6.1.0 2 m2w64-libwinpthread-git 5.0.0.4634.697f757 2 make-dataset 1.0 pypi_0 pypi markdown 3.1.1 py37_0 anaconda markupsafe 1.1.1 py37he774522_0 anaconda matplotlib 3.1.0 py37hc8f65d3_0 anaconda mccabe 0.6.1 py37_1 anaconda menuinst 1.4.16 py37he774522_0 anaconda mistune 0.8.4 py37he774522_0 anaconda mkl 2019.0 pypi_0 pypi mkl-service 2.0.2 py37he774522_0 anaconda mkl_fft 1.0.12 py37h14836fe_0 anaconda mkl_random 1.0.2 py37h343c172_0 anaconda mock 3.0.5 py37_0 anaconda more-itertools 7.0.0 py37_0 anaconda moviepy 1.0.0 pypi_0 pypi mpmath 1.1.0 py37_0 anaconda msgpack-python 0.6.1 py37h74a9793_1 anaconda msys2-conda-epoch 20160418 1 multipledispatch 0.6.0 py37_0 anaconda mysqlclient 1.4.2.post1 pypi_0 pypi navigator-updater 0.2.1 py37_0 anaconda nbconvert 5.5.0 py_0 anaconda nbformat 4.4.0 py37_0 anaconda networkx 2.3 py_0 anaconda ninja 1.9.0 py37h74a9793_0 anaconda nltk 3.4.4 py37_0 anaconda nose 1.3.7 py37_2 anaconda notebook 6.0.0 py37_0 anaconda numba 0.44.1 py37hf9181ef_0 anaconda numexpr 2.6.9 py37hdce8814_0 anaconda numpy 1.16.4 pypi_0 pypi numpy-base 1.16.4 py37hc3f5095_0 anaconda numpydoc 0.9.1 py_0 anaconda olefile 0.46 py37_0 anaconda opencv-contrib-python 4.1.0.25 pypi_0 pypi opencv-python 4.1.0.25 pypi_0 pypi openpyxl 2.6.2 py_0 anaconda openssl 1.1.1c he774522_1 anaconda packaging 19.0 py37_0 anaconda pandas 0.24.2 py37ha925a31_0 anaconda pandoc 2.2.3.2 0 anaconda pandocfilters 1.4.2 py37_1 anaconda parso 0.5.0 py_0 anaconda partd 1.0.0 py_0 anaconda path.py 12.0.1 py_0 anaconda pathlib2 2.3.4 py37_0 anaconda patsy 0.5.1 py37_0 anaconda pattern 3.6 pypi_0 pypi pdfminer-six 20181108 pypi_0 pypi pep8 1.7.1 py37_0 anaconda pickleshare 0.7.5 py37_0 anaconda pillow 6.1.0 py37hdc69c19_0 anaconda pip 19.1.1 py37_0 anaconda pkginfo 1.5.0.1 py37_0 anaconda pluggy 0.12.0 py_0 anaconda ply 3.11 py37_0 anaconda portend 2.5 pypi_0 pypi post 2019.4.13 pypi_0 pypi powershell_shortcut 0.0.1 2 anaconda proglog 0.1.9 pypi_0 pypi prometheus_client 0.7.1 py_0 anaconda prompt_toolkit 2.0.9 py37_0 anaconda protobuf 3.7.1 pypi_0 pypi psutil 5.6.3 py37he774522_0 anaconda public 2019.4.13 pypi_0 pypi py 1.8.0 py37_0 anaconda py-lief 0.9.0 py37ha925a31_2 anaconda pybind11 2.3.0 pypi_0 pypi pycodestyle 2.5.0 py37_0 anaconda pycosat 0.6.3 py37hfa6e2cd_0 anaconda pycparser 2.19 py37_0 anaconda pycrypto 2.6.1 py37hfa6e2cd_9 anaconda pycryptodome 3.8.2 pypi_0 pypi pycurl 7.43.0.3 py37h7a1dbc1_0 anaconda pydot 1.4.1 pypi_0 pypi pyflakes 2.1.1 py37_0 anaconda pygments 2.4.2 py_0 anaconda pylint 2.3.1 py37_0 anaconda pyodbc 4.0.26 py37ha925a31_0 anaconda pyopenssl 19.0.0 py37_0 anaconda pyparsing 2.4.0 py_0 anaconda pyqt 5.9.2 py37h6538335_2 anaconda pyreadline 2.1 py37_1 anaconda pyrsistent 0.14.11 py37he774522_0 anaconda pysocks 1.7.0 py37_0 anaconda pytables 3.5.2 py37h1da0976_1 anaconda pytest 5.0.1 py37_0 anaconda pytest-arraydiff 0.3 py37h39e3cac_0 anaconda pytest-astropy 0.5.0 py37_0 anaconda pytest-doctestplus 0.3.0 py37_0 anaconda pytest-openfiles 0.3.2 py37_0 anaconda pytest-remotedata 0.3.1 py37_0 anaconda python 3.7.3 h8c8aaf0_1 anaconda python-dateutil 2.8.0 py37_0 anaconda python-docx 0.8.10 pypi_0 pypi python-graphviz 0.11.1 pypi_0 pypi python-libarchive-c 2.8 py37_11 anaconda pytorch 1.2.0 py3.7_cpu_1 [cpuonly] pytorch pytube 9.5.1 pypi_0 pypi pytz 2019.1 py_0 anaconda pywavelets 1.0.3 py37h8c2d366_1 anaconda pywin32 223 py37hfa6e2cd_1 anaconda pywinpty 0.5.5 py37_1000 anaconda pyyaml 5.1.1 py37he774522_0 anaconda pyzmq 18.0.0 py37ha925a31_0 anaconda qt 5.9.7 vc14h73c81de_0 [vc14] anaconda qtawesome 0.5.7 py37_1 anaconda qtconsole 4.5.1 py_0 anaconda qtpy 1.8.0 py_0 anaconda query-string 2019.4.13 pypi_0 pypi request 2019.4.13 pypi_0 pypi requests 2.22.0 py37_0 anaconda rope 0.14.0 py_0 anaconda ruamel_yaml 0.15.46 py37hfa6e2cd_0 anaconda scikit-image 0.15.0 py37ha925a31_0 anaconda scikit-learn 0.21.2 py37h6288b17_0 anaconda scipy 1.3.0 pypi_0 pypi scipy-stack 0.0.5 pypi_0 pypi seaborn 0.9.0 py37_0 anaconda send2trash 1.5.0 py37_0 anaconda setuptools 41.1.0 pypi_0 pypi simplegeneric 0.8.1 py37_2 anaconda singledispatch 3.4.0.3 py37_0 anaconda sip 4.19.8 py37h6538335_0 anaconda six 1.12.0 py37_0 anaconda snappy 1.1.7 h777316e_3 anaconda snowballstemmer 1.9.0 py_0 anaconda sortedcollections 1.1.2 py37_0 anaconda sortedcontainers 2.1.0 py37_0 anaconda soupsieve 1.8 py37_0 anaconda sphinx 2.1.2 py_0 anaconda sphinxcontrib 1.0 py37_1 anaconda sphinxcontrib-applehelp 1.0.1 py_0 anaconda sphinxcontrib-devhelp 1.0.1 py_0 anaconda sphinxcontrib-htmlhelp 1.0.2 py_0 anaconda sphinxcontrib-jsmath 1.0.1 py_0 anaconda sphinxcontrib-qthelp 1.0.2 py_0 anaconda sphinxcontrib-serializinghtml 1.1.3 py_0 anaconda sphinxcontrib-websupport 1.1.2 py_0 anaconda spyder 3.3.6 py37_0 anaconda spyder-kernels 0.5.1 py37_0 anaconda sqlalchemy 1.3.5 py37he774522_0 anaconda sqlite 3.29.0 he774522_0 anaconda statsmodels 0.10.0 py37h8c2d366_0 anaconda summa 1.2.0 pypi_0 pypi sympy 1.4 py37_0 anaconda tbb 2019.4 h74a9793_0 anaconda tblib 1.4.0 py_0 anaconda tempora 1.14.1 pypi_0 pypi tensorboard 1.14.0 py37he3c9ec2_0 anaconda tensorboardx 1.8 pypi_0 pypi tensorflow 1.14.0 mkl_py37h7908ca0_0 anaconda tensorflow-base 1.14.0 mkl_py37ha978198_0 anaconda tensorflow-estimator 1.14.0 py_0 anaconda tensorflow-mkl 1.14.0 h4fcabd2_0 anaconda termcolor 1.1.0 pypi_0 pypi terminado 0.8.2 py37_0 anaconda testpath 0.4.2 py37_0 anaconda tk 8.6.8 hfa6e2cd_0 anaconda toolz 0.10.0 py_0 anaconda torchvision 0.4.0 py37_cpu [cpuonly] pytorch tornado 6.0.3 py37he774522_0 anaconda tqdm 4.32.1 py_0 anaconda traitlets 4.3.2 py37_0 anaconda typing 3.6.6 pypi_0 pypi typing-extensions 3.6.6 pypi_0 pypi unicodecsv 0.14.1 py37_0 anaconda urllib3 1.24.2 py37_0 anaconda validators 0.13.0 pypi_0 pypi vc 14.1 h0510ff6_4 anaconda vs2015_runtime 14.15.26706 h3a45250_4 anaconda wcwidth 0.1.7 py37_0 anaconda webencodings 0.5.1 py37_1 anaconda werkzeug 0.15.4 py_0 anaconda wheel 0.33.4 py37_0 anaconda widgetsnbextension 3.5.0 py37_0 anaconda win_inet_pton 1.1.0 py37_0 anaconda win_unicode_console 0.5 py37_0 anaconda wincertstore 0.2 py37_0 anaconda winpty 0.4.3 4 anaconda wrapt 1.11.2 py37he774522_0 anaconda xlrd 1.2.0 py37_0 anaconda xlsxwriter 1.1.8 py_0 anaconda xlwings 0.15.8 py37_0 anaconda xlwt 1.3.0 py37_0 anaconda xz 5.2.4 h2fa13f4_4 anaconda yaml 0.1.7 hc54c509_2 anaconda youtube-dl 2019.8.2 pypi_0 pypi zc-lockfile 1.4 pypi_0 pypi zeromq 4.3.1 h33f27b4_3 anaconda zict 1.0.0 py_0 anaconda zipp 0.5.1 py_0 anaconda zlib 1.2.11 h62dcd97_3 anaconda zstd 1.3.7 h508b16e_0 anaconda ```
2019/09/06
[ "https://Stackoverflow.com/questions/57814535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3204706/" ]
First activate your environment. Replace <name> with your environment name. ``` conda activate <name> ``` Then see cuda version in your machine. To see cuda version: ``` nvcc --version ``` Now for CUDA 10.1 use: ``` conda install pytorch==1.4.0 torchvision==0.5.0 cudatoolkit=10.1 -c pytorch ``` For CUDA 10.0 use: ``` conda install pytorch==1.4.0 torchvision==0.5.0 cudatoolkit=10.0 -c pytorch ``` For CUDA 9.2 use: ``` conda install pytorch==1.4.0 torchvision==0.5.0 cudatoolkit=9.2 -c pytorch ```
One more thing to note here is if you are installing PyTorch with CUDA support in an anaconda environment, Please make sure that the **Python** version should be **3.7-3.9**. conda install pytorch torchvision torchaudio cudatoolkit=11.6 -c pytorch -c conda-forge. I was getting the same "AssertionError: Torch not compiled with CUDA enabled" with python 3.10.
57,814,535
I figured out this is a popular question, but still I couldn't find a solution for that. I'm trying to run a simple repo [Here](https://github.com/swathikirans/violence-recognition-pytorch) which uses `PyTorch`. Although I just upgraded my Pytorch to the latest CUDA version from pytorch.org (`1.2.0`), it still throws the same error. I'm on Windows 10 and use conda with python 3.7. ``` raise AssertionError("Torch not compiled with CUDA enabled") AssertionError: Torch not compiled with CUDA enabled ``` How to fix the problem? Here is my `conda list`: ``` # Name Version Build Channel _ipyw_jlab_nb_ext_conf 0.1.0 py37_0 anaconda _pytorch_select 1.1.0 cpu anaconda _tflow_select 2.3.0 mkl anaconda absl-py 0.7.1 pypi_0 pypi alabaster 0.7.12 py37_0 anaconda anaconda 2019.07 py37_0 anaconda anaconda-client 1.7.2 py37_0 anaconda anaconda-navigator 1.9.7 py37_0 anaconda anaconda-project 0.8.3 py_0 anaconda argparse 1.4.0 pypi_0 pypi asn1crypto 0.24.0 py37_0 anaconda astor 0.8.0 pypi_0 pypi astroid 2.2.5 py37_0 anaconda astropy 3.2.1 py37he774522_0 anaconda atomicwrites 1.3.0 py37_1 anaconda attrs 19.1.0 py37_1 anaconda babel 2.7.0 py_0 anaconda backcall 0.1.0 py37_0 anaconda backports 1.0 py_2 anaconda backports-csv 1.0.7 pypi_0 pypi backports-functools-lru-cache 1.5 pypi_0 pypi backports.functools_lru_cache 1.5 py_2 anaconda backports.os 0.1.1 py37_0 anaconda backports.shutil_get_terminal_size 1.0.0 py37_2 anaconda backports.tempfile 1.0 py_1 anaconda backports.weakref 1.0.post1 py_1 anaconda beautifulsoup4 4.7.1 py37_1 anaconda bitarray 0.9.3 py37he774522_0 anaconda bkcharts 0.2 py37_0 anaconda blas 1.0 mkl anaconda bleach 3.1.0 py37_0 anaconda blosc 1.16.3 h7bd577a_0 anaconda bokeh 1.2.0 py37_0 anaconda boto 2.49.0 py37_0 anaconda bottleneck 1.2.1 py37h452e1ab_1 anaconda bzip2 1.0.8 he774522_0 anaconda ca-certificates 2019.5.15 0 anaconda certifi 2019.6.16 py37_0 anaconda cffi 1.12.3 py37h7a1dbc1_0 anaconda chainer 6.2.0 pypi_0 pypi chardet 3.0.4 py37_1 anaconda cheroot 6.5.5 pypi_0 pypi cherrypy 18.1.2 pypi_0 pypi click 7.0 py37_0 anaconda cloudpickle 1.2.1 py_0 anaconda clyent 1.2.2 py37_1 anaconda colorama 0.4.1 py37_0 anaconda comtypes 1.1.7 py37_0 anaconda conda 4.7.11 py37_0 anaconda conda-build 3.18.9 py37_3 anaconda conda-env 2.6.0 1 anaconda conda-package-handling 1.3.11 py37_0 anaconda conda-verify 3.4.2 py_1 anaconda console_shortcut 0.1.1 3 anaconda constants 0.6.0 pypi_0 pypi contextlib2 0.5.5 py37_0 anaconda cpuonly 1.0 0 pytorch cryptography 2.7 py37h7a1dbc1_0 anaconda cudatoolkit 10.0.130 0 anaconda curl 7.65.2 h2a8f88b_0 anaconda cycler 0.10.0 py37_0 anaconda cython 0.29.12 py37ha925a31_0 anaconda cytoolz 0.10.0 py37he774522_0 anaconda dask 2.1.0 py_0 anaconda dask-core 2.1.0 py_0 anaconda decorator 4.4.0 py37_1 anaconda defusedxml 0.6.0 py_0 anaconda distributed 2.1.0 py_0 anaconda docutils 0.14 py37_0 anaconda entrypoints 0.3 py37_0 anaconda et_xmlfile 1.0.1 py37_0 anaconda ez-setup 0.9 pypi_0 pypi fastcache 1.1.0 py37he774522_0 anaconda fasttext 0.9.1 pypi_0 pypi feedparser 5.2.1 pypi_0 pypi ffmpeg 4.1.3 h6538335_0 conda-forge filelock 3.0.12 py_0 anaconda first 2.0.2 pypi_0 pypi flask 1.1.1 py_0 anaconda freetype 2.9.1 ha9979f8_1 anaconda future 0.17.1 py37_0 anaconda gast 0.2.2 py37_0 anaconda get 2019.4.13 pypi_0 pypi get_terminal_size 1.0.0 h38e98db_0 anaconda gevent 1.4.0 py37he774522_0 anaconda glob2 0.7 py_0 anaconda google-pasta 0.1.7 pypi_0 pypi graphviz 2.38.0 4 anaconda greenlet 0.4.15 py37hfa6e2cd_0 anaconda grpcio 1.22.0 pypi_0 pypi h5py 2.9.0 py37h5e291fa_0 anaconda hdf5 1.10.4 h7ebc959_0 anaconda heapdict 1.0.0 py37_2 anaconda html5lib 1.0.1 py37_0 anaconda http-client 0.1.22 pypi_0 pypi hypothesis 4.34.0 pypi_0 pypi icc_rt 2019.0.0 h0cc432a_1 anaconda icu 58.2 ha66f8fd_1 anaconda idna 2.8 py37_0 anaconda imageio 2.4.1 pypi_0 pypi imageio-ffmpeg 0.3.0 pypi_0 pypi imagesize 1.1.0 py37_0 anaconda importlib_metadata 0.17 py37_1 anaconda imutils 0.5.2 pypi_0 pypi intel-openmp 2019.0 pypi_0 pypi ipykernel 5.1.1 py37h39e3cac_0 anaconda ipython 7.6.1 py37h39e3cac_0 anaconda ipython_genutils 0.2.0 py37_0 anaconda ipywidgets 7.5.0 py_0 anaconda isort 4.3.21 py37_0 anaconda itsdangerous 1.1.0 py37_0 anaconda jaraco-functools 2.0 pypi_0 pypi jdcal 1.4.1 py_0 anaconda jedi 0.13.3 py37_0 anaconda jinja2 2.10.1 py37_0 anaconda joblib 0.13.2 py37_0 anaconda jpeg 9b hb83a4c4_2 anaconda json5 0.8.4 py_0 anaconda jsonschema 3.0.1 py37_0 anaconda jupyter 1.0.0 py37_7 anaconda jupyter_client 5.3.1 py_0 anaconda jupyter_console 6.0.0 py37_0 anaconda jupyter_core 4.5.0 py_0 anaconda jupyterlab 1.0.2 py37hf63ae98_0 anaconda jupyterlab_server 1.0.0 py_0 anaconda keras 2.2.4 0 anaconda keras-applications 1.0.8 py_0 anaconda keras-base 2.2.4 py37_0 anaconda keras-preprocessing 1.1.0 py_1 anaconda keyring 18.0.0 py37_0 anaconda kiwisolver 1.1.0 py37ha925a31_0 anaconda krb5 1.16.1 hc04afaa_7 lazy-object-proxy 1.4.1 py37he774522_0 anaconda libarchive 3.3.3 h0643e63_5 anaconda libcurl 7.65.2 h2a8f88b_0 anaconda libiconv 1.15 h1df5818_7 anaconda liblief 0.9.0 ha925a31_2 anaconda libmklml 2019.0.5 0 anaconda libpng 1.6.37 h2a8f88b_0 anaconda libprotobuf 3.8.0 h7bd577a_0 anaconda libsodium 1.0.16 h9d3ae62_0 anaconda libssh2 1.8.2 h7a1dbc1_0 anaconda libtiff 4.0.10 hb898794_2 anaconda libxml2 2.9.9 h464c3ec_0 anaconda libxslt 1.1.33 h579f668_0 anaconda llvmlite 0.29.0 py37ha925a31_0 anaconda locket 0.2.0 py37_1 anaconda lxml 4.3.4 py37h1350720_0 anaconda lz4-c 1.8.1.2 h2fa13f4_0 anaconda lzo 2.10 h6df0209_2 anaconda m2w64-gcc-libgfortran 5.3.0 6 m2w64-gcc-libs 5.3.0 7 m2w64-gcc-libs-core 5.3.0 7 m2w64-gmp 6.1.0 2 m2w64-libwinpthread-git 5.0.0.4634.697f757 2 make-dataset 1.0 pypi_0 pypi markdown 3.1.1 py37_0 anaconda markupsafe 1.1.1 py37he774522_0 anaconda matplotlib 3.1.0 py37hc8f65d3_0 anaconda mccabe 0.6.1 py37_1 anaconda menuinst 1.4.16 py37he774522_0 anaconda mistune 0.8.4 py37he774522_0 anaconda mkl 2019.0 pypi_0 pypi mkl-service 2.0.2 py37he774522_0 anaconda mkl_fft 1.0.12 py37h14836fe_0 anaconda mkl_random 1.0.2 py37h343c172_0 anaconda mock 3.0.5 py37_0 anaconda more-itertools 7.0.0 py37_0 anaconda moviepy 1.0.0 pypi_0 pypi mpmath 1.1.0 py37_0 anaconda msgpack-python 0.6.1 py37h74a9793_1 anaconda msys2-conda-epoch 20160418 1 multipledispatch 0.6.0 py37_0 anaconda mysqlclient 1.4.2.post1 pypi_0 pypi navigator-updater 0.2.1 py37_0 anaconda nbconvert 5.5.0 py_0 anaconda nbformat 4.4.0 py37_0 anaconda networkx 2.3 py_0 anaconda ninja 1.9.0 py37h74a9793_0 anaconda nltk 3.4.4 py37_0 anaconda nose 1.3.7 py37_2 anaconda notebook 6.0.0 py37_0 anaconda numba 0.44.1 py37hf9181ef_0 anaconda numexpr 2.6.9 py37hdce8814_0 anaconda numpy 1.16.4 pypi_0 pypi numpy-base 1.16.4 py37hc3f5095_0 anaconda numpydoc 0.9.1 py_0 anaconda olefile 0.46 py37_0 anaconda opencv-contrib-python 4.1.0.25 pypi_0 pypi opencv-python 4.1.0.25 pypi_0 pypi openpyxl 2.6.2 py_0 anaconda openssl 1.1.1c he774522_1 anaconda packaging 19.0 py37_0 anaconda pandas 0.24.2 py37ha925a31_0 anaconda pandoc 2.2.3.2 0 anaconda pandocfilters 1.4.2 py37_1 anaconda parso 0.5.0 py_0 anaconda partd 1.0.0 py_0 anaconda path.py 12.0.1 py_0 anaconda pathlib2 2.3.4 py37_0 anaconda patsy 0.5.1 py37_0 anaconda pattern 3.6 pypi_0 pypi pdfminer-six 20181108 pypi_0 pypi pep8 1.7.1 py37_0 anaconda pickleshare 0.7.5 py37_0 anaconda pillow 6.1.0 py37hdc69c19_0 anaconda pip 19.1.1 py37_0 anaconda pkginfo 1.5.0.1 py37_0 anaconda pluggy 0.12.0 py_0 anaconda ply 3.11 py37_0 anaconda portend 2.5 pypi_0 pypi post 2019.4.13 pypi_0 pypi powershell_shortcut 0.0.1 2 anaconda proglog 0.1.9 pypi_0 pypi prometheus_client 0.7.1 py_0 anaconda prompt_toolkit 2.0.9 py37_0 anaconda protobuf 3.7.1 pypi_0 pypi psutil 5.6.3 py37he774522_0 anaconda public 2019.4.13 pypi_0 pypi py 1.8.0 py37_0 anaconda py-lief 0.9.0 py37ha925a31_2 anaconda pybind11 2.3.0 pypi_0 pypi pycodestyle 2.5.0 py37_0 anaconda pycosat 0.6.3 py37hfa6e2cd_0 anaconda pycparser 2.19 py37_0 anaconda pycrypto 2.6.1 py37hfa6e2cd_9 anaconda pycryptodome 3.8.2 pypi_0 pypi pycurl 7.43.0.3 py37h7a1dbc1_0 anaconda pydot 1.4.1 pypi_0 pypi pyflakes 2.1.1 py37_0 anaconda pygments 2.4.2 py_0 anaconda pylint 2.3.1 py37_0 anaconda pyodbc 4.0.26 py37ha925a31_0 anaconda pyopenssl 19.0.0 py37_0 anaconda pyparsing 2.4.0 py_0 anaconda pyqt 5.9.2 py37h6538335_2 anaconda pyreadline 2.1 py37_1 anaconda pyrsistent 0.14.11 py37he774522_0 anaconda pysocks 1.7.0 py37_0 anaconda pytables 3.5.2 py37h1da0976_1 anaconda pytest 5.0.1 py37_0 anaconda pytest-arraydiff 0.3 py37h39e3cac_0 anaconda pytest-astropy 0.5.0 py37_0 anaconda pytest-doctestplus 0.3.0 py37_0 anaconda pytest-openfiles 0.3.2 py37_0 anaconda pytest-remotedata 0.3.1 py37_0 anaconda python 3.7.3 h8c8aaf0_1 anaconda python-dateutil 2.8.0 py37_0 anaconda python-docx 0.8.10 pypi_0 pypi python-graphviz 0.11.1 pypi_0 pypi python-libarchive-c 2.8 py37_11 anaconda pytorch 1.2.0 py3.7_cpu_1 [cpuonly] pytorch pytube 9.5.1 pypi_0 pypi pytz 2019.1 py_0 anaconda pywavelets 1.0.3 py37h8c2d366_1 anaconda pywin32 223 py37hfa6e2cd_1 anaconda pywinpty 0.5.5 py37_1000 anaconda pyyaml 5.1.1 py37he774522_0 anaconda pyzmq 18.0.0 py37ha925a31_0 anaconda qt 5.9.7 vc14h73c81de_0 [vc14] anaconda qtawesome 0.5.7 py37_1 anaconda qtconsole 4.5.1 py_0 anaconda qtpy 1.8.0 py_0 anaconda query-string 2019.4.13 pypi_0 pypi request 2019.4.13 pypi_0 pypi requests 2.22.0 py37_0 anaconda rope 0.14.0 py_0 anaconda ruamel_yaml 0.15.46 py37hfa6e2cd_0 anaconda scikit-image 0.15.0 py37ha925a31_0 anaconda scikit-learn 0.21.2 py37h6288b17_0 anaconda scipy 1.3.0 pypi_0 pypi scipy-stack 0.0.5 pypi_0 pypi seaborn 0.9.0 py37_0 anaconda send2trash 1.5.0 py37_0 anaconda setuptools 41.1.0 pypi_0 pypi simplegeneric 0.8.1 py37_2 anaconda singledispatch 3.4.0.3 py37_0 anaconda sip 4.19.8 py37h6538335_0 anaconda six 1.12.0 py37_0 anaconda snappy 1.1.7 h777316e_3 anaconda snowballstemmer 1.9.0 py_0 anaconda sortedcollections 1.1.2 py37_0 anaconda sortedcontainers 2.1.0 py37_0 anaconda soupsieve 1.8 py37_0 anaconda sphinx 2.1.2 py_0 anaconda sphinxcontrib 1.0 py37_1 anaconda sphinxcontrib-applehelp 1.0.1 py_0 anaconda sphinxcontrib-devhelp 1.0.1 py_0 anaconda sphinxcontrib-htmlhelp 1.0.2 py_0 anaconda sphinxcontrib-jsmath 1.0.1 py_0 anaconda sphinxcontrib-qthelp 1.0.2 py_0 anaconda sphinxcontrib-serializinghtml 1.1.3 py_0 anaconda sphinxcontrib-websupport 1.1.2 py_0 anaconda spyder 3.3.6 py37_0 anaconda spyder-kernels 0.5.1 py37_0 anaconda sqlalchemy 1.3.5 py37he774522_0 anaconda sqlite 3.29.0 he774522_0 anaconda statsmodels 0.10.0 py37h8c2d366_0 anaconda summa 1.2.0 pypi_0 pypi sympy 1.4 py37_0 anaconda tbb 2019.4 h74a9793_0 anaconda tblib 1.4.0 py_0 anaconda tempora 1.14.1 pypi_0 pypi tensorboard 1.14.0 py37he3c9ec2_0 anaconda tensorboardx 1.8 pypi_0 pypi tensorflow 1.14.0 mkl_py37h7908ca0_0 anaconda tensorflow-base 1.14.0 mkl_py37ha978198_0 anaconda tensorflow-estimator 1.14.0 py_0 anaconda tensorflow-mkl 1.14.0 h4fcabd2_0 anaconda termcolor 1.1.0 pypi_0 pypi terminado 0.8.2 py37_0 anaconda testpath 0.4.2 py37_0 anaconda tk 8.6.8 hfa6e2cd_0 anaconda toolz 0.10.0 py_0 anaconda torchvision 0.4.0 py37_cpu [cpuonly] pytorch tornado 6.0.3 py37he774522_0 anaconda tqdm 4.32.1 py_0 anaconda traitlets 4.3.2 py37_0 anaconda typing 3.6.6 pypi_0 pypi typing-extensions 3.6.6 pypi_0 pypi unicodecsv 0.14.1 py37_0 anaconda urllib3 1.24.2 py37_0 anaconda validators 0.13.0 pypi_0 pypi vc 14.1 h0510ff6_4 anaconda vs2015_runtime 14.15.26706 h3a45250_4 anaconda wcwidth 0.1.7 py37_0 anaconda webencodings 0.5.1 py37_1 anaconda werkzeug 0.15.4 py_0 anaconda wheel 0.33.4 py37_0 anaconda widgetsnbextension 3.5.0 py37_0 anaconda win_inet_pton 1.1.0 py37_0 anaconda win_unicode_console 0.5 py37_0 anaconda wincertstore 0.2 py37_0 anaconda winpty 0.4.3 4 anaconda wrapt 1.11.2 py37he774522_0 anaconda xlrd 1.2.0 py37_0 anaconda xlsxwriter 1.1.8 py_0 anaconda xlwings 0.15.8 py37_0 anaconda xlwt 1.3.0 py37_0 anaconda xz 5.2.4 h2fa13f4_4 anaconda yaml 0.1.7 hc54c509_2 anaconda youtube-dl 2019.8.2 pypi_0 pypi zc-lockfile 1.4 pypi_0 pypi zeromq 4.3.1 h33f27b4_3 anaconda zict 1.0.0 py_0 anaconda zipp 0.5.1 py_0 anaconda zlib 1.2.11 h62dcd97_3 anaconda zstd 1.3.7 h508b16e_0 anaconda ```
2019/09/06
[ "https://Stackoverflow.com/questions/57814535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3204706/" ]
How did you install pytorch? It sounds like you installed pytorch without CUDA support. <https://pytorch.org/> has instructions for how to install pytorch with cuda support. In this case, we have the following command: `conda install pytorch torchvision cudatoolkit=10.1 -c pytorch` OR the command with latest cudatoolkit version.
First activate your environment. Replace <name> with your environment name. ``` conda activate <name> ``` Then see cuda version in your machine. To see cuda version: ``` nvcc --version ``` Now for CUDA 10.1 use: ``` conda install pytorch==1.4.0 torchvision==0.5.0 cudatoolkit=10.1 -c pytorch ``` For CUDA 10.0 use: ``` conda install pytorch==1.4.0 torchvision==0.5.0 cudatoolkit=10.0 -c pytorch ``` For CUDA 9.2 use: ``` conda install pytorch==1.4.0 torchvision==0.5.0 cudatoolkit=9.2 -c pytorch ```
57,814,535
I figured out this is a popular question, but still I couldn't find a solution for that. I'm trying to run a simple repo [Here](https://github.com/swathikirans/violence-recognition-pytorch) which uses `PyTorch`. Although I just upgraded my Pytorch to the latest CUDA version from pytorch.org (`1.2.0`), it still throws the same error. I'm on Windows 10 and use conda with python 3.7. ``` raise AssertionError("Torch not compiled with CUDA enabled") AssertionError: Torch not compiled with CUDA enabled ``` How to fix the problem? Here is my `conda list`: ``` # Name Version Build Channel _ipyw_jlab_nb_ext_conf 0.1.0 py37_0 anaconda _pytorch_select 1.1.0 cpu anaconda _tflow_select 2.3.0 mkl anaconda absl-py 0.7.1 pypi_0 pypi alabaster 0.7.12 py37_0 anaconda anaconda 2019.07 py37_0 anaconda anaconda-client 1.7.2 py37_0 anaconda anaconda-navigator 1.9.7 py37_0 anaconda anaconda-project 0.8.3 py_0 anaconda argparse 1.4.0 pypi_0 pypi asn1crypto 0.24.0 py37_0 anaconda astor 0.8.0 pypi_0 pypi astroid 2.2.5 py37_0 anaconda astropy 3.2.1 py37he774522_0 anaconda atomicwrites 1.3.0 py37_1 anaconda attrs 19.1.0 py37_1 anaconda babel 2.7.0 py_0 anaconda backcall 0.1.0 py37_0 anaconda backports 1.0 py_2 anaconda backports-csv 1.0.7 pypi_0 pypi backports-functools-lru-cache 1.5 pypi_0 pypi backports.functools_lru_cache 1.5 py_2 anaconda backports.os 0.1.1 py37_0 anaconda backports.shutil_get_terminal_size 1.0.0 py37_2 anaconda backports.tempfile 1.0 py_1 anaconda backports.weakref 1.0.post1 py_1 anaconda beautifulsoup4 4.7.1 py37_1 anaconda bitarray 0.9.3 py37he774522_0 anaconda bkcharts 0.2 py37_0 anaconda blas 1.0 mkl anaconda bleach 3.1.0 py37_0 anaconda blosc 1.16.3 h7bd577a_0 anaconda bokeh 1.2.0 py37_0 anaconda boto 2.49.0 py37_0 anaconda bottleneck 1.2.1 py37h452e1ab_1 anaconda bzip2 1.0.8 he774522_0 anaconda ca-certificates 2019.5.15 0 anaconda certifi 2019.6.16 py37_0 anaconda cffi 1.12.3 py37h7a1dbc1_0 anaconda chainer 6.2.0 pypi_0 pypi chardet 3.0.4 py37_1 anaconda cheroot 6.5.5 pypi_0 pypi cherrypy 18.1.2 pypi_0 pypi click 7.0 py37_0 anaconda cloudpickle 1.2.1 py_0 anaconda clyent 1.2.2 py37_1 anaconda colorama 0.4.1 py37_0 anaconda comtypes 1.1.7 py37_0 anaconda conda 4.7.11 py37_0 anaconda conda-build 3.18.9 py37_3 anaconda conda-env 2.6.0 1 anaconda conda-package-handling 1.3.11 py37_0 anaconda conda-verify 3.4.2 py_1 anaconda console_shortcut 0.1.1 3 anaconda constants 0.6.0 pypi_0 pypi contextlib2 0.5.5 py37_0 anaconda cpuonly 1.0 0 pytorch cryptography 2.7 py37h7a1dbc1_0 anaconda cudatoolkit 10.0.130 0 anaconda curl 7.65.2 h2a8f88b_0 anaconda cycler 0.10.0 py37_0 anaconda cython 0.29.12 py37ha925a31_0 anaconda cytoolz 0.10.0 py37he774522_0 anaconda dask 2.1.0 py_0 anaconda dask-core 2.1.0 py_0 anaconda decorator 4.4.0 py37_1 anaconda defusedxml 0.6.0 py_0 anaconda distributed 2.1.0 py_0 anaconda docutils 0.14 py37_0 anaconda entrypoints 0.3 py37_0 anaconda et_xmlfile 1.0.1 py37_0 anaconda ez-setup 0.9 pypi_0 pypi fastcache 1.1.0 py37he774522_0 anaconda fasttext 0.9.1 pypi_0 pypi feedparser 5.2.1 pypi_0 pypi ffmpeg 4.1.3 h6538335_0 conda-forge filelock 3.0.12 py_0 anaconda first 2.0.2 pypi_0 pypi flask 1.1.1 py_0 anaconda freetype 2.9.1 ha9979f8_1 anaconda future 0.17.1 py37_0 anaconda gast 0.2.2 py37_0 anaconda get 2019.4.13 pypi_0 pypi get_terminal_size 1.0.0 h38e98db_0 anaconda gevent 1.4.0 py37he774522_0 anaconda glob2 0.7 py_0 anaconda google-pasta 0.1.7 pypi_0 pypi graphviz 2.38.0 4 anaconda greenlet 0.4.15 py37hfa6e2cd_0 anaconda grpcio 1.22.0 pypi_0 pypi h5py 2.9.0 py37h5e291fa_0 anaconda hdf5 1.10.4 h7ebc959_0 anaconda heapdict 1.0.0 py37_2 anaconda html5lib 1.0.1 py37_0 anaconda http-client 0.1.22 pypi_0 pypi hypothesis 4.34.0 pypi_0 pypi icc_rt 2019.0.0 h0cc432a_1 anaconda icu 58.2 ha66f8fd_1 anaconda idna 2.8 py37_0 anaconda imageio 2.4.1 pypi_0 pypi imageio-ffmpeg 0.3.0 pypi_0 pypi imagesize 1.1.0 py37_0 anaconda importlib_metadata 0.17 py37_1 anaconda imutils 0.5.2 pypi_0 pypi intel-openmp 2019.0 pypi_0 pypi ipykernel 5.1.1 py37h39e3cac_0 anaconda ipython 7.6.1 py37h39e3cac_0 anaconda ipython_genutils 0.2.0 py37_0 anaconda ipywidgets 7.5.0 py_0 anaconda isort 4.3.21 py37_0 anaconda itsdangerous 1.1.0 py37_0 anaconda jaraco-functools 2.0 pypi_0 pypi jdcal 1.4.1 py_0 anaconda jedi 0.13.3 py37_0 anaconda jinja2 2.10.1 py37_0 anaconda joblib 0.13.2 py37_0 anaconda jpeg 9b hb83a4c4_2 anaconda json5 0.8.4 py_0 anaconda jsonschema 3.0.1 py37_0 anaconda jupyter 1.0.0 py37_7 anaconda jupyter_client 5.3.1 py_0 anaconda jupyter_console 6.0.0 py37_0 anaconda jupyter_core 4.5.0 py_0 anaconda jupyterlab 1.0.2 py37hf63ae98_0 anaconda jupyterlab_server 1.0.0 py_0 anaconda keras 2.2.4 0 anaconda keras-applications 1.0.8 py_0 anaconda keras-base 2.2.4 py37_0 anaconda keras-preprocessing 1.1.0 py_1 anaconda keyring 18.0.0 py37_0 anaconda kiwisolver 1.1.0 py37ha925a31_0 anaconda krb5 1.16.1 hc04afaa_7 lazy-object-proxy 1.4.1 py37he774522_0 anaconda libarchive 3.3.3 h0643e63_5 anaconda libcurl 7.65.2 h2a8f88b_0 anaconda libiconv 1.15 h1df5818_7 anaconda liblief 0.9.0 ha925a31_2 anaconda libmklml 2019.0.5 0 anaconda libpng 1.6.37 h2a8f88b_0 anaconda libprotobuf 3.8.0 h7bd577a_0 anaconda libsodium 1.0.16 h9d3ae62_0 anaconda libssh2 1.8.2 h7a1dbc1_0 anaconda libtiff 4.0.10 hb898794_2 anaconda libxml2 2.9.9 h464c3ec_0 anaconda libxslt 1.1.33 h579f668_0 anaconda llvmlite 0.29.0 py37ha925a31_0 anaconda locket 0.2.0 py37_1 anaconda lxml 4.3.4 py37h1350720_0 anaconda lz4-c 1.8.1.2 h2fa13f4_0 anaconda lzo 2.10 h6df0209_2 anaconda m2w64-gcc-libgfortran 5.3.0 6 m2w64-gcc-libs 5.3.0 7 m2w64-gcc-libs-core 5.3.0 7 m2w64-gmp 6.1.0 2 m2w64-libwinpthread-git 5.0.0.4634.697f757 2 make-dataset 1.0 pypi_0 pypi markdown 3.1.1 py37_0 anaconda markupsafe 1.1.1 py37he774522_0 anaconda matplotlib 3.1.0 py37hc8f65d3_0 anaconda mccabe 0.6.1 py37_1 anaconda menuinst 1.4.16 py37he774522_0 anaconda mistune 0.8.4 py37he774522_0 anaconda mkl 2019.0 pypi_0 pypi mkl-service 2.0.2 py37he774522_0 anaconda mkl_fft 1.0.12 py37h14836fe_0 anaconda mkl_random 1.0.2 py37h343c172_0 anaconda mock 3.0.5 py37_0 anaconda more-itertools 7.0.0 py37_0 anaconda moviepy 1.0.0 pypi_0 pypi mpmath 1.1.0 py37_0 anaconda msgpack-python 0.6.1 py37h74a9793_1 anaconda msys2-conda-epoch 20160418 1 multipledispatch 0.6.0 py37_0 anaconda mysqlclient 1.4.2.post1 pypi_0 pypi navigator-updater 0.2.1 py37_0 anaconda nbconvert 5.5.0 py_0 anaconda nbformat 4.4.0 py37_0 anaconda networkx 2.3 py_0 anaconda ninja 1.9.0 py37h74a9793_0 anaconda nltk 3.4.4 py37_0 anaconda nose 1.3.7 py37_2 anaconda notebook 6.0.0 py37_0 anaconda numba 0.44.1 py37hf9181ef_0 anaconda numexpr 2.6.9 py37hdce8814_0 anaconda numpy 1.16.4 pypi_0 pypi numpy-base 1.16.4 py37hc3f5095_0 anaconda numpydoc 0.9.1 py_0 anaconda olefile 0.46 py37_0 anaconda opencv-contrib-python 4.1.0.25 pypi_0 pypi opencv-python 4.1.0.25 pypi_0 pypi openpyxl 2.6.2 py_0 anaconda openssl 1.1.1c he774522_1 anaconda packaging 19.0 py37_0 anaconda pandas 0.24.2 py37ha925a31_0 anaconda pandoc 2.2.3.2 0 anaconda pandocfilters 1.4.2 py37_1 anaconda parso 0.5.0 py_0 anaconda partd 1.0.0 py_0 anaconda path.py 12.0.1 py_0 anaconda pathlib2 2.3.4 py37_0 anaconda patsy 0.5.1 py37_0 anaconda pattern 3.6 pypi_0 pypi pdfminer-six 20181108 pypi_0 pypi pep8 1.7.1 py37_0 anaconda pickleshare 0.7.5 py37_0 anaconda pillow 6.1.0 py37hdc69c19_0 anaconda pip 19.1.1 py37_0 anaconda pkginfo 1.5.0.1 py37_0 anaconda pluggy 0.12.0 py_0 anaconda ply 3.11 py37_0 anaconda portend 2.5 pypi_0 pypi post 2019.4.13 pypi_0 pypi powershell_shortcut 0.0.1 2 anaconda proglog 0.1.9 pypi_0 pypi prometheus_client 0.7.1 py_0 anaconda prompt_toolkit 2.0.9 py37_0 anaconda protobuf 3.7.1 pypi_0 pypi psutil 5.6.3 py37he774522_0 anaconda public 2019.4.13 pypi_0 pypi py 1.8.0 py37_0 anaconda py-lief 0.9.0 py37ha925a31_2 anaconda pybind11 2.3.0 pypi_0 pypi pycodestyle 2.5.0 py37_0 anaconda pycosat 0.6.3 py37hfa6e2cd_0 anaconda pycparser 2.19 py37_0 anaconda pycrypto 2.6.1 py37hfa6e2cd_9 anaconda pycryptodome 3.8.2 pypi_0 pypi pycurl 7.43.0.3 py37h7a1dbc1_0 anaconda pydot 1.4.1 pypi_0 pypi pyflakes 2.1.1 py37_0 anaconda pygments 2.4.2 py_0 anaconda pylint 2.3.1 py37_0 anaconda pyodbc 4.0.26 py37ha925a31_0 anaconda pyopenssl 19.0.0 py37_0 anaconda pyparsing 2.4.0 py_0 anaconda pyqt 5.9.2 py37h6538335_2 anaconda pyreadline 2.1 py37_1 anaconda pyrsistent 0.14.11 py37he774522_0 anaconda pysocks 1.7.0 py37_0 anaconda pytables 3.5.2 py37h1da0976_1 anaconda pytest 5.0.1 py37_0 anaconda pytest-arraydiff 0.3 py37h39e3cac_0 anaconda pytest-astropy 0.5.0 py37_0 anaconda pytest-doctestplus 0.3.0 py37_0 anaconda pytest-openfiles 0.3.2 py37_0 anaconda pytest-remotedata 0.3.1 py37_0 anaconda python 3.7.3 h8c8aaf0_1 anaconda python-dateutil 2.8.0 py37_0 anaconda python-docx 0.8.10 pypi_0 pypi python-graphviz 0.11.1 pypi_0 pypi python-libarchive-c 2.8 py37_11 anaconda pytorch 1.2.0 py3.7_cpu_1 [cpuonly] pytorch pytube 9.5.1 pypi_0 pypi pytz 2019.1 py_0 anaconda pywavelets 1.0.3 py37h8c2d366_1 anaconda pywin32 223 py37hfa6e2cd_1 anaconda pywinpty 0.5.5 py37_1000 anaconda pyyaml 5.1.1 py37he774522_0 anaconda pyzmq 18.0.0 py37ha925a31_0 anaconda qt 5.9.7 vc14h73c81de_0 [vc14] anaconda qtawesome 0.5.7 py37_1 anaconda qtconsole 4.5.1 py_0 anaconda qtpy 1.8.0 py_0 anaconda query-string 2019.4.13 pypi_0 pypi request 2019.4.13 pypi_0 pypi requests 2.22.0 py37_0 anaconda rope 0.14.0 py_0 anaconda ruamel_yaml 0.15.46 py37hfa6e2cd_0 anaconda scikit-image 0.15.0 py37ha925a31_0 anaconda scikit-learn 0.21.2 py37h6288b17_0 anaconda scipy 1.3.0 pypi_0 pypi scipy-stack 0.0.5 pypi_0 pypi seaborn 0.9.0 py37_0 anaconda send2trash 1.5.0 py37_0 anaconda setuptools 41.1.0 pypi_0 pypi simplegeneric 0.8.1 py37_2 anaconda singledispatch 3.4.0.3 py37_0 anaconda sip 4.19.8 py37h6538335_0 anaconda six 1.12.0 py37_0 anaconda snappy 1.1.7 h777316e_3 anaconda snowballstemmer 1.9.0 py_0 anaconda sortedcollections 1.1.2 py37_0 anaconda sortedcontainers 2.1.0 py37_0 anaconda soupsieve 1.8 py37_0 anaconda sphinx 2.1.2 py_0 anaconda sphinxcontrib 1.0 py37_1 anaconda sphinxcontrib-applehelp 1.0.1 py_0 anaconda sphinxcontrib-devhelp 1.0.1 py_0 anaconda sphinxcontrib-htmlhelp 1.0.2 py_0 anaconda sphinxcontrib-jsmath 1.0.1 py_0 anaconda sphinxcontrib-qthelp 1.0.2 py_0 anaconda sphinxcontrib-serializinghtml 1.1.3 py_0 anaconda sphinxcontrib-websupport 1.1.2 py_0 anaconda spyder 3.3.6 py37_0 anaconda spyder-kernels 0.5.1 py37_0 anaconda sqlalchemy 1.3.5 py37he774522_0 anaconda sqlite 3.29.0 he774522_0 anaconda statsmodels 0.10.0 py37h8c2d366_0 anaconda summa 1.2.0 pypi_0 pypi sympy 1.4 py37_0 anaconda tbb 2019.4 h74a9793_0 anaconda tblib 1.4.0 py_0 anaconda tempora 1.14.1 pypi_0 pypi tensorboard 1.14.0 py37he3c9ec2_0 anaconda tensorboardx 1.8 pypi_0 pypi tensorflow 1.14.0 mkl_py37h7908ca0_0 anaconda tensorflow-base 1.14.0 mkl_py37ha978198_0 anaconda tensorflow-estimator 1.14.0 py_0 anaconda tensorflow-mkl 1.14.0 h4fcabd2_0 anaconda termcolor 1.1.0 pypi_0 pypi terminado 0.8.2 py37_0 anaconda testpath 0.4.2 py37_0 anaconda tk 8.6.8 hfa6e2cd_0 anaconda toolz 0.10.0 py_0 anaconda torchvision 0.4.0 py37_cpu [cpuonly] pytorch tornado 6.0.3 py37he774522_0 anaconda tqdm 4.32.1 py_0 anaconda traitlets 4.3.2 py37_0 anaconda typing 3.6.6 pypi_0 pypi typing-extensions 3.6.6 pypi_0 pypi unicodecsv 0.14.1 py37_0 anaconda urllib3 1.24.2 py37_0 anaconda validators 0.13.0 pypi_0 pypi vc 14.1 h0510ff6_4 anaconda vs2015_runtime 14.15.26706 h3a45250_4 anaconda wcwidth 0.1.7 py37_0 anaconda webencodings 0.5.1 py37_1 anaconda werkzeug 0.15.4 py_0 anaconda wheel 0.33.4 py37_0 anaconda widgetsnbextension 3.5.0 py37_0 anaconda win_inet_pton 1.1.0 py37_0 anaconda win_unicode_console 0.5 py37_0 anaconda wincertstore 0.2 py37_0 anaconda winpty 0.4.3 4 anaconda wrapt 1.11.2 py37he774522_0 anaconda xlrd 1.2.0 py37_0 anaconda xlsxwriter 1.1.8 py_0 anaconda xlwings 0.15.8 py37_0 anaconda xlwt 1.3.0 py37_0 anaconda xz 5.2.4 h2fa13f4_4 anaconda yaml 0.1.7 hc54c509_2 anaconda youtube-dl 2019.8.2 pypi_0 pypi zc-lockfile 1.4 pypi_0 pypi zeromq 4.3.1 h33f27b4_3 anaconda zict 1.0.0 py_0 anaconda zipp 0.5.1 py_0 anaconda zlib 1.2.11 h62dcd97_3 anaconda zstd 1.3.7 h508b16e_0 anaconda ```
2019/09/06
[ "https://Stackoverflow.com/questions/57814535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3204706/" ]
How did you install pytorch? It sounds like you installed pytorch without CUDA support. <https://pytorch.org/> has instructions for how to install pytorch with cuda support. In this case, we have the following command: `conda install pytorch torchvision cudatoolkit=10.1 -c pytorch` OR the command with latest cudatoolkit version.
try this: ``` conda install pytorch torchvision cudatoolkit=10.2 -c pytorch ```
57,814,535
I figured out this is a popular question, but still I couldn't find a solution for that. I'm trying to run a simple repo [Here](https://github.com/swathikirans/violence-recognition-pytorch) which uses `PyTorch`. Although I just upgraded my Pytorch to the latest CUDA version from pytorch.org (`1.2.0`), it still throws the same error. I'm on Windows 10 and use conda with python 3.7. ``` raise AssertionError("Torch not compiled with CUDA enabled") AssertionError: Torch not compiled with CUDA enabled ``` How to fix the problem? Here is my `conda list`: ``` # Name Version Build Channel _ipyw_jlab_nb_ext_conf 0.1.0 py37_0 anaconda _pytorch_select 1.1.0 cpu anaconda _tflow_select 2.3.0 mkl anaconda absl-py 0.7.1 pypi_0 pypi alabaster 0.7.12 py37_0 anaconda anaconda 2019.07 py37_0 anaconda anaconda-client 1.7.2 py37_0 anaconda anaconda-navigator 1.9.7 py37_0 anaconda anaconda-project 0.8.3 py_0 anaconda argparse 1.4.0 pypi_0 pypi asn1crypto 0.24.0 py37_0 anaconda astor 0.8.0 pypi_0 pypi astroid 2.2.5 py37_0 anaconda astropy 3.2.1 py37he774522_0 anaconda atomicwrites 1.3.0 py37_1 anaconda attrs 19.1.0 py37_1 anaconda babel 2.7.0 py_0 anaconda backcall 0.1.0 py37_0 anaconda backports 1.0 py_2 anaconda backports-csv 1.0.7 pypi_0 pypi backports-functools-lru-cache 1.5 pypi_0 pypi backports.functools_lru_cache 1.5 py_2 anaconda backports.os 0.1.1 py37_0 anaconda backports.shutil_get_terminal_size 1.0.0 py37_2 anaconda backports.tempfile 1.0 py_1 anaconda backports.weakref 1.0.post1 py_1 anaconda beautifulsoup4 4.7.1 py37_1 anaconda bitarray 0.9.3 py37he774522_0 anaconda bkcharts 0.2 py37_0 anaconda blas 1.0 mkl anaconda bleach 3.1.0 py37_0 anaconda blosc 1.16.3 h7bd577a_0 anaconda bokeh 1.2.0 py37_0 anaconda boto 2.49.0 py37_0 anaconda bottleneck 1.2.1 py37h452e1ab_1 anaconda bzip2 1.0.8 he774522_0 anaconda ca-certificates 2019.5.15 0 anaconda certifi 2019.6.16 py37_0 anaconda cffi 1.12.3 py37h7a1dbc1_0 anaconda chainer 6.2.0 pypi_0 pypi chardet 3.0.4 py37_1 anaconda cheroot 6.5.5 pypi_0 pypi cherrypy 18.1.2 pypi_0 pypi click 7.0 py37_0 anaconda cloudpickle 1.2.1 py_0 anaconda clyent 1.2.2 py37_1 anaconda colorama 0.4.1 py37_0 anaconda comtypes 1.1.7 py37_0 anaconda conda 4.7.11 py37_0 anaconda conda-build 3.18.9 py37_3 anaconda conda-env 2.6.0 1 anaconda conda-package-handling 1.3.11 py37_0 anaconda conda-verify 3.4.2 py_1 anaconda console_shortcut 0.1.1 3 anaconda constants 0.6.0 pypi_0 pypi contextlib2 0.5.5 py37_0 anaconda cpuonly 1.0 0 pytorch cryptography 2.7 py37h7a1dbc1_0 anaconda cudatoolkit 10.0.130 0 anaconda curl 7.65.2 h2a8f88b_0 anaconda cycler 0.10.0 py37_0 anaconda cython 0.29.12 py37ha925a31_0 anaconda cytoolz 0.10.0 py37he774522_0 anaconda dask 2.1.0 py_0 anaconda dask-core 2.1.0 py_0 anaconda decorator 4.4.0 py37_1 anaconda defusedxml 0.6.0 py_0 anaconda distributed 2.1.0 py_0 anaconda docutils 0.14 py37_0 anaconda entrypoints 0.3 py37_0 anaconda et_xmlfile 1.0.1 py37_0 anaconda ez-setup 0.9 pypi_0 pypi fastcache 1.1.0 py37he774522_0 anaconda fasttext 0.9.1 pypi_0 pypi feedparser 5.2.1 pypi_0 pypi ffmpeg 4.1.3 h6538335_0 conda-forge filelock 3.0.12 py_0 anaconda first 2.0.2 pypi_0 pypi flask 1.1.1 py_0 anaconda freetype 2.9.1 ha9979f8_1 anaconda future 0.17.1 py37_0 anaconda gast 0.2.2 py37_0 anaconda get 2019.4.13 pypi_0 pypi get_terminal_size 1.0.0 h38e98db_0 anaconda gevent 1.4.0 py37he774522_0 anaconda glob2 0.7 py_0 anaconda google-pasta 0.1.7 pypi_0 pypi graphviz 2.38.0 4 anaconda greenlet 0.4.15 py37hfa6e2cd_0 anaconda grpcio 1.22.0 pypi_0 pypi h5py 2.9.0 py37h5e291fa_0 anaconda hdf5 1.10.4 h7ebc959_0 anaconda heapdict 1.0.0 py37_2 anaconda html5lib 1.0.1 py37_0 anaconda http-client 0.1.22 pypi_0 pypi hypothesis 4.34.0 pypi_0 pypi icc_rt 2019.0.0 h0cc432a_1 anaconda icu 58.2 ha66f8fd_1 anaconda idna 2.8 py37_0 anaconda imageio 2.4.1 pypi_0 pypi imageio-ffmpeg 0.3.0 pypi_0 pypi imagesize 1.1.0 py37_0 anaconda importlib_metadata 0.17 py37_1 anaconda imutils 0.5.2 pypi_0 pypi intel-openmp 2019.0 pypi_0 pypi ipykernel 5.1.1 py37h39e3cac_0 anaconda ipython 7.6.1 py37h39e3cac_0 anaconda ipython_genutils 0.2.0 py37_0 anaconda ipywidgets 7.5.0 py_0 anaconda isort 4.3.21 py37_0 anaconda itsdangerous 1.1.0 py37_0 anaconda jaraco-functools 2.0 pypi_0 pypi jdcal 1.4.1 py_0 anaconda jedi 0.13.3 py37_0 anaconda jinja2 2.10.1 py37_0 anaconda joblib 0.13.2 py37_0 anaconda jpeg 9b hb83a4c4_2 anaconda json5 0.8.4 py_0 anaconda jsonschema 3.0.1 py37_0 anaconda jupyter 1.0.0 py37_7 anaconda jupyter_client 5.3.1 py_0 anaconda jupyter_console 6.0.0 py37_0 anaconda jupyter_core 4.5.0 py_0 anaconda jupyterlab 1.0.2 py37hf63ae98_0 anaconda jupyterlab_server 1.0.0 py_0 anaconda keras 2.2.4 0 anaconda keras-applications 1.0.8 py_0 anaconda keras-base 2.2.4 py37_0 anaconda keras-preprocessing 1.1.0 py_1 anaconda keyring 18.0.0 py37_0 anaconda kiwisolver 1.1.0 py37ha925a31_0 anaconda krb5 1.16.1 hc04afaa_7 lazy-object-proxy 1.4.1 py37he774522_0 anaconda libarchive 3.3.3 h0643e63_5 anaconda libcurl 7.65.2 h2a8f88b_0 anaconda libiconv 1.15 h1df5818_7 anaconda liblief 0.9.0 ha925a31_2 anaconda libmklml 2019.0.5 0 anaconda libpng 1.6.37 h2a8f88b_0 anaconda libprotobuf 3.8.0 h7bd577a_0 anaconda libsodium 1.0.16 h9d3ae62_0 anaconda libssh2 1.8.2 h7a1dbc1_0 anaconda libtiff 4.0.10 hb898794_2 anaconda libxml2 2.9.9 h464c3ec_0 anaconda libxslt 1.1.33 h579f668_0 anaconda llvmlite 0.29.0 py37ha925a31_0 anaconda locket 0.2.0 py37_1 anaconda lxml 4.3.4 py37h1350720_0 anaconda lz4-c 1.8.1.2 h2fa13f4_0 anaconda lzo 2.10 h6df0209_2 anaconda m2w64-gcc-libgfortran 5.3.0 6 m2w64-gcc-libs 5.3.0 7 m2w64-gcc-libs-core 5.3.0 7 m2w64-gmp 6.1.0 2 m2w64-libwinpthread-git 5.0.0.4634.697f757 2 make-dataset 1.0 pypi_0 pypi markdown 3.1.1 py37_0 anaconda markupsafe 1.1.1 py37he774522_0 anaconda matplotlib 3.1.0 py37hc8f65d3_0 anaconda mccabe 0.6.1 py37_1 anaconda menuinst 1.4.16 py37he774522_0 anaconda mistune 0.8.4 py37he774522_0 anaconda mkl 2019.0 pypi_0 pypi mkl-service 2.0.2 py37he774522_0 anaconda mkl_fft 1.0.12 py37h14836fe_0 anaconda mkl_random 1.0.2 py37h343c172_0 anaconda mock 3.0.5 py37_0 anaconda more-itertools 7.0.0 py37_0 anaconda moviepy 1.0.0 pypi_0 pypi mpmath 1.1.0 py37_0 anaconda msgpack-python 0.6.1 py37h74a9793_1 anaconda msys2-conda-epoch 20160418 1 multipledispatch 0.6.0 py37_0 anaconda mysqlclient 1.4.2.post1 pypi_0 pypi navigator-updater 0.2.1 py37_0 anaconda nbconvert 5.5.0 py_0 anaconda nbformat 4.4.0 py37_0 anaconda networkx 2.3 py_0 anaconda ninja 1.9.0 py37h74a9793_0 anaconda nltk 3.4.4 py37_0 anaconda nose 1.3.7 py37_2 anaconda notebook 6.0.0 py37_0 anaconda numba 0.44.1 py37hf9181ef_0 anaconda numexpr 2.6.9 py37hdce8814_0 anaconda numpy 1.16.4 pypi_0 pypi numpy-base 1.16.4 py37hc3f5095_0 anaconda numpydoc 0.9.1 py_0 anaconda olefile 0.46 py37_0 anaconda opencv-contrib-python 4.1.0.25 pypi_0 pypi opencv-python 4.1.0.25 pypi_0 pypi openpyxl 2.6.2 py_0 anaconda openssl 1.1.1c he774522_1 anaconda packaging 19.0 py37_0 anaconda pandas 0.24.2 py37ha925a31_0 anaconda pandoc 2.2.3.2 0 anaconda pandocfilters 1.4.2 py37_1 anaconda parso 0.5.0 py_0 anaconda partd 1.0.0 py_0 anaconda path.py 12.0.1 py_0 anaconda pathlib2 2.3.4 py37_0 anaconda patsy 0.5.1 py37_0 anaconda pattern 3.6 pypi_0 pypi pdfminer-six 20181108 pypi_0 pypi pep8 1.7.1 py37_0 anaconda pickleshare 0.7.5 py37_0 anaconda pillow 6.1.0 py37hdc69c19_0 anaconda pip 19.1.1 py37_0 anaconda pkginfo 1.5.0.1 py37_0 anaconda pluggy 0.12.0 py_0 anaconda ply 3.11 py37_0 anaconda portend 2.5 pypi_0 pypi post 2019.4.13 pypi_0 pypi powershell_shortcut 0.0.1 2 anaconda proglog 0.1.9 pypi_0 pypi prometheus_client 0.7.1 py_0 anaconda prompt_toolkit 2.0.9 py37_0 anaconda protobuf 3.7.1 pypi_0 pypi psutil 5.6.3 py37he774522_0 anaconda public 2019.4.13 pypi_0 pypi py 1.8.0 py37_0 anaconda py-lief 0.9.0 py37ha925a31_2 anaconda pybind11 2.3.0 pypi_0 pypi pycodestyle 2.5.0 py37_0 anaconda pycosat 0.6.3 py37hfa6e2cd_0 anaconda pycparser 2.19 py37_0 anaconda pycrypto 2.6.1 py37hfa6e2cd_9 anaconda pycryptodome 3.8.2 pypi_0 pypi pycurl 7.43.0.3 py37h7a1dbc1_0 anaconda pydot 1.4.1 pypi_0 pypi pyflakes 2.1.1 py37_0 anaconda pygments 2.4.2 py_0 anaconda pylint 2.3.1 py37_0 anaconda pyodbc 4.0.26 py37ha925a31_0 anaconda pyopenssl 19.0.0 py37_0 anaconda pyparsing 2.4.0 py_0 anaconda pyqt 5.9.2 py37h6538335_2 anaconda pyreadline 2.1 py37_1 anaconda pyrsistent 0.14.11 py37he774522_0 anaconda pysocks 1.7.0 py37_0 anaconda pytables 3.5.2 py37h1da0976_1 anaconda pytest 5.0.1 py37_0 anaconda pytest-arraydiff 0.3 py37h39e3cac_0 anaconda pytest-astropy 0.5.0 py37_0 anaconda pytest-doctestplus 0.3.0 py37_0 anaconda pytest-openfiles 0.3.2 py37_0 anaconda pytest-remotedata 0.3.1 py37_0 anaconda python 3.7.3 h8c8aaf0_1 anaconda python-dateutil 2.8.0 py37_0 anaconda python-docx 0.8.10 pypi_0 pypi python-graphviz 0.11.1 pypi_0 pypi python-libarchive-c 2.8 py37_11 anaconda pytorch 1.2.0 py3.7_cpu_1 [cpuonly] pytorch pytube 9.5.1 pypi_0 pypi pytz 2019.1 py_0 anaconda pywavelets 1.0.3 py37h8c2d366_1 anaconda pywin32 223 py37hfa6e2cd_1 anaconda pywinpty 0.5.5 py37_1000 anaconda pyyaml 5.1.1 py37he774522_0 anaconda pyzmq 18.0.0 py37ha925a31_0 anaconda qt 5.9.7 vc14h73c81de_0 [vc14] anaconda qtawesome 0.5.7 py37_1 anaconda qtconsole 4.5.1 py_0 anaconda qtpy 1.8.0 py_0 anaconda query-string 2019.4.13 pypi_0 pypi request 2019.4.13 pypi_0 pypi requests 2.22.0 py37_0 anaconda rope 0.14.0 py_0 anaconda ruamel_yaml 0.15.46 py37hfa6e2cd_0 anaconda scikit-image 0.15.0 py37ha925a31_0 anaconda scikit-learn 0.21.2 py37h6288b17_0 anaconda scipy 1.3.0 pypi_0 pypi scipy-stack 0.0.5 pypi_0 pypi seaborn 0.9.0 py37_0 anaconda send2trash 1.5.0 py37_0 anaconda setuptools 41.1.0 pypi_0 pypi simplegeneric 0.8.1 py37_2 anaconda singledispatch 3.4.0.3 py37_0 anaconda sip 4.19.8 py37h6538335_0 anaconda six 1.12.0 py37_0 anaconda snappy 1.1.7 h777316e_3 anaconda snowballstemmer 1.9.0 py_0 anaconda sortedcollections 1.1.2 py37_0 anaconda sortedcontainers 2.1.0 py37_0 anaconda soupsieve 1.8 py37_0 anaconda sphinx 2.1.2 py_0 anaconda sphinxcontrib 1.0 py37_1 anaconda sphinxcontrib-applehelp 1.0.1 py_0 anaconda sphinxcontrib-devhelp 1.0.1 py_0 anaconda sphinxcontrib-htmlhelp 1.0.2 py_0 anaconda sphinxcontrib-jsmath 1.0.1 py_0 anaconda sphinxcontrib-qthelp 1.0.2 py_0 anaconda sphinxcontrib-serializinghtml 1.1.3 py_0 anaconda sphinxcontrib-websupport 1.1.2 py_0 anaconda spyder 3.3.6 py37_0 anaconda spyder-kernels 0.5.1 py37_0 anaconda sqlalchemy 1.3.5 py37he774522_0 anaconda sqlite 3.29.0 he774522_0 anaconda statsmodels 0.10.0 py37h8c2d366_0 anaconda summa 1.2.0 pypi_0 pypi sympy 1.4 py37_0 anaconda tbb 2019.4 h74a9793_0 anaconda tblib 1.4.0 py_0 anaconda tempora 1.14.1 pypi_0 pypi tensorboard 1.14.0 py37he3c9ec2_0 anaconda tensorboardx 1.8 pypi_0 pypi tensorflow 1.14.0 mkl_py37h7908ca0_0 anaconda tensorflow-base 1.14.0 mkl_py37ha978198_0 anaconda tensorflow-estimator 1.14.0 py_0 anaconda tensorflow-mkl 1.14.0 h4fcabd2_0 anaconda termcolor 1.1.0 pypi_0 pypi terminado 0.8.2 py37_0 anaconda testpath 0.4.2 py37_0 anaconda tk 8.6.8 hfa6e2cd_0 anaconda toolz 0.10.0 py_0 anaconda torchvision 0.4.0 py37_cpu [cpuonly] pytorch tornado 6.0.3 py37he774522_0 anaconda tqdm 4.32.1 py_0 anaconda traitlets 4.3.2 py37_0 anaconda typing 3.6.6 pypi_0 pypi typing-extensions 3.6.6 pypi_0 pypi unicodecsv 0.14.1 py37_0 anaconda urllib3 1.24.2 py37_0 anaconda validators 0.13.0 pypi_0 pypi vc 14.1 h0510ff6_4 anaconda vs2015_runtime 14.15.26706 h3a45250_4 anaconda wcwidth 0.1.7 py37_0 anaconda webencodings 0.5.1 py37_1 anaconda werkzeug 0.15.4 py_0 anaconda wheel 0.33.4 py37_0 anaconda widgetsnbextension 3.5.0 py37_0 anaconda win_inet_pton 1.1.0 py37_0 anaconda win_unicode_console 0.5 py37_0 anaconda wincertstore 0.2 py37_0 anaconda winpty 0.4.3 4 anaconda wrapt 1.11.2 py37he774522_0 anaconda xlrd 1.2.0 py37_0 anaconda xlsxwriter 1.1.8 py_0 anaconda xlwings 0.15.8 py37_0 anaconda xlwt 1.3.0 py37_0 anaconda xz 5.2.4 h2fa13f4_4 anaconda yaml 0.1.7 hc54c509_2 anaconda youtube-dl 2019.8.2 pypi_0 pypi zc-lockfile 1.4 pypi_0 pypi zeromq 4.3.1 h33f27b4_3 anaconda zict 1.0.0 py_0 anaconda zipp 0.5.1 py_0 anaconda zlib 1.2.11 h62dcd97_3 anaconda zstd 1.3.7 h508b16e_0 anaconda ```
2019/09/06
[ "https://Stackoverflow.com/questions/57814535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3204706/" ]
you dont have to install it via anaconda, you could install cuda from their [website](https://developer.nvidia.com/cuda-downloads). after install ends open a new terminal and check your cuda version with: ``` >>> nvcc --version nvcc: NVIDIA (R) Cuda compiler driver Copyright (c) 2005-2021 NVIDIA Corporation Built on Thu_Nov_18_09:52:33_Pacific_Standard_Time_2021 Cuda compilation tools, release 11.5, V11.5.119 Build cuda_11.5.r11.5/compiler.30672275_0 ``` my is V11.5 after, go [here](https://pytorch.org/get-started/locally/) and select your os and preferred package manager(pip or anaconda), and the cuda version you installed, and copy the generated install command, I got: ``` pip3 install torch==1.10.1+cu113 torchvision==0.11.2+cu113 torchaudio===0.10.1+cu113 -f https://download.pytorch.org/whl/cu113/torch_stable.html ``` notice that for me I had python 3.10 installed but my project run over 3.9 so either use virtual environment or run pip of your wanted base interpreter explicitly (for example `C:\Software\Python\Python39\python.exe -m pip install .....`) else you will be stuck with `Could not find a version that satisfies the requirement torch` errors after, open python console and check for cuda availability ```py >>> import torch >>> torch.cuda.is_available() True ```
try this: ``` conda install pytorch torchvision cudatoolkit=10.2 -c pytorch ```
57,814,535
I figured out this is a popular question, but still I couldn't find a solution for that. I'm trying to run a simple repo [Here](https://github.com/swathikirans/violence-recognition-pytorch) which uses `PyTorch`. Although I just upgraded my Pytorch to the latest CUDA version from pytorch.org (`1.2.0`), it still throws the same error. I'm on Windows 10 and use conda with python 3.7. ``` raise AssertionError("Torch not compiled with CUDA enabled") AssertionError: Torch not compiled with CUDA enabled ``` How to fix the problem? Here is my `conda list`: ``` # Name Version Build Channel _ipyw_jlab_nb_ext_conf 0.1.0 py37_0 anaconda _pytorch_select 1.1.0 cpu anaconda _tflow_select 2.3.0 mkl anaconda absl-py 0.7.1 pypi_0 pypi alabaster 0.7.12 py37_0 anaconda anaconda 2019.07 py37_0 anaconda anaconda-client 1.7.2 py37_0 anaconda anaconda-navigator 1.9.7 py37_0 anaconda anaconda-project 0.8.3 py_0 anaconda argparse 1.4.0 pypi_0 pypi asn1crypto 0.24.0 py37_0 anaconda astor 0.8.0 pypi_0 pypi astroid 2.2.5 py37_0 anaconda astropy 3.2.1 py37he774522_0 anaconda atomicwrites 1.3.0 py37_1 anaconda attrs 19.1.0 py37_1 anaconda babel 2.7.0 py_0 anaconda backcall 0.1.0 py37_0 anaconda backports 1.0 py_2 anaconda backports-csv 1.0.7 pypi_0 pypi backports-functools-lru-cache 1.5 pypi_0 pypi backports.functools_lru_cache 1.5 py_2 anaconda backports.os 0.1.1 py37_0 anaconda backports.shutil_get_terminal_size 1.0.0 py37_2 anaconda backports.tempfile 1.0 py_1 anaconda backports.weakref 1.0.post1 py_1 anaconda beautifulsoup4 4.7.1 py37_1 anaconda bitarray 0.9.3 py37he774522_0 anaconda bkcharts 0.2 py37_0 anaconda blas 1.0 mkl anaconda bleach 3.1.0 py37_0 anaconda blosc 1.16.3 h7bd577a_0 anaconda bokeh 1.2.0 py37_0 anaconda boto 2.49.0 py37_0 anaconda bottleneck 1.2.1 py37h452e1ab_1 anaconda bzip2 1.0.8 he774522_0 anaconda ca-certificates 2019.5.15 0 anaconda certifi 2019.6.16 py37_0 anaconda cffi 1.12.3 py37h7a1dbc1_0 anaconda chainer 6.2.0 pypi_0 pypi chardet 3.0.4 py37_1 anaconda cheroot 6.5.5 pypi_0 pypi cherrypy 18.1.2 pypi_0 pypi click 7.0 py37_0 anaconda cloudpickle 1.2.1 py_0 anaconda clyent 1.2.2 py37_1 anaconda colorama 0.4.1 py37_0 anaconda comtypes 1.1.7 py37_0 anaconda conda 4.7.11 py37_0 anaconda conda-build 3.18.9 py37_3 anaconda conda-env 2.6.0 1 anaconda conda-package-handling 1.3.11 py37_0 anaconda conda-verify 3.4.2 py_1 anaconda console_shortcut 0.1.1 3 anaconda constants 0.6.0 pypi_0 pypi contextlib2 0.5.5 py37_0 anaconda cpuonly 1.0 0 pytorch cryptography 2.7 py37h7a1dbc1_0 anaconda cudatoolkit 10.0.130 0 anaconda curl 7.65.2 h2a8f88b_0 anaconda cycler 0.10.0 py37_0 anaconda cython 0.29.12 py37ha925a31_0 anaconda cytoolz 0.10.0 py37he774522_0 anaconda dask 2.1.0 py_0 anaconda dask-core 2.1.0 py_0 anaconda decorator 4.4.0 py37_1 anaconda defusedxml 0.6.0 py_0 anaconda distributed 2.1.0 py_0 anaconda docutils 0.14 py37_0 anaconda entrypoints 0.3 py37_0 anaconda et_xmlfile 1.0.1 py37_0 anaconda ez-setup 0.9 pypi_0 pypi fastcache 1.1.0 py37he774522_0 anaconda fasttext 0.9.1 pypi_0 pypi feedparser 5.2.1 pypi_0 pypi ffmpeg 4.1.3 h6538335_0 conda-forge filelock 3.0.12 py_0 anaconda first 2.0.2 pypi_0 pypi flask 1.1.1 py_0 anaconda freetype 2.9.1 ha9979f8_1 anaconda future 0.17.1 py37_0 anaconda gast 0.2.2 py37_0 anaconda get 2019.4.13 pypi_0 pypi get_terminal_size 1.0.0 h38e98db_0 anaconda gevent 1.4.0 py37he774522_0 anaconda glob2 0.7 py_0 anaconda google-pasta 0.1.7 pypi_0 pypi graphviz 2.38.0 4 anaconda greenlet 0.4.15 py37hfa6e2cd_0 anaconda grpcio 1.22.0 pypi_0 pypi h5py 2.9.0 py37h5e291fa_0 anaconda hdf5 1.10.4 h7ebc959_0 anaconda heapdict 1.0.0 py37_2 anaconda html5lib 1.0.1 py37_0 anaconda http-client 0.1.22 pypi_0 pypi hypothesis 4.34.0 pypi_0 pypi icc_rt 2019.0.0 h0cc432a_1 anaconda icu 58.2 ha66f8fd_1 anaconda idna 2.8 py37_0 anaconda imageio 2.4.1 pypi_0 pypi imageio-ffmpeg 0.3.0 pypi_0 pypi imagesize 1.1.0 py37_0 anaconda importlib_metadata 0.17 py37_1 anaconda imutils 0.5.2 pypi_0 pypi intel-openmp 2019.0 pypi_0 pypi ipykernel 5.1.1 py37h39e3cac_0 anaconda ipython 7.6.1 py37h39e3cac_0 anaconda ipython_genutils 0.2.0 py37_0 anaconda ipywidgets 7.5.0 py_0 anaconda isort 4.3.21 py37_0 anaconda itsdangerous 1.1.0 py37_0 anaconda jaraco-functools 2.0 pypi_0 pypi jdcal 1.4.1 py_0 anaconda jedi 0.13.3 py37_0 anaconda jinja2 2.10.1 py37_0 anaconda joblib 0.13.2 py37_0 anaconda jpeg 9b hb83a4c4_2 anaconda json5 0.8.4 py_0 anaconda jsonschema 3.0.1 py37_0 anaconda jupyter 1.0.0 py37_7 anaconda jupyter_client 5.3.1 py_0 anaconda jupyter_console 6.0.0 py37_0 anaconda jupyter_core 4.5.0 py_0 anaconda jupyterlab 1.0.2 py37hf63ae98_0 anaconda jupyterlab_server 1.0.0 py_0 anaconda keras 2.2.4 0 anaconda keras-applications 1.0.8 py_0 anaconda keras-base 2.2.4 py37_0 anaconda keras-preprocessing 1.1.0 py_1 anaconda keyring 18.0.0 py37_0 anaconda kiwisolver 1.1.0 py37ha925a31_0 anaconda krb5 1.16.1 hc04afaa_7 lazy-object-proxy 1.4.1 py37he774522_0 anaconda libarchive 3.3.3 h0643e63_5 anaconda libcurl 7.65.2 h2a8f88b_0 anaconda libiconv 1.15 h1df5818_7 anaconda liblief 0.9.0 ha925a31_2 anaconda libmklml 2019.0.5 0 anaconda libpng 1.6.37 h2a8f88b_0 anaconda libprotobuf 3.8.0 h7bd577a_0 anaconda libsodium 1.0.16 h9d3ae62_0 anaconda libssh2 1.8.2 h7a1dbc1_0 anaconda libtiff 4.0.10 hb898794_2 anaconda libxml2 2.9.9 h464c3ec_0 anaconda libxslt 1.1.33 h579f668_0 anaconda llvmlite 0.29.0 py37ha925a31_0 anaconda locket 0.2.0 py37_1 anaconda lxml 4.3.4 py37h1350720_0 anaconda lz4-c 1.8.1.2 h2fa13f4_0 anaconda lzo 2.10 h6df0209_2 anaconda m2w64-gcc-libgfortran 5.3.0 6 m2w64-gcc-libs 5.3.0 7 m2w64-gcc-libs-core 5.3.0 7 m2w64-gmp 6.1.0 2 m2w64-libwinpthread-git 5.0.0.4634.697f757 2 make-dataset 1.0 pypi_0 pypi markdown 3.1.1 py37_0 anaconda markupsafe 1.1.1 py37he774522_0 anaconda matplotlib 3.1.0 py37hc8f65d3_0 anaconda mccabe 0.6.1 py37_1 anaconda menuinst 1.4.16 py37he774522_0 anaconda mistune 0.8.4 py37he774522_0 anaconda mkl 2019.0 pypi_0 pypi mkl-service 2.0.2 py37he774522_0 anaconda mkl_fft 1.0.12 py37h14836fe_0 anaconda mkl_random 1.0.2 py37h343c172_0 anaconda mock 3.0.5 py37_0 anaconda more-itertools 7.0.0 py37_0 anaconda moviepy 1.0.0 pypi_0 pypi mpmath 1.1.0 py37_0 anaconda msgpack-python 0.6.1 py37h74a9793_1 anaconda msys2-conda-epoch 20160418 1 multipledispatch 0.6.0 py37_0 anaconda mysqlclient 1.4.2.post1 pypi_0 pypi navigator-updater 0.2.1 py37_0 anaconda nbconvert 5.5.0 py_0 anaconda nbformat 4.4.0 py37_0 anaconda networkx 2.3 py_0 anaconda ninja 1.9.0 py37h74a9793_0 anaconda nltk 3.4.4 py37_0 anaconda nose 1.3.7 py37_2 anaconda notebook 6.0.0 py37_0 anaconda numba 0.44.1 py37hf9181ef_0 anaconda numexpr 2.6.9 py37hdce8814_0 anaconda numpy 1.16.4 pypi_0 pypi numpy-base 1.16.4 py37hc3f5095_0 anaconda numpydoc 0.9.1 py_0 anaconda olefile 0.46 py37_0 anaconda opencv-contrib-python 4.1.0.25 pypi_0 pypi opencv-python 4.1.0.25 pypi_0 pypi openpyxl 2.6.2 py_0 anaconda openssl 1.1.1c he774522_1 anaconda packaging 19.0 py37_0 anaconda pandas 0.24.2 py37ha925a31_0 anaconda pandoc 2.2.3.2 0 anaconda pandocfilters 1.4.2 py37_1 anaconda parso 0.5.0 py_0 anaconda partd 1.0.0 py_0 anaconda path.py 12.0.1 py_0 anaconda pathlib2 2.3.4 py37_0 anaconda patsy 0.5.1 py37_0 anaconda pattern 3.6 pypi_0 pypi pdfminer-six 20181108 pypi_0 pypi pep8 1.7.1 py37_0 anaconda pickleshare 0.7.5 py37_0 anaconda pillow 6.1.0 py37hdc69c19_0 anaconda pip 19.1.1 py37_0 anaconda pkginfo 1.5.0.1 py37_0 anaconda pluggy 0.12.0 py_0 anaconda ply 3.11 py37_0 anaconda portend 2.5 pypi_0 pypi post 2019.4.13 pypi_0 pypi powershell_shortcut 0.0.1 2 anaconda proglog 0.1.9 pypi_0 pypi prometheus_client 0.7.1 py_0 anaconda prompt_toolkit 2.0.9 py37_0 anaconda protobuf 3.7.1 pypi_0 pypi psutil 5.6.3 py37he774522_0 anaconda public 2019.4.13 pypi_0 pypi py 1.8.0 py37_0 anaconda py-lief 0.9.0 py37ha925a31_2 anaconda pybind11 2.3.0 pypi_0 pypi pycodestyle 2.5.0 py37_0 anaconda pycosat 0.6.3 py37hfa6e2cd_0 anaconda pycparser 2.19 py37_0 anaconda pycrypto 2.6.1 py37hfa6e2cd_9 anaconda pycryptodome 3.8.2 pypi_0 pypi pycurl 7.43.0.3 py37h7a1dbc1_0 anaconda pydot 1.4.1 pypi_0 pypi pyflakes 2.1.1 py37_0 anaconda pygments 2.4.2 py_0 anaconda pylint 2.3.1 py37_0 anaconda pyodbc 4.0.26 py37ha925a31_0 anaconda pyopenssl 19.0.0 py37_0 anaconda pyparsing 2.4.0 py_0 anaconda pyqt 5.9.2 py37h6538335_2 anaconda pyreadline 2.1 py37_1 anaconda pyrsistent 0.14.11 py37he774522_0 anaconda pysocks 1.7.0 py37_0 anaconda pytables 3.5.2 py37h1da0976_1 anaconda pytest 5.0.1 py37_0 anaconda pytest-arraydiff 0.3 py37h39e3cac_0 anaconda pytest-astropy 0.5.0 py37_0 anaconda pytest-doctestplus 0.3.0 py37_0 anaconda pytest-openfiles 0.3.2 py37_0 anaconda pytest-remotedata 0.3.1 py37_0 anaconda python 3.7.3 h8c8aaf0_1 anaconda python-dateutil 2.8.0 py37_0 anaconda python-docx 0.8.10 pypi_0 pypi python-graphviz 0.11.1 pypi_0 pypi python-libarchive-c 2.8 py37_11 anaconda pytorch 1.2.0 py3.7_cpu_1 [cpuonly] pytorch pytube 9.5.1 pypi_0 pypi pytz 2019.1 py_0 anaconda pywavelets 1.0.3 py37h8c2d366_1 anaconda pywin32 223 py37hfa6e2cd_1 anaconda pywinpty 0.5.5 py37_1000 anaconda pyyaml 5.1.1 py37he774522_0 anaconda pyzmq 18.0.0 py37ha925a31_0 anaconda qt 5.9.7 vc14h73c81de_0 [vc14] anaconda qtawesome 0.5.7 py37_1 anaconda qtconsole 4.5.1 py_0 anaconda qtpy 1.8.0 py_0 anaconda query-string 2019.4.13 pypi_0 pypi request 2019.4.13 pypi_0 pypi requests 2.22.0 py37_0 anaconda rope 0.14.0 py_0 anaconda ruamel_yaml 0.15.46 py37hfa6e2cd_0 anaconda scikit-image 0.15.0 py37ha925a31_0 anaconda scikit-learn 0.21.2 py37h6288b17_0 anaconda scipy 1.3.0 pypi_0 pypi scipy-stack 0.0.5 pypi_0 pypi seaborn 0.9.0 py37_0 anaconda send2trash 1.5.0 py37_0 anaconda setuptools 41.1.0 pypi_0 pypi simplegeneric 0.8.1 py37_2 anaconda singledispatch 3.4.0.3 py37_0 anaconda sip 4.19.8 py37h6538335_0 anaconda six 1.12.0 py37_0 anaconda snappy 1.1.7 h777316e_3 anaconda snowballstemmer 1.9.0 py_0 anaconda sortedcollections 1.1.2 py37_0 anaconda sortedcontainers 2.1.0 py37_0 anaconda soupsieve 1.8 py37_0 anaconda sphinx 2.1.2 py_0 anaconda sphinxcontrib 1.0 py37_1 anaconda sphinxcontrib-applehelp 1.0.1 py_0 anaconda sphinxcontrib-devhelp 1.0.1 py_0 anaconda sphinxcontrib-htmlhelp 1.0.2 py_0 anaconda sphinxcontrib-jsmath 1.0.1 py_0 anaconda sphinxcontrib-qthelp 1.0.2 py_0 anaconda sphinxcontrib-serializinghtml 1.1.3 py_0 anaconda sphinxcontrib-websupport 1.1.2 py_0 anaconda spyder 3.3.6 py37_0 anaconda spyder-kernels 0.5.1 py37_0 anaconda sqlalchemy 1.3.5 py37he774522_0 anaconda sqlite 3.29.0 he774522_0 anaconda statsmodels 0.10.0 py37h8c2d366_0 anaconda summa 1.2.0 pypi_0 pypi sympy 1.4 py37_0 anaconda tbb 2019.4 h74a9793_0 anaconda tblib 1.4.0 py_0 anaconda tempora 1.14.1 pypi_0 pypi tensorboard 1.14.0 py37he3c9ec2_0 anaconda tensorboardx 1.8 pypi_0 pypi tensorflow 1.14.0 mkl_py37h7908ca0_0 anaconda tensorflow-base 1.14.0 mkl_py37ha978198_0 anaconda tensorflow-estimator 1.14.0 py_0 anaconda tensorflow-mkl 1.14.0 h4fcabd2_0 anaconda termcolor 1.1.0 pypi_0 pypi terminado 0.8.2 py37_0 anaconda testpath 0.4.2 py37_0 anaconda tk 8.6.8 hfa6e2cd_0 anaconda toolz 0.10.0 py_0 anaconda torchvision 0.4.0 py37_cpu [cpuonly] pytorch tornado 6.0.3 py37he774522_0 anaconda tqdm 4.32.1 py_0 anaconda traitlets 4.3.2 py37_0 anaconda typing 3.6.6 pypi_0 pypi typing-extensions 3.6.6 pypi_0 pypi unicodecsv 0.14.1 py37_0 anaconda urllib3 1.24.2 py37_0 anaconda validators 0.13.0 pypi_0 pypi vc 14.1 h0510ff6_4 anaconda vs2015_runtime 14.15.26706 h3a45250_4 anaconda wcwidth 0.1.7 py37_0 anaconda webencodings 0.5.1 py37_1 anaconda werkzeug 0.15.4 py_0 anaconda wheel 0.33.4 py37_0 anaconda widgetsnbextension 3.5.0 py37_0 anaconda win_inet_pton 1.1.0 py37_0 anaconda win_unicode_console 0.5 py37_0 anaconda wincertstore 0.2 py37_0 anaconda winpty 0.4.3 4 anaconda wrapt 1.11.2 py37he774522_0 anaconda xlrd 1.2.0 py37_0 anaconda xlsxwriter 1.1.8 py_0 anaconda xlwings 0.15.8 py37_0 anaconda xlwt 1.3.0 py37_0 anaconda xz 5.2.4 h2fa13f4_4 anaconda yaml 0.1.7 hc54c509_2 anaconda youtube-dl 2019.8.2 pypi_0 pypi zc-lockfile 1.4 pypi_0 pypi zeromq 4.3.1 h33f27b4_3 anaconda zict 1.0.0 py_0 anaconda zipp 0.5.1 py_0 anaconda zlib 1.2.11 h62dcd97_3 anaconda zstd 1.3.7 h508b16e_0 anaconda ```
2019/09/06
[ "https://Stackoverflow.com/questions/57814535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3204706/" ]
How did you install pytorch? It sounds like you installed pytorch without CUDA support. <https://pytorch.org/> has instructions for how to install pytorch with cuda support. In this case, we have the following command: `conda install pytorch torchvision cudatoolkit=10.1 -c pytorch` OR the command with latest cudatoolkit version.
Uninstalling the packages and reinstalling it with pip instead solved it for me. 1.`conda remove pytorch torchvision torchaudio cudatoolkit` 2.`pip3 install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu116`
57,814,535
I figured out this is a popular question, but still I couldn't find a solution for that. I'm trying to run a simple repo [Here](https://github.com/swathikirans/violence-recognition-pytorch) which uses `PyTorch`. Although I just upgraded my Pytorch to the latest CUDA version from pytorch.org (`1.2.0`), it still throws the same error. I'm on Windows 10 and use conda with python 3.7. ``` raise AssertionError("Torch not compiled with CUDA enabled") AssertionError: Torch not compiled with CUDA enabled ``` How to fix the problem? Here is my `conda list`: ``` # Name Version Build Channel _ipyw_jlab_nb_ext_conf 0.1.0 py37_0 anaconda _pytorch_select 1.1.0 cpu anaconda _tflow_select 2.3.0 mkl anaconda absl-py 0.7.1 pypi_0 pypi alabaster 0.7.12 py37_0 anaconda anaconda 2019.07 py37_0 anaconda anaconda-client 1.7.2 py37_0 anaconda anaconda-navigator 1.9.7 py37_0 anaconda anaconda-project 0.8.3 py_0 anaconda argparse 1.4.0 pypi_0 pypi asn1crypto 0.24.0 py37_0 anaconda astor 0.8.0 pypi_0 pypi astroid 2.2.5 py37_0 anaconda astropy 3.2.1 py37he774522_0 anaconda atomicwrites 1.3.0 py37_1 anaconda attrs 19.1.0 py37_1 anaconda babel 2.7.0 py_0 anaconda backcall 0.1.0 py37_0 anaconda backports 1.0 py_2 anaconda backports-csv 1.0.7 pypi_0 pypi backports-functools-lru-cache 1.5 pypi_0 pypi backports.functools_lru_cache 1.5 py_2 anaconda backports.os 0.1.1 py37_0 anaconda backports.shutil_get_terminal_size 1.0.0 py37_2 anaconda backports.tempfile 1.0 py_1 anaconda backports.weakref 1.0.post1 py_1 anaconda beautifulsoup4 4.7.1 py37_1 anaconda bitarray 0.9.3 py37he774522_0 anaconda bkcharts 0.2 py37_0 anaconda blas 1.0 mkl anaconda bleach 3.1.0 py37_0 anaconda blosc 1.16.3 h7bd577a_0 anaconda bokeh 1.2.0 py37_0 anaconda boto 2.49.0 py37_0 anaconda bottleneck 1.2.1 py37h452e1ab_1 anaconda bzip2 1.0.8 he774522_0 anaconda ca-certificates 2019.5.15 0 anaconda certifi 2019.6.16 py37_0 anaconda cffi 1.12.3 py37h7a1dbc1_0 anaconda chainer 6.2.0 pypi_0 pypi chardet 3.0.4 py37_1 anaconda cheroot 6.5.5 pypi_0 pypi cherrypy 18.1.2 pypi_0 pypi click 7.0 py37_0 anaconda cloudpickle 1.2.1 py_0 anaconda clyent 1.2.2 py37_1 anaconda colorama 0.4.1 py37_0 anaconda comtypes 1.1.7 py37_0 anaconda conda 4.7.11 py37_0 anaconda conda-build 3.18.9 py37_3 anaconda conda-env 2.6.0 1 anaconda conda-package-handling 1.3.11 py37_0 anaconda conda-verify 3.4.2 py_1 anaconda console_shortcut 0.1.1 3 anaconda constants 0.6.0 pypi_0 pypi contextlib2 0.5.5 py37_0 anaconda cpuonly 1.0 0 pytorch cryptography 2.7 py37h7a1dbc1_0 anaconda cudatoolkit 10.0.130 0 anaconda curl 7.65.2 h2a8f88b_0 anaconda cycler 0.10.0 py37_0 anaconda cython 0.29.12 py37ha925a31_0 anaconda cytoolz 0.10.0 py37he774522_0 anaconda dask 2.1.0 py_0 anaconda dask-core 2.1.0 py_0 anaconda decorator 4.4.0 py37_1 anaconda defusedxml 0.6.0 py_0 anaconda distributed 2.1.0 py_0 anaconda docutils 0.14 py37_0 anaconda entrypoints 0.3 py37_0 anaconda et_xmlfile 1.0.1 py37_0 anaconda ez-setup 0.9 pypi_0 pypi fastcache 1.1.0 py37he774522_0 anaconda fasttext 0.9.1 pypi_0 pypi feedparser 5.2.1 pypi_0 pypi ffmpeg 4.1.3 h6538335_0 conda-forge filelock 3.0.12 py_0 anaconda first 2.0.2 pypi_0 pypi flask 1.1.1 py_0 anaconda freetype 2.9.1 ha9979f8_1 anaconda future 0.17.1 py37_0 anaconda gast 0.2.2 py37_0 anaconda get 2019.4.13 pypi_0 pypi get_terminal_size 1.0.0 h38e98db_0 anaconda gevent 1.4.0 py37he774522_0 anaconda glob2 0.7 py_0 anaconda google-pasta 0.1.7 pypi_0 pypi graphviz 2.38.0 4 anaconda greenlet 0.4.15 py37hfa6e2cd_0 anaconda grpcio 1.22.0 pypi_0 pypi h5py 2.9.0 py37h5e291fa_0 anaconda hdf5 1.10.4 h7ebc959_0 anaconda heapdict 1.0.0 py37_2 anaconda html5lib 1.0.1 py37_0 anaconda http-client 0.1.22 pypi_0 pypi hypothesis 4.34.0 pypi_0 pypi icc_rt 2019.0.0 h0cc432a_1 anaconda icu 58.2 ha66f8fd_1 anaconda idna 2.8 py37_0 anaconda imageio 2.4.1 pypi_0 pypi imageio-ffmpeg 0.3.0 pypi_0 pypi imagesize 1.1.0 py37_0 anaconda importlib_metadata 0.17 py37_1 anaconda imutils 0.5.2 pypi_0 pypi intel-openmp 2019.0 pypi_0 pypi ipykernel 5.1.1 py37h39e3cac_0 anaconda ipython 7.6.1 py37h39e3cac_0 anaconda ipython_genutils 0.2.0 py37_0 anaconda ipywidgets 7.5.0 py_0 anaconda isort 4.3.21 py37_0 anaconda itsdangerous 1.1.0 py37_0 anaconda jaraco-functools 2.0 pypi_0 pypi jdcal 1.4.1 py_0 anaconda jedi 0.13.3 py37_0 anaconda jinja2 2.10.1 py37_0 anaconda joblib 0.13.2 py37_0 anaconda jpeg 9b hb83a4c4_2 anaconda json5 0.8.4 py_0 anaconda jsonschema 3.0.1 py37_0 anaconda jupyter 1.0.0 py37_7 anaconda jupyter_client 5.3.1 py_0 anaconda jupyter_console 6.0.0 py37_0 anaconda jupyter_core 4.5.0 py_0 anaconda jupyterlab 1.0.2 py37hf63ae98_0 anaconda jupyterlab_server 1.0.0 py_0 anaconda keras 2.2.4 0 anaconda keras-applications 1.0.8 py_0 anaconda keras-base 2.2.4 py37_0 anaconda keras-preprocessing 1.1.0 py_1 anaconda keyring 18.0.0 py37_0 anaconda kiwisolver 1.1.0 py37ha925a31_0 anaconda krb5 1.16.1 hc04afaa_7 lazy-object-proxy 1.4.1 py37he774522_0 anaconda libarchive 3.3.3 h0643e63_5 anaconda libcurl 7.65.2 h2a8f88b_0 anaconda libiconv 1.15 h1df5818_7 anaconda liblief 0.9.0 ha925a31_2 anaconda libmklml 2019.0.5 0 anaconda libpng 1.6.37 h2a8f88b_0 anaconda libprotobuf 3.8.0 h7bd577a_0 anaconda libsodium 1.0.16 h9d3ae62_0 anaconda libssh2 1.8.2 h7a1dbc1_0 anaconda libtiff 4.0.10 hb898794_2 anaconda libxml2 2.9.9 h464c3ec_0 anaconda libxslt 1.1.33 h579f668_0 anaconda llvmlite 0.29.0 py37ha925a31_0 anaconda locket 0.2.0 py37_1 anaconda lxml 4.3.4 py37h1350720_0 anaconda lz4-c 1.8.1.2 h2fa13f4_0 anaconda lzo 2.10 h6df0209_2 anaconda m2w64-gcc-libgfortran 5.3.0 6 m2w64-gcc-libs 5.3.0 7 m2w64-gcc-libs-core 5.3.0 7 m2w64-gmp 6.1.0 2 m2w64-libwinpthread-git 5.0.0.4634.697f757 2 make-dataset 1.0 pypi_0 pypi markdown 3.1.1 py37_0 anaconda markupsafe 1.1.1 py37he774522_0 anaconda matplotlib 3.1.0 py37hc8f65d3_0 anaconda mccabe 0.6.1 py37_1 anaconda menuinst 1.4.16 py37he774522_0 anaconda mistune 0.8.4 py37he774522_0 anaconda mkl 2019.0 pypi_0 pypi mkl-service 2.0.2 py37he774522_0 anaconda mkl_fft 1.0.12 py37h14836fe_0 anaconda mkl_random 1.0.2 py37h343c172_0 anaconda mock 3.0.5 py37_0 anaconda more-itertools 7.0.0 py37_0 anaconda moviepy 1.0.0 pypi_0 pypi mpmath 1.1.0 py37_0 anaconda msgpack-python 0.6.1 py37h74a9793_1 anaconda msys2-conda-epoch 20160418 1 multipledispatch 0.6.0 py37_0 anaconda mysqlclient 1.4.2.post1 pypi_0 pypi navigator-updater 0.2.1 py37_0 anaconda nbconvert 5.5.0 py_0 anaconda nbformat 4.4.0 py37_0 anaconda networkx 2.3 py_0 anaconda ninja 1.9.0 py37h74a9793_0 anaconda nltk 3.4.4 py37_0 anaconda nose 1.3.7 py37_2 anaconda notebook 6.0.0 py37_0 anaconda numba 0.44.1 py37hf9181ef_0 anaconda numexpr 2.6.9 py37hdce8814_0 anaconda numpy 1.16.4 pypi_0 pypi numpy-base 1.16.4 py37hc3f5095_0 anaconda numpydoc 0.9.1 py_0 anaconda olefile 0.46 py37_0 anaconda opencv-contrib-python 4.1.0.25 pypi_0 pypi opencv-python 4.1.0.25 pypi_0 pypi openpyxl 2.6.2 py_0 anaconda openssl 1.1.1c he774522_1 anaconda packaging 19.0 py37_0 anaconda pandas 0.24.2 py37ha925a31_0 anaconda pandoc 2.2.3.2 0 anaconda pandocfilters 1.4.2 py37_1 anaconda parso 0.5.0 py_0 anaconda partd 1.0.0 py_0 anaconda path.py 12.0.1 py_0 anaconda pathlib2 2.3.4 py37_0 anaconda patsy 0.5.1 py37_0 anaconda pattern 3.6 pypi_0 pypi pdfminer-six 20181108 pypi_0 pypi pep8 1.7.1 py37_0 anaconda pickleshare 0.7.5 py37_0 anaconda pillow 6.1.0 py37hdc69c19_0 anaconda pip 19.1.1 py37_0 anaconda pkginfo 1.5.0.1 py37_0 anaconda pluggy 0.12.0 py_0 anaconda ply 3.11 py37_0 anaconda portend 2.5 pypi_0 pypi post 2019.4.13 pypi_0 pypi powershell_shortcut 0.0.1 2 anaconda proglog 0.1.9 pypi_0 pypi prometheus_client 0.7.1 py_0 anaconda prompt_toolkit 2.0.9 py37_0 anaconda protobuf 3.7.1 pypi_0 pypi psutil 5.6.3 py37he774522_0 anaconda public 2019.4.13 pypi_0 pypi py 1.8.0 py37_0 anaconda py-lief 0.9.0 py37ha925a31_2 anaconda pybind11 2.3.0 pypi_0 pypi pycodestyle 2.5.0 py37_0 anaconda pycosat 0.6.3 py37hfa6e2cd_0 anaconda pycparser 2.19 py37_0 anaconda pycrypto 2.6.1 py37hfa6e2cd_9 anaconda pycryptodome 3.8.2 pypi_0 pypi pycurl 7.43.0.3 py37h7a1dbc1_0 anaconda pydot 1.4.1 pypi_0 pypi pyflakes 2.1.1 py37_0 anaconda pygments 2.4.2 py_0 anaconda pylint 2.3.1 py37_0 anaconda pyodbc 4.0.26 py37ha925a31_0 anaconda pyopenssl 19.0.0 py37_0 anaconda pyparsing 2.4.0 py_0 anaconda pyqt 5.9.2 py37h6538335_2 anaconda pyreadline 2.1 py37_1 anaconda pyrsistent 0.14.11 py37he774522_0 anaconda pysocks 1.7.0 py37_0 anaconda pytables 3.5.2 py37h1da0976_1 anaconda pytest 5.0.1 py37_0 anaconda pytest-arraydiff 0.3 py37h39e3cac_0 anaconda pytest-astropy 0.5.0 py37_0 anaconda pytest-doctestplus 0.3.0 py37_0 anaconda pytest-openfiles 0.3.2 py37_0 anaconda pytest-remotedata 0.3.1 py37_0 anaconda python 3.7.3 h8c8aaf0_1 anaconda python-dateutil 2.8.0 py37_0 anaconda python-docx 0.8.10 pypi_0 pypi python-graphviz 0.11.1 pypi_0 pypi python-libarchive-c 2.8 py37_11 anaconda pytorch 1.2.0 py3.7_cpu_1 [cpuonly] pytorch pytube 9.5.1 pypi_0 pypi pytz 2019.1 py_0 anaconda pywavelets 1.0.3 py37h8c2d366_1 anaconda pywin32 223 py37hfa6e2cd_1 anaconda pywinpty 0.5.5 py37_1000 anaconda pyyaml 5.1.1 py37he774522_0 anaconda pyzmq 18.0.0 py37ha925a31_0 anaconda qt 5.9.7 vc14h73c81de_0 [vc14] anaconda qtawesome 0.5.7 py37_1 anaconda qtconsole 4.5.1 py_0 anaconda qtpy 1.8.0 py_0 anaconda query-string 2019.4.13 pypi_0 pypi request 2019.4.13 pypi_0 pypi requests 2.22.0 py37_0 anaconda rope 0.14.0 py_0 anaconda ruamel_yaml 0.15.46 py37hfa6e2cd_0 anaconda scikit-image 0.15.0 py37ha925a31_0 anaconda scikit-learn 0.21.2 py37h6288b17_0 anaconda scipy 1.3.0 pypi_0 pypi scipy-stack 0.0.5 pypi_0 pypi seaborn 0.9.0 py37_0 anaconda send2trash 1.5.0 py37_0 anaconda setuptools 41.1.0 pypi_0 pypi simplegeneric 0.8.1 py37_2 anaconda singledispatch 3.4.0.3 py37_0 anaconda sip 4.19.8 py37h6538335_0 anaconda six 1.12.0 py37_0 anaconda snappy 1.1.7 h777316e_3 anaconda snowballstemmer 1.9.0 py_0 anaconda sortedcollections 1.1.2 py37_0 anaconda sortedcontainers 2.1.0 py37_0 anaconda soupsieve 1.8 py37_0 anaconda sphinx 2.1.2 py_0 anaconda sphinxcontrib 1.0 py37_1 anaconda sphinxcontrib-applehelp 1.0.1 py_0 anaconda sphinxcontrib-devhelp 1.0.1 py_0 anaconda sphinxcontrib-htmlhelp 1.0.2 py_0 anaconda sphinxcontrib-jsmath 1.0.1 py_0 anaconda sphinxcontrib-qthelp 1.0.2 py_0 anaconda sphinxcontrib-serializinghtml 1.1.3 py_0 anaconda sphinxcontrib-websupport 1.1.2 py_0 anaconda spyder 3.3.6 py37_0 anaconda spyder-kernels 0.5.1 py37_0 anaconda sqlalchemy 1.3.5 py37he774522_0 anaconda sqlite 3.29.0 he774522_0 anaconda statsmodels 0.10.0 py37h8c2d366_0 anaconda summa 1.2.0 pypi_0 pypi sympy 1.4 py37_0 anaconda tbb 2019.4 h74a9793_0 anaconda tblib 1.4.0 py_0 anaconda tempora 1.14.1 pypi_0 pypi tensorboard 1.14.0 py37he3c9ec2_0 anaconda tensorboardx 1.8 pypi_0 pypi tensorflow 1.14.0 mkl_py37h7908ca0_0 anaconda tensorflow-base 1.14.0 mkl_py37ha978198_0 anaconda tensorflow-estimator 1.14.0 py_0 anaconda tensorflow-mkl 1.14.0 h4fcabd2_0 anaconda termcolor 1.1.0 pypi_0 pypi terminado 0.8.2 py37_0 anaconda testpath 0.4.2 py37_0 anaconda tk 8.6.8 hfa6e2cd_0 anaconda toolz 0.10.0 py_0 anaconda torchvision 0.4.0 py37_cpu [cpuonly] pytorch tornado 6.0.3 py37he774522_0 anaconda tqdm 4.32.1 py_0 anaconda traitlets 4.3.2 py37_0 anaconda typing 3.6.6 pypi_0 pypi typing-extensions 3.6.6 pypi_0 pypi unicodecsv 0.14.1 py37_0 anaconda urllib3 1.24.2 py37_0 anaconda validators 0.13.0 pypi_0 pypi vc 14.1 h0510ff6_4 anaconda vs2015_runtime 14.15.26706 h3a45250_4 anaconda wcwidth 0.1.7 py37_0 anaconda webencodings 0.5.1 py37_1 anaconda werkzeug 0.15.4 py_0 anaconda wheel 0.33.4 py37_0 anaconda widgetsnbextension 3.5.0 py37_0 anaconda win_inet_pton 1.1.0 py37_0 anaconda win_unicode_console 0.5 py37_0 anaconda wincertstore 0.2 py37_0 anaconda winpty 0.4.3 4 anaconda wrapt 1.11.2 py37he774522_0 anaconda xlrd 1.2.0 py37_0 anaconda xlsxwriter 1.1.8 py_0 anaconda xlwings 0.15.8 py37_0 anaconda xlwt 1.3.0 py37_0 anaconda xz 5.2.4 h2fa13f4_4 anaconda yaml 0.1.7 hc54c509_2 anaconda youtube-dl 2019.8.2 pypi_0 pypi zc-lockfile 1.4 pypi_0 pypi zeromq 4.3.1 h33f27b4_3 anaconda zict 1.0.0 py_0 anaconda zipp 0.5.1 py_0 anaconda zlib 1.2.11 h62dcd97_3 anaconda zstd 1.3.7 h508b16e_0 anaconda ```
2019/09/06
[ "https://Stackoverflow.com/questions/57814535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3204706/" ]
This error is happening because of incorrect device. Make sure to run this snippet before every experiment. ``` device = "cuda" if torch.cuda.is_available() else "cpu" device ```
Uninstalling the packages and reinstalling it with pip instead solved it for me. 1.`conda remove pytorch torchvision torchaudio cudatoolkit` 2.`pip3 install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu116`
57,814,535
I figured out this is a popular question, but still I couldn't find a solution for that. I'm trying to run a simple repo [Here](https://github.com/swathikirans/violence-recognition-pytorch) which uses `PyTorch`. Although I just upgraded my Pytorch to the latest CUDA version from pytorch.org (`1.2.0`), it still throws the same error. I'm on Windows 10 and use conda with python 3.7. ``` raise AssertionError("Torch not compiled with CUDA enabled") AssertionError: Torch not compiled with CUDA enabled ``` How to fix the problem? Here is my `conda list`: ``` # Name Version Build Channel _ipyw_jlab_nb_ext_conf 0.1.0 py37_0 anaconda _pytorch_select 1.1.0 cpu anaconda _tflow_select 2.3.0 mkl anaconda absl-py 0.7.1 pypi_0 pypi alabaster 0.7.12 py37_0 anaconda anaconda 2019.07 py37_0 anaconda anaconda-client 1.7.2 py37_0 anaconda anaconda-navigator 1.9.7 py37_0 anaconda anaconda-project 0.8.3 py_0 anaconda argparse 1.4.0 pypi_0 pypi asn1crypto 0.24.0 py37_0 anaconda astor 0.8.0 pypi_0 pypi astroid 2.2.5 py37_0 anaconda astropy 3.2.1 py37he774522_0 anaconda atomicwrites 1.3.0 py37_1 anaconda attrs 19.1.0 py37_1 anaconda babel 2.7.0 py_0 anaconda backcall 0.1.0 py37_0 anaconda backports 1.0 py_2 anaconda backports-csv 1.0.7 pypi_0 pypi backports-functools-lru-cache 1.5 pypi_0 pypi backports.functools_lru_cache 1.5 py_2 anaconda backports.os 0.1.1 py37_0 anaconda backports.shutil_get_terminal_size 1.0.0 py37_2 anaconda backports.tempfile 1.0 py_1 anaconda backports.weakref 1.0.post1 py_1 anaconda beautifulsoup4 4.7.1 py37_1 anaconda bitarray 0.9.3 py37he774522_0 anaconda bkcharts 0.2 py37_0 anaconda blas 1.0 mkl anaconda bleach 3.1.0 py37_0 anaconda blosc 1.16.3 h7bd577a_0 anaconda bokeh 1.2.0 py37_0 anaconda boto 2.49.0 py37_0 anaconda bottleneck 1.2.1 py37h452e1ab_1 anaconda bzip2 1.0.8 he774522_0 anaconda ca-certificates 2019.5.15 0 anaconda certifi 2019.6.16 py37_0 anaconda cffi 1.12.3 py37h7a1dbc1_0 anaconda chainer 6.2.0 pypi_0 pypi chardet 3.0.4 py37_1 anaconda cheroot 6.5.5 pypi_0 pypi cherrypy 18.1.2 pypi_0 pypi click 7.0 py37_0 anaconda cloudpickle 1.2.1 py_0 anaconda clyent 1.2.2 py37_1 anaconda colorama 0.4.1 py37_0 anaconda comtypes 1.1.7 py37_0 anaconda conda 4.7.11 py37_0 anaconda conda-build 3.18.9 py37_3 anaconda conda-env 2.6.0 1 anaconda conda-package-handling 1.3.11 py37_0 anaconda conda-verify 3.4.2 py_1 anaconda console_shortcut 0.1.1 3 anaconda constants 0.6.0 pypi_0 pypi contextlib2 0.5.5 py37_0 anaconda cpuonly 1.0 0 pytorch cryptography 2.7 py37h7a1dbc1_0 anaconda cudatoolkit 10.0.130 0 anaconda curl 7.65.2 h2a8f88b_0 anaconda cycler 0.10.0 py37_0 anaconda cython 0.29.12 py37ha925a31_0 anaconda cytoolz 0.10.0 py37he774522_0 anaconda dask 2.1.0 py_0 anaconda dask-core 2.1.0 py_0 anaconda decorator 4.4.0 py37_1 anaconda defusedxml 0.6.0 py_0 anaconda distributed 2.1.0 py_0 anaconda docutils 0.14 py37_0 anaconda entrypoints 0.3 py37_0 anaconda et_xmlfile 1.0.1 py37_0 anaconda ez-setup 0.9 pypi_0 pypi fastcache 1.1.0 py37he774522_0 anaconda fasttext 0.9.1 pypi_0 pypi feedparser 5.2.1 pypi_0 pypi ffmpeg 4.1.3 h6538335_0 conda-forge filelock 3.0.12 py_0 anaconda first 2.0.2 pypi_0 pypi flask 1.1.1 py_0 anaconda freetype 2.9.1 ha9979f8_1 anaconda future 0.17.1 py37_0 anaconda gast 0.2.2 py37_0 anaconda get 2019.4.13 pypi_0 pypi get_terminal_size 1.0.0 h38e98db_0 anaconda gevent 1.4.0 py37he774522_0 anaconda glob2 0.7 py_0 anaconda google-pasta 0.1.7 pypi_0 pypi graphviz 2.38.0 4 anaconda greenlet 0.4.15 py37hfa6e2cd_0 anaconda grpcio 1.22.0 pypi_0 pypi h5py 2.9.0 py37h5e291fa_0 anaconda hdf5 1.10.4 h7ebc959_0 anaconda heapdict 1.0.0 py37_2 anaconda html5lib 1.0.1 py37_0 anaconda http-client 0.1.22 pypi_0 pypi hypothesis 4.34.0 pypi_0 pypi icc_rt 2019.0.0 h0cc432a_1 anaconda icu 58.2 ha66f8fd_1 anaconda idna 2.8 py37_0 anaconda imageio 2.4.1 pypi_0 pypi imageio-ffmpeg 0.3.0 pypi_0 pypi imagesize 1.1.0 py37_0 anaconda importlib_metadata 0.17 py37_1 anaconda imutils 0.5.2 pypi_0 pypi intel-openmp 2019.0 pypi_0 pypi ipykernel 5.1.1 py37h39e3cac_0 anaconda ipython 7.6.1 py37h39e3cac_0 anaconda ipython_genutils 0.2.0 py37_0 anaconda ipywidgets 7.5.0 py_0 anaconda isort 4.3.21 py37_0 anaconda itsdangerous 1.1.0 py37_0 anaconda jaraco-functools 2.0 pypi_0 pypi jdcal 1.4.1 py_0 anaconda jedi 0.13.3 py37_0 anaconda jinja2 2.10.1 py37_0 anaconda joblib 0.13.2 py37_0 anaconda jpeg 9b hb83a4c4_2 anaconda json5 0.8.4 py_0 anaconda jsonschema 3.0.1 py37_0 anaconda jupyter 1.0.0 py37_7 anaconda jupyter_client 5.3.1 py_0 anaconda jupyter_console 6.0.0 py37_0 anaconda jupyter_core 4.5.0 py_0 anaconda jupyterlab 1.0.2 py37hf63ae98_0 anaconda jupyterlab_server 1.0.0 py_0 anaconda keras 2.2.4 0 anaconda keras-applications 1.0.8 py_0 anaconda keras-base 2.2.4 py37_0 anaconda keras-preprocessing 1.1.0 py_1 anaconda keyring 18.0.0 py37_0 anaconda kiwisolver 1.1.0 py37ha925a31_0 anaconda krb5 1.16.1 hc04afaa_7 lazy-object-proxy 1.4.1 py37he774522_0 anaconda libarchive 3.3.3 h0643e63_5 anaconda libcurl 7.65.2 h2a8f88b_0 anaconda libiconv 1.15 h1df5818_7 anaconda liblief 0.9.0 ha925a31_2 anaconda libmklml 2019.0.5 0 anaconda libpng 1.6.37 h2a8f88b_0 anaconda libprotobuf 3.8.0 h7bd577a_0 anaconda libsodium 1.0.16 h9d3ae62_0 anaconda libssh2 1.8.2 h7a1dbc1_0 anaconda libtiff 4.0.10 hb898794_2 anaconda libxml2 2.9.9 h464c3ec_0 anaconda libxslt 1.1.33 h579f668_0 anaconda llvmlite 0.29.0 py37ha925a31_0 anaconda locket 0.2.0 py37_1 anaconda lxml 4.3.4 py37h1350720_0 anaconda lz4-c 1.8.1.2 h2fa13f4_0 anaconda lzo 2.10 h6df0209_2 anaconda m2w64-gcc-libgfortran 5.3.0 6 m2w64-gcc-libs 5.3.0 7 m2w64-gcc-libs-core 5.3.0 7 m2w64-gmp 6.1.0 2 m2w64-libwinpthread-git 5.0.0.4634.697f757 2 make-dataset 1.0 pypi_0 pypi markdown 3.1.1 py37_0 anaconda markupsafe 1.1.1 py37he774522_0 anaconda matplotlib 3.1.0 py37hc8f65d3_0 anaconda mccabe 0.6.1 py37_1 anaconda menuinst 1.4.16 py37he774522_0 anaconda mistune 0.8.4 py37he774522_0 anaconda mkl 2019.0 pypi_0 pypi mkl-service 2.0.2 py37he774522_0 anaconda mkl_fft 1.0.12 py37h14836fe_0 anaconda mkl_random 1.0.2 py37h343c172_0 anaconda mock 3.0.5 py37_0 anaconda more-itertools 7.0.0 py37_0 anaconda moviepy 1.0.0 pypi_0 pypi mpmath 1.1.0 py37_0 anaconda msgpack-python 0.6.1 py37h74a9793_1 anaconda msys2-conda-epoch 20160418 1 multipledispatch 0.6.0 py37_0 anaconda mysqlclient 1.4.2.post1 pypi_0 pypi navigator-updater 0.2.1 py37_0 anaconda nbconvert 5.5.0 py_0 anaconda nbformat 4.4.0 py37_0 anaconda networkx 2.3 py_0 anaconda ninja 1.9.0 py37h74a9793_0 anaconda nltk 3.4.4 py37_0 anaconda nose 1.3.7 py37_2 anaconda notebook 6.0.0 py37_0 anaconda numba 0.44.1 py37hf9181ef_0 anaconda numexpr 2.6.9 py37hdce8814_0 anaconda numpy 1.16.4 pypi_0 pypi numpy-base 1.16.4 py37hc3f5095_0 anaconda numpydoc 0.9.1 py_0 anaconda olefile 0.46 py37_0 anaconda opencv-contrib-python 4.1.0.25 pypi_0 pypi opencv-python 4.1.0.25 pypi_0 pypi openpyxl 2.6.2 py_0 anaconda openssl 1.1.1c he774522_1 anaconda packaging 19.0 py37_0 anaconda pandas 0.24.2 py37ha925a31_0 anaconda pandoc 2.2.3.2 0 anaconda pandocfilters 1.4.2 py37_1 anaconda parso 0.5.0 py_0 anaconda partd 1.0.0 py_0 anaconda path.py 12.0.1 py_0 anaconda pathlib2 2.3.4 py37_0 anaconda patsy 0.5.1 py37_0 anaconda pattern 3.6 pypi_0 pypi pdfminer-six 20181108 pypi_0 pypi pep8 1.7.1 py37_0 anaconda pickleshare 0.7.5 py37_0 anaconda pillow 6.1.0 py37hdc69c19_0 anaconda pip 19.1.1 py37_0 anaconda pkginfo 1.5.0.1 py37_0 anaconda pluggy 0.12.0 py_0 anaconda ply 3.11 py37_0 anaconda portend 2.5 pypi_0 pypi post 2019.4.13 pypi_0 pypi powershell_shortcut 0.0.1 2 anaconda proglog 0.1.9 pypi_0 pypi prometheus_client 0.7.1 py_0 anaconda prompt_toolkit 2.0.9 py37_0 anaconda protobuf 3.7.1 pypi_0 pypi psutil 5.6.3 py37he774522_0 anaconda public 2019.4.13 pypi_0 pypi py 1.8.0 py37_0 anaconda py-lief 0.9.0 py37ha925a31_2 anaconda pybind11 2.3.0 pypi_0 pypi pycodestyle 2.5.0 py37_0 anaconda pycosat 0.6.3 py37hfa6e2cd_0 anaconda pycparser 2.19 py37_0 anaconda pycrypto 2.6.1 py37hfa6e2cd_9 anaconda pycryptodome 3.8.2 pypi_0 pypi pycurl 7.43.0.3 py37h7a1dbc1_0 anaconda pydot 1.4.1 pypi_0 pypi pyflakes 2.1.1 py37_0 anaconda pygments 2.4.2 py_0 anaconda pylint 2.3.1 py37_0 anaconda pyodbc 4.0.26 py37ha925a31_0 anaconda pyopenssl 19.0.0 py37_0 anaconda pyparsing 2.4.0 py_0 anaconda pyqt 5.9.2 py37h6538335_2 anaconda pyreadline 2.1 py37_1 anaconda pyrsistent 0.14.11 py37he774522_0 anaconda pysocks 1.7.0 py37_0 anaconda pytables 3.5.2 py37h1da0976_1 anaconda pytest 5.0.1 py37_0 anaconda pytest-arraydiff 0.3 py37h39e3cac_0 anaconda pytest-astropy 0.5.0 py37_0 anaconda pytest-doctestplus 0.3.0 py37_0 anaconda pytest-openfiles 0.3.2 py37_0 anaconda pytest-remotedata 0.3.1 py37_0 anaconda python 3.7.3 h8c8aaf0_1 anaconda python-dateutil 2.8.0 py37_0 anaconda python-docx 0.8.10 pypi_0 pypi python-graphviz 0.11.1 pypi_0 pypi python-libarchive-c 2.8 py37_11 anaconda pytorch 1.2.0 py3.7_cpu_1 [cpuonly] pytorch pytube 9.5.1 pypi_0 pypi pytz 2019.1 py_0 anaconda pywavelets 1.0.3 py37h8c2d366_1 anaconda pywin32 223 py37hfa6e2cd_1 anaconda pywinpty 0.5.5 py37_1000 anaconda pyyaml 5.1.1 py37he774522_0 anaconda pyzmq 18.0.0 py37ha925a31_0 anaconda qt 5.9.7 vc14h73c81de_0 [vc14] anaconda qtawesome 0.5.7 py37_1 anaconda qtconsole 4.5.1 py_0 anaconda qtpy 1.8.0 py_0 anaconda query-string 2019.4.13 pypi_0 pypi request 2019.4.13 pypi_0 pypi requests 2.22.0 py37_0 anaconda rope 0.14.0 py_0 anaconda ruamel_yaml 0.15.46 py37hfa6e2cd_0 anaconda scikit-image 0.15.0 py37ha925a31_0 anaconda scikit-learn 0.21.2 py37h6288b17_0 anaconda scipy 1.3.0 pypi_0 pypi scipy-stack 0.0.5 pypi_0 pypi seaborn 0.9.0 py37_0 anaconda send2trash 1.5.0 py37_0 anaconda setuptools 41.1.0 pypi_0 pypi simplegeneric 0.8.1 py37_2 anaconda singledispatch 3.4.0.3 py37_0 anaconda sip 4.19.8 py37h6538335_0 anaconda six 1.12.0 py37_0 anaconda snappy 1.1.7 h777316e_3 anaconda snowballstemmer 1.9.0 py_0 anaconda sortedcollections 1.1.2 py37_0 anaconda sortedcontainers 2.1.0 py37_0 anaconda soupsieve 1.8 py37_0 anaconda sphinx 2.1.2 py_0 anaconda sphinxcontrib 1.0 py37_1 anaconda sphinxcontrib-applehelp 1.0.1 py_0 anaconda sphinxcontrib-devhelp 1.0.1 py_0 anaconda sphinxcontrib-htmlhelp 1.0.2 py_0 anaconda sphinxcontrib-jsmath 1.0.1 py_0 anaconda sphinxcontrib-qthelp 1.0.2 py_0 anaconda sphinxcontrib-serializinghtml 1.1.3 py_0 anaconda sphinxcontrib-websupport 1.1.2 py_0 anaconda spyder 3.3.6 py37_0 anaconda spyder-kernels 0.5.1 py37_0 anaconda sqlalchemy 1.3.5 py37he774522_0 anaconda sqlite 3.29.0 he774522_0 anaconda statsmodels 0.10.0 py37h8c2d366_0 anaconda summa 1.2.0 pypi_0 pypi sympy 1.4 py37_0 anaconda tbb 2019.4 h74a9793_0 anaconda tblib 1.4.0 py_0 anaconda tempora 1.14.1 pypi_0 pypi tensorboard 1.14.0 py37he3c9ec2_0 anaconda tensorboardx 1.8 pypi_0 pypi tensorflow 1.14.0 mkl_py37h7908ca0_0 anaconda tensorflow-base 1.14.0 mkl_py37ha978198_0 anaconda tensorflow-estimator 1.14.0 py_0 anaconda tensorflow-mkl 1.14.0 h4fcabd2_0 anaconda termcolor 1.1.0 pypi_0 pypi terminado 0.8.2 py37_0 anaconda testpath 0.4.2 py37_0 anaconda tk 8.6.8 hfa6e2cd_0 anaconda toolz 0.10.0 py_0 anaconda torchvision 0.4.0 py37_cpu [cpuonly] pytorch tornado 6.0.3 py37he774522_0 anaconda tqdm 4.32.1 py_0 anaconda traitlets 4.3.2 py37_0 anaconda typing 3.6.6 pypi_0 pypi typing-extensions 3.6.6 pypi_0 pypi unicodecsv 0.14.1 py37_0 anaconda urllib3 1.24.2 py37_0 anaconda validators 0.13.0 pypi_0 pypi vc 14.1 h0510ff6_4 anaconda vs2015_runtime 14.15.26706 h3a45250_4 anaconda wcwidth 0.1.7 py37_0 anaconda webencodings 0.5.1 py37_1 anaconda werkzeug 0.15.4 py_0 anaconda wheel 0.33.4 py37_0 anaconda widgetsnbextension 3.5.0 py37_0 anaconda win_inet_pton 1.1.0 py37_0 anaconda win_unicode_console 0.5 py37_0 anaconda wincertstore 0.2 py37_0 anaconda winpty 0.4.3 4 anaconda wrapt 1.11.2 py37he774522_0 anaconda xlrd 1.2.0 py37_0 anaconda xlsxwriter 1.1.8 py_0 anaconda xlwings 0.15.8 py37_0 anaconda xlwt 1.3.0 py37_0 anaconda xz 5.2.4 h2fa13f4_4 anaconda yaml 0.1.7 hc54c509_2 anaconda youtube-dl 2019.8.2 pypi_0 pypi zc-lockfile 1.4 pypi_0 pypi zeromq 4.3.1 h33f27b4_3 anaconda zict 1.0.0 py_0 anaconda zipp 0.5.1 py_0 anaconda zlib 1.2.11 h62dcd97_3 anaconda zstd 1.3.7 h508b16e_0 anaconda ```
2019/09/06
[ "https://Stackoverflow.com/questions/57814535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3204706/" ]
you dont have to install it via anaconda, you could install cuda from their [website](https://developer.nvidia.com/cuda-downloads). after install ends open a new terminal and check your cuda version with: ``` >>> nvcc --version nvcc: NVIDIA (R) Cuda compiler driver Copyright (c) 2005-2021 NVIDIA Corporation Built on Thu_Nov_18_09:52:33_Pacific_Standard_Time_2021 Cuda compilation tools, release 11.5, V11.5.119 Build cuda_11.5.r11.5/compiler.30672275_0 ``` my is V11.5 after, go [here](https://pytorch.org/get-started/locally/) and select your os and preferred package manager(pip or anaconda), and the cuda version you installed, and copy the generated install command, I got: ``` pip3 install torch==1.10.1+cu113 torchvision==0.11.2+cu113 torchaudio===0.10.1+cu113 -f https://download.pytorch.org/whl/cu113/torch_stable.html ``` notice that for me I had python 3.10 installed but my project run over 3.9 so either use virtual environment or run pip of your wanted base interpreter explicitly (for example `C:\Software\Python\Python39\python.exe -m pip install .....`) else you will be stuck with `Could not find a version that satisfies the requirement torch` errors after, open python console and check for cuda availability ```py >>> import torch >>> torch.cuda.is_available() True ```
This error is happening because of incorrect device. Make sure to run this snippet before every experiment. ``` device = "cuda" if torch.cuda.is_available() else "cpu" device ```
10,891,670
I'm using the [runwithfriends](http://apps.facebook.com/runwithfriends) example app to learn canvas programming and GAE. I can upload the sample code to GAE without any errors. Here are my config.py and app.yaml files: ### conf.py: ``` # Facebook Application ID and Secret. FACEBOOK_APP_ID = '' FACEBOOK_APP_SECRET = '' # Canvas Page name. FACEBOOK_CANVAS_NAME = 'blah' # A random token for use with the Real-time API. FACEBOOK_REALTIME_VERIFY_TOKEN = 'RANDOM TOKEN' # The external URL this application is available at where the Real-time API will # send it's pings. EXTERNAL_HREF = 'http://blah.appspot.com' # Facebook User IDs of admins. The poor mans admin system. ADMIN_USER_IDS = [''] ``` ### app.yaml ``` application: blah version: 1 runtime: python api_version: 1 handlers: - url: /(.*\.(html|css|js|gif|jpg|png|ico)) static_files: static/\1 upload: static/.* expiration: "1d" - url: .* script: main.py - url: /task/.* script: main.py login: admin ``` Accessing the demo app on their GAE works just fine. When I take the [exact same code](https://github.com/fbsamples/runwithfriends), except for the changes I need to run under my own GAE account, the app won't work. I can login to the app using my account and the app shows up under my Apps menu. So, OAuth is good. Every time I go to access the main page, I'm always redirected to the iframe showing I use the app (can't show that image, runwithfriends app is over quota as I type this) but won't go to this iframe: ![runwithfriends app window](https://i.stack.imgur.com/kM2XN.png) at all. I've looked at and understand how url routing works: ``` def main(): routes = [ (r'/', RecentRunsHandler), (r'/user/(.*)', UserRunsHandler), (r'/run', RunHandler), (r'/realtime', RealtimeHandler), (r'/task/refresh-user/(.*)', RefreshUserHandler), ] application = webapp.WSGIApplication(routes, debug=os.environ.get('SERVER_SOFTWARE', '').startswith('Dev')) util.run_wsgi_app(application) ``` All the handlers are there with what looks like correct post/get methods. There are no errors logged in my GAE instance either, such as 404 or 405. When I first use `http://localhost:8080`, I see plenty of 200s and nothing else. I started out using dev\_appengine.py but had to move development to GAE because of my HTTPS security setting. I disabled HTTPS temporarily but still always get redirected to the apps.facebook.com/path no matter what and can't keep all my development within dev\_appengine.py. Don't know if that's related to my issue or not. Since the demo works (when not over quota), I'm sure the problem is with my own GAE instance, or configuration within FB to use my GAE, I just for the life of me can't figure out. I'm using Eclipse with PyDev and GAE plugins. ### Update Adding the app's FB configuration and the window that's displayed after I login to the app. Sandbox: ![Sandbox](https://i.stack.imgur.com/yoJk4.png) Redirects: ![Redirects](https://i.stack.imgur.com/u4F67.png) Running under my GAE, this is the only page that is returned: ![Only page displayed](https://i.stack.imgur.com/leesm.png)
2012/06/05
[ "https://Stackoverflow.com/questions/10891670", "https://Stackoverflow.com", "https://Stackoverflow.com/users/137527/" ]
Read the [documentation for `__del__`](http://docs.python.org/reference/datamodel.html#object.__del__) and [for the garbage collector](http://docs.python.org/library/gc.html#gc.garbage). `__del__` doesn't do what you probably think it does, nor does `del`. `__del__` is not necessarily called when you do a `del`, and may never be called in case of circular references. All `del` does is decrement the reference count by 1.
Because the garbage collector has no way of knowing which can safely be deleted first.
10,891,670
I'm using the [runwithfriends](http://apps.facebook.com/runwithfriends) example app to learn canvas programming and GAE. I can upload the sample code to GAE without any errors. Here are my config.py and app.yaml files: ### conf.py: ``` # Facebook Application ID and Secret. FACEBOOK_APP_ID = '' FACEBOOK_APP_SECRET = '' # Canvas Page name. FACEBOOK_CANVAS_NAME = 'blah' # A random token for use with the Real-time API. FACEBOOK_REALTIME_VERIFY_TOKEN = 'RANDOM TOKEN' # The external URL this application is available at where the Real-time API will # send it's pings. EXTERNAL_HREF = 'http://blah.appspot.com' # Facebook User IDs of admins. The poor mans admin system. ADMIN_USER_IDS = [''] ``` ### app.yaml ``` application: blah version: 1 runtime: python api_version: 1 handlers: - url: /(.*\.(html|css|js|gif|jpg|png|ico)) static_files: static/\1 upload: static/.* expiration: "1d" - url: .* script: main.py - url: /task/.* script: main.py login: admin ``` Accessing the demo app on their GAE works just fine. When I take the [exact same code](https://github.com/fbsamples/runwithfriends), except for the changes I need to run under my own GAE account, the app won't work. I can login to the app using my account and the app shows up under my Apps menu. So, OAuth is good. Every time I go to access the main page, I'm always redirected to the iframe showing I use the app (can't show that image, runwithfriends app is over quota as I type this) but won't go to this iframe: ![runwithfriends app window](https://i.stack.imgur.com/kM2XN.png) at all. I've looked at and understand how url routing works: ``` def main(): routes = [ (r'/', RecentRunsHandler), (r'/user/(.*)', UserRunsHandler), (r'/run', RunHandler), (r'/realtime', RealtimeHandler), (r'/task/refresh-user/(.*)', RefreshUserHandler), ] application = webapp.WSGIApplication(routes, debug=os.environ.get('SERVER_SOFTWARE', '').startswith('Dev')) util.run_wsgi_app(application) ``` All the handlers are there with what looks like correct post/get methods. There are no errors logged in my GAE instance either, such as 404 or 405. When I first use `http://localhost:8080`, I see plenty of 200s and nothing else. I started out using dev\_appengine.py but had to move development to GAE because of my HTTPS security setting. I disabled HTTPS temporarily but still always get redirected to the apps.facebook.com/path no matter what and can't keep all my development within dev\_appengine.py. Don't know if that's related to my issue or not. Since the demo works (when not over quota), I'm sure the problem is with my own GAE instance, or configuration within FB to use my GAE, I just for the life of me can't figure out. I'm using Eclipse with PyDev and GAE plugins. ### Update Adding the app's FB configuration and the window that's displayed after I login to the app. Sandbox: ![Sandbox](https://i.stack.imgur.com/yoJk4.png) Redirects: ![Redirects](https://i.stack.imgur.com/u4F67.png) Running under my GAE, this is the only page that is returned: ![Only page displayed](https://i.stack.imgur.com/leesm.png)
2012/06/05
[ "https://Stackoverflow.com/questions/10891670", "https://Stackoverflow.com", "https://Stackoverflow.com/users/137527/" ]
This is not true anymore since python 3.4. See [PEP-442](https://www.python.org/dev/peps/pep-0442/).
Because the garbage collector has no way of knowing which can safely be deleted first.
10,891,670
I'm using the [runwithfriends](http://apps.facebook.com/runwithfriends) example app to learn canvas programming and GAE. I can upload the sample code to GAE without any errors. Here are my config.py and app.yaml files: ### conf.py: ``` # Facebook Application ID and Secret. FACEBOOK_APP_ID = '' FACEBOOK_APP_SECRET = '' # Canvas Page name. FACEBOOK_CANVAS_NAME = 'blah' # A random token for use with the Real-time API. FACEBOOK_REALTIME_VERIFY_TOKEN = 'RANDOM TOKEN' # The external URL this application is available at where the Real-time API will # send it's pings. EXTERNAL_HREF = 'http://blah.appspot.com' # Facebook User IDs of admins. The poor mans admin system. ADMIN_USER_IDS = [''] ``` ### app.yaml ``` application: blah version: 1 runtime: python api_version: 1 handlers: - url: /(.*\.(html|css|js|gif|jpg|png|ico)) static_files: static/\1 upload: static/.* expiration: "1d" - url: .* script: main.py - url: /task/.* script: main.py login: admin ``` Accessing the demo app on their GAE works just fine. When I take the [exact same code](https://github.com/fbsamples/runwithfriends), except for the changes I need to run under my own GAE account, the app won't work. I can login to the app using my account and the app shows up under my Apps menu. So, OAuth is good. Every time I go to access the main page, I'm always redirected to the iframe showing I use the app (can't show that image, runwithfriends app is over quota as I type this) but won't go to this iframe: ![runwithfriends app window](https://i.stack.imgur.com/kM2XN.png) at all. I've looked at and understand how url routing works: ``` def main(): routes = [ (r'/', RecentRunsHandler), (r'/user/(.*)', UserRunsHandler), (r'/run', RunHandler), (r'/realtime', RealtimeHandler), (r'/task/refresh-user/(.*)', RefreshUserHandler), ] application = webapp.WSGIApplication(routes, debug=os.environ.get('SERVER_SOFTWARE', '').startswith('Dev')) util.run_wsgi_app(application) ``` All the handlers are there with what looks like correct post/get methods. There are no errors logged in my GAE instance either, such as 404 or 405. When I first use `http://localhost:8080`, I see plenty of 200s and nothing else. I started out using dev\_appengine.py but had to move development to GAE because of my HTTPS security setting. I disabled HTTPS temporarily but still always get redirected to the apps.facebook.com/path no matter what and can't keep all my development within dev\_appengine.py. Don't know if that's related to my issue or not. Since the demo works (when not over quota), I'm sure the problem is with my own GAE instance, or configuration within FB to use my GAE, I just for the life of me can't figure out. I'm using Eclipse with PyDev and GAE plugins. ### Update Adding the app's FB configuration and the window that's displayed after I login to the app. Sandbox: ![Sandbox](https://i.stack.imgur.com/yoJk4.png) Redirects: ![Redirects](https://i.stack.imgur.com/u4F67.png) Running under my GAE, this is the only page that is returned: ![Only page displayed](https://i.stack.imgur.com/leesm.png)
2012/06/05
[ "https://Stackoverflow.com/questions/10891670", "https://Stackoverflow.com", "https://Stackoverflow.com/users/137527/" ]
Read the [documentation for `__del__`](http://docs.python.org/reference/datamodel.html#object.__del__) and [for the garbage collector](http://docs.python.org/library/gc.html#gc.garbage). `__del__` doesn't do what you probably think it does, nor does `del`. `__del__` is not necessarily called when you do a `del`, and may never be called in case of circular references. All `del` does is decrement the reference count by 1.
Read this [link](https://stackoverflow.com/questions/6104535/i-dont-understand-this-python-del-behaviour). I think this will help you. > > `del` doesn't call `__del__` > > > `del` in the way you are using removes a local variable. `__del__` is called when the object is destroyed. Python as a language makes no guarantees as to when it will destroy an object. > > > ----Update Edit---- Answer to `Some implicit del operation happens?` Read this [link](https://stackoverflow.com/a/9796689/379941) will help you > > Python doesn't make any guarantees about when `__del__` is called, or whether it is called at all. As it is, `__del__` methods are unlikely to be called if the object is part of a reference cycle, because even if the cycle as a whole is cleaned up, Python has no way to decide where to break the cycle and in what order the `__del__` methods (if any) should be called. Because of `__del__`'s rather quirky semantics (in order to call `__del__` the refcount of the object is temporarily increased, and the `__del__` method can prevent destruction of the object by storing the reference somewhere else) what happens in other implementations is a bit of a crapshoot. (I don't remember the exact details in current Jython, but it has changed a few times in the past.) > > > That said, in CPython, if `__del__` is called, it's called as soon as the reference count drops to zero (since refcounting is the only way `__del__` methods are called, and the only chance CPython has of calling `__del__` is when the actual refcount is changed.) > > >
10,891,670
I'm using the [runwithfriends](http://apps.facebook.com/runwithfriends) example app to learn canvas programming and GAE. I can upload the sample code to GAE without any errors. Here are my config.py and app.yaml files: ### conf.py: ``` # Facebook Application ID and Secret. FACEBOOK_APP_ID = '' FACEBOOK_APP_SECRET = '' # Canvas Page name. FACEBOOK_CANVAS_NAME = 'blah' # A random token for use with the Real-time API. FACEBOOK_REALTIME_VERIFY_TOKEN = 'RANDOM TOKEN' # The external URL this application is available at where the Real-time API will # send it's pings. EXTERNAL_HREF = 'http://blah.appspot.com' # Facebook User IDs of admins. The poor mans admin system. ADMIN_USER_IDS = [''] ``` ### app.yaml ``` application: blah version: 1 runtime: python api_version: 1 handlers: - url: /(.*\.(html|css|js|gif|jpg|png|ico)) static_files: static/\1 upload: static/.* expiration: "1d" - url: .* script: main.py - url: /task/.* script: main.py login: admin ``` Accessing the demo app on their GAE works just fine. When I take the [exact same code](https://github.com/fbsamples/runwithfriends), except for the changes I need to run under my own GAE account, the app won't work. I can login to the app using my account and the app shows up under my Apps menu. So, OAuth is good. Every time I go to access the main page, I'm always redirected to the iframe showing I use the app (can't show that image, runwithfriends app is over quota as I type this) but won't go to this iframe: ![runwithfriends app window](https://i.stack.imgur.com/kM2XN.png) at all. I've looked at and understand how url routing works: ``` def main(): routes = [ (r'/', RecentRunsHandler), (r'/user/(.*)', UserRunsHandler), (r'/run', RunHandler), (r'/realtime', RealtimeHandler), (r'/task/refresh-user/(.*)', RefreshUserHandler), ] application = webapp.WSGIApplication(routes, debug=os.environ.get('SERVER_SOFTWARE', '').startswith('Dev')) util.run_wsgi_app(application) ``` All the handlers are there with what looks like correct post/get methods. There are no errors logged in my GAE instance either, such as 404 or 405. When I first use `http://localhost:8080`, I see plenty of 200s and nothing else. I started out using dev\_appengine.py but had to move development to GAE because of my HTTPS security setting. I disabled HTTPS temporarily but still always get redirected to the apps.facebook.com/path no matter what and can't keep all my development within dev\_appengine.py. Don't know if that's related to my issue or not. Since the demo works (when not over quota), I'm sure the problem is with my own GAE instance, or configuration within FB to use my GAE, I just for the life of me can't figure out. I'm using Eclipse with PyDev and GAE plugins. ### Update Adding the app's FB configuration and the window that's displayed after I login to the app. Sandbox: ![Sandbox](https://i.stack.imgur.com/yoJk4.png) Redirects: ![Redirects](https://i.stack.imgur.com/u4F67.png) Running under my GAE, this is the only page that is returned: ![Only page displayed](https://i.stack.imgur.com/leesm.png)
2012/06/05
[ "https://Stackoverflow.com/questions/10891670", "https://Stackoverflow.com", "https://Stackoverflow.com/users/137527/" ]
This is not true anymore since python 3.4. See [PEP-442](https://www.python.org/dev/peps/pep-0442/).
Read this [link](https://stackoverflow.com/questions/6104535/i-dont-understand-this-python-del-behaviour). I think this will help you. > > `del` doesn't call `__del__` > > > `del` in the way you are using removes a local variable. `__del__` is called when the object is destroyed. Python as a language makes no guarantees as to when it will destroy an object. > > > ----Update Edit---- Answer to `Some implicit del operation happens?` Read this [link](https://stackoverflow.com/a/9796689/379941) will help you > > Python doesn't make any guarantees about when `__del__` is called, or whether it is called at all. As it is, `__del__` methods are unlikely to be called if the object is part of a reference cycle, because even if the cycle as a whole is cleaned up, Python has no way to decide where to break the cycle and in what order the `__del__` methods (if any) should be called. Because of `__del__`'s rather quirky semantics (in order to call `__del__` the refcount of the object is temporarily increased, and the `__del__` method can prevent destruction of the object by storing the reference somewhere else) what happens in other implementations is a bit of a crapshoot. (I don't remember the exact details in current Jython, but it has changed a few times in the past.) > > > That said, in CPython, if `__del__` is called, it's called as soon as the reference count drops to zero (since refcounting is the only way `__del__` methods are called, and the only chance CPython has of calling `__del__` is when the actual refcount is changed.) > > >
53,784,485
I am using python to collect temperature data but only want to store the last 24 hours of data. I am currently generating my .csv file with this ``` while True: tempC = mcp.temperature tempF = tempC * 9 / 5 + 32 timestamp = datetime.datetime.now().strftime("%y-%m-%d %H:%M ") f = open("24hr.csv", "a") f.write(timestamp) f.write(',{}'.format(tempF)) f.write("\n") f.close() ``` The .csv looks like this The .csv this outputs looks like this ``` 18-12-13 10:58 ,44.7125 18-12-13 11:03 ,44.6 18-12-13 11:08 ,44.6 18-12-13 11:13 ,44.4875 18-12-13 11:18 ,44.6 18-12-13 11:23 ,44.4875 18-12-13 11:28 ,44.7125 ``` I don't want to roll over, just keep the last 24 hours of data. Since I am sampling data every 5 minutes I should end up with 144 lines in my CSV after 24 hours. so if I use readlines() I can tell how many lines I have but how do I get rid of any lines that are older than 24 hours? This is what I came up with which obviously doesn't work. Suggestions? ``` f = open("24hr.csv","r") lines = f.readlines() f.close() if lines => 144: f = open("24hr.csv","w") for line in lines: if line <= "timestamp"+","+"tempF"+\n": f.write(line) f.close() ```
2018/12/14
[ "https://Stackoverflow.com/questions/53784485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10792002/" ]
You've done most of the work already. I've got a couple of suggestions. 1. Use `with`. This will mean that if there's an error mid-way through your program and an exception is raised, the file will be closed properly. 2. Parse the timestamp from the file and compare it with the current time. 3. Use `len` to check the length of a `list`. Here's the amended program: ``` import datetime with open("24hr.csv","r") as f: lines = f.readlines() # read out the contents of the file if len(lines) >= 144: yesterday = datetime.datetime.now() - datetime.timedelta(days=1) with open("24hr.csv","w") as f: for line in lines: line_time_string = line.split(",")[0] line_time = datetime.datetime.strptime(line_time_string, "%y-%m-%d %H:%M ") if line_time > yesterday: # if the line's time is after yesterday f.write(line) # write it back into the file ``` This code's not very clean (doesn't conform to PEP-8) but you see the general process.
Are u using linux ? If u jus need last 144 lines u can try ``` tail -n 144 file.csv ``` U can find tail for windows too, I got one with CMDer. If u have to use python and u have small file which fit in RAM, load it with readlines() into list, cut it (lst = lst[:144]) and rewrite. If u dont shure how many lines u have - parse it with <https://docs.python.org/3.7/library/csv.html> , parse time into python datetime (its similar like u write time originaly) and write lines by condition
53,784,485
I am using python to collect temperature data but only want to store the last 24 hours of data. I am currently generating my .csv file with this ``` while True: tempC = mcp.temperature tempF = tempC * 9 / 5 + 32 timestamp = datetime.datetime.now().strftime("%y-%m-%d %H:%M ") f = open("24hr.csv", "a") f.write(timestamp) f.write(',{}'.format(tempF)) f.write("\n") f.close() ``` The .csv looks like this The .csv this outputs looks like this ``` 18-12-13 10:58 ,44.7125 18-12-13 11:03 ,44.6 18-12-13 11:08 ,44.6 18-12-13 11:13 ,44.4875 18-12-13 11:18 ,44.6 18-12-13 11:23 ,44.4875 18-12-13 11:28 ,44.7125 ``` I don't want to roll over, just keep the last 24 hours of data. Since I am sampling data every 5 minutes I should end up with 144 lines in my CSV after 24 hours. so if I use readlines() I can tell how many lines I have but how do I get rid of any lines that are older than 24 hours? This is what I came up with which obviously doesn't work. Suggestions? ``` f = open("24hr.csv","r") lines = f.readlines() f.close() if lines => 144: f = open("24hr.csv","w") for line in lines: if line <= "timestamp"+","+"tempF"+\n": f.write(line) f.close() ```
2018/12/14
[ "https://Stackoverflow.com/questions/53784485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10792002/" ]
You've done most of the work already. I've got a couple of suggestions. 1. Use `with`. This will mean that if there's an error mid-way through your program and an exception is raised, the file will be closed properly. 2. Parse the timestamp from the file and compare it with the current time. 3. Use `len` to check the length of a `list`. Here's the amended program: ``` import datetime with open("24hr.csv","r") as f: lines = f.readlines() # read out the contents of the file if len(lines) >= 144: yesterday = datetime.datetime.now() - datetime.timedelta(days=1) with open("24hr.csv","w") as f: for line in lines: line_time_string = line.split(",")[0] line_time = datetime.datetime.strptime(line_time_string, "%y-%m-%d %H:%M ") if line_time > yesterday: # if the line's time is after yesterday f.write(line) # write it back into the file ``` This code's not very clean (doesn't conform to PEP-8) but you see the general process.
Given that 288 lines will not take up much memory, I think is perfectly fine just reading the lines, truncating the file, and putting back the desired lines: ``` # Unless you are working in a system with limited memory # reading 288 lines isn't much def remove_old_entries(file_): file_.seek(0) # Just in case go to start lines = file_.readlines()[-288:] # Read the last 288 lines file_.truncate(0) # Empty the file file_.writelines(lines) # Put back just the desired lines return _file while True: tempC = mcp.temperature tempF = tempC * 9 / 5 + 32 timestamp = datetime.datetime.now().strftime("%y-%m-%d %H:%M ") with open("24hr.csv", "r+") as file_: file_ = remove_old_entries(file_) # Consider that the function will return the file at the end file_.write('{},{}\n'.format(timestamp, tempF)) # I hope mcp.temperature is blocking or you are sleeping out the 5min # else this file reading in an infinite loop will get out of hand # time.sleep(300) # Call me maybe ```
53,784,485
I am using python to collect temperature data but only want to store the last 24 hours of data. I am currently generating my .csv file with this ``` while True: tempC = mcp.temperature tempF = tempC * 9 / 5 + 32 timestamp = datetime.datetime.now().strftime("%y-%m-%d %H:%M ") f = open("24hr.csv", "a") f.write(timestamp) f.write(',{}'.format(tempF)) f.write("\n") f.close() ``` The .csv looks like this The .csv this outputs looks like this ``` 18-12-13 10:58 ,44.7125 18-12-13 11:03 ,44.6 18-12-13 11:08 ,44.6 18-12-13 11:13 ,44.4875 18-12-13 11:18 ,44.6 18-12-13 11:23 ,44.4875 18-12-13 11:28 ,44.7125 ``` I don't want to roll over, just keep the last 24 hours of data. Since I am sampling data every 5 minutes I should end up with 144 lines in my CSV after 24 hours. so if I use readlines() I can tell how many lines I have but how do I get rid of any lines that are older than 24 hours? This is what I came up with which obviously doesn't work. Suggestions? ``` f = open("24hr.csv","r") lines = f.readlines() f.close() if lines => 144: f = open("24hr.csv","w") for line in lines: if line <= "timestamp"+","+"tempF"+\n": f.write(line) f.close() ```
2018/12/14
[ "https://Stackoverflow.com/questions/53784485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10792002/" ]
You've done most of the work already. I've got a couple of suggestions. 1. Use `with`. This will mean that if there's an error mid-way through your program and an exception is raised, the file will be closed properly. 2. Parse the timestamp from the file and compare it with the current time. 3. Use `len` to check the length of a `list`. Here's the amended program: ``` import datetime with open("24hr.csv","r") as f: lines = f.readlines() # read out the contents of the file if len(lines) >= 144: yesterday = datetime.datetime.now() - datetime.timedelta(days=1) with open("24hr.csv","w") as f: for line in lines: line_time_string = line.split(",")[0] line_time = datetime.datetime.strptime(line_time_string, "%y-%m-%d %H:%M ") if line_time > yesterday: # if the line's time is after yesterday f.write(line) # write it back into the file ``` This code's not very clean (doesn't conform to PEP-8) but you see the general process.
If you are on Linux or likes, the right approach is to implement [logrotaion](https://manpages.debian.org/jessie/logrotate/logrotate.8.en.html)
47,128,570
I have a set of data that looks like the following: ``` index 902.4 909.4 915.3 n 0.6 0.3 1.4 n.1 0.4 0.3 1.3 n.2 0.3 0.2 1.1 n.3 0.2 0.2 1.3 n.4 0.4 0.3 1.4 DCIS 0.3 1.6 DCIS.1 0.3 1.2 DCIS.2 1.1 DCIS.3 0.2 1.2 DCIS.4 0.2 1.3 DCIS.5 0.2 0.1 1.5 br_1 0.5 0.4 1.4 br_1.1 0.2 1.3 br_1.2 0.5 0.2 1.4 br_1.3 0.5 0.2 1.6 br_1.4 1.4 ``` with the regular python indexing for the column[0]. The below is a code that I've written with lots of help from members of Stackoverflow: ``` nh = pd.ExcelFile(file) df = pd.read_excel(nh) df = df.set_index('Samples').transpose() df = df.reset_index() df_n = df.loc[df['index'].str.startswith('n')] df_DCIS = df.loc[df['index'].str.startswith('DCIS')] df_br1234 = df.loc[df['index'].str.startswith('br')] #plt.tight_layout() for i in range(1, df.shape[1]): plt.figure() df_n.iloc[:, i].hist(histtype='step', color='k', label='N') df_DCIS.iloc[:, i].hist(histtype='step', color='r', label='DCIS') df_br1234.iloc[:, i].hist(histtype='step', color='orange', label='IDC') plt.legend(loc='center left', bbox_to_anchor=(1, 0.5), fancybox=True, shadow=True) plt.title("Histograms for " + df.columns[i], loc='center') plt.show() ``` This creates multiple figures with cut-off legend (this was not cut off when the figure was made by pycharm). However, the plt.title gives an error message saying TypeError: must be str, not float. I do understand that the columns of the different dataframes are floating numbers, and when I type print(df.columns), it says dtype is object. Is there a way to convert the float object to str? I tried using ``` plt.title("Histograms for " + df.columns[i].astype('str')) ``` but it said float object has no attribute astype.
2017/11/06
[ "https://Stackoverflow.com/questions/47128570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8147329/" ]
You can use this: ``` plt.title("Histograms for " + str(df.columns[i])) ```
Try ``` plt.title("Histograms for {0:.2f}".format(df.columns[i])) ``` The characters inside the curly brackets are from the [Format Specification Mini-Language](https://docs.python.org/3/library/string.html#format-specification-mini-language). This example formats a float with 2 decimal places. If you follow the link you'll see lots of other options.
47,128,570
I have a set of data that looks like the following: ``` index 902.4 909.4 915.3 n 0.6 0.3 1.4 n.1 0.4 0.3 1.3 n.2 0.3 0.2 1.1 n.3 0.2 0.2 1.3 n.4 0.4 0.3 1.4 DCIS 0.3 1.6 DCIS.1 0.3 1.2 DCIS.2 1.1 DCIS.3 0.2 1.2 DCIS.4 0.2 1.3 DCIS.5 0.2 0.1 1.5 br_1 0.5 0.4 1.4 br_1.1 0.2 1.3 br_1.2 0.5 0.2 1.4 br_1.3 0.5 0.2 1.6 br_1.4 1.4 ``` with the regular python indexing for the column[0]. The below is a code that I've written with lots of help from members of Stackoverflow: ``` nh = pd.ExcelFile(file) df = pd.read_excel(nh) df = df.set_index('Samples').transpose() df = df.reset_index() df_n = df.loc[df['index'].str.startswith('n')] df_DCIS = df.loc[df['index'].str.startswith('DCIS')] df_br1234 = df.loc[df['index'].str.startswith('br')] #plt.tight_layout() for i in range(1, df.shape[1]): plt.figure() df_n.iloc[:, i].hist(histtype='step', color='k', label='N') df_DCIS.iloc[:, i].hist(histtype='step', color='r', label='DCIS') df_br1234.iloc[:, i].hist(histtype='step', color='orange', label='IDC') plt.legend(loc='center left', bbox_to_anchor=(1, 0.5), fancybox=True, shadow=True) plt.title("Histograms for " + df.columns[i], loc='center') plt.show() ``` This creates multiple figures with cut-off legend (this was not cut off when the figure was made by pycharm). However, the plt.title gives an error message saying TypeError: must be str, not float. I do understand that the columns of the different dataframes are floating numbers, and when I type print(df.columns), it says dtype is object. Is there a way to convert the float object to str? I tried using ``` plt.title("Histograms for " + df.columns[i].astype('str')) ``` but it said float object has no attribute astype.
2017/11/06
[ "https://Stackoverflow.com/questions/47128570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8147329/" ]
You can use this: ``` plt.title("Histograms for " + str(df.columns[i])) ```
If you don't want the plots to be attached together, I'd suggest avoiding `subplots()` entirely. Instead, separate each plot with `plt.show()`: ``` cols = ["902.4", "909.4", "915.3"] data = [{"df":df_n, "color":"k", "label":"N"}, {"df":df_DCIS, "color":"r", "label":"DCIS"}, {"df":df_br1234, "color":"orange", "label":"IDC"}] for col in cols: for dataset in data: dataset["df"][col].hist(histtype='step', color=dataset["color"], label=dataset["label"]) plt.title(f"{dataset['label']} for {col}") plt.savefig(f"{dataset['label']}_for_{col}_plot.png") plt.show() ```
62,741,775
With my python script below, I wanted to check if a cron job is defined in my linux (centOS 7.5) server, and if it doesn't exist, I will add one by using python-crontab module.. It was working well until I gave CRONTAB -R to delete existing cron jobs and when I re-execute my python script, it is saying cronjob exists even after they were removed using crontab -r.. ``` import os from crontab import CronTab cron = CronTab(user="ansible") job = cron.new(command='echo hello_world') job.minute.every(1) basic_command = "* * * * * echo hello_world" basic_iter = cron.find_command("hello_world") for item in basic_iter: if str(item) == basic_command: print("crontab job already exist", item) break else: job.enable() cron.write() print("cronjob does not exist and added successfully.. please see \"crontab -l\" ") break ``` list of current cron jobs ``` [ansible@node1 ansible]$ crontab -l no crontab for ansible ``` [user - ansible] `python code results:` ``` crontab job already exist * * * * * echo hello_world ``` It was working until I removed cron jobs using command `crontab -r` and now my python output is saying that cron job already exists. Not sure what my mistake was - please help.. (or if there is any better way to find cron jobs in local user, please help with that).
2020/07/05
[ "https://Stackoverflow.com/questions/62741775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11999777/" ]
The problem is that you have initialized a new Cron job before checking if it exists. You assumed that `Cron.find_command()` is only identifying enabled cron jobs. But it also identifies cronjobs that are created, but not enabled yet. So, you have to check if the cronjob exists before creating a new job. Then, if it does not exist, you can create a new cron job and enable it. You can try the below code: ``` import os from crontab import CronTab cron = CronTab("ansible") basic_command = "* * * * * echo hello_world" basic_iter = cron.find_command("hello_world") exsist=False for item in basic_iter: if str(item) == basic_command: print("crontab job already exist", item) exsist=True break if not exsist: job = cron.new(command='echo hello_world') job.minute.every(1) job.enable() cron.write() print("cronjob does not exist and added successfully.. please see \"crontab -l\" ") ```
Another Solution might be to add the items to an list as the output of the find command is an generator object but by putting the items into an list makes it easier to work on. This is what I did to solve the problem you had Below here based on everything else already being initialized ``` List_A=[] basic_iter = cron.find_command("hello world") for item in basic_iter: List_A.append(item) #From there you can do more but here are 2 examples if len(List_A) == 0: #create cronjob else: #don't create cron job #or you could do a for loop comparing if you want to iterate for i in List_A: if i =="hello world": don't create cron job else: create cron job ``` Hope this helps sorry for formatting this is my first time
46,418,897
I have a list as shown below which contain some dictionaries. ``` dlist=[ { "a":1, "b":[1,2] }, { "a":3, "b":[4,5] }, { "a":1, "b":[1,2,3] } ] ``` I want the result to be as in this form as shown below ``` dlist=[ { "a":1, "b":[1,2,3] }, { "a":3, "b":[4,5] } ] ``` I can solve this using multiple iteration of loops and comparison, but is there a pythonic way?
2017/09/26
[ "https://Stackoverflow.com/questions/46418897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6858122/" ]
Here is a solution that uses a temporary defaultdict: ```python from collections import defaultdict dd = defaultdict(set) # create temporary defaultdict for d in dlist: dd[d["a"]] |= set(d["b"]) # union set(b) for each a l = [{"a":k, "b":list(v)} for k,v in dd.items()] # generate result list ``` [Try it online!](https://tio.run/##XY7BCoMwDIbvfYrgqYUyULeL4JOUHtRUVqytaCYM57O76g4Tc0ry5//zDW96Bp9tGzo7UakWBrGSKilS@WvrpFCpzDRbJfur@Um9y8dFvXhlHnXNWDuGHprgnGnIBj@B7YcwEqBpq5cjtA0xRCjPCz4ZEqwNIyBYDwdmAYgKVfykNXxKiCc8jnWiBXPRrpYdopMHwG7gs1hhz@jkfKTgzZLpJy4i1TBaT@C27Qs "Python 2 – Try It Online")
if My understanding is right ``` uniques, theNewList = set(), [] for d in dlist: cur = d["a"] # Avoid multiple lookups of the same thing if cur not in uniques: theNewList.append(d) uniques.add(cur) print(theNewList) ```
18,305,026
I want to monitor a dir , and the dir has sub dirs and in subdir there are somes files with `.md`. (maybe there are some other files, such as \*.swp...) I only want to monitor the .md files, I have read the doc, and there is only a `ExcludeFilter`, and in the issue : <https://github.com/seb-m/pyinotify/issues/31> says, only dir can be filter but not files. Now what I do is to filter in `process_*` functions to check the `event.name` by `fnmatch`. So if I only want to monitor the specified suffix files, is there a better way? Thanks. This is the main code I have written: ``` !/usr/bin/env python # -*- coding: utf-8 -*- import pyinotify import fnmatch def suffix_filter(fn): suffixes = ["*.md", "*.markdown"] for suffix in suffixes: if fnmatch.fnmatch(fn, suffix): return False return True class EventHandler(pyinotify.ProcessEvent): def process_IN_CREATE(self, event): if not suffix_filter(event.name): print "Creating:", event.pathname def process_IN_DELETE(self, event): if not suffix_filter(event.name): print "Removing:", event.pathname def process_IN_MODIFY(self, event): if not suffix_filter(event.name): print "Modifing:", event.pathname def process_default(self, event): print "Default:", event.pathname ```
2013/08/19
[ "https://Stackoverflow.com/questions/18305026", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1276501/" ]
I think you basically have the right idea, but that it could be implemented more easily. The `ProcessEvent` class in the **pyinotify** module already has a hook you can use to filter the processing of events. It's specified via an optional `pevent` keyword argument given on the call to the constructor and is saved in the instance's `self.pevent` attribute. The default value is `None`. It's value is used in the class' `__call__()` method as shown in the following snippet from the `pyinotify.py` source file: ``` def __call__(self, event): stop_chaining = False if self.pevent is not None: # By default methods return None so we set as guideline # that methods asking for stop chaining must explicitly # return non None or non False values, otherwise the default # behavior will be to accept chain call to the corresponding # local method. stop_chaining = self.pevent(event) if not stop_chaining: return _ProcessEvent.__call__(self, event) ``` So you could use it only allow events for files with certain suffixes (aka extensions) with something like this: ``` SUFFIXES = {".md", ".markdown"} def suffix_filter(event): # return True to stop processing of event (to "stop chaining") return os.path.splitext(event.name)[1] not in SUFFIXES processevent = ProcessEvent(pevent=suffix_filter) ```
There's nothing particularly wrong with your solution, but you want your inotify handler to be as fast as possible, so there are a few optimizations you can make. You should move your match suffixes out of your function, so the compiler only builds them once: ``` EXTS = set([".md", ".markdown"]) ``` I made them a set so you can do a more efficient match: ``` def suffix_filter(fn): ext = os.path.splitext(fn)[1] if ext in EXTS: return False return True ``` I'm only presuming that `os.path.splitext` and a set search are faster than an iterative `fnmatch`, but this may not be true for your really small list of extensions - you should test it. (Note: I've mirrored your code above where you return False when you make a match, but I'm not convinced that's what you want - it is at the very least not very clear to someone reading your code)
18,305,026
I want to monitor a dir , and the dir has sub dirs and in subdir there are somes files with `.md`. (maybe there are some other files, such as \*.swp...) I only want to monitor the .md files, I have read the doc, and there is only a `ExcludeFilter`, and in the issue : <https://github.com/seb-m/pyinotify/issues/31> says, only dir can be filter but not files. Now what I do is to filter in `process_*` functions to check the `event.name` by `fnmatch`. So if I only want to monitor the specified suffix files, is there a better way? Thanks. This is the main code I have written: ``` !/usr/bin/env python # -*- coding: utf-8 -*- import pyinotify import fnmatch def suffix_filter(fn): suffixes = ["*.md", "*.markdown"] for suffix in suffixes: if fnmatch.fnmatch(fn, suffix): return False return True class EventHandler(pyinotify.ProcessEvent): def process_IN_CREATE(self, event): if not suffix_filter(event.name): print "Creating:", event.pathname def process_IN_DELETE(self, event): if not suffix_filter(event.name): print "Removing:", event.pathname def process_IN_MODIFY(self, event): if not suffix_filter(event.name): print "Modifing:", event.pathname def process_default(self, event): print "Default:", event.pathname ```
2013/08/19
[ "https://Stackoverflow.com/questions/18305026", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1276501/" ]
I think you basically have the right idea, but that it could be implemented more easily. The `ProcessEvent` class in the **pyinotify** module already has a hook you can use to filter the processing of events. It's specified via an optional `pevent` keyword argument given on the call to the constructor and is saved in the instance's `self.pevent` attribute. The default value is `None`. It's value is used in the class' `__call__()` method as shown in the following snippet from the `pyinotify.py` source file: ``` def __call__(self, event): stop_chaining = False if self.pevent is not None: # By default methods return None so we set as guideline # that methods asking for stop chaining must explicitly # return non None or non False values, otherwise the default # behavior will be to accept chain call to the corresponding # local method. stop_chaining = self.pevent(event) if not stop_chaining: return _ProcessEvent.__call__(self, event) ``` So you could use it only allow events for files with certain suffixes (aka extensions) with something like this: ``` SUFFIXES = {".md", ".markdown"} def suffix_filter(event): # return True to stop processing of event (to "stop chaining") return os.path.splitext(event.name)[1] not in SUFFIXES processevent = ProcessEvent(pevent=suffix_filter) ```
You can use the `__call__` method of `ProcessEvent` to centralize the call to `suffix_filter`: ``` class EventHandler(pyinotify.ProcessEvent): def __call__(self, event): if not suffix_filter(event.name): super(EventHandler, self).__call__(event) def process_IN_CREATE(self, event): print "Creating:", event.pathname def process_IN_DELETE(self, event): print "Removing:", event.pathname def process_IN_MODIFY(self, event): print "Modifying:", event.pathname ```
40,613,590
I would like to design a function `f(x : float, up : bool)` with these input/output: ``` # 2 decimals part rounded up (up = True) f(142.452, True) = 142.46 f(142.449, True) = 142.45 # 2 decimals part rounded down (up = False) f(142.452, False) = 142.45 f(142.449, False) = 142.44 ``` Now, I know about Python's `round` built-in function but it will always round `142.449` up, which is not what I want. Is there a way to do this in a nicer pythonic way than to do a bunch of float comparisons with epsilons (prone to errors)?
2016/11/15
[ "https://Stackoverflow.com/questions/40613590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1974842/" ]
Have you considered a mathematical approach using `floor` and `ceil`? If you always want to round to 2 digits, then you could premultiply the number to be rounded by 100, then perform the rounding to the nearest integer and then divide again by 100. ``` from math import floor, ceil def rounder(num, up=True): digits = 2 mul = 10**digits if up: return ceil(num * mul)/mul else: return floor(num*mul)/mul ```
`math.ceil()` rounds up, and `math.floor()` rounds down. So, the following is an example of how to use it: ``` import math def f(x, b): if b: return (math.ceil(100*x) / 100) else: return (math.floor(100*x) / 100) ``` This function should do exactly what you want.
40,613,590
I would like to design a function `f(x : float, up : bool)` with these input/output: ``` # 2 decimals part rounded up (up = True) f(142.452, True) = 142.46 f(142.449, True) = 142.45 # 2 decimals part rounded down (up = False) f(142.452, False) = 142.45 f(142.449, False) = 142.44 ``` Now, I know about Python's `round` built-in function but it will always round `142.449` up, which is not what I want. Is there a way to do this in a nicer pythonic way than to do a bunch of float comparisons with epsilons (prone to errors)?
2016/11/15
[ "https://Stackoverflow.com/questions/40613590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1974842/" ]
Have you considered a mathematical approach using `floor` and `ceil`? If you always want to round to 2 digits, then you could premultiply the number to be rounded by 100, then perform the rounding to the nearest integer and then divide again by 100. ``` from math import floor, ceil def rounder(num, up=True): digits = 2 mul = 10**digits if up: return ceil(num * mul)/mul else: return floor(num*mul)/mul ```
You can also perform some mathematical logic if you do not want to use any explicit function as: ``` def f(num, up): num = num * 100 if up and num != int(num): # if up and "float' value != 'int' value num += 1 return int(num) / (100.0) ``` Here, the idea is if `up` is `True` and `int` value of number is not equal to `float` value then increase the number by 1. Else it will be same as the original number
40,613,590
I would like to design a function `f(x : float, up : bool)` with these input/output: ``` # 2 decimals part rounded up (up = True) f(142.452, True) = 142.46 f(142.449, True) = 142.45 # 2 decimals part rounded down (up = False) f(142.452, False) = 142.45 f(142.449, False) = 142.44 ``` Now, I know about Python's `round` built-in function but it will always round `142.449` up, which is not what I want. Is there a way to do this in a nicer pythonic way than to do a bunch of float comparisons with epsilons (prone to errors)?
2016/11/15
[ "https://Stackoverflow.com/questions/40613590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1974842/" ]
You can also perform some mathematical logic if you do not want to use any explicit function as: ``` def f(num, up): num = num * 100 if up and num != int(num): # if up and "float' value != 'int' value num += 1 return int(num) / (100.0) ``` Here, the idea is if `up` is `True` and `int` value of number is not equal to `float` value then increase the number by 1. Else it will be same as the original number
`math.ceil()` rounds up, and `math.floor()` rounds down. So, the following is an example of how to use it: ``` import math def f(x, b): if b: return (math.ceil(100*x) / 100) else: return (math.floor(100*x) / 100) ``` This function should do exactly what you want.
5,104,366
users, I have a basic question concerning inheritance (in python). I have two classes and one of them is inherited from the other like ``` class p: def __init__(self,name): self.pname = name class c(p): def __init__(self,name): self.cname = name ``` Is there any possibility that I can create a parent object and several child objects which refer to the SAME parent object? It should work like that that the parent object contains several variables and whenever I access the corresponding variables from a child I actually access the variable form the parent. I.e. if I change it for one child it is changed also for all other childes and the data are only stored once in memory (and not copied for each child...) Thank you in advance. Here is a possible workaround which I do not consider as so nice ``` class P: def __init__(self, name): self.pname = name class C: def __init__(self, name,pobject): self.pobject = pobject self.cname = name ``` Is this really the state of the art or do there exist other concepts? Sebastian Thank you all for helping me, also with the name conventions :) But I am still not very satisfied. Maybe I give a more advanced example to stress what I really want to do. ``` class P: data = "shareddata" def __init__(self,newdata): self.data = newdata def printname(self): print self.name class C(P): def __init__(self,name): self.name = name ``` Now I can do the following ``` In [33]: c1 = test.C("name1") In [34]: c2 = test.C("name2") In [35]: c1.printname() name1 In [36]: c2.printname() name2 In [37]: c1.data Out[37]: 'shareddata' In [38]: c2.data Out[38]: 'shareddata' ``` And this is so far exactly what I want. There is a variable name which is different for every child and the parent class accesses the individual variables. Normal inheritance. Then there is the variable data which comes from the parent class and every child access it. However, now the following does not work any more ``` In [39]: c1.data = "tst" In [40]: c2.data Out[40]: 'shareddata' In [41]: c1.data Out[41]: 'tst' ``` I want the change in c1.data to affect also c2.data since I want the variable to be shared, somehow a global variable of this parent class. And more than that. I also want to create different instances of P, each having its own data variable. And when I create a new C object I want to specify from which P object data should be inhetited i.e. shared.... UPDATE: remark to the comment of @eyquem: Thanks for this, it is going into the direction I want. However, now the `__class__.pvar` is shared among all objects of the class. What I want is that several instances of P may have a different pvar. Lets assume P1 has pvar=1 and P2 has pvar=2. Then I want to create children C1a, C1b, C1c which are related to P1, i.e. if I say C1a.pvar it should acess pvar from P1. Then I create C2a, C2b, C2c and if I access i.e. C2b.pvar I want to access pvar from P2. Since the class C inherits pvar from the class P pvar is known to C. My naive idea is that if I create a new instance of C I should be able to specify which (existing) P object should be used as the parent object and not to create a completely new P object as it is done when calling `P.__init__` inside of the `__init__` of C... It sounds simple to me, maybe I forget something... UPDATE: So I found [this discussion](http://www.velocityreviews.com/forums/t356880-can-you-create-an-instance-of-a-subclass-with-an-existing-instance-of-the-base-class.html) which is pretty much my question Any suggestions? UPDATE: The method .**class**.\_*subclasses*\_ seems to be not existing any more.. UPDATE: Here is onother link: [link to discussion](http://bytes.com/topic/python/answers/834541-using-existing-instance-parent) There it is solved by copying. But I do not want to copy the parent class since I would like that it exists only once... UPDATE: Sorry for leaving the discussion yesterday, I am a bit ill... And thank you for the posts! I will now read through them. I thought about it a bit more and here is a possible solution I found ``` class P(object): def __init__(self,pvar): self.pobject = None self._pvar = pvar @property def pvar(self): if self.pobject != None: return self.pobject.pvar else: return self._pvar @pvar.setter def pvar(self,val): if self.pobject != None: self.pobject.pvar = val else: self._pvar=val def printname(self): print self.name class C(P): def __init__(self,name,pobject): #<-- The same default `P()` is # used for all instances of `C`, # unless pobject is explicitly defined. P.__init__(self,None) self.name = name self.pobject = pobject p1 = P("1") p2 = P("2") c1a = C("c1a",p1) c1b = C("c1b",p1) c1c = C("c1c",p1) c2a = C("c2a",p2) c2b = C("c2b",p2) c2c = C("c2c",p2) print id(c1a.pvar) print id(c1b.pvar) print id(c1c.pvar) print id(c2a.pvar) print id(c2b.pvar) print id(c2c.pvar) print id(p1.pvar) print id(p2.pvar) print id(c1a.name) print id(c1b.name) print id(c1c.name) print id(c2a.name) print id(c2b.name) print id(c2c.name) ``` It is a bit cumbersome and I hope that there is a simpler way to achieve this. But it has the feature that pvar is only mentioned in the class P and the class C does not know about pvar as it should be according to my understanding of inheritance. Nevertheless when I create a new instance of C I can specify an existing instance of P which will be stored in the variable pobject. When the variable pvar is accessed actually pvar of the P-instance stored in this variable is accessed... The output is given by ``` 3078326816 3078326816 3078326816 3074996544 3074996544 3074996544 3078326816 3074996544 156582944 156583040 156583200 156583232 156583296 156583360 ``` I will read now through your last comments, all the best, Sebastian UPDATE: I think the most elegant way would be the following (which DOES NOT work) ``` class P(object): def __init__(self,pvar): self.pvar = pvar def printname(self): print self.name class C(P): def __init__(self,name,pobject): P = pobject self.name = name ``` I think python should allow for this... UPDATE: Ok, now I found a way to achieve this, due to the explanations by eyquem. But Since this is really a hack there should be an official version for the same... ``` def replaceinstance(parent,child): for item in parent.__dict__.items(): child.__dict__.__setitem__(item[0],item[1]) print item class P(object): def __init__(self,pvar): self.pvar = pvar def printname(self): print self.name class C(P): def __init__(self,name,pobject): P.__init__(self,None) replaceinstance(pobject,self) self.name = name p1 = P("1") p2 = P("2") c1a = C("c1a",p1) c1b = C("c1b",p1) c1c = C("c1c",p1) c2a = C("c2a",p2) c2b = C("c2b",p2) c2c = C("c2c",p2) print id(c1a.pvar) print id(c1b.pvar) print id(c1c.pvar) print id(c2a.pvar) print id(c2b.pvar) print id(c2c.pvar) print id(p1.pvar) print id(p2.pvar) print id(c1a.name) print id(c1b.name) print id(c1c.name) print id(c2a.name) print id(c2b.name) print id(c2c.name) ``` the output is the same as above ``` 3077745184 3077745184 3077745184 3074414912 3074414912 3074414912 3077745184 3074414912 144028416 144028448 144028480 144028512 144028544 144028576 ``` UPDATE: Even if the id's seem to be right, the last code does not work as is clear from this test ``` c1a.pvar = "newpvar1" print c1a.pvar print c1b.pvar print c1c.pvar print c2a.pvar print c2b.pvar print c2c.pvar print p1.pvar print p2.pvar ``` it has the output ``` newpvar1 1 1 2 2 2 1 2 ``` However the version I posted first works: ``` class P(object): def __init__(self,pvar): self.pobject = None self._pvar = pvar @property def pvar(self): if self.pobject != None: return self.pobject.pvar else: return self._pvar @pvar.setter def pvar(self,val): if self.pobject != None: self.pobject.pvar = val else: self._pvar=val def printname(self): print self.name class C(P): def __init__(self,name,pobject): #<-- The same default `P()` is # used for all instances of `C`, # unless pobject is explicitly defined. P.__init__(self,None) self.name = name self.pobject = pobject p1 = P("1") p2 = P("2") c1a = C("c1a",p1) c1b = C("c1b",p1) c1c = C("c1c",p1) c2a = C("c2a",p2) c2b = C("c2b",p2) c2c = C("c2c",p2) print id(c1a.pvar) print id(c1b.pvar) print id(c1c.pvar) print id(c2a.pvar) print id(c2b.pvar) print id(c2c.pvar) print id(p1.pvar) print id(p2.pvar) print id(c1a.name) print id(c1b.name) print id(c1c.name) print id(c2a.name) print id(c2b.name) print id(c2c.name) print "testing\n" c1a.printname() c1b.printname() c1c.printname() c2a.printname() c2b.printname() c2c.printname() print "\n" c1a.name = "c1anewname" c2b.name = "c2bnewname" c1a.printname() c1b.printname() c1c.printname() c2a.printname() c2b.printname() c2c.printname() print "pvar\n" print c1a.pvar print c1b.pvar print c1c.pvar print c2a.pvar print c2b.pvar print c2c.pvar print p1.pvar print p2.pvar print "\n" c1a.pvar = "newpvar1" print c1a.pvar print c1b.pvar print c1c.pvar print c2a.pvar print c2b.pvar print c2c.pvar print p1.pvar print p2.pvar print "\n" c2c.pvar = "newpvar2" print c1a.pvar print c1b.pvar print c1c.pvar print c2a.pvar print c2b.pvar print c2c.pvar print p1.pvar print p2.pvar ``` with the output ``` 3077745184 3077745184 3077745184 3074414912 3074414912 3074414912 3077745184 3074414912 144028416 144028448 144028480 144028512 144028544 144028576 testing c1a c1b c1c c2a c2b c2c c1anewname c1b c1c c2a c2bnewname c2c pvar 1 1 1 2 2 2 1 2 newpvar1 newpvar1 newpvar1 2 2 2 newpvar1 2 newpvar1 newpvar1 newpvar1 newpvar2 newpvar2 newpvar2 newpvar1 newpvar2 ``` Does anybody know why it is like that? I probably do not understand the internal way python works with this `__dict__` so well...
2011/02/24
[ "https://Stackoverflow.com/questions/5104366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/632263/" ]
> > It should work like that that the parent object contains several variables and whenever I access the corresponding variables from a child I actually access the variable form the parent. I.e. if I change it for one child it is changed also for all other childes and the data are only stored once in memory (and not copied for each child...) > > > That's not inheritance. That's a completely different concept. Your "shared variables" are simply objects that can be mutated and have references in other objects. Nothing interesting. Inheritance is completely different from this.
I am lost in all these diverse answers. But I think that what you need is expressed in the following code: ``` class P: pvar=1 # <--- class attribute def __init__(self,name): self.cname = name class C(P): def __init__(self,name): self.cname = name c1=C('1') c2=C('2') print print "C.pvar ==",C.pvar,' id(C.pvar) ==',id(C.pvar) print "c1.pvar==",c1.pvar,' id(c1.pvar)==',id(c1.pvar) print "c2.pvar==",c2.pvar,' id(c2.pvar)==',id(c2.pvar) print C.pvar = [1,2] print "instruction C.pvar = [1,2] executed" print "C.pvar ==",C.pvar,' id(C.pvar) ==',id(C.pvar) print "c1.pvar==",c1.pvar,' id(c1.pvar)==',id(c1.pvar) print "c2.pvar==",c2.pvar,' id(c2.pvar)==',id(c2.pvar) print c2.__class__.pvar = 'sun' print "instruction c2.__class__.pvar = 'sun' executed" print "C.pvar ==",C.pvar,' id(C.pvar) ==',id(C.pvar) print "c1.pvar==",c1.pvar,' id(c1.pvar)==',id(c1.pvar) print "c2.pvar==",c2.pvar,' id(c2.pvar)==',id(c2.pvar) print c2.pvar = 145 print "instruction c2.pvar = 145 executed" print "C.pvar ==",C.pvar,' id(C.pvar) ==',id(C.pvar) print "c1.pvar==",c1.pvar,' id(c1.pvar)==',id(c1.pvar) print "c2.pvar==",c2.pvar,' id(c2.pvar)==',id(c2.pvar) ``` result ``` C.pvar == 1 id(C.pvar) == 10021768 c1.pvar== 1 id(c1.pvar)== 10021768 c2.pvar== 1 id(c2.pvar)== 10021768 instruction C.pvar = [1,2] executed C.pvar == [1, 2] id(C.pvar) == 18729640 c1.pvar== [1, 2] id(c1.pvar)== 18729640 c2.pvar== [1, 2] id(c2.pvar)== 18729640 instruction c2.__class__.pvar = 'sun' executed C.pvar == sun id(C.pvar) == 18579136 c1.pvar== sun id(c1.pvar)== 18579136 c2.pvar== sun id(c2.pvar)== 18579136 instruction c2.pvar = 145 executed C.pvar == sun id(C.pvar) == 18579136 c1.pvar== sun id(c1.pvar)== 18579136 c2.pvar== 145 id(c2.pvar)== 10022024 ``` I mean that what you must know is that to change , through an instruction implying directly the name of an instance (and not through a change implying only the parent class's name) the class attribute **pvar** while it continues to be shared by all the **P** 's instances, you must write ``` c2.__class__.pvar = something ``` and not ``` c2.pvar =something ``` Note that C is a class effectively inheriting from a parent class P
5,104,366
users, I have a basic question concerning inheritance (in python). I have two classes and one of them is inherited from the other like ``` class p: def __init__(self,name): self.pname = name class c(p): def __init__(self,name): self.cname = name ``` Is there any possibility that I can create a parent object and several child objects which refer to the SAME parent object? It should work like that that the parent object contains several variables and whenever I access the corresponding variables from a child I actually access the variable form the parent. I.e. if I change it for one child it is changed also for all other childes and the data are only stored once in memory (and not copied for each child...) Thank you in advance. Here is a possible workaround which I do not consider as so nice ``` class P: def __init__(self, name): self.pname = name class C: def __init__(self, name,pobject): self.pobject = pobject self.cname = name ``` Is this really the state of the art or do there exist other concepts? Sebastian Thank you all for helping me, also with the name conventions :) But I am still not very satisfied. Maybe I give a more advanced example to stress what I really want to do. ``` class P: data = "shareddata" def __init__(self,newdata): self.data = newdata def printname(self): print self.name class C(P): def __init__(self,name): self.name = name ``` Now I can do the following ``` In [33]: c1 = test.C("name1") In [34]: c2 = test.C("name2") In [35]: c1.printname() name1 In [36]: c2.printname() name2 In [37]: c1.data Out[37]: 'shareddata' In [38]: c2.data Out[38]: 'shareddata' ``` And this is so far exactly what I want. There is a variable name which is different for every child and the parent class accesses the individual variables. Normal inheritance. Then there is the variable data which comes from the parent class and every child access it. However, now the following does not work any more ``` In [39]: c1.data = "tst" In [40]: c2.data Out[40]: 'shareddata' In [41]: c1.data Out[41]: 'tst' ``` I want the change in c1.data to affect also c2.data since I want the variable to be shared, somehow a global variable of this parent class. And more than that. I also want to create different instances of P, each having its own data variable. And when I create a new C object I want to specify from which P object data should be inhetited i.e. shared.... UPDATE: remark to the comment of @eyquem: Thanks for this, it is going into the direction I want. However, now the `__class__.pvar` is shared among all objects of the class. What I want is that several instances of P may have a different pvar. Lets assume P1 has pvar=1 and P2 has pvar=2. Then I want to create children C1a, C1b, C1c which are related to P1, i.e. if I say C1a.pvar it should acess pvar from P1. Then I create C2a, C2b, C2c and if I access i.e. C2b.pvar I want to access pvar from P2. Since the class C inherits pvar from the class P pvar is known to C. My naive idea is that if I create a new instance of C I should be able to specify which (existing) P object should be used as the parent object and not to create a completely new P object as it is done when calling `P.__init__` inside of the `__init__` of C... It sounds simple to me, maybe I forget something... UPDATE: So I found [this discussion](http://www.velocityreviews.com/forums/t356880-can-you-create-an-instance-of-a-subclass-with-an-existing-instance-of-the-base-class.html) which is pretty much my question Any suggestions? UPDATE: The method .**class**.\_*subclasses*\_ seems to be not existing any more.. UPDATE: Here is onother link: [link to discussion](http://bytes.com/topic/python/answers/834541-using-existing-instance-parent) There it is solved by copying. But I do not want to copy the parent class since I would like that it exists only once... UPDATE: Sorry for leaving the discussion yesterday, I am a bit ill... And thank you for the posts! I will now read through them. I thought about it a bit more and here is a possible solution I found ``` class P(object): def __init__(self,pvar): self.pobject = None self._pvar = pvar @property def pvar(self): if self.pobject != None: return self.pobject.pvar else: return self._pvar @pvar.setter def pvar(self,val): if self.pobject != None: self.pobject.pvar = val else: self._pvar=val def printname(self): print self.name class C(P): def __init__(self,name,pobject): #<-- The same default `P()` is # used for all instances of `C`, # unless pobject is explicitly defined. P.__init__(self,None) self.name = name self.pobject = pobject p1 = P("1") p2 = P("2") c1a = C("c1a",p1) c1b = C("c1b",p1) c1c = C("c1c",p1) c2a = C("c2a",p2) c2b = C("c2b",p2) c2c = C("c2c",p2) print id(c1a.pvar) print id(c1b.pvar) print id(c1c.pvar) print id(c2a.pvar) print id(c2b.pvar) print id(c2c.pvar) print id(p1.pvar) print id(p2.pvar) print id(c1a.name) print id(c1b.name) print id(c1c.name) print id(c2a.name) print id(c2b.name) print id(c2c.name) ``` It is a bit cumbersome and I hope that there is a simpler way to achieve this. But it has the feature that pvar is only mentioned in the class P and the class C does not know about pvar as it should be according to my understanding of inheritance. Nevertheless when I create a new instance of C I can specify an existing instance of P which will be stored in the variable pobject. When the variable pvar is accessed actually pvar of the P-instance stored in this variable is accessed... The output is given by ``` 3078326816 3078326816 3078326816 3074996544 3074996544 3074996544 3078326816 3074996544 156582944 156583040 156583200 156583232 156583296 156583360 ``` I will read now through your last comments, all the best, Sebastian UPDATE: I think the most elegant way would be the following (which DOES NOT work) ``` class P(object): def __init__(self,pvar): self.pvar = pvar def printname(self): print self.name class C(P): def __init__(self,name,pobject): P = pobject self.name = name ``` I think python should allow for this... UPDATE: Ok, now I found a way to achieve this, due to the explanations by eyquem. But Since this is really a hack there should be an official version for the same... ``` def replaceinstance(parent,child): for item in parent.__dict__.items(): child.__dict__.__setitem__(item[0],item[1]) print item class P(object): def __init__(self,pvar): self.pvar = pvar def printname(self): print self.name class C(P): def __init__(self,name,pobject): P.__init__(self,None) replaceinstance(pobject,self) self.name = name p1 = P("1") p2 = P("2") c1a = C("c1a",p1) c1b = C("c1b",p1) c1c = C("c1c",p1) c2a = C("c2a",p2) c2b = C("c2b",p2) c2c = C("c2c",p2) print id(c1a.pvar) print id(c1b.pvar) print id(c1c.pvar) print id(c2a.pvar) print id(c2b.pvar) print id(c2c.pvar) print id(p1.pvar) print id(p2.pvar) print id(c1a.name) print id(c1b.name) print id(c1c.name) print id(c2a.name) print id(c2b.name) print id(c2c.name) ``` the output is the same as above ``` 3077745184 3077745184 3077745184 3074414912 3074414912 3074414912 3077745184 3074414912 144028416 144028448 144028480 144028512 144028544 144028576 ``` UPDATE: Even if the id's seem to be right, the last code does not work as is clear from this test ``` c1a.pvar = "newpvar1" print c1a.pvar print c1b.pvar print c1c.pvar print c2a.pvar print c2b.pvar print c2c.pvar print p1.pvar print p2.pvar ``` it has the output ``` newpvar1 1 1 2 2 2 1 2 ``` However the version I posted first works: ``` class P(object): def __init__(self,pvar): self.pobject = None self._pvar = pvar @property def pvar(self): if self.pobject != None: return self.pobject.pvar else: return self._pvar @pvar.setter def pvar(self,val): if self.pobject != None: self.pobject.pvar = val else: self._pvar=val def printname(self): print self.name class C(P): def __init__(self,name,pobject): #<-- The same default `P()` is # used for all instances of `C`, # unless pobject is explicitly defined. P.__init__(self,None) self.name = name self.pobject = pobject p1 = P("1") p2 = P("2") c1a = C("c1a",p1) c1b = C("c1b",p1) c1c = C("c1c",p1) c2a = C("c2a",p2) c2b = C("c2b",p2) c2c = C("c2c",p2) print id(c1a.pvar) print id(c1b.pvar) print id(c1c.pvar) print id(c2a.pvar) print id(c2b.pvar) print id(c2c.pvar) print id(p1.pvar) print id(p2.pvar) print id(c1a.name) print id(c1b.name) print id(c1c.name) print id(c2a.name) print id(c2b.name) print id(c2c.name) print "testing\n" c1a.printname() c1b.printname() c1c.printname() c2a.printname() c2b.printname() c2c.printname() print "\n" c1a.name = "c1anewname" c2b.name = "c2bnewname" c1a.printname() c1b.printname() c1c.printname() c2a.printname() c2b.printname() c2c.printname() print "pvar\n" print c1a.pvar print c1b.pvar print c1c.pvar print c2a.pvar print c2b.pvar print c2c.pvar print p1.pvar print p2.pvar print "\n" c1a.pvar = "newpvar1" print c1a.pvar print c1b.pvar print c1c.pvar print c2a.pvar print c2b.pvar print c2c.pvar print p1.pvar print p2.pvar print "\n" c2c.pvar = "newpvar2" print c1a.pvar print c1b.pvar print c1c.pvar print c2a.pvar print c2b.pvar print c2c.pvar print p1.pvar print p2.pvar ``` with the output ``` 3077745184 3077745184 3077745184 3074414912 3074414912 3074414912 3077745184 3074414912 144028416 144028448 144028480 144028512 144028544 144028576 testing c1a c1b c1c c2a c2b c2c c1anewname c1b c1c c2a c2bnewname c2c pvar 1 1 1 2 2 2 1 2 newpvar1 newpvar1 newpvar1 2 2 2 newpvar1 2 newpvar1 newpvar1 newpvar1 newpvar2 newpvar2 newpvar2 newpvar1 newpvar2 ``` Does anybody know why it is like that? I probably do not understand the internal way python works with this `__dict__` so well...
2011/02/24
[ "https://Stackoverflow.com/questions/5104366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/632263/" ]
> > It should work like that that the parent object contains several variables and whenever I access the corresponding variables from a child I actually access the variable form the parent. I.e. if I change it for one child it is changed also for all other childes and the data are only stored once in memory (and not copied for each child...) > > > That's not inheritance. That's a completely different concept. Your "shared variables" are simply objects that can be mutated and have references in other objects. Nothing interesting. Inheritance is completely different from this.
Finally, I found a way to do it. The key point is to abandon the aim to obtain instances **c** with real **pvar** field, because it is impossible: Since it is the same **\_*init*\_()** function (the one being in class P) that processes to create the objects **pvar**, it isn't possible to create **pvar** in instances **c** that will points to the **pvar** in an instance **p** to mirror its value and that will also give the possibility to change this value of a **p**'s **pvar** each time a **c**'s **pvar**'s value will change. That makes too much contradictory conditions to verify. Consequently, since the instances **c** can't have a real **pvar** field, the best is to set up a mechanism controling the creation of ( with **\_*setattr*\_** ) and access to ( with **\_*getattr*\_** ) these **c**'s seemingly **pvar** objects to give the illusion that they exist. ``` class P(object): def __init__(self,pvar_arg,foo="^^^ "): self.pvar = pvar_arg self.cat = foo def printname(self): print self.name class C(P): def __init__(self,name,pobject,foo=''): self.__dict__['name'] = name P.__init__(self,None,pobject.cat+foo) C.dic[name] = pobject def __setattr__(self,xn,val): if xn!='pvar': self.__dict__[xn] = val elif self.name in C.dic: # During the creation of an instance c, # this condition is False because the instruction # C.dic[name] = pobject is written after # P.__init__(self,None,pobject.cat+foo). # Hence the value of pobject.pvar is preserved, # not changed with the value val being None # due to P.__init__(self,None,pobject.cat+foo) # that provokes self.pvar = pvar_arg and # consequently a call __setattr__(self,'pvar',None) C.dic[self.name].pvar = val def __getattribute__(self,xn): if xn=='pvar': return object.__getattribute__(C.dic[self.name],'pvar') else: return object.__getattribute__(self,xn) dic = {} p1 = P("1") p2 = P("2","QZX ") print '--- p1 = P("1") and p2 = P("2","QZX ") executed ---' print "p1.__dict__ ==",p1.__dict__ print "p2.__dict__ ==",p2.__dict__ print 'p1.pvar==',p1.pvar print 'p2.pvar==',p2.pvar c1a = C("c1a",p1,'sea') c1b = C("c1b",p1,'mountain') c1c = C("c1c",p1,'desert') c2a = C("c2a",p2,'banana') c2b = C("c2b",p2) c2c = C("c2c",p2,'pear') print '\n--- creations of c1a, c1b, c1c, c2a, c2b, c2c executed ---' print "p1.__dict__ ==",p1.__dict__ print "p2.__dict__ ==",p2.__dict__ print "c1a.__dict__ ==",c1a.__dict__ print "c1b.__dict__ ==",c1b.__dict__ print "c1c.__dict__ ==",c1c.__dict__ print "c2a.__dict__ ==",c2a.__dict__ print "c2b.__dict__ ==",c2b.__dict__ print "c2c.__dict__ ==",c2c.__dict__ print 'p1.pvar==',p1.pvar print 'p2.pvar==',p2.pvar print '(c1a.pvar, c1b.pvar, c1c.pvar)==',(c1a.pvar,c1b.pvar,c1c.pvar) print '(c2a.pvar, c2b.pvar, c2c.pvar)==',(c2a.pvar,c2b.pvar,c2c.pvar) c1a.pvar = "newpvar1" print '\n--- c1a.pvar = "newpvar1" executed ---' print 'p1.pvar==',p1.pvar print 'p2.pvar==',p2.pvar print '(c1a.pvar, c1b.pvar, c1c.pvar)==',(c1a.pvar,c1b.pvar,c1c.pvar) print '(c2a.pvar, c2b.pvar, c2c.pvar)==',(c2a.pvar,c2b.pvar,c2c.pvar) c2c.pvar = 45789 print '\n--- c2c.pvar = 45789 executed ---' print 'p1.pvar==',p1.pvar print 'p2.pvar==',p2.pvar print '(c1a.pvar, c1b.pvar, c1c.pvar)==',(c1a.pvar,c1b.pvar,c1c.pvar) print '(c2a.pvar, c2b.pvar, c2c.pvar)==',(c2a.pvar,c2b.pvar,c2c.pvar) ``` result ``` --- p1 = P("1") and p2 = P("2","QZX ") executed --- p1.__dict__ == {'cat': '^^^ ', 'pvar': '1'} p2.__dict__ == {'cat': 'QZX ', 'pvar': '2'} p1.pvar== 1 p2.pvar== 2 --- creations of c1a, c1b, c1c, c2a, c2b, c2c executed --- p1.__dict__ == {'cat': '^^^ ', 'pvar': '1'} p2.__dict__ == {'cat': 'QZX ', 'pvar': '2'} c1a.__dict__ == {'name': 'c1a', 'cat': '^^^ sea'} c1b.__dict__ == {'name': 'c1b', 'cat': '^^^ mountain'} c1c.__dict__ == {'name': 'c1c', 'cat': '^^^ desert'} c2a.__dict__ == {'name': 'c2a', 'cat': 'QZX banana'} c2b.__dict__ == {'name': 'c2b', 'cat': 'QZX '} c2c.__dict__ == {'name': 'c2c', 'cat': 'QZX pear'} p1.pvar== 1 p2.pvar== 2 (c1a.pvar, c1b.pvar, c1c.pvar)== ('1', '1', '1') (c2a.pvar, c2b.pvar, c2c.pvar)== ('2', '2', '2') --- c1a.pvar = "newpvar1" executed --- p1.pvar== newpvar1 p2.pvar== 2 (c1a.pvar, c1b.pvar, c1c.pvar)== ('newpvar1', 'newpvar1', 'newpvar1') (c2a.pvar, c2b.pvar, c2c.pvar)== ('2', '2', '2') --- c2c.pvar = 45789 executed --- p1.pvar== newpvar1 p2.pvar== 45789 (c1a.pvar, c1b.pvar, c1c.pvar)== ('newpvar1', 'newpvar1', 'newpvar1') (c2a.pvar, c2b.pvar, c2c.pvar)== (45789, 45789, 45789) ``` Remarks: 1. the attribute **name** must be defined before the instruction P.**init**(self,None,pobject.cat+foo) ------------------------------------- because the execution of this instruction calls `__setattr__(self,'pvar',"1")` that executes itself the instruction `C.dic[self.name].pvar = "1"` when `c1a = C("c1a",p1,'sea')` is executed, for example. AnHence this call needs **self.name** as key for dic. 2. I introduced **foo** and **cat** to justify the need to write the instruction P.**init**(self,None,pobject.cat+foo) ------------------------------------- otherwise, as no **pvar** is in fact defined into the instances **c** , this instuction wouldn't be useful. 3. There are two situations in which `__setattr__` is called: at the creation of an instance, and at the modifications of the attributes of an existing instance. When an instance is created, the value of **pvar** of the instance **p** must remain unaffected by the instruction `C.dic[self.name].pvar = None` . Hence the condition `elif self.name in C.dic:` In order that this condition gives a correct result, the instruction `C.dic[name] = pobject` must follow the call to `P.__init__(self,None,pobject.cat+foo)` . EDIT 1 I think it's better to write ``` def __setattr__(self,xn,val): if xn=='pvar': self.__class__.dic[self.name].pvar = val ``` than ``` def __setattr__(self,xn,val): if xn=='pvar': C.dic[self.name].pvar = val ``` In the first case, the interpreter has to search for the reference to the **self**'s class **C** ( that is to say under the name **'\_*class*\_'** ) in the namespace of self. In the second case, the interpreter must search for the same reference ( but under the name **'C'**) in the namespace of the level in which classes **P** and **C** are defined. This second namespace may be more more big than the limited namespace of an instance. In the first case, the name **'\_*class*\_'** is looked for as a key in the dictionary implementing the self's namespace. In the second, the name **'C'** is the key searched for in the dictionary of the level inclosing the classes **P** and **C**. The identity of these two objects can be verified with the function **id()** . . EDIT 2 There is another possibility for the `dic` object: instead of making it a class attribute of the class **C**, it can be defined in the outer scope of the class **C**. If this outer level is a module, then **dic** is a global object. ``` class P(object): def __init__(self,pvar,foo="^^^ "): self.pvar = pvar self.cat = foo def printname(self): print self.name class C(P): def __init__(self,name,pobject,foo=''): self.__dict__['name'] = name P.__init__(self,None,pobject.cat+foo) dic[name] = pobject def __setattr__(self,xn,val): if xn!='pvar': self.__dict__[xn] = val elif self.name in dic: # During the creation of an instance c, # this condition is False because the instruction # dic[name] = pobject is written after # P.__init__(self,None,pobject.cat+foo). # Hence the value of pobject.pvar is preserved, # not changed with the value val being None # due to P.__init__(self,None,pobject.cat+foo) # that provokes self.pvar = pvar_arg and # consequently a call __setattr__(self,'pvar',None) dic[self.name].pvar = val def __getattribute__(self,xn): if xn=='pvar': return object.__getattribute__(dic[self.name],'pvar') else: return object.__getattribute__(self,xn) dic = {} ``` The result is exactly the same Doing so, **dic** looses its OOish nature. . . EDIT 3 At last, there is still another way: instead of creating an illusory attribute **pvar** for each instance **c** with help of functions `__setattr__` and `__getattribute__` , it is better, according to me, to use a function with the dictionary **dic** as a default argument and that will replace them. ``` class P(object): def __init__(self,pvar,foo="^^^ "): self.pvar = pvar self.cat = foo def printname(self): print self.name class C(P): def __init__(self,name,pobject,foo=''): P.__init__(self,None,pobject.cat+foo) self.__dict__['name'] = name del self.pvar self.pvar(pobject) def pvar(self,x = None,dic = {}): if x.__class__==P: # a pobject dic[self.name] = x elif x: # a value dic[self.name].pvar = x else: # to return value return dic[self.name].pvar p1 = P("1") p2 = P("2","QZX ") print '--- p1 = P("1") and p2 = P("2","QZX ") executed ---' print "p1.__dict__ ==",p1.__dict__ print "p2.__dict__ ==",p2.__dict__ print 'p1.pvar==',p1.pvar print 'p2.pvar==',p2.pvar c1a = C("c1a",p1,'sea') c1b = C("c1b",p1,'mountain') c1c = C("c1c",p1,'desert') c2a = C("c2a",p2,'banana') c2b = C("c2b",p2) c2c = C("c2c",p2,'pear') print '\n--- creations of c1a, c1b, c1c, c2a, c2b, c2c executed ---' print "p1.__dict__ ==",p1.__dict__ print "p2.__dict__ ==",p2.__dict__ print "c1a.__dict__ ==",c1a.__dict__ print "c1b.__dict__ ==",c1b.__dict__ print "c1c.__dict__ ==",c1c.__dict__ print "c2a.__dict__ ==",c2a.__dict__ print "c2b.__dict__ ==",c2b.__dict__ print "c2c.__dict__ ==",c2c.__dict__ print 'p1.pvar==',p1.pvar print 'p2.pvar==',p2.pvar print '(c1a.pvar(),c1b.pvar(),c1c.pvar())==',(c1a.pvar(),c1b.pvar(),c1c.pvar()) print '(c2a.pvar(),c2b.pvar(),c2c.pvar())==',(c2a.pvar(),c2b.pvar(),c2c.pvar()) c1a.pvar("newpvar1") print '\n--- c1a.pvar("newpvar1") executed ---' print 'p1.pvar==',p1.pvar print 'p2.pvar==',p2.pvar print '(c1a.pvar(),c1b.pvar(),c1c.pvar())==',(c1a.pvar(),c1b.pvar(),c1c.pvar()) print '(c2a.pvar(),c2b.pvar(),c2c.pvar())==',(c2a.pvar(),c2b.pvar(),c2c.pvar()) c2c.pvar(45789) print '\n--- c2c.pvar(45789) ---' print 'p1.pvar==',p1.pvar print 'p2.pvar==',p2.pvar print '(c1a.pvar(),c1b.pvar(),c1c.pvar())==',(c1a.pvar(),c1b.pvar(),c1c.pvar()) print '(c2a.pvar(),c2b.pvar(),c2c.pvar())==',(c2a.pvar(),c2b.pvar(),c2c.pvar()) ``` Results are the same, only use of c.pvar() is slightly different: ``` --- p1 = P("1") and p2 = P("2","QZX ") executed --- p1.__dict__ == {'cat': '^^^ ', 'pvar': '1'} p2.__dict__ == {'cat': 'QZX ', 'pvar': '2'} p1.pvar== 1 p2.pvar== 2 --- creations of c1a, c1b, c1c, c2a, c2b, c2c executed --- p1.__dict__ == {'cat': '^^^ ', 'pvar': '1'} p2.__dict__ == {'cat': 'QZX ', 'pvar': '2'} c1a.__dict__ == {'cat': '^^^ sea', 'name': 'c1a'} c1b.__dict__ == {'cat': '^^^ mountain', 'name': 'c1b'} c1c.__dict__ == {'cat': '^^^ desert', 'name': 'c1c'} c2a.__dict__ == {'cat': 'QZX banana', 'name': 'c2a'} c2b.__dict__ == {'cat': 'QZX ', 'name': 'c2b'} c2c.__dict__ == {'cat': 'QZX pear', 'name': 'c2c'} p1.pvar== 1 p2.pvar== 2 (c1a.pvar(),c1b.pvar(),c1c.pvar())== ('1', '1', '1') (c2a.pvar(),c2b.pvar(),c2c.pvar())== ('2', '2', '2') --- c1a.pvar("newpvar1") executed --- p1.pvar== newpvar1 p2.pvar== 2 (c1a.pvar(),c1b.pvar(),c1c.pvar())== ('newpvar1', 'newpvar1', 'newpvar1') (c2a.pvar(),c2b.pvar(),c2c.pvar())== ('2', '2', '2') --- c2c.pvar(45789) --- p1.pvar== newpvar1 p2.pvar== 45789 (c1a.pvar(),c1b.pvar(),c1c.pvar())== ('newpvar1', 'newpvar1', 'newpvar1') (c2a.pvar(),c2b.pvar(),c2c.pvar())== (45789, 45789, 45789) ``` Note that in this last code **P**'s instances can't be values of **C**'instances because a **pobject** passed to a **c.pvar()** method will never be considered as a value.
5,104,366
users, I have a basic question concerning inheritance (in python). I have two classes and one of them is inherited from the other like ``` class p: def __init__(self,name): self.pname = name class c(p): def __init__(self,name): self.cname = name ``` Is there any possibility that I can create a parent object and several child objects which refer to the SAME parent object? It should work like that that the parent object contains several variables and whenever I access the corresponding variables from a child I actually access the variable form the parent. I.e. if I change it for one child it is changed also for all other childes and the data are only stored once in memory (and not copied for each child...) Thank you in advance. Here is a possible workaround which I do not consider as so nice ``` class P: def __init__(self, name): self.pname = name class C: def __init__(self, name,pobject): self.pobject = pobject self.cname = name ``` Is this really the state of the art or do there exist other concepts? Sebastian Thank you all for helping me, also with the name conventions :) But I am still not very satisfied. Maybe I give a more advanced example to stress what I really want to do. ``` class P: data = "shareddata" def __init__(self,newdata): self.data = newdata def printname(self): print self.name class C(P): def __init__(self,name): self.name = name ``` Now I can do the following ``` In [33]: c1 = test.C("name1") In [34]: c2 = test.C("name2") In [35]: c1.printname() name1 In [36]: c2.printname() name2 In [37]: c1.data Out[37]: 'shareddata' In [38]: c2.data Out[38]: 'shareddata' ``` And this is so far exactly what I want. There is a variable name which is different for every child and the parent class accesses the individual variables. Normal inheritance. Then there is the variable data which comes from the parent class and every child access it. However, now the following does not work any more ``` In [39]: c1.data = "tst" In [40]: c2.data Out[40]: 'shareddata' In [41]: c1.data Out[41]: 'tst' ``` I want the change in c1.data to affect also c2.data since I want the variable to be shared, somehow a global variable of this parent class. And more than that. I also want to create different instances of P, each having its own data variable. And when I create a new C object I want to specify from which P object data should be inhetited i.e. shared.... UPDATE: remark to the comment of @eyquem: Thanks for this, it is going into the direction I want. However, now the `__class__.pvar` is shared among all objects of the class. What I want is that several instances of P may have a different pvar. Lets assume P1 has pvar=1 and P2 has pvar=2. Then I want to create children C1a, C1b, C1c which are related to P1, i.e. if I say C1a.pvar it should acess pvar from P1. Then I create C2a, C2b, C2c and if I access i.e. C2b.pvar I want to access pvar from P2. Since the class C inherits pvar from the class P pvar is known to C. My naive idea is that if I create a new instance of C I should be able to specify which (existing) P object should be used as the parent object and not to create a completely new P object as it is done when calling `P.__init__` inside of the `__init__` of C... It sounds simple to me, maybe I forget something... UPDATE: So I found [this discussion](http://www.velocityreviews.com/forums/t356880-can-you-create-an-instance-of-a-subclass-with-an-existing-instance-of-the-base-class.html) which is pretty much my question Any suggestions? UPDATE: The method .**class**.\_*subclasses*\_ seems to be not existing any more.. UPDATE: Here is onother link: [link to discussion](http://bytes.com/topic/python/answers/834541-using-existing-instance-parent) There it is solved by copying. But I do not want to copy the parent class since I would like that it exists only once... UPDATE: Sorry for leaving the discussion yesterday, I am a bit ill... And thank you for the posts! I will now read through them. I thought about it a bit more and here is a possible solution I found ``` class P(object): def __init__(self,pvar): self.pobject = None self._pvar = pvar @property def pvar(self): if self.pobject != None: return self.pobject.pvar else: return self._pvar @pvar.setter def pvar(self,val): if self.pobject != None: self.pobject.pvar = val else: self._pvar=val def printname(self): print self.name class C(P): def __init__(self,name,pobject): #<-- The same default `P()` is # used for all instances of `C`, # unless pobject is explicitly defined. P.__init__(self,None) self.name = name self.pobject = pobject p1 = P("1") p2 = P("2") c1a = C("c1a",p1) c1b = C("c1b",p1) c1c = C("c1c",p1) c2a = C("c2a",p2) c2b = C("c2b",p2) c2c = C("c2c",p2) print id(c1a.pvar) print id(c1b.pvar) print id(c1c.pvar) print id(c2a.pvar) print id(c2b.pvar) print id(c2c.pvar) print id(p1.pvar) print id(p2.pvar) print id(c1a.name) print id(c1b.name) print id(c1c.name) print id(c2a.name) print id(c2b.name) print id(c2c.name) ``` It is a bit cumbersome and I hope that there is a simpler way to achieve this. But it has the feature that pvar is only mentioned in the class P and the class C does not know about pvar as it should be according to my understanding of inheritance. Nevertheless when I create a new instance of C I can specify an existing instance of P which will be stored in the variable pobject. When the variable pvar is accessed actually pvar of the P-instance stored in this variable is accessed... The output is given by ``` 3078326816 3078326816 3078326816 3074996544 3074996544 3074996544 3078326816 3074996544 156582944 156583040 156583200 156583232 156583296 156583360 ``` I will read now through your last comments, all the best, Sebastian UPDATE: I think the most elegant way would be the following (which DOES NOT work) ``` class P(object): def __init__(self,pvar): self.pvar = pvar def printname(self): print self.name class C(P): def __init__(self,name,pobject): P = pobject self.name = name ``` I think python should allow for this... UPDATE: Ok, now I found a way to achieve this, due to the explanations by eyquem. But Since this is really a hack there should be an official version for the same... ``` def replaceinstance(parent,child): for item in parent.__dict__.items(): child.__dict__.__setitem__(item[0],item[1]) print item class P(object): def __init__(self,pvar): self.pvar = pvar def printname(self): print self.name class C(P): def __init__(self,name,pobject): P.__init__(self,None) replaceinstance(pobject,self) self.name = name p1 = P("1") p2 = P("2") c1a = C("c1a",p1) c1b = C("c1b",p1) c1c = C("c1c",p1) c2a = C("c2a",p2) c2b = C("c2b",p2) c2c = C("c2c",p2) print id(c1a.pvar) print id(c1b.pvar) print id(c1c.pvar) print id(c2a.pvar) print id(c2b.pvar) print id(c2c.pvar) print id(p1.pvar) print id(p2.pvar) print id(c1a.name) print id(c1b.name) print id(c1c.name) print id(c2a.name) print id(c2b.name) print id(c2c.name) ``` the output is the same as above ``` 3077745184 3077745184 3077745184 3074414912 3074414912 3074414912 3077745184 3074414912 144028416 144028448 144028480 144028512 144028544 144028576 ``` UPDATE: Even if the id's seem to be right, the last code does not work as is clear from this test ``` c1a.pvar = "newpvar1" print c1a.pvar print c1b.pvar print c1c.pvar print c2a.pvar print c2b.pvar print c2c.pvar print p1.pvar print p2.pvar ``` it has the output ``` newpvar1 1 1 2 2 2 1 2 ``` However the version I posted first works: ``` class P(object): def __init__(self,pvar): self.pobject = None self._pvar = pvar @property def pvar(self): if self.pobject != None: return self.pobject.pvar else: return self._pvar @pvar.setter def pvar(self,val): if self.pobject != None: self.pobject.pvar = val else: self._pvar=val def printname(self): print self.name class C(P): def __init__(self,name,pobject): #<-- The same default `P()` is # used for all instances of `C`, # unless pobject is explicitly defined. P.__init__(self,None) self.name = name self.pobject = pobject p1 = P("1") p2 = P("2") c1a = C("c1a",p1) c1b = C("c1b",p1) c1c = C("c1c",p1) c2a = C("c2a",p2) c2b = C("c2b",p2) c2c = C("c2c",p2) print id(c1a.pvar) print id(c1b.pvar) print id(c1c.pvar) print id(c2a.pvar) print id(c2b.pvar) print id(c2c.pvar) print id(p1.pvar) print id(p2.pvar) print id(c1a.name) print id(c1b.name) print id(c1c.name) print id(c2a.name) print id(c2b.name) print id(c2c.name) print "testing\n" c1a.printname() c1b.printname() c1c.printname() c2a.printname() c2b.printname() c2c.printname() print "\n" c1a.name = "c1anewname" c2b.name = "c2bnewname" c1a.printname() c1b.printname() c1c.printname() c2a.printname() c2b.printname() c2c.printname() print "pvar\n" print c1a.pvar print c1b.pvar print c1c.pvar print c2a.pvar print c2b.pvar print c2c.pvar print p1.pvar print p2.pvar print "\n" c1a.pvar = "newpvar1" print c1a.pvar print c1b.pvar print c1c.pvar print c2a.pvar print c2b.pvar print c2c.pvar print p1.pvar print p2.pvar print "\n" c2c.pvar = "newpvar2" print c1a.pvar print c1b.pvar print c1c.pvar print c2a.pvar print c2b.pvar print c2c.pvar print p1.pvar print p2.pvar ``` with the output ``` 3077745184 3077745184 3077745184 3074414912 3074414912 3074414912 3077745184 3074414912 144028416 144028448 144028480 144028512 144028544 144028576 testing c1a c1b c1c c2a c2b c2c c1anewname c1b c1c c2a c2bnewname c2c pvar 1 1 1 2 2 2 1 2 newpvar1 newpvar1 newpvar1 2 2 2 newpvar1 2 newpvar1 newpvar1 newpvar1 newpvar2 newpvar2 newpvar2 newpvar1 newpvar2 ``` Does anybody know why it is like that? I probably do not understand the internal way python works with this `__dict__` so well...
2011/02/24
[ "https://Stackoverflow.com/questions/5104366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/632263/" ]
> > It should work like that that the parent object contains several variables and whenever I access the corresponding variables from a child I actually access the variable form the parent. I.e. if I change it for one child it is changed also for all other childes and the data are only stored once in memory (and not copied for each child...) > > > That's not inheritance. That's a completely different concept. Your "shared variables" are simply objects that can be mutated and have references in other objects. Nothing interesting. Inheritance is completely different from this.
r6d9, please, when you write an update, you should put the date and hour by the word UPDATE. It begins to be complcated to follow all that . . Concerning this code of you: ``` def replaceinstance(parent,child): for item in parent.__dict__.items(): child.__dict__.__setitem__(item[0],item[1]) print item class P(object): def __init__(self,pvar): self.pvar = pvar def printname(self): print self.name class C(P): def __init__(self,name,pobject): P.__init__(self,None) replaceinstance(pobject,self) self.name = name ``` it can be replaced by this one: ``` class P(object): def __init__(self,pvar): self.pvar = pvar def printname(self): print self.name class C(P): def __init__(self,name,pobject): P.__init__(self,None) self.pvar = pobject.pvar self.name = name ``` but it seems to simple
5,104,366
users, I have a basic question concerning inheritance (in python). I have two classes and one of them is inherited from the other like ``` class p: def __init__(self,name): self.pname = name class c(p): def __init__(self,name): self.cname = name ``` Is there any possibility that I can create a parent object and several child objects which refer to the SAME parent object? It should work like that that the parent object contains several variables and whenever I access the corresponding variables from a child I actually access the variable form the parent. I.e. if I change it for one child it is changed also for all other childes and the data are only stored once in memory (and not copied for each child...) Thank you in advance. Here is a possible workaround which I do not consider as so nice ``` class P: def __init__(self, name): self.pname = name class C: def __init__(self, name,pobject): self.pobject = pobject self.cname = name ``` Is this really the state of the art or do there exist other concepts? Sebastian Thank you all for helping me, also with the name conventions :) But I am still not very satisfied. Maybe I give a more advanced example to stress what I really want to do. ``` class P: data = "shareddata" def __init__(self,newdata): self.data = newdata def printname(self): print self.name class C(P): def __init__(self,name): self.name = name ``` Now I can do the following ``` In [33]: c1 = test.C("name1") In [34]: c2 = test.C("name2") In [35]: c1.printname() name1 In [36]: c2.printname() name2 In [37]: c1.data Out[37]: 'shareddata' In [38]: c2.data Out[38]: 'shareddata' ``` And this is so far exactly what I want. There is a variable name which is different for every child and the parent class accesses the individual variables. Normal inheritance. Then there is the variable data which comes from the parent class and every child access it. However, now the following does not work any more ``` In [39]: c1.data = "tst" In [40]: c2.data Out[40]: 'shareddata' In [41]: c1.data Out[41]: 'tst' ``` I want the change in c1.data to affect also c2.data since I want the variable to be shared, somehow a global variable of this parent class. And more than that. I also want to create different instances of P, each having its own data variable. And when I create a new C object I want to specify from which P object data should be inhetited i.e. shared.... UPDATE: remark to the comment of @eyquem: Thanks for this, it is going into the direction I want. However, now the `__class__.pvar` is shared among all objects of the class. What I want is that several instances of P may have a different pvar. Lets assume P1 has pvar=1 and P2 has pvar=2. Then I want to create children C1a, C1b, C1c which are related to P1, i.e. if I say C1a.pvar it should acess pvar from P1. Then I create C2a, C2b, C2c and if I access i.e. C2b.pvar I want to access pvar from P2. Since the class C inherits pvar from the class P pvar is known to C. My naive idea is that if I create a new instance of C I should be able to specify which (existing) P object should be used as the parent object and not to create a completely new P object as it is done when calling `P.__init__` inside of the `__init__` of C... It sounds simple to me, maybe I forget something... UPDATE: So I found [this discussion](http://www.velocityreviews.com/forums/t356880-can-you-create-an-instance-of-a-subclass-with-an-existing-instance-of-the-base-class.html) which is pretty much my question Any suggestions? UPDATE: The method .**class**.\_*subclasses*\_ seems to be not existing any more.. UPDATE: Here is onother link: [link to discussion](http://bytes.com/topic/python/answers/834541-using-existing-instance-parent) There it is solved by copying. But I do not want to copy the parent class since I would like that it exists only once... UPDATE: Sorry for leaving the discussion yesterday, I am a bit ill... And thank you for the posts! I will now read through them. I thought about it a bit more and here is a possible solution I found ``` class P(object): def __init__(self,pvar): self.pobject = None self._pvar = pvar @property def pvar(self): if self.pobject != None: return self.pobject.pvar else: return self._pvar @pvar.setter def pvar(self,val): if self.pobject != None: self.pobject.pvar = val else: self._pvar=val def printname(self): print self.name class C(P): def __init__(self,name,pobject): #<-- The same default `P()` is # used for all instances of `C`, # unless pobject is explicitly defined. P.__init__(self,None) self.name = name self.pobject = pobject p1 = P("1") p2 = P("2") c1a = C("c1a",p1) c1b = C("c1b",p1) c1c = C("c1c",p1) c2a = C("c2a",p2) c2b = C("c2b",p2) c2c = C("c2c",p2) print id(c1a.pvar) print id(c1b.pvar) print id(c1c.pvar) print id(c2a.pvar) print id(c2b.pvar) print id(c2c.pvar) print id(p1.pvar) print id(p2.pvar) print id(c1a.name) print id(c1b.name) print id(c1c.name) print id(c2a.name) print id(c2b.name) print id(c2c.name) ``` It is a bit cumbersome and I hope that there is a simpler way to achieve this. But it has the feature that pvar is only mentioned in the class P and the class C does not know about pvar as it should be according to my understanding of inheritance. Nevertheless when I create a new instance of C I can specify an existing instance of P which will be stored in the variable pobject. When the variable pvar is accessed actually pvar of the P-instance stored in this variable is accessed... The output is given by ``` 3078326816 3078326816 3078326816 3074996544 3074996544 3074996544 3078326816 3074996544 156582944 156583040 156583200 156583232 156583296 156583360 ``` I will read now through your last comments, all the best, Sebastian UPDATE: I think the most elegant way would be the following (which DOES NOT work) ``` class P(object): def __init__(self,pvar): self.pvar = pvar def printname(self): print self.name class C(P): def __init__(self,name,pobject): P = pobject self.name = name ``` I think python should allow for this... UPDATE: Ok, now I found a way to achieve this, due to the explanations by eyquem. But Since this is really a hack there should be an official version for the same... ``` def replaceinstance(parent,child): for item in parent.__dict__.items(): child.__dict__.__setitem__(item[0],item[1]) print item class P(object): def __init__(self,pvar): self.pvar = pvar def printname(self): print self.name class C(P): def __init__(self,name,pobject): P.__init__(self,None) replaceinstance(pobject,self) self.name = name p1 = P("1") p2 = P("2") c1a = C("c1a",p1) c1b = C("c1b",p1) c1c = C("c1c",p1) c2a = C("c2a",p2) c2b = C("c2b",p2) c2c = C("c2c",p2) print id(c1a.pvar) print id(c1b.pvar) print id(c1c.pvar) print id(c2a.pvar) print id(c2b.pvar) print id(c2c.pvar) print id(p1.pvar) print id(p2.pvar) print id(c1a.name) print id(c1b.name) print id(c1c.name) print id(c2a.name) print id(c2b.name) print id(c2c.name) ``` the output is the same as above ``` 3077745184 3077745184 3077745184 3074414912 3074414912 3074414912 3077745184 3074414912 144028416 144028448 144028480 144028512 144028544 144028576 ``` UPDATE: Even if the id's seem to be right, the last code does not work as is clear from this test ``` c1a.pvar = "newpvar1" print c1a.pvar print c1b.pvar print c1c.pvar print c2a.pvar print c2b.pvar print c2c.pvar print p1.pvar print p2.pvar ``` it has the output ``` newpvar1 1 1 2 2 2 1 2 ``` However the version I posted first works: ``` class P(object): def __init__(self,pvar): self.pobject = None self._pvar = pvar @property def pvar(self): if self.pobject != None: return self.pobject.pvar else: return self._pvar @pvar.setter def pvar(self,val): if self.pobject != None: self.pobject.pvar = val else: self._pvar=val def printname(self): print self.name class C(P): def __init__(self,name,pobject): #<-- The same default `P()` is # used for all instances of `C`, # unless pobject is explicitly defined. P.__init__(self,None) self.name = name self.pobject = pobject p1 = P("1") p2 = P("2") c1a = C("c1a",p1) c1b = C("c1b",p1) c1c = C("c1c",p1) c2a = C("c2a",p2) c2b = C("c2b",p2) c2c = C("c2c",p2) print id(c1a.pvar) print id(c1b.pvar) print id(c1c.pvar) print id(c2a.pvar) print id(c2b.pvar) print id(c2c.pvar) print id(p1.pvar) print id(p2.pvar) print id(c1a.name) print id(c1b.name) print id(c1c.name) print id(c2a.name) print id(c2b.name) print id(c2c.name) print "testing\n" c1a.printname() c1b.printname() c1c.printname() c2a.printname() c2b.printname() c2c.printname() print "\n" c1a.name = "c1anewname" c2b.name = "c2bnewname" c1a.printname() c1b.printname() c1c.printname() c2a.printname() c2b.printname() c2c.printname() print "pvar\n" print c1a.pvar print c1b.pvar print c1c.pvar print c2a.pvar print c2b.pvar print c2c.pvar print p1.pvar print p2.pvar print "\n" c1a.pvar = "newpvar1" print c1a.pvar print c1b.pvar print c1c.pvar print c2a.pvar print c2b.pvar print c2c.pvar print p1.pvar print p2.pvar print "\n" c2c.pvar = "newpvar2" print c1a.pvar print c1b.pvar print c1c.pvar print c2a.pvar print c2b.pvar print c2c.pvar print p1.pvar print p2.pvar ``` with the output ``` 3077745184 3077745184 3077745184 3074414912 3074414912 3074414912 3077745184 3074414912 144028416 144028448 144028480 144028512 144028544 144028576 testing c1a c1b c1c c2a c2b c2c c1anewname c1b c1c c2a c2bnewname c2c pvar 1 1 1 2 2 2 1 2 newpvar1 newpvar1 newpvar1 2 2 2 newpvar1 2 newpvar1 newpvar1 newpvar1 newpvar2 newpvar2 newpvar2 newpvar1 newpvar2 ``` Does anybody know why it is like that? I probably do not understand the internal way python works with this `__dict__` so well...
2011/02/24
[ "https://Stackoverflow.com/questions/5104366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/632263/" ]
> > It should work like that that the parent object contains several variables and whenever I access the corresponding variables from a child I actually access the variable form the parent. I.e. if I change it for one child it is changed also for all other childes and the data are only stored once in memory (and not copied for each child...) > > > That's not inheritance. That's a completely different concept. Your "shared variables" are simply objects that can be mutated and have references in other objects. Nothing interesting. Inheritance is completely different from this.
One thing you must know as a base of the understanding of functionning of classes and instances: > > A class instance has a namespace > implemented as a dictionary which is > the **first place in which attribute > references are searched**. > > > When an attribute is not found there, > and the instance’s class has an > attribute by that name, the search > continues with the class attributes. > > > <http://docs.python.org/reference/datamodel.html#the-standard-type-hierarchy> > > > In the second sentence, I don't exactly understand the meaning of "by that name" , but I understand of the global that an attribute is searched first in the namespace of an instance and then in the namespace of its type. In the following code : * For class `P` and instance `c` : the name **'dataclass'** and object `dataclass` really belong to the `P` class's namespace and only APPARENTLY belong to the `c` instance's namespace: when `c.dataclass` is called , that's in fact `c.__class__.dataclass` that is attained, by the course of search described above. * But in an instance `cc` of the class `PP` , the name **'data'** , which belongs to the `P` class's namespace, is assigned (binded) by the definition occuring in `__init__()` to a new `data` object created in the `c` instance's namespace. Hence, the only solution to obtain the class's `data`'s value is to call it by its real reference, either `PP.data` or `cc.__class__.data` . ``` class P: dataclass = "shareddata" def __init__(self,newdata): self.data = newdata def printname(self): print self.name c = P(1) print 'P.__dict__.keys()==',P.__dict__.keys() print 'c.__dict__.keys()==',c.__dict__.keys() print print 'c.data==',c.data print 'c.dataclass==',c.dataclass print class PP: data = "shareddata" def __init__(self,newdata): self.data = newdata def printname(self): print self.name cc = PP(2) print 'PP.__dict__.keys()==',PP.__dict__.keys() print 'cc.__dict__.keys()==',cc.__dict__.keys() print print 'cc.data==',cc.data print 'PP.data==',PP.data print 'cc.__class__.data==',cc.__class__.data ``` result ``` P.__dict__.keys()== ['dataclass', '__module__', 'printname', '__init__', '__doc__'] c.__dict__.keys()== ['data'] c.data== 1 c.dataclass== shareddata PP.__dict__.keys()== ['__module__', 'data', 'printname', '__init__', '__doc__'] cc.__dict__.keys()== ['data'] cc.data== 2 PP.data== shareddata cc.__class__.data== shareddata ``` . Note: > > **dir([object])** > > > With an argument, attempt to return a > list of valid attributes for that > object. > > > If the object does not provide > **dir**(), the function tries its best to gather information from the > object’s **dict** attribute, if > defined, and from its type object. > > > The default dir() mechanism behaves > differently with different types of > objects, as it attempts to produce the > most relevant, rather than complete, > information: > > > •If the object is a type or class > object, the list contains the names of > its attributes, and recursively of the > attributes of its bases. > > > •Otherwise, the list contains the > object’s attributes’ names, the names > of its class’s attributes, and > recursively of the attributes of its > class’s base classes. > > > <http://docs.python.org/library/functions.html#dir> > > > . Hence, the use of `dir(ob)` to display the attributes of the object `ob` is a trap because it display more attributes than the ones belonging strictly to the object. In other words, **\_\_dict\_\_** is the real thing, while **dir()** gives a dashboard, in a sense.
5,104,366
users, I have a basic question concerning inheritance (in python). I have two classes and one of them is inherited from the other like ``` class p: def __init__(self,name): self.pname = name class c(p): def __init__(self,name): self.cname = name ``` Is there any possibility that I can create a parent object and several child objects which refer to the SAME parent object? It should work like that that the parent object contains several variables and whenever I access the corresponding variables from a child I actually access the variable form the parent. I.e. if I change it for one child it is changed also for all other childes and the data are only stored once in memory (and not copied for each child...) Thank you in advance. Here is a possible workaround which I do not consider as so nice ``` class P: def __init__(self, name): self.pname = name class C: def __init__(self, name,pobject): self.pobject = pobject self.cname = name ``` Is this really the state of the art or do there exist other concepts? Sebastian Thank you all for helping me, also with the name conventions :) But I am still not very satisfied. Maybe I give a more advanced example to stress what I really want to do. ``` class P: data = "shareddata" def __init__(self,newdata): self.data = newdata def printname(self): print self.name class C(P): def __init__(self,name): self.name = name ``` Now I can do the following ``` In [33]: c1 = test.C("name1") In [34]: c2 = test.C("name2") In [35]: c1.printname() name1 In [36]: c2.printname() name2 In [37]: c1.data Out[37]: 'shareddata' In [38]: c2.data Out[38]: 'shareddata' ``` And this is so far exactly what I want. There is a variable name which is different for every child and the parent class accesses the individual variables. Normal inheritance. Then there is the variable data which comes from the parent class and every child access it. However, now the following does not work any more ``` In [39]: c1.data = "tst" In [40]: c2.data Out[40]: 'shareddata' In [41]: c1.data Out[41]: 'tst' ``` I want the change in c1.data to affect also c2.data since I want the variable to be shared, somehow a global variable of this parent class. And more than that. I also want to create different instances of P, each having its own data variable. And when I create a new C object I want to specify from which P object data should be inhetited i.e. shared.... UPDATE: remark to the comment of @eyquem: Thanks for this, it is going into the direction I want. However, now the `__class__.pvar` is shared among all objects of the class. What I want is that several instances of P may have a different pvar. Lets assume P1 has pvar=1 and P2 has pvar=2. Then I want to create children C1a, C1b, C1c which are related to P1, i.e. if I say C1a.pvar it should acess pvar from P1. Then I create C2a, C2b, C2c and if I access i.e. C2b.pvar I want to access pvar from P2. Since the class C inherits pvar from the class P pvar is known to C. My naive idea is that if I create a new instance of C I should be able to specify which (existing) P object should be used as the parent object and not to create a completely new P object as it is done when calling `P.__init__` inside of the `__init__` of C... It sounds simple to me, maybe I forget something... UPDATE: So I found [this discussion](http://www.velocityreviews.com/forums/t356880-can-you-create-an-instance-of-a-subclass-with-an-existing-instance-of-the-base-class.html) which is pretty much my question Any suggestions? UPDATE: The method .**class**.\_*subclasses*\_ seems to be not existing any more.. UPDATE: Here is onother link: [link to discussion](http://bytes.com/topic/python/answers/834541-using-existing-instance-parent) There it is solved by copying. But I do not want to copy the parent class since I would like that it exists only once... UPDATE: Sorry for leaving the discussion yesterday, I am a bit ill... And thank you for the posts! I will now read through them. I thought about it a bit more and here is a possible solution I found ``` class P(object): def __init__(self,pvar): self.pobject = None self._pvar = pvar @property def pvar(self): if self.pobject != None: return self.pobject.pvar else: return self._pvar @pvar.setter def pvar(self,val): if self.pobject != None: self.pobject.pvar = val else: self._pvar=val def printname(self): print self.name class C(P): def __init__(self,name,pobject): #<-- The same default `P()` is # used for all instances of `C`, # unless pobject is explicitly defined. P.__init__(self,None) self.name = name self.pobject = pobject p1 = P("1") p2 = P("2") c1a = C("c1a",p1) c1b = C("c1b",p1) c1c = C("c1c",p1) c2a = C("c2a",p2) c2b = C("c2b",p2) c2c = C("c2c",p2) print id(c1a.pvar) print id(c1b.pvar) print id(c1c.pvar) print id(c2a.pvar) print id(c2b.pvar) print id(c2c.pvar) print id(p1.pvar) print id(p2.pvar) print id(c1a.name) print id(c1b.name) print id(c1c.name) print id(c2a.name) print id(c2b.name) print id(c2c.name) ``` It is a bit cumbersome and I hope that there is a simpler way to achieve this. But it has the feature that pvar is only mentioned in the class P and the class C does not know about pvar as it should be according to my understanding of inheritance. Nevertheless when I create a new instance of C I can specify an existing instance of P which will be stored in the variable pobject. When the variable pvar is accessed actually pvar of the P-instance stored in this variable is accessed... The output is given by ``` 3078326816 3078326816 3078326816 3074996544 3074996544 3074996544 3078326816 3074996544 156582944 156583040 156583200 156583232 156583296 156583360 ``` I will read now through your last comments, all the best, Sebastian UPDATE: I think the most elegant way would be the following (which DOES NOT work) ``` class P(object): def __init__(self,pvar): self.pvar = pvar def printname(self): print self.name class C(P): def __init__(self,name,pobject): P = pobject self.name = name ``` I think python should allow for this... UPDATE: Ok, now I found a way to achieve this, due to the explanations by eyquem. But Since this is really a hack there should be an official version for the same... ``` def replaceinstance(parent,child): for item in parent.__dict__.items(): child.__dict__.__setitem__(item[0],item[1]) print item class P(object): def __init__(self,pvar): self.pvar = pvar def printname(self): print self.name class C(P): def __init__(self,name,pobject): P.__init__(self,None) replaceinstance(pobject,self) self.name = name p1 = P("1") p2 = P("2") c1a = C("c1a",p1) c1b = C("c1b",p1) c1c = C("c1c",p1) c2a = C("c2a",p2) c2b = C("c2b",p2) c2c = C("c2c",p2) print id(c1a.pvar) print id(c1b.pvar) print id(c1c.pvar) print id(c2a.pvar) print id(c2b.pvar) print id(c2c.pvar) print id(p1.pvar) print id(p2.pvar) print id(c1a.name) print id(c1b.name) print id(c1c.name) print id(c2a.name) print id(c2b.name) print id(c2c.name) ``` the output is the same as above ``` 3077745184 3077745184 3077745184 3074414912 3074414912 3074414912 3077745184 3074414912 144028416 144028448 144028480 144028512 144028544 144028576 ``` UPDATE: Even if the id's seem to be right, the last code does not work as is clear from this test ``` c1a.pvar = "newpvar1" print c1a.pvar print c1b.pvar print c1c.pvar print c2a.pvar print c2b.pvar print c2c.pvar print p1.pvar print p2.pvar ``` it has the output ``` newpvar1 1 1 2 2 2 1 2 ``` However the version I posted first works: ``` class P(object): def __init__(self,pvar): self.pobject = None self._pvar = pvar @property def pvar(self): if self.pobject != None: return self.pobject.pvar else: return self._pvar @pvar.setter def pvar(self,val): if self.pobject != None: self.pobject.pvar = val else: self._pvar=val def printname(self): print self.name class C(P): def __init__(self,name,pobject): #<-- The same default `P()` is # used for all instances of `C`, # unless pobject is explicitly defined. P.__init__(self,None) self.name = name self.pobject = pobject p1 = P("1") p2 = P("2") c1a = C("c1a",p1) c1b = C("c1b",p1) c1c = C("c1c",p1) c2a = C("c2a",p2) c2b = C("c2b",p2) c2c = C("c2c",p2) print id(c1a.pvar) print id(c1b.pvar) print id(c1c.pvar) print id(c2a.pvar) print id(c2b.pvar) print id(c2c.pvar) print id(p1.pvar) print id(p2.pvar) print id(c1a.name) print id(c1b.name) print id(c1c.name) print id(c2a.name) print id(c2b.name) print id(c2c.name) print "testing\n" c1a.printname() c1b.printname() c1c.printname() c2a.printname() c2b.printname() c2c.printname() print "\n" c1a.name = "c1anewname" c2b.name = "c2bnewname" c1a.printname() c1b.printname() c1c.printname() c2a.printname() c2b.printname() c2c.printname() print "pvar\n" print c1a.pvar print c1b.pvar print c1c.pvar print c2a.pvar print c2b.pvar print c2c.pvar print p1.pvar print p2.pvar print "\n" c1a.pvar = "newpvar1" print c1a.pvar print c1b.pvar print c1c.pvar print c2a.pvar print c2b.pvar print c2c.pvar print p1.pvar print p2.pvar print "\n" c2c.pvar = "newpvar2" print c1a.pvar print c1b.pvar print c1c.pvar print c2a.pvar print c2b.pvar print c2c.pvar print p1.pvar print p2.pvar ``` with the output ``` 3077745184 3077745184 3077745184 3074414912 3074414912 3074414912 3077745184 3074414912 144028416 144028448 144028480 144028512 144028544 144028576 testing c1a c1b c1c c2a c2b c2c c1anewname c1b c1c c2a c2bnewname c2c pvar 1 1 1 2 2 2 1 2 newpvar1 newpvar1 newpvar1 2 2 2 newpvar1 2 newpvar1 newpvar1 newpvar1 newpvar2 newpvar2 newpvar2 newpvar1 newpvar2 ``` Does anybody know why it is like that? I probably do not understand the internal way python works with this `__dict__` so well...
2011/02/24
[ "https://Stackoverflow.com/questions/5104366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/632263/" ]
I think your workaround is doable; You could use properties to make access to `P`'s attributes easier: ``` class P(object): def __init__(self,name='default',pvar=1): self.pname = name self.pvar=pvar class C(object): def __init__(self,name,pobject=P()): #<-- The same default `P()` is # used for all instances of `C`, # unless pobject is explicitly defined. self.cname = name self.pobject=pobject @property def pvar(self): return self.pobject.pvar @pvar.setter def pvar(self,val): self.pobject.pvar=val c1=C('1') c2=C('2') ``` `c1` and `c2` share the same `pobject`: ``` print(c1.pvar) # 1 c1.pvar=2 ``` Notice that changing `pvar` through `c1` changes `c2.pvar`: ``` print(c2.pvar) # 2 ``` `c3` has a different `pobject`: ``` c3=C('3',P()) print(c3.pvar) # 1 ``` --- Regarding OOP design for the psychology experiment (mentioned in the comments): ``` import Image class Picture(object): def __init__(self,filename): self.filename = filename self.image=Image.open(filename) class Person(object): def __init__(self,name): self.name=name # other vital statistics associated with people as individuals here class Trial(object): # A trial is composed of one person, one picture, and the places they look def __init__(self,person,picture,locations): self.person=person self.picture=picture self.locations = locations # put methods for analyzing where the person looked here ``` A `Picture` is certainly not a `Person`, nor vice versa. And the same goes for `Trial`s. So none of these classes should inherit from each other. Each of these classes have a public (and maybe a private) interface. Public methods and attributes should be freely accessible from other classes. So given a `Trial` instance, `t`, the image should be accessible through `t.picture.image`. As long as you are only accessing public attributes and methods, then everything should be fine. For convenience, you can use `properties` to link attributes to component-attributes. For example: ``` class Trial(object): ... @property def image(self): return self.picture.image ``` But to short-cut this by making, say, `Trial` a subclass of `Picture` would be contrary to fundamental OOP design principles.
Finally, I found a way to do it. The key point is to abandon the aim to obtain instances **c** with real **pvar** field, because it is impossible: Since it is the same **\_*init*\_()** function (the one being in class P) that processes to create the objects **pvar**, it isn't possible to create **pvar** in instances **c** that will points to the **pvar** in an instance **p** to mirror its value and that will also give the possibility to change this value of a **p**'s **pvar** each time a **c**'s **pvar**'s value will change. That makes too much contradictory conditions to verify. Consequently, since the instances **c** can't have a real **pvar** field, the best is to set up a mechanism controling the creation of ( with **\_*setattr*\_** ) and access to ( with **\_*getattr*\_** ) these **c**'s seemingly **pvar** objects to give the illusion that they exist. ``` class P(object): def __init__(self,pvar_arg,foo="^^^ "): self.pvar = pvar_arg self.cat = foo def printname(self): print self.name class C(P): def __init__(self,name,pobject,foo=''): self.__dict__['name'] = name P.__init__(self,None,pobject.cat+foo) C.dic[name] = pobject def __setattr__(self,xn,val): if xn!='pvar': self.__dict__[xn] = val elif self.name in C.dic: # During the creation of an instance c, # this condition is False because the instruction # C.dic[name] = pobject is written after # P.__init__(self,None,pobject.cat+foo). # Hence the value of pobject.pvar is preserved, # not changed with the value val being None # due to P.__init__(self,None,pobject.cat+foo) # that provokes self.pvar = pvar_arg and # consequently a call __setattr__(self,'pvar',None) C.dic[self.name].pvar = val def __getattribute__(self,xn): if xn=='pvar': return object.__getattribute__(C.dic[self.name],'pvar') else: return object.__getattribute__(self,xn) dic = {} p1 = P("1") p2 = P("2","QZX ") print '--- p1 = P("1") and p2 = P("2","QZX ") executed ---' print "p1.__dict__ ==",p1.__dict__ print "p2.__dict__ ==",p2.__dict__ print 'p1.pvar==',p1.pvar print 'p2.pvar==',p2.pvar c1a = C("c1a",p1,'sea') c1b = C("c1b",p1,'mountain') c1c = C("c1c",p1,'desert') c2a = C("c2a",p2,'banana') c2b = C("c2b",p2) c2c = C("c2c",p2,'pear') print '\n--- creations of c1a, c1b, c1c, c2a, c2b, c2c executed ---' print "p1.__dict__ ==",p1.__dict__ print "p2.__dict__ ==",p2.__dict__ print "c1a.__dict__ ==",c1a.__dict__ print "c1b.__dict__ ==",c1b.__dict__ print "c1c.__dict__ ==",c1c.__dict__ print "c2a.__dict__ ==",c2a.__dict__ print "c2b.__dict__ ==",c2b.__dict__ print "c2c.__dict__ ==",c2c.__dict__ print 'p1.pvar==',p1.pvar print 'p2.pvar==',p2.pvar print '(c1a.pvar, c1b.pvar, c1c.pvar)==',(c1a.pvar,c1b.pvar,c1c.pvar) print '(c2a.pvar, c2b.pvar, c2c.pvar)==',(c2a.pvar,c2b.pvar,c2c.pvar) c1a.pvar = "newpvar1" print '\n--- c1a.pvar = "newpvar1" executed ---' print 'p1.pvar==',p1.pvar print 'p2.pvar==',p2.pvar print '(c1a.pvar, c1b.pvar, c1c.pvar)==',(c1a.pvar,c1b.pvar,c1c.pvar) print '(c2a.pvar, c2b.pvar, c2c.pvar)==',(c2a.pvar,c2b.pvar,c2c.pvar) c2c.pvar = 45789 print '\n--- c2c.pvar = 45789 executed ---' print 'p1.pvar==',p1.pvar print 'p2.pvar==',p2.pvar print '(c1a.pvar, c1b.pvar, c1c.pvar)==',(c1a.pvar,c1b.pvar,c1c.pvar) print '(c2a.pvar, c2b.pvar, c2c.pvar)==',(c2a.pvar,c2b.pvar,c2c.pvar) ``` result ``` --- p1 = P("1") and p2 = P("2","QZX ") executed --- p1.__dict__ == {'cat': '^^^ ', 'pvar': '1'} p2.__dict__ == {'cat': 'QZX ', 'pvar': '2'} p1.pvar== 1 p2.pvar== 2 --- creations of c1a, c1b, c1c, c2a, c2b, c2c executed --- p1.__dict__ == {'cat': '^^^ ', 'pvar': '1'} p2.__dict__ == {'cat': 'QZX ', 'pvar': '2'} c1a.__dict__ == {'name': 'c1a', 'cat': '^^^ sea'} c1b.__dict__ == {'name': 'c1b', 'cat': '^^^ mountain'} c1c.__dict__ == {'name': 'c1c', 'cat': '^^^ desert'} c2a.__dict__ == {'name': 'c2a', 'cat': 'QZX banana'} c2b.__dict__ == {'name': 'c2b', 'cat': 'QZX '} c2c.__dict__ == {'name': 'c2c', 'cat': 'QZX pear'} p1.pvar== 1 p2.pvar== 2 (c1a.pvar, c1b.pvar, c1c.pvar)== ('1', '1', '1') (c2a.pvar, c2b.pvar, c2c.pvar)== ('2', '2', '2') --- c1a.pvar = "newpvar1" executed --- p1.pvar== newpvar1 p2.pvar== 2 (c1a.pvar, c1b.pvar, c1c.pvar)== ('newpvar1', 'newpvar1', 'newpvar1') (c2a.pvar, c2b.pvar, c2c.pvar)== ('2', '2', '2') --- c2c.pvar = 45789 executed --- p1.pvar== newpvar1 p2.pvar== 45789 (c1a.pvar, c1b.pvar, c1c.pvar)== ('newpvar1', 'newpvar1', 'newpvar1') (c2a.pvar, c2b.pvar, c2c.pvar)== (45789, 45789, 45789) ``` Remarks: 1. the attribute **name** must be defined before the instruction P.**init**(self,None,pobject.cat+foo) ------------------------------------- because the execution of this instruction calls `__setattr__(self,'pvar',"1")` that executes itself the instruction `C.dic[self.name].pvar = "1"` when `c1a = C("c1a",p1,'sea')` is executed, for example. AnHence this call needs **self.name** as key for dic. 2. I introduced **foo** and **cat** to justify the need to write the instruction P.**init**(self,None,pobject.cat+foo) ------------------------------------- otherwise, as no **pvar** is in fact defined into the instances **c** , this instuction wouldn't be useful. 3. There are two situations in which `__setattr__` is called: at the creation of an instance, and at the modifications of the attributes of an existing instance. When an instance is created, the value of **pvar** of the instance **p** must remain unaffected by the instruction `C.dic[self.name].pvar = None` . Hence the condition `elif self.name in C.dic:` In order that this condition gives a correct result, the instruction `C.dic[name] = pobject` must follow the call to `P.__init__(self,None,pobject.cat+foo)` . EDIT 1 I think it's better to write ``` def __setattr__(self,xn,val): if xn=='pvar': self.__class__.dic[self.name].pvar = val ``` than ``` def __setattr__(self,xn,val): if xn=='pvar': C.dic[self.name].pvar = val ``` In the first case, the interpreter has to search for the reference to the **self**'s class **C** ( that is to say under the name **'\_*class*\_'** ) in the namespace of self. In the second case, the interpreter must search for the same reference ( but under the name **'C'**) in the namespace of the level in which classes **P** and **C** are defined. This second namespace may be more more big than the limited namespace of an instance. In the first case, the name **'\_*class*\_'** is looked for as a key in the dictionary implementing the self's namespace. In the second, the name **'C'** is the key searched for in the dictionary of the level inclosing the classes **P** and **C**. The identity of these two objects can be verified with the function **id()** . . EDIT 2 There is another possibility for the `dic` object: instead of making it a class attribute of the class **C**, it can be defined in the outer scope of the class **C**. If this outer level is a module, then **dic** is a global object. ``` class P(object): def __init__(self,pvar,foo="^^^ "): self.pvar = pvar self.cat = foo def printname(self): print self.name class C(P): def __init__(self,name,pobject,foo=''): self.__dict__['name'] = name P.__init__(self,None,pobject.cat+foo) dic[name] = pobject def __setattr__(self,xn,val): if xn!='pvar': self.__dict__[xn] = val elif self.name in dic: # During the creation of an instance c, # this condition is False because the instruction # dic[name] = pobject is written after # P.__init__(self,None,pobject.cat+foo). # Hence the value of pobject.pvar is preserved, # not changed with the value val being None # due to P.__init__(self,None,pobject.cat+foo) # that provokes self.pvar = pvar_arg and # consequently a call __setattr__(self,'pvar',None) dic[self.name].pvar = val def __getattribute__(self,xn): if xn=='pvar': return object.__getattribute__(dic[self.name],'pvar') else: return object.__getattribute__(self,xn) dic = {} ``` The result is exactly the same Doing so, **dic** looses its OOish nature. . . EDIT 3 At last, there is still another way: instead of creating an illusory attribute **pvar** for each instance **c** with help of functions `__setattr__` and `__getattribute__` , it is better, according to me, to use a function with the dictionary **dic** as a default argument and that will replace them. ``` class P(object): def __init__(self,pvar,foo="^^^ "): self.pvar = pvar self.cat = foo def printname(self): print self.name class C(P): def __init__(self,name,pobject,foo=''): P.__init__(self,None,pobject.cat+foo) self.__dict__['name'] = name del self.pvar self.pvar(pobject) def pvar(self,x = None,dic = {}): if x.__class__==P: # a pobject dic[self.name] = x elif x: # a value dic[self.name].pvar = x else: # to return value return dic[self.name].pvar p1 = P("1") p2 = P("2","QZX ") print '--- p1 = P("1") and p2 = P("2","QZX ") executed ---' print "p1.__dict__ ==",p1.__dict__ print "p2.__dict__ ==",p2.__dict__ print 'p1.pvar==',p1.pvar print 'p2.pvar==',p2.pvar c1a = C("c1a",p1,'sea') c1b = C("c1b",p1,'mountain') c1c = C("c1c",p1,'desert') c2a = C("c2a",p2,'banana') c2b = C("c2b",p2) c2c = C("c2c",p2,'pear') print '\n--- creations of c1a, c1b, c1c, c2a, c2b, c2c executed ---' print "p1.__dict__ ==",p1.__dict__ print "p2.__dict__ ==",p2.__dict__ print "c1a.__dict__ ==",c1a.__dict__ print "c1b.__dict__ ==",c1b.__dict__ print "c1c.__dict__ ==",c1c.__dict__ print "c2a.__dict__ ==",c2a.__dict__ print "c2b.__dict__ ==",c2b.__dict__ print "c2c.__dict__ ==",c2c.__dict__ print 'p1.pvar==',p1.pvar print 'p2.pvar==',p2.pvar print '(c1a.pvar(),c1b.pvar(),c1c.pvar())==',(c1a.pvar(),c1b.pvar(),c1c.pvar()) print '(c2a.pvar(),c2b.pvar(),c2c.pvar())==',(c2a.pvar(),c2b.pvar(),c2c.pvar()) c1a.pvar("newpvar1") print '\n--- c1a.pvar("newpvar1") executed ---' print 'p1.pvar==',p1.pvar print 'p2.pvar==',p2.pvar print '(c1a.pvar(),c1b.pvar(),c1c.pvar())==',(c1a.pvar(),c1b.pvar(),c1c.pvar()) print '(c2a.pvar(),c2b.pvar(),c2c.pvar())==',(c2a.pvar(),c2b.pvar(),c2c.pvar()) c2c.pvar(45789) print '\n--- c2c.pvar(45789) ---' print 'p1.pvar==',p1.pvar print 'p2.pvar==',p2.pvar print '(c1a.pvar(),c1b.pvar(),c1c.pvar())==',(c1a.pvar(),c1b.pvar(),c1c.pvar()) print '(c2a.pvar(),c2b.pvar(),c2c.pvar())==',(c2a.pvar(),c2b.pvar(),c2c.pvar()) ``` Results are the same, only use of c.pvar() is slightly different: ``` --- p1 = P("1") and p2 = P("2","QZX ") executed --- p1.__dict__ == {'cat': '^^^ ', 'pvar': '1'} p2.__dict__ == {'cat': 'QZX ', 'pvar': '2'} p1.pvar== 1 p2.pvar== 2 --- creations of c1a, c1b, c1c, c2a, c2b, c2c executed --- p1.__dict__ == {'cat': '^^^ ', 'pvar': '1'} p2.__dict__ == {'cat': 'QZX ', 'pvar': '2'} c1a.__dict__ == {'cat': '^^^ sea', 'name': 'c1a'} c1b.__dict__ == {'cat': '^^^ mountain', 'name': 'c1b'} c1c.__dict__ == {'cat': '^^^ desert', 'name': 'c1c'} c2a.__dict__ == {'cat': 'QZX banana', 'name': 'c2a'} c2b.__dict__ == {'cat': 'QZX ', 'name': 'c2b'} c2c.__dict__ == {'cat': 'QZX pear', 'name': 'c2c'} p1.pvar== 1 p2.pvar== 2 (c1a.pvar(),c1b.pvar(),c1c.pvar())== ('1', '1', '1') (c2a.pvar(),c2b.pvar(),c2c.pvar())== ('2', '2', '2') --- c1a.pvar("newpvar1") executed --- p1.pvar== newpvar1 p2.pvar== 2 (c1a.pvar(),c1b.pvar(),c1c.pvar())== ('newpvar1', 'newpvar1', 'newpvar1') (c2a.pvar(),c2b.pvar(),c2c.pvar())== ('2', '2', '2') --- c2c.pvar(45789) --- p1.pvar== newpvar1 p2.pvar== 45789 (c1a.pvar(),c1b.pvar(),c1c.pvar())== ('newpvar1', 'newpvar1', 'newpvar1') (c2a.pvar(),c2b.pvar(),c2c.pvar())== (45789, 45789, 45789) ``` Note that in this last code **P**'s instances can't be values of **C**'instances because a **pobject** passed to a **c.pvar()** method will never be considered as a value.
5,104,366
users, I have a basic question concerning inheritance (in python). I have two classes and one of them is inherited from the other like ``` class p: def __init__(self,name): self.pname = name class c(p): def __init__(self,name): self.cname = name ``` Is there any possibility that I can create a parent object and several child objects which refer to the SAME parent object? It should work like that that the parent object contains several variables and whenever I access the corresponding variables from a child I actually access the variable form the parent. I.e. if I change it for one child it is changed also for all other childes and the data are only stored once in memory (and not copied for each child...) Thank you in advance. Here is a possible workaround which I do not consider as so nice ``` class P: def __init__(self, name): self.pname = name class C: def __init__(self, name,pobject): self.pobject = pobject self.cname = name ``` Is this really the state of the art or do there exist other concepts? Sebastian Thank you all for helping me, also with the name conventions :) But I am still not very satisfied. Maybe I give a more advanced example to stress what I really want to do. ``` class P: data = "shareddata" def __init__(self,newdata): self.data = newdata def printname(self): print self.name class C(P): def __init__(self,name): self.name = name ``` Now I can do the following ``` In [33]: c1 = test.C("name1") In [34]: c2 = test.C("name2") In [35]: c1.printname() name1 In [36]: c2.printname() name2 In [37]: c1.data Out[37]: 'shareddata' In [38]: c2.data Out[38]: 'shareddata' ``` And this is so far exactly what I want. There is a variable name which is different for every child and the parent class accesses the individual variables. Normal inheritance. Then there is the variable data which comes from the parent class and every child access it. However, now the following does not work any more ``` In [39]: c1.data = "tst" In [40]: c2.data Out[40]: 'shareddata' In [41]: c1.data Out[41]: 'tst' ``` I want the change in c1.data to affect also c2.data since I want the variable to be shared, somehow a global variable of this parent class. And more than that. I also want to create different instances of P, each having its own data variable. And when I create a new C object I want to specify from which P object data should be inhetited i.e. shared.... UPDATE: remark to the comment of @eyquem: Thanks for this, it is going into the direction I want. However, now the `__class__.pvar` is shared among all objects of the class. What I want is that several instances of P may have a different pvar. Lets assume P1 has pvar=1 and P2 has pvar=2. Then I want to create children C1a, C1b, C1c which are related to P1, i.e. if I say C1a.pvar it should acess pvar from P1. Then I create C2a, C2b, C2c and if I access i.e. C2b.pvar I want to access pvar from P2. Since the class C inherits pvar from the class P pvar is known to C. My naive idea is that if I create a new instance of C I should be able to specify which (existing) P object should be used as the parent object and not to create a completely new P object as it is done when calling `P.__init__` inside of the `__init__` of C... It sounds simple to me, maybe I forget something... UPDATE: So I found [this discussion](http://www.velocityreviews.com/forums/t356880-can-you-create-an-instance-of-a-subclass-with-an-existing-instance-of-the-base-class.html) which is pretty much my question Any suggestions? UPDATE: The method .**class**.\_*subclasses*\_ seems to be not existing any more.. UPDATE: Here is onother link: [link to discussion](http://bytes.com/topic/python/answers/834541-using-existing-instance-parent) There it is solved by copying. But I do not want to copy the parent class since I would like that it exists only once... UPDATE: Sorry for leaving the discussion yesterday, I am a bit ill... And thank you for the posts! I will now read through them. I thought about it a bit more and here is a possible solution I found ``` class P(object): def __init__(self,pvar): self.pobject = None self._pvar = pvar @property def pvar(self): if self.pobject != None: return self.pobject.pvar else: return self._pvar @pvar.setter def pvar(self,val): if self.pobject != None: self.pobject.pvar = val else: self._pvar=val def printname(self): print self.name class C(P): def __init__(self,name,pobject): #<-- The same default `P()` is # used for all instances of `C`, # unless pobject is explicitly defined. P.__init__(self,None) self.name = name self.pobject = pobject p1 = P("1") p2 = P("2") c1a = C("c1a",p1) c1b = C("c1b",p1) c1c = C("c1c",p1) c2a = C("c2a",p2) c2b = C("c2b",p2) c2c = C("c2c",p2) print id(c1a.pvar) print id(c1b.pvar) print id(c1c.pvar) print id(c2a.pvar) print id(c2b.pvar) print id(c2c.pvar) print id(p1.pvar) print id(p2.pvar) print id(c1a.name) print id(c1b.name) print id(c1c.name) print id(c2a.name) print id(c2b.name) print id(c2c.name) ``` It is a bit cumbersome and I hope that there is a simpler way to achieve this. But it has the feature that pvar is only mentioned in the class P and the class C does not know about pvar as it should be according to my understanding of inheritance. Nevertheless when I create a new instance of C I can specify an existing instance of P which will be stored in the variable pobject. When the variable pvar is accessed actually pvar of the P-instance stored in this variable is accessed... The output is given by ``` 3078326816 3078326816 3078326816 3074996544 3074996544 3074996544 3078326816 3074996544 156582944 156583040 156583200 156583232 156583296 156583360 ``` I will read now through your last comments, all the best, Sebastian UPDATE: I think the most elegant way would be the following (which DOES NOT work) ``` class P(object): def __init__(self,pvar): self.pvar = pvar def printname(self): print self.name class C(P): def __init__(self,name,pobject): P = pobject self.name = name ``` I think python should allow for this... UPDATE: Ok, now I found a way to achieve this, due to the explanations by eyquem. But Since this is really a hack there should be an official version for the same... ``` def replaceinstance(parent,child): for item in parent.__dict__.items(): child.__dict__.__setitem__(item[0],item[1]) print item class P(object): def __init__(self,pvar): self.pvar = pvar def printname(self): print self.name class C(P): def __init__(self,name,pobject): P.__init__(self,None) replaceinstance(pobject,self) self.name = name p1 = P("1") p2 = P("2") c1a = C("c1a",p1) c1b = C("c1b",p1) c1c = C("c1c",p1) c2a = C("c2a",p2) c2b = C("c2b",p2) c2c = C("c2c",p2) print id(c1a.pvar) print id(c1b.pvar) print id(c1c.pvar) print id(c2a.pvar) print id(c2b.pvar) print id(c2c.pvar) print id(p1.pvar) print id(p2.pvar) print id(c1a.name) print id(c1b.name) print id(c1c.name) print id(c2a.name) print id(c2b.name) print id(c2c.name) ``` the output is the same as above ``` 3077745184 3077745184 3077745184 3074414912 3074414912 3074414912 3077745184 3074414912 144028416 144028448 144028480 144028512 144028544 144028576 ``` UPDATE: Even if the id's seem to be right, the last code does not work as is clear from this test ``` c1a.pvar = "newpvar1" print c1a.pvar print c1b.pvar print c1c.pvar print c2a.pvar print c2b.pvar print c2c.pvar print p1.pvar print p2.pvar ``` it has the output ``` newpvar1 1 1 2 2 2 1 2 ``` However the version I posted first works: ``` class P(object): def __init__(self,pvar): self.pobject = None self._pvar = pvar @property def pvar(self): if self.pobject != None: return self.pobject.pvar else: return self._pvar @pvar.setter def pvar(self,val): if self.pobject != None: self.pobject.pvar = val else: self._pvar=val def printname(self): print self.name class C(P): def __init__(self,name,pobject): #<-- The same default `P()` is # used for all instances of `C`, # unless pobject is explicitly defined. P.__init__(self,None) self.name = name self.pobject = pobject p1 = P("1") p2 = P("2") c1a = C("c1a",p1) c1b = C("c1b",p1) c1c = C("c1c",p1) c2a = C("c2a",p2) c2b = C("c2b",p2) c2c = C("c2c",p2) print id(c1a.pvar) print id(c1b.pvar) print id(c1c.pvar) print id(c2a.pvar) print id(c2b.pvar) print id(c2c.pvar) print id(p1.pvar) print id(p2.pvar) print id(c1a.name) print id(c1b.name) print id(c1c.name) print id(c2a.name) print id(c2b.name) print id(c2c.name) print "testing\n" c1a.printname() c1b.printname() c1c.printname() c2a.printname() c2b.printname() c2c.printname() print "\n" c1a.name = "c1anewname" c2b.name = "c2bnewname" c1a.printname() c1b.printname() c1c.printname() c2a.printname() c2b.printname() c2c.printname() print "pvar\n" print c1a.pvar print c1b.pvar print c1c.pvar print c2a.pvar print c2b.pvar print c2c.pvar print p1.pvar print p2.pvar print "\n" c1a.pvar = "newpvar1" print c1a.pvar print c1b.pvar print c1c.pvar print c2a.pvar print c2b.pvar print c2c.pvar print p1.pvar print p2.pvar print "\n" c2c.pvar = "newpvar2" print c1a.pvar print c1b.pvar print c1c.pvar print c2a.pvar print c2b.pvar print c2c.pvar print p1.pvar print p2.pvar ``` with the output ``` 3077745184 3077745184 3077745184 3074414912 3074414912 3074414912 3077745184 3074414912 144028416 144028448 144028480 144028512 144028544 144028576 testing c1a c1b c1c c2a c2b c2c c1anewname c1b c1c c2a c2bnewname c2c pvar 1 1 1 2 2 2 1 2 newpvar1 newpvar1 newpvar1 2 2 2 newpvar1 2 newpvar1 newpvar1 newpvar1 newpvar2 newpvar2 newpvar2 newpvar1 newpvar2 ``` Does anybody know why it is like that? I probably do not understand the internal way python works with this `__dict__` so well...
2011/02/24
[ "https://Stackoverflow.com/questions/5104366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/632263/" ]
> > It should work like that that the parent object contains several variables and whenever I access the corresponding variables from a child I actually access the variable form the parent. I.e. if I change it for one child it is changed also for all other childes and the data are only stored once in memory (and not copied for each child...) > > > That's not inheritance. That's a completely different concept. Your "shared variables" are simply objects that can be mutated and have references in other objects. Nothing interesting. Inheritance is completely different from this.
I think your workaround is doable; You could use properties to make access to `P`'s attributes easier: ``` class P(object): def __init__(self,name='default',pvar=1): self.pname = name self.pvar=pvar class C(object): def __init__(self,name,pobject=P()): #<-- The same default `P()` is # used for all instances of `C`, # unless pobject is explicitly defined. self.cname = name self.pobject=pobject @property def pvar(self): return self.pobject.pvar @pvar.setter def pvar(self,val): self.pobject.pvar=val c1=C('1') c2=C('2') ``` `c1` and `c2` share the same `pobject`: ``` print(c1.pvar) # 1 c1.pvar=2 ``` Notice that changing `pvar` through `c1` changes `c2.pvar`: ``` print(c2.pvar) # 2 ``` `c3` has a different `pobject`: ``` c3=C('3',P()) print(c3.pvar) # 1 ``` --- Regarding OOP design for the psychology experiment (mentioned in the comments): ``` import Image class Picture(object): def __init__(self,filename): self.filename = filename self.image=Image.open(filename) class Person(object): def __init__(self,name): self.name=name # other vital statistics associated with people as individuals here class Trial(object): # A trial is composed of one person, one picture, and the places they look def __init__(self,person,picture,locations): self.person=person self.picture=picture self.locations = locations # put methods for analyzing where the person looked here ``` A `Picture` is certainly not a `Person`, nor vice versa. And the same goes for `Trial`s. So none of these classes should inherit from each other. Each of these classes have a public (and maybe a private) interface. Public methods and attributes should be freely accessible from other classes. So given a `Trial` instance, `t`, the image should be accessible through `t.picture.image`. As long as you are only accessing public attributes and methods, then everything should be fine. For convenience, you can use `properties` to link attributes to component-attributes. For example: ``` class Trial(object): ... @property def image(self): return self.picture.image ``` But to short-cut this by making, say, `Trial` a subclass of `Picture` would be contrary to fundamental OOP design principles.
5,104,366
users, I have a basic question concerning inheritance (in python). I have two classes and one of them is inherited from the other like ``` class p: def __init__(self,name): self.pname = name class c(p): def __init__(self,name): self.cname = name ``` Is there any possibility that I can create a parent object and several child objects which refer to the SAME parent object? It should work like that that the parent object contains several variables and whenever I access the corresponding variables from a child I actually access the variable form the parent. I.e. if I change it for one child it is changed also for all other childes and the data are only stored once in memory (and not copied for each child...) Thank you in advance. Here is a possible workaround which I do not consider as so nice ``` class P: def __init__(self, name): self.pname = name class C: def __init__(self, name,pobject): self.pobject = pobject self.cname = name ``` Is this really the state of the art or do there exist other concepts? Sebastian Thank you all for helping me, also with the name conventions :) But I am still not very satisfied. Maybe I give a more advanced example to stress what I really want to do. ``` class P: data = "shareddata" def __init__(self,newdata): self.data = newdata def printname(self): print self.name class C(P): def __init__(self,name): self.name = name ``` Now I can do the following ``` In [33]: c1 = test.C("name1") In [34]: c2 = test.C("name2") In [35]: c1.printname() name1 In [36]: c2.printname() name2 In [37]: c1.data Out[37]: 'shareddata' In [38]: c2.data Out[38]: 'shareddata' ``` And this is so far exactly what I want. There is a variable name which is different for every child and the parent class accesses the individual variables. Normal inheritance. Then there is the variable data which comes from the parent class and every child access it. However, now the following does not work any more ``` In [39]: c1.data = "tst" In [40]: c2.data Out[40]: 'shareddata' In [41]: c1.data Out[41]: 'tst' ``` I want the change in c1.data to affect also c2.data since I want the variable to be shared, somehow a global variable of this parent class. And more than that. I also want to create different instances of P, each having its own data variable. And when I create a new C object I want to specify from which P object data should be inhetited i.e. shared.... UPDATE: remark to the comment of @eyquem: Thanks for this, it is going into the direction I want. However, now the `__class__.pvar` is shared among all objects of the class. What I want is that several instances of P may have a different pvar. Lets assume P1 has pvar=1 and P2 has pvar=2. Then I want to create children C1a, C1b, C1c which are related to P1, i.e. if I say C1a.pvar it should acess pvar from P1. Then I create C2a, C2b, C2c and if I access i.e. C2b.pvar I want to access pvar from P2. Since the class C inherits pvar from the class P pvar is known to C. My naive idea is that if I create a new instance of C I should be able to specify which (existing) P object should be used as the parent object and not to create a completely new P object as it is done when calling `P.__init__` inside of the `__init__` of C... It sounds simple to me, maybe I forget something... UPDATE: So I found [this discussion](http://www.velocityreviews.com/forums/t356880-can-you-create-an-instance-of-a-subclass-with-an-existing-instance-of-the-base-class.html) which is pretty much my question Any suggestions? UPDATE: The method .**class**.\_*subclasses*\_ seems to be not existing any more.. UPDATE: Here is onother link: [link to discussion](http://bytes.com/topic/python/answers/834541-using-existing-instance-parent) There it is solved by copying. But I do not want to copy the parent class since I would like that it exists only once... UPDATE: Sorry for leaving the discussion yesterday, I am a bit ill... And thank you for the posts! I will now read through them. I thought about it a bit more and here is a possible solution I found ``` class P(object): def __init__(self,pvar): self.pobject = None self._pvar = pvar @property def pvar(self): if self.pobject != None: return self.pobject.pvar else: return self._pvar @pvar.setter def pvar(self,val): if self.pobject != None: self.pobject.pvar = val else: self._pvar=val def printname(self): print self.name class C(P): def __init__(self,name,pobject): #<-- The same default `P()` is # used for all instances of `C`, # unless pobject is explicitly defined. P.__init__(self,None) self.name = name self.pobject = pobject p1 = P("1") p2 = P("2") c1a = C("c1a",p1) c1b = C("c1b",p1) c1c = C("c1c",p1) c2a = C("c2a",p2) c2b = C("c2b",p2) c2c = C("c2c",p2) print id(c1a.pvar) print id(c1b.pvar) print id(c1c.pvar) print id(c2a.pvar) print id(c2b.pvar) print id(c2c.pvar) print id(p1.pvar) print id(p2.pvar) print id(c1a.name) print id(c1b.name) print id(c1c.name) print id(c2a.name) print id(c2b.name) print id(c2c.name) ``` It is a bit cumbersome and I hope that there is a simpler way to achieve this. But it has the feature that pvar is only mentioned in the class P and the class C does not know about pvar as it should be according to my understanding of inheritance. Nevertheless when I create a new instance of C I can specify an existing instance of P which will be stored in the variable pobject. When the variable pvar is accessed actually pvar of the P-instance stored in this variable is accessed... The output is given by ``` 3078326816 3078326816 3078326816 3074996544 3074996544 3074996544 3078326816 3074996544 156582944 156583040 156583200 156583232 156583296 156583360 ``` I will read now through your last comments, all the best, Sebastian UPDATE: I think the most elegant way would be the following (which DOES NOT work) ``` class P(object): def __init__(self,pvar): self.pvar = pvar def printname(self): print self.name class C(P): def __init__(self,name,pobject): P = pobject self.name = name ``` I think python should allow for this... UPDATE: Ok, now I found a way to achieve this, due to the explanations by eyquem. But Since this is really a hack there should be an official version for the same... ``` def replaceinstance(parent,child): for item in parent.__dict__.items(): child.__dict__.__setitem__(item[0],item[1]) print item class P(object): def __init__(self,pvar): self.pvar = pvar def printname(self): print self.name class C(P): def __init__(self,name,pobject): P.__init__(self,None) replaceinstance(pobject,self) self.name = name p1 = P("1") p2 = P("2") c1a = C("c1a",p1) c1b = C("c1b",p1) c1c = C("c1c",p1) c2a = C("c2a",p2) c2b = C("c2b",p2) c2c = C("c2c",p2) print id(c1a.pvar) print id(c1b.pvar) print id(c1c.pvar) print id(c2a.pvar) print id(c2b.pvar) print id(c2c.pvar) print id(p1.pvar) print id(p2.pvar) print id(c1a.name) print id(c1b.name) print id(c1c.name) print id(c2a.name) print id(c2b.name) print id(c2c.name) ``` the output is the same as above ``` 3077745184 3077745184 3077745184 3074414912 3074414912 3074414912 3077745184 3074414912 144028416 144028448 144028480 144028512 144028544 144028576 ``` UPDATE: Even if the id's seem to be right, the last code does not work as is clear from this test ``` c1a.pvar = "newpvar1" print c1a.pvar print c1b.pvar print c1c.pvar print c2a.pvar print c2b.pvar print c2c.pvar print p1.pvar print p2.pvar ``` it has the output ``` newpvar1 1 1 2 2 2 1 2 ``` However the version I posted first works: ``` class P(object): def __init__(self,pvar): self.pobject = None self._pvar = pvar @property def pvar(self): if self.pobject != None: return self.pobject.pvar else: return self._pvar @pvar.setter def pvar(self,val): if self.pobject != None: self.pobject.pvar = val else: self._pvar=val def printname(self): print self.name class C(P): def __init__(self,name,pobject): #<-- The same default `P()` is # used for all instances of `C`, # unless pobject is explicitly defined. P.__init__(self,None) self.name = name self.pobject = pobject p1 = P("1") p2 = P("2") c1a = C("c1a",p1) c1b = C("c1b",p1) c1c = C("c1c",p1) c2a = C("c2a",p2) c2b = C("c2b",p2) c2c = C("c2c",p2) print id(c1a.pvar) print id(c1b.pvar) print id(c1c.pvar) print id(c2a.pvar) print id(c2b.pvar) print id(c2c.pvar) print id(p1.pvar) print id(p2.pvar) print id(c1a.name) print id(c1b.name) print id(c1c.name) print id(c2a.name) print id(c2b.name) print id(c2c.name) print "testing\n" c1a.printname() c1b.printname() c1c.printname() c2a.printname() c2b.printname() c2c.printname() print "\n" c1a.name = "c1anewname" c2b.name = "c2bnewname" c1a.printname() c1b.printname() c1c.printname() c2a.printname() c2b.printname() c2c.printname() print "pvar\n" print c1a.pvar print c1b.pvar print c1c.pvar print c2a.pvar print c2b.pvar print c2c.pvar print p1.pvar print p2.pvar print "\n" c1a.pvar = "newpvar1" print c1a.pvar print c1b.pvar print c1c.pvar print c2a.pvar print c2b.pvar print c2c.pvar print p1.pvar print p2.pvar print "\n" c2c.pvar = "newpvar2" print c1a.pvar print c1b.pvar print c1c.pvar print c2a.pvar print c2b.pvar print c2c.pvar print p1.pvar print p2.pvar ``` with the output ``` 3077745184 3077745184 3077745184 3074414912 3074414912 3074414912 3077745184 3074414912 144028416 144028448 144028480 144028512 144028544 144028576 testing c1a c1b c1c c2a c2b c2c c1anewname c1b c1c c2a c2bnewname c2c pvar 1 1 1 2 2 2 1 2 newpvar1 newpvar1 newpvar1 2 2 2 newpvar1 2 newpvar1 newpvar1 newpvar1 newpvar2 newpvar2 newpvar2 newpvar1 newpvar2 ``` Does anybody know why it is like that? I probably do not understand the internal way python works with this `__dict__` so well...
2011/02/24
[ "https://Stackoverflow.com/questions/5104366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/632263/" ]
The other answer is right, your question is more about namespaces and references than about inheritance. All variables in Python are references, and all object instance is a namespace. So you can do: ``` class C(): def __init__(self, x): self.x = x class Shared(object): def __init__(self, value): self.value = value # instances: >>> shared1 = Shared(1) >>> shared2 = Shared(2) >>> c1 = C(shared1) >>> c2 = C(shared1) >>> c3 = C(shared2) >>> c4 = C(shared2) # c1 and c2 sharing a reference to shared1 >>> c1.x.value 1 >>> c2.x.value 1 # change c2.x will reflect on c1 >>> c2.x.value = 3 >>> c1.x.value 3 # but not on c3, because shared1 and shared2 are distinct namespaces >>> c3.x.value 2 ``` UPDATE: But watch out, it is easy to make a mistake: ``` >>> c4.x = 4 >>> c3.x.value 2 >>> c4.x.value Traceback (most recent call last): File "<interactive input>", line 1, in <module> AttributeError: 'int' object has no attribute 'value' >>> ``` I think the state of the art would be using [properties](http://docs.python.org/library/functions.html#property) to hide the [`__shared_instance`](http://docs.python.org/tutorial/classes.html#private-variables) in a private instance variable - so you can use c1.x instead of c1.x.value and avoid a typo like the example above.
Okay, I think you might want to rephrase your question as: **How can I extend Python's OOP to make inheritance work on the level of objects rather than classes?** *First off - don't mess with the dicts:* If you are just copying the entries of the parent dict over to the child-dict, this works for instantiation, but changes in any of the dicts will not automagically update entries in all the other dicts. Assigning a new value to an attribute will simply create a new reference, so the attribute will not point to the same object any more. The solution is to tell python to look for the attribute in the right place using some Python magic ... ``` class ProxyMixin (object): def __init__(self, parent): self.parent = parent def __getattribute__(self, name): if name != 'parent' and hasattr(self.parent, name): return getattr(self.parent, name) else: return object.__getattribute__(self, name) def __setattr__(self, name, val): if name != 'parent' and hasattr(self.parent, name): setattr(self.parent, name) else: object.__setattr__(self, name, val) ``` (see the [python reference on attribute access](http://docs.python.org/reference/datamodel.html#attribute-access)) Just add the ProxyMixin to your child class, and you will be fine. ``` class P: data = "shared data" def __init__(self, name): self.name = name def printname(self): print self.name class C(P, ProxyMixin): def __init__(self, parent=None): if parent: ProxyMixin.__init__(self, parent) ``` Now youn can dynamically rewire the parent object at any time using a simple assignment: ``` c.parent = newparent ```
5,104,366
users, I have a basic question concerning inheritance (in python). I have two classes and one of them is inherited from the other like ``` class p: def __init__(self,name): self.pname = name class c(p): def __init__(self,name): self.cname = name ``` Is there any possibility that I can create a parent object and several child objects which refer to the SAME parent object? It should work like that that the parent object contains several variables and whenever I access the corresponding variables from a child I actually access the variable form the parent. I.e. if I change it for one child it is changed also for all other childes and the data are only stored once in memory (and not copied for each child...) Thank you in advance. Here is a possible workaround which I do not consider as so nice ``` class P: def __init__(self, name): self.pname = name class C: def __init__(self, name,pobject): self.pobject = pobject self.cname = name ``` Is this really the state of the art or do there exist other concepts? Sebastian Thank you all for helping me, also with the name conventions :) But I am still not very satisfied. Maybe I give a more advanced example to stress what I really want to do. ``` class P: data = "shareddata" def __init__(self,newdata): self.data = newdata def printname(self): print self.name class C(P): def __init__(self,name): self.name = name ``` Now I can do the following ``` In [33]: c1 = test.C("name1") In [34]: c2 = test.C("name2") In [35]: c1.printname() name1 In [36]: c2.printname() name2 In [37]: c1.data Out[37]: 'shareddata' In [38]: c2.data Out[38]: 'shareddata' ``` And this is so far exactly what I want. There is a variable name which is different for every child and the parent class accesses the individual variables. Normal inheritance. Then there is the variable data which comes from the parent class and every child access it. However, now the following does not work any more ``` In [39]: c1.data = "tst" In [40]: c2.data Out[40]: 'shareddata' In [41]: c1.data Out[41]: 'tst' ``` I want the change in c1.data to affect also c2.data since I want the variable to be shared, somehow a global variable of this parent class. And more than that. I also want to create different instances of P, each having its own data variable. And when I create a new C object I want to specify from which P object data should be inhetited i.e. shared.... UPDATE: remark to the comment of @eyquem: Thanks for this, it is going into the direction I want. However, now the `__class__.pvar` is shared among all objects of the class. What I want is that several instances of P may have a different pvar. Lets assume P1 has pvar=1 and P2 has pvar=2. Then I want to create children C1a, C1b, C1c which are related to P1, i.e. if I say C1a.pvar it should acess pvar from P1. Then I create C2a, C2b, C2c and if I access i.e. C2b.pvar I want to access pvar from P2. Since the class C inherits pvar from the class P pvar is known to C. My naive idea is that if I create a new instance of C I should be able to specify which (existing) P object should be used as the parent object and not to create a completely new P object as it is done when calling `P.__init__` inside of the `__init__` of C... It sounds simple to me, maybe I forget something... UPDATE: So I found [this discussion](http://www.velocityreviews.com/forums/t356880-can-you-create-an-instance-of-a-subclass-with-an-existing-instance-of-the-base-class.html) which is pretty much my question Any suggestions? UPDATE: The method .**class**.\_*subclasses*\_ seems to be not existing any more.. UPDATE: Here is onother link: [link to discussion](http://bytes.com/topic/python/answers/834541-using-existing-instance-parent) There it is solved by copying. But I do not want to copy the parent class since I would like that it exists only once... UPDATE: Sorry for leaving the discussion yesterday, I am a bit ill... And thank you for the posts! I will now read through them. I thought about it a bit more and here is a possible solution I found ``` class P(object): def __init__(self,pvar): self.pobject = None self._pvar = pvar @property def pvar(self): if self.pobject != None: return self.pobject.pvar else: return self._pvar @pvar.setter def pvar(self,val): if self.pobject != None: self.pobject.pvar = val else: self._pvar=val def printname(self): print self.name class C(P): def __init__(self,name,pobject): #<-- The same default `P()` is # used for all instances of `C`, # unless pobject is explicitly defined. P.__init__(self,None) self.name = name self.pobject = pobject p1 = P("1") p2 = P("2") c1a = C("c1a",p1) c1b = C("c1b",p1) c1c = C("c1c",p1) c2a = C("c2a",p2) c2b = C("c2b",p2) c2c = C("c2c",p2) print id(c1a.pvar) print id(c1b.pvar) print id(c1c.pvar) print id(c2a.pvar) print id(c2b.pvar) print id(c2c.pvar) print id(p1.pvar) print id(p2.pvar) print id(c1a.name) print id(c1b.name) print id(c1c.name) print id(c2a.name) print id(c2b.name) print id(c2c.name) ``` It is a bit cumbersome and I hope that there is a simpler way to achieve this. But it has the feature that pvar is only mentioned in the class P and the class C does not know about pvar as it should be according to my understanding of inheritance. Nevertheless when I create a new instance of C I can specify an existing instance of P which will be stored in the variable pobject. When the variable pvar is accessed actually pvar of the P-instance stored in this variable is accessed... The output is given by ``` 3078326816 3078326816 3078326816 3074996544 3074996544 3074996544 3078326816 3074996544 156582944 156583040 156583200 156583232 156583296 156583360 ``` I will read now through your last comments, all the best, Sebastian UPDATE: I think the most elegant way would be the following (which DOES NOT work) ``` class P(object): def __init__(self,pvar): self.pvar = pvar def printname(self): print self.name class C(P): def __init__(self,name,pobject): P = pobject self.name = name ``` I think python should allow for this... UPDATE: Ok, now I found a way to achieve this, due to the explanations by eyquem. But Since this is really a hack there should be an official version for the same... ``` def replaceinstance(parent,child): for item in parent.__dict__.items(): child.__dict__.__setitem__(item[0],item[1]) print item class P(object): def __init__(self,pvar): self.pvar = pvar def printname(self): print self.name class C(P): def __init__(self,name,pobject): P.__init__(self,None) replaceinstance(pobject,self) self.name = name p1 = P("1") p2 = P("2") c1a = C("c1a",p1) c1b = C("c1b",p1) c1c = C("c1c",p1) c2a = C("c2a",p2) c2b = C("c2b",p2) c2c = C("c2c",p2) print id(c1a.pvar) print id(c1b.pvar) print id(c1c.pvar) print id(c2a.pvar) print id(c2b.pvar) print id(c2c.pvar) print id(p1.pvar) print id(p2.pvar) print id(c1a.name) print id(c1b.name) print id(c1c.name) print id(c2a.name) print id(c2b.name) print id(c2c.name) ``` the output is the same as above ``` 3077745184 3077745184 3077745184 3074414912 3074414912 3074414912 3077745184 3074414912 144028416 144028448 144028480 144028512 144028544 144028576 ``` UPDATE: Even if the id's seem to be right, the last code does not work as is clear from this test ``` c1a.pvar = "newpvar1" print c1a.pvar print c1b.pvar print c1c.pvar print c2a.pvar print c2b.pvar print c2c.pvar print p1.pvar print p2.pvar ``` it has the output ``` newpvar1 1 1 2 2 2 1 2 ``` However the version I posted first works: ``` class P(object): def __init__(self,pvar): self.pobject = None self._pvar = pvar @property def pvar(self): if self.pobject != None: return self.pobject.pvar else: return self._pvar @pvar.setter def pvar(self,val): if self.pobject != None: self.pobject.pvar = val else: self._pvar=val def printname(self): print self.name class C(P): def __init__(self,name,pobject): #<-- The same default `P()` is # used for all instances of `C`, # unless pobject is explicitly defined. P.__init__(self,None) self.name = name self.pobject = pobject p1 = P("1") p2 = P("2") c1a = C("c1a",p1) c1b = C("c1b",p1) c1c = C("c1c",p1) c2a = C("c2a",p2) c2b = C("c2b",p2) c2c = C("c2c",p2) print id(c1a.pvar) print id(c1b.pvar) print id(c1c.pvar) print id(c2a.pvar) print id(c2b.pvar) print id(c2c.pvar) print id(p1.pvar) print id(p2.pvar) print id(c1a.name) print id(c1b.name) print id(c1c.name) print id(c2a.name) print id(c2b.name) print id(c2c.name) print "testing\n" c1a.printname() c1b.printname() c1c.printname() c2a.printname() c2b.printname() c2c.printname() print "\n" c1a.name = "c1anewname" c2b.name = "c2bnewname" c1a.printname() c1b.printname() c1c.printname() c2a.printname() c2b.printname() c2c.printname() print "pvar\n" print c1a.pvar print c1b.pvar print c1c.pvar print c2a.pvar print c2b.pvar print c2c.pvar print p1.pvar print p2.pvar print "\n" c1a.pvar = "newpvar1" print c1a.pvar print c1b.pvar print c1c.pvar print c2a.pvar print c2b.pvar print c2c.pvar print p1.pvar print p2.pvar print "\n" c2c.pvar = "newpvar2" print c1a.pvar print c1b.pvar print c1c.pvar print c2a.pvar print c2b.pvar print c2c.pvar print p1.pvar print p2.pvar ``` with the output ``` 3077745184 3077745184 3077745184 3074414912 3074414912 3074414912 3077745184 3074414912 144028416 144028448 144028480 144028512 144028544 144028576 testing c1a c1b c1c c2a c2b c2c c1anewname c1b c1c c2a c2bnewname c2c pvar 1 1 1 2 2 2 1 2 newpvar1 newpvar1 newpvar1 2 2 2 newpvar1 2 newpvar1 newpvar1 newpvar1 newpvar2 newpvar2 newpvar2 newpvar1 newpvar2 ``` Does anybody know why it is like that? I probably do not understand the internal way python works with this `__dict__` so well...
2011/02/24
[ "https://Stackoverflow.com/questions/5104366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/632263/" ]
I think your workaround is doable; You could use properties to make access to `P`'s attributes easier: ``` class P(object): def __init__(self,name='default',pvar=1): self.pname = name self.pvar=pvar class C(object): def __init__(self,name,pobject=P()): #<-- The same default `P()` is # used for all instances of `C`, # unless pobject is explicitly defined. self.cname = name self.pobject=pobject @property def pvar(self): return self.pobject.pvar @pvar.setter def pvar(self,val): self.pobject.pvar=val c1=C('1') c2=C('2') ``` `c1` and `c2` share the same `pobject`: ``` print(c1.pvar) # 1 c1.pvar=2 ``` Notice that changing `pvar` through `c1` changes `c2.pvar`: ``` print(c2.pvar) # 2 ``` `c3` has a different `pobject`: ``` c3=C('3',P()) print(c3.pvar) # 1 ``` --- Regarding OOP design for the psychology experiment (mentioned in the comments): ``` import Image class Picture(object): def __init__(self,filename): self.filename = filename self.image=Image.open(filename) class Person(object): def __init__(self,name): self.name=name # other vital statistics associated with people as individuals here class Trial(object): # A trial is composed of one person, one picture, and the places they look def __init__(self,person,picture,locations): self.person=person self.picture=picture self.locations = locations # put methods for analyzing where the person looked here ``` A `Picture` is certainly not a `Person`, nor vice versa. And the same goes for `Trial`s. So none of these classes should inherit from each other. Each of these classes have a public (and maybe a private) interface. Public methods and attributes should be freely accessible from other classes. So given a `Trial` instance, `t`, the image should be accessible through `t.picture.image`. As long as you are only accessing public attributes and methods, then everything should be fine. For convenience, you can use `properties` to link attributes to component-attributes. For example: ``` class Trial(object): ... @property def image(self): return self.picture.image ``` But to short-cut this by making, say, `Trial` a subclass of `Picture` would be contrary to fundamental OOP design principles.
One thing you must know as a base of the understanding of functionning of classes and instances: > > A class instance has a namespace > implemented as a dictionary which is > the **first place in which attribute > references are searched**. > > > When an attribute is not found there, > and the instance’s class has an > attribute by that name, the search > continues with the class attributes. > > > <http://docs.python.org/reference/datamodel.html#the-standard-type-hierarchy> > > > In the second sentence, I don't exactly understand the meaning of "by that name" , but I understand of the global that an attribute is searched first in the namespace of an instance and then in the namespace of its type. In the following code : * For class `P` and instance `c` : the name **'dataclass'** and object `dataclass` really belong to the `P` class's namespace and only APPARENTLY belong to the `c` instance's namespace: when `c.dataclass` is called , that's in fact `c.__class__.dataclass` that is attained, by the course of search described above. * But in an instance `cc` of the class `PP` , the name **'data'** , which belongs to the `P` class's namespace, is assigned (binded) by the definition occuring in `__init__()` to a new `data` object created in the `c` instance's namespace. Hence, the only solution to obtain the class's `data`'s value is to call it by its real reference, either `PP.data` or `cc.__class__.data` . ``` class P: dataclass = "shareddata" def __init__(self,newdata): self.data = newdata def printname(self): print self.name c = P(1) print 'P.__dict__.keys()==',P.__dict__.keys() print 'c.__dict__.keys()==',c.__dict__.keys() print print 'c.data==',c.data print 'c.dataclass==',c.dataclass print class PP: data = "shareddata" def __init__(self,newdata): self.data = newdata def printname(self): print self.name cc = PP(2) print 'PP.__dict__.keys()==',PP.__dict__.keys() print 'cc.__dict__.keys()==',cc.__dict__.keys() print print 'cc.data==',cc.data print 'PP.data==',PP.data print 'cc.__class__.data==',cc.__class__.data ``` result ``` P.__dict__.keys()== ['dataclass', '__module__', 'printname', '__init__', '__doc__'] c.__dict__.keys()== ['data'] c.data== 1 c.dataclass== shareddata PP.__dict__.keys()== ['__module__', 'data', 'printname', '__init__', '__doc__'] cc.__dict__.keys()== ['data'] cc.data== 2 PP.data== shareddata cc.__class__.data== shareddata ``` . Note: > > **dir([object])** > > > With an argument, attempt to return a > list of valid attributes for that > object. > > > If the object does not provide > **dir**(), the function tries its best to gather information from the > object’s **dict** attribute, if > defined, and from its type object. > > > The default dir() mechanism behaves > differently with different types of > objects, as it attempts to produce the > most relevant, rather than complete, > information: > > > •If the object is a type or class > object, the list contains the names of > its attributes, and recursively of the > attributes of its bases. > > > •Otherwise, the list contains the > object’s attributes’ names, the names > of its class’s attributes, and > recursively of the attributes of its > class’s base classes. > > > <http://docs.python.org/library/functions.html#dir> > > > . Hence, the use of `dir(ob)` to display the attributes of the object `ob` is a trap because it display more attributes than the ones belonging strictly to the object. In other words, **\_\_dict\_\_** is the real thing, while **dir()** gives a dashboard, in a sense.
5,104,366
users, I have a basic question concerning inheritance (in python). I have two classes and one of them is inherited from the other like ``` class p: def __init__(self,name): self.pname = name class c(p): def __init__(self,name): self.cname = name ``` Is there any possibility that I can create a parent object and several child objects which refer to the SAME parent object? It should work like that that the parent object contains several variables and whenever I access the corresponding variables from a child I actually access the variable form the parent. I.e. if I change it for one child it is changed also for all other childes and the data are only stored once in memory (and not copied for each child...) Thank you in advance. Here is a possible workaround which I do not consider as so nice ``` class P: def __init__(self, name): self.pname = name class C: def __init__(self, name,pobject): self.pobject = pobject self.cname = name ``` Is this really the state of the art or do there exist other concepts? Sebastian Thank you all for helping me, also with the name conventions :) But I am still not very satisfied. Maybe I give a more advanced example to stress what I really want to do. ``` class P: data = "shareddata" def __init__(self,newdata): self.data = newdata def printname(self): print self.name class C(P): def __init__(self,name): self.name = name ``` Now I can do the following ``` In [33]: c1 = test.C("name1") In [34]: c2 = test.C("name2") In [35]: c1.printname() name1 In [36]: c2.printname() name2 In [37]: c1.data Out[37]: 'shareddata' In [38]: c2.data Out[38]: 'shareddata' ``` And this is so far exactly what I want. There is a variable name which is different for every child and the parent class accesses the individual variables. Normal inheritance. Then there is the variable data which comes from the parent class and every child access it. However, now the following does not work any more ``` In [39]: c1.data = "tst" In [40]: c2.data Out[40]: 'shareddata' In [41]: c1.data Out[41]: 'tst' ``` I want the change in c1.data to affect also c2.data since I want the variable to be shared, somehow a global variable of this parent class. And more than that. I also want to create different instances of P, each having its own data variable. And when I create a new C object I want to specify from which P object data should be inhetited i.e. shared.... UPDATE: remark to the comment of @eyquem: Thanks for this, it is going into the direction I want. However, now the `__class__.pvar` is shared among all objects of the class. What I want is that several instances of P may have a different pvar. Lets assume P1 has pvar=1 and P2 has pvar=2. Then I want to create children C1a, C1b, C1c which are related to P1, i.e. if I say C1a.pvar it should acess pvar from P1. Then I create C2a, C2b, C2c and if I access i.e. C2b.pvar I want to access pvar from P2. Since the class C inherits pvar from the class P pvar is known to C. My naive idea is that if I create a new instance of C I should be able to specify which (existing) P object should be used as the parent object and not to create a completely new P object as it is done when calling `P.__init__` inside of the `__init__` of C... It sounds simple to me, maybe I forget something... UPDATE: So I found [this discussion](http://www.velocityreviews.com/forums/t356880-can-you-create-an-instance-of-a-subclass-with-an-existing-instance-of-the-base-class.html) which is pretty much my question Any suggestions? UPDATE: The method .**class**.\_*subclasses*\_ seems to be not existing any more.. UPDATE: Here is onother link: [link to discussion](http://bytes.com/topic/python/answers/834541-using-existing-instance-parent) There it is solved by copying. But I do not want to copy the parent class since I would like that it exists only once... UPDATE: Sorry for leaving the discussion yesterday, I am a bit ill... And thank you for the posts! I will now read through them. I thought about it a bit more and here is a possible solution I found ``` class P(object): def __init__(self,pvar): self.pobject = None self._pvar = pvar @property def pvar(self): if self.pobject != None: return self.pobject.pvar else: return self._pvar @pvar.setter def pvar(self,val): if self.pobject != None: self.pobject.pvar = val else: self._pvar=val def printname(self): print self.name class C(P): def __init__(self,name,pobject): #<-- The same default `P()` is # used for all instances of `C`, # unless pobject is explicitly defined. P.__init__(self,None) self.name = name self.pobject = pobject p1 = P("1") p2 = P("2") c1a = C("c1a",p1) c1b = C("c1b",p1) c1c = C("c1c",p1) c2a = C("c2a",p2) c2b = C("c2b",p2) c2c = C("c2c",p2) print id(c1a.pvar) print id(c1b.pvar) print id(c1c.pvar) print id(c2a.pvar) print id(c2b.pvar) print id(c2c.pvar) print id(p1.pvar) print id(p2.pvar) print id(c1a.name) print id(c1b.name) print id(c1c.name) print id(c2a.name) print id(c2b.name) print id(c2c.name) ``` It is a bit cumbersome and I hope that there is a simpler way to achieve this. But it has the feature that pvar is only mentioned in the class P and the class C does not know about pvar as it should be according to my understanding of inheritance. Nevertheless when I create a new instance of C I can specify an existing instance of P which will be stored in the variable pobject. When the variable pvar is accessed actually pvar of the P-instance stored in this variable is accessed... The output is given by ``` 3078326816 3078326816 3078326816 3074996544 3074996544 3074996544 3078326816 3074996544 156582944 156583040 156583200 156583232 156583296 156583360 ``` I will read now through your last comments, all the best, Sebastian UPDATE: I think the most elegant way would be the following (which DOES NOT work) ``` class P(object): def __init__(self,pvar): self.pvar = pvar def printname(self): print self.name class C(P): def __init__(self,name,pobject): P = pobject self.name = name ``` I think python should allow for this... UPDATE: Ok, now I found a way to achieve this, due to the explanations by eyquem. But Since this is really a hack there should be an official version for the same... ``` def replaceinstance(parent,child): for item in parent.__dict__.items(): child.__dict__.__setitem__(item[0],item[1]) print item class P(object): def __init__(self,pvar): self.pvar = pvar def printname(self): print self.name class C(P): def __init__(self,name,pobject): P.__init__(self,None) replaceinstance(pobject,self) self.name = name p1 = P("1") p2 = P("2") c1a = C("c1a",p1) c1b = C("c1b",p1) c1c = C("c1c",p1) c2a = C("c2a",p2) c2b = C("c2b",p2) c2c = C("c2c",p2) print id(c1a.pvar) print id(c1b.pvar) print id(c1c.pvar) print id(c2a.pvar) print id(c2b.pvar) print id(c2c.pvar) print id(p1.pvar) print id(p2.pvar) print id(c1a.name) print id(c1b.name) print id(c1c.name) print id(c2a.name) print id(c2b.name) print id(c2c.name) ``` the output is the same as above ``` 3077745184 3077745184 3077745184 3074414912 3074414912 3074414912 3077745184 3074414912 144028416 144028448 144028480 144028512 144028544 144028576 ``` UPDATE: Even if the id's seem to be right, the last code does not work as is clear from this test ``` c1a.pvar = "newpvar1" print c1a.pvar print c1b.pvar print c1c.pvar print c2a.pvar print c2b.pvar print c2c.pvar print p1.pvar print p2.pvar ``` it has the output ``` newpvar1 1 1 2 2 2 1 2 ``` However the version I posted first works: ``` class P(object): def __init__(self,pvar): self.pobject = None self._pvar = pvar @property def pvar(self): if self.pobject != None: return self.pobject.pvar else: return self._pvar @pvar.setter def pvar(self,val): if self.pobject != None: self.pobject.pvar = val else: self._pvar=val def printname(self): print self.name class C(P): def __init__(self,name,pobject): #<-- The same default `P()` is # used for all instances of `C`, # unless pobject is explicitly defined. P.__init__(self,None) self.name = name self.pobject = pobject p1 = P("1") p2 = P("2") c1a = C("c1a",p1) c1b = C("c1b",p1) c1c = C("c1c",p1) c2a = C("c2a",p2) c2b = C("c2b",p2) c2c = C("c2c",p2) print id(c1a.pvar) print id(c1b.pvar) print id(c1c.pvar) print id(c2a.pvar) print id(c2b.pvar) print id(c2c.pvar) print id(p1.pvar) print id(p2.pvar) print id(c1a.name) print id(c1b.name) print id(c1c.name) print id(c2a.name) print id(c2b.name) print id(c2c.name) print "testing\n" c1a.printname() c1b.printname() c1c.printname() c2a.printname() c2b.printname() c2c.printname() print "\n" c1a.name = "c1anewname" c2b.name = "c2bnewname" c1a.printname() c1b.printname() c1c.printname() c2a.printname() c2b.printname() c2c.printname() print "pvar\n" print c1a.pvar print c1b.pvar print c1c.pvar print c2a.pvar print c2b.pvar print c2c.pvar print p1.pvar print p2.pvar print "\n" c1a.pvar = "newpvar1" print c1a.pvar print c1b.pvar print c1c.pvar print c2a.pvar print c2b.pvar print c2c.pvar print p1.pvar print p2.pvar print "\n" c2c.pvar = "newpvar2" print c1a.pvar print c1b.pvar print c1c.pvar print c2a.pvar print c2b.pvar print c2c.pvar print p1.pvar print p2.pvar ``` with the output ``` 3077745184 3077745184 3077745184 3074414912 3074414912 3074414912 3077745184 3074414912 144028416 144028448 144028480 144028512 144028544 144028576 testing c1a c1b c1c c2a c2b c2c c1anewname c1b c1c c2a c2bnewname c2c pvar 1 1 1 2 2 2 1 2 newpvar1 newpvar1 newpvar1 2 2 2 newpvar1 2 newpvar1 newpvar1 newpvar1 newpvar2 newpvar2 newpvar2 newpvar1 newpvar2 ``` Does anybody know why it is like that? I probably do not understand the internal way python works with this `__dict__` so well...
2011/02/24
[ "https://Stackoverflow.com/questions/5104366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/632263/" ]
The other answer is right, your question is more about namespaces and references than about inheritance. All variables in Python are references, and all object instance is a namespace. So you can do: ``` class C(): def __init__(self, x): self.x = x class Shared(object): def __init__(self, value): self.value = value # instances: >>> shared1 = Shared(1) >>> shared2 = Shared(2) >>> c1 = C(shared1) >>> c2 = C(shared1) >>> c3 = C(shared2) >>> c4 = C(shared2) # c1 and c2 sharing a reference to shared1 >>> c1.x.value 1 >>> c2.x.value 1 # change c2.x will reflect on c1 >>> c2.x.value = 3 >>> c1.x.value 3 # but not on c3, because shared1 and shared2 are distinct namespaces >>> c3.x.value 2 ``` UPDATE: But watch out, it is easy to make a mistake: ``` >>> c4.x = 4 >>> c3.x.value 2 >>> c4.x.value Traceback (most recent call last): File "<interactive input>", line 1, in <module> AttributeError: 'int' object has no attribute 'value' >>> ``` I think the state of the art would be using [properties](http://docs.python.org/library/functions.html#property) to hide the [`__shared_instance`](http://docs.python.org/tutorial/classes.html#private-variables) in a private instance variable - so you can use c1.x instead of c1.x.value and avoid a typo like the example above.
One thing you must know as a base of the understanding of functionning of classes and instances: > > A class instance has a namespace > implemented as a dictionary which is > the **first place in which attribute > references are searched**. > > > When an attribute is not found there, > and the instance’s class has an > attribute by that name, the search > continues with the class attributes. > > > <http://docs.python.org/reference/datamodel.html#the-standard-type-hierarchy> > > > In the second sentence, I don't exactly understand the meaning of "by that name" , but I understand of the global that an attribute is searched first in the namespace of an instance and then in the namespace of its type. In the following code : * For class `P` and instance `c` : the name **'dataclass'** and object `dataclass` really belong to the `P` class's namespace and only APPARENTLY belong to the `c` instance's namespace: when `c.dataclass` is called , that's in fact `c.__class__.dataclass` that is attained, by the course of search described above. * But in an instance `cc` of the class `PP` , the name **'data'** , which belongs to the `P` class's namespace, is assigned (binded) by the definition occuring in `__init__()` to a new `data` object created in the `c` instance's namespace. Hence, the only solution to obtain the class's `data`'s value is to call it by its real reference, either `PP.data` or `cc.__class__.data` . ``` class P: dataclass = "shareddata" def __init__(self,newdata): self.data = newdata def printname(self): print self.name c = P(1) print 'P.__dict__.keys()==',P.__dict__.keys() print 'c.__dict__.keys()==',c.__dict__.keys() print print 'c.data==',c.data print 'c.dataclass==',c.dataclass print class PP: data = "shareddata" def __init__(self,newdata): self.data = newdata def printname(self): print self.name cc = PP(2) print 'PP.__dict__.keys()==',PP.__dict__.keys() print 'cc.__dict__.keys()==',cc.__dict__.keys() print print 'cc.data==',cc.data print 'PP.data==',PP.data print 'cc.__class__.data==',cc.__class__.data ``` result ``` P.__dict__.keys()== ['dataclass', '__module__', 'printname', '__init__', '__doc__'] c.__dict__.keys()== ['data'] c.data== 1 c.dataclass== shareddata PP.__dict__.keys()== ['__module__', 'data', 'printname', '__init__', '__doc__'] cc.__dict__.keys()== ['data'] cc.data== 2 PP.data== shareddata cc.__class__.data== shareddata ``` . Note: > > **dir([object])** > > > With an argument, attempt to return a > list of valid attributes for that > object. > > > If the object does not provide > **dir**(), the function tries its best to gather information from the > object’s **dict** attribute, if > defined, and from its type object. > > > The default dir() mechanism behaves > differently with different types of > objects, as it attempts to produce the > most relevant, rather than complete, > information: > > > •If the object is a type or class > object, the list contains the names of > its attributes, and recursively of the > attributes of its bases. > > > •Otherwise, the list contains the > object’s attributes’ names, the names > of its class’s attributes, and > recursively of the attributes of its > class’s base classes. > > > <http://docs.python.org/library/functions.html#dir> > > > . Hence, the use of `dir(ob)` to display the attributes of the object `ob` is a trap because it display more attributes than the ones belonging strictly to the object. In other words, **\_\_dict\_\_** is the real thing, while **dir()** gives a dashboard, in a sense.
5,104,366
users, I have a basic question concerning inheritance (in python). I have two classes and one of them is inherited from the other like ``` class p: def __init__(self,name): self.pname = name class c(p): def __init__(self,name): self.cname = name ``` Is there any possibility that I can create a parent object and several child objects which refer to the SAME parent object? It should work like that that the parent object contains several variables and whenever I access the corresponding variables from a child I actually access the variable form the parent. I.e. if I change it for one child it is changed also for all other childes and the data are only stored once in memory (and not copied for each child...) Thank you in advance. Here is a possible workaround which I do not consider as so nice ``` class P: def __init__(self, name): self.pname = name class C: def __init__(self, name,pobject): self.pobject = pobject self.cname = name ``` Is this really the state of the art or do there exist other concepts? Sebastian Thank you all for helping me, also with the name conventions :) But I am still not very satisfied. Maybe I give a more advanced example to stress what I really want to do. ``` class P: data = "shareddata" def __init__(self,newdata): self.data = newdata def printname(self): print self.name class C(P): def __init__(self,name): self.name = name ``` Now I can do the following ``` In [33]: c1 = test.C("name1") In [34]: c2 = test.C("name2") In [35]: c1.printname() name1 In [36]: c2.printname() name2 In [37]: c1.data Out[37]: 'shareddata' In [38]: c2.data Out[38]: 'shareddata' ``` And this is so far exactly what I want. There is a variable name which is different for every child and the parent class accesses the individual variables. Normal inheritance. Then there is the variable data which comes from the parent class and every child access it. However, now the following does not work any more ``` In [39]: c1.data = "tst" In [40]: c2.data Out[40]: 'shareddata' In [41]: c1.data Out[41]: 'tst' ``` I want the change in c1.data to affect also c2.data since I want the variable to be shared, somehow a global variable of this parent class. And more than that. I also want to create different instances of P, each having its own data variable. And when I create a new C object I want to specify from which P object data should be inhetited i.e. shared.... UPDATE: remark to the comment of @eyquem: Thanks for this, it is going into the direction I want. However, now the `__class__.pvar` is shared among all objects of the class. What I want is that several instances of P may have a different pvar. Lets assume P1 has pvar=1 and P2 has pvar=2. Then I want to create children C1a, C1b, C1c which are related to P1, i.e. if I say C1a.pvar it should acess pvar from P1. Then I create C2a, C2b, C2c and if I access i.e. C2b.pvar I want to access pvar from P2. Since the class C inherits pvar from the class P pvar is known to C. My naive idea is that if I create a new instance of C I should be able to specify which (existing) P object should be used as the parent object and not to create a completely new P object as it is done when calling `P.__init__` inside of the `__init__` of C... It sounds simple to me, maybe I forget something... UPDATE: So I found [this discussion](http://www.velocityreviews.com/forums/t356880-can-you-create-an-instance-of-a-subclass-with-an-existing-instance-of-the-base-class.html) which is pretty much my question Any suggestions? UPDATE: The method .**class**.\_*subclasses*\_ seems to be not existing any more.. UPDATE: Here is onother link: [link to discussion](http://bytes.com/topic/python/answers/834541-using-existing-instance-parent) There it is solved by copying. But I do not want to copy the parent class since I would like that it exists only once... UPDATE: Sorry for leaving the discussion yesterday, I am a bit ill... And thank you for the posts! I will now read through them. I thought about it a bit more and here is a possible solution I found ``` class P(object): def __init__(self,pvar): self.pobject = None self._pvar = pvar @property def pvar(self): if self.pobject != None: return self.pobject.pvar else: return self._pvar @pvar.setter def pvar(self,val): if self.pobject != None: self.pobject.pvar = val else: self._pvar=val def printname(self): print self.name class C(P): def __init__(self,name,pobject): #<-- The same default `P()` is # used for all instances of `C`, # unless pobject is explicitly defined. P.__init__(self,None) self.name = name self.pobject = pobject p1 = P("1") p2 = P("2") c1a = C("c1a",p1) c1b = C("c1b",p1) c1c = C("c1c",p1) c2a = C("c2a",p2) c2b = C("c2b",p2) c2c = C("c2c",p2) print id(c1a.pvar) print id(c1b.pvar) print id(c1c.pvar) print id(c2a.pvar) print id(c2b.pvar) print id(c2c.pvar) print id(p1.pvar) print id(p2.pvar) print id(c1a.name) print id(c1b.name) print id(c1c.name) print id(c2a.name) print id(c2b.name) print id(c2c.name) ``` It is a bit cumbersome and I hope that there is a simpler way to achieve this. But it has the feature that pvar is only mentioned in the class P and the class C does not know about pvar as it should be according to my understanding of inheritance. Nevertheless when I create a new instance of C I can specify an existing instance of P which will be stored in the variable pobject. When the variable pvar is accessed actually pvar of the P-instance stored in this variable is accessed... The output is given by ``` 3078326816 3078326816 3078326816 3074996544 3074996544 3074996544 3078326816 3074996544 156582944 156583040 156583200 156583232 156583296 156583360 ``` I will read now through your last comments, all the best, Sebastian UPDATE: I think the most elegant way would be the following (which DOES NOT work) ``` class P(object): def __init__(self,pvar): self.pvar = pvar def printname(self): print self.name class C(P): def __init__(self,name,pobject): P = pobject self.name = name ``` I think python should allow for this... UPDATE: Ok, now I found a way to achieve this, due to the explanations by eyquem. But Since this is really a hack there should be an official version for the same... ``` def replaceinstance(parent,child): for item in parent.__dict__.items(): child.__dict__.__setitem__(item[0],item[1]) print item class P(object): def __init__(self,pvar): self.pvar = pvar def printname(self): print self.name class C(P): def __init__(self,name,pobject): P.__init__(self,None) replaceinstance(pobject,self) self.name = name p1 = P("1") p2 = P("2") c1a = C("c1a",p1) c1b = C("c1b",p1) c1c = C("c1c",p1) c2a = C("c2a",p2) c2b = C("c2b",p2) c2c = C("c2c",p2) print id(c1a.pvar) print id(c1b.pvar) print id(c1c.pvar) print id(c2a.pvar) print id(c2b.pvar) print id(c2c.pvar) print id(p1.pvar) print id(p2.pvar) print id(c1a.name) print id(c1b.name) print id(c1c.name) print id(c2a.name) print id(c2b.name) print id(c2c.name) ``` the output is the same as above ``` 3077745184 3077745184 3077745184 3074414912 3074414912 3074414912 3077745184 3074414912 144028416 144028448 144028480 144028512 144028544 144028576 ``` UPDATE: Even if the id's seem to be right, the last code does not work as is clear from this test ``` c1a.pvar = "newpvar1" print c1a.pvar print c1b.pvar print c1c.pvar print c2a.pvar print c2b.pvar print c2c.pvar print p1.pvar print p2.pvar ``` it has the output ``` newpvar1 1 1 2 2 2 1 2 ``` However the version I posted first works: ``` class P(object): def __init__(self,pvar): self.pobject = None self._pvar = pvar @property def pvar(self): if self.pobject != None: return self.pobject.pvar else: return self._pvar @pvar.setter def pvar(self,val): if self.pobject != None: self.pobject.pvar = val else: self._pvar=val def printname(self): print self.name class C(P): def __init__(self,name,pobject): #<-- The same default `P()` is # used for all instances of `C`, # unless pobject is explicitly defined. P.__init__(self,None) self.name = name self.pobject = pobject p1 = P("1") p2 = P("2") c1a = C("c1a",p1) c1b = C("c1b",p1) c1c = C("c1c",p1) c2a = C("c2a",p2) c2b = C("c2b",p2) c2c = C("c2c",p2) print id(c1a.pvar) print id(c1b.pvar) print id(c1c.pvar) print id(c2a.pvar) print id(c2b.pvar) print id(c2c.pvar) print id(p1.pvar) print id(p2.pvar) print id(c1a.name) print id(c1b.name) print id(c1c.name) print id(c2a.name) print id(c2b.name) print id(c2c.name) print "testing\n" c1a.printname() c1b.printname() c1c.printname() c2a.printname() c2b.printname() c2c.printname() print "\n" c1a.name = "c1anewname" c2b.name = "c2bnewname" c1a.printname() c1b.printname() c1c.printname() c2a.printname() c2b.printname() c2c.printname() print "pvar\n" print c1a.pvar print c1b.pvar print c1c.pvar print c2a.pvar print c2b.pvar print c2c.pvar print p1.pvar print p2.pvar print "\n" c1a.pvar = "newpvar1" print c1a.pvar print c1b.pvar print c1c.pvar print c2a.pvar print c2b.pvar print c2c.pvar print p1.pvar print p2.pvar print "\n" c2c.pvar = "newpvar2" print c1a.pvar print c1b.pvar print c1c.pvar print c2a.pvar print c2b.pvar print c2c.pvar print p1.pvar print p2.pvar ``` with the output ``` 3077745184 3077745184 3077745184 3074414912 3074414912 3074414912 3077745184 3074414912 144028416 144028448 144028480 144028512 144028544 144028576 testing c1a c1b c1c c2a c2b c2c c1anewname c1b c1c c2a c2bnewname c2c pvar 1 1 1 2 2 2 1 2 newpvar1 newpvar1 newpvar1 2 2 2 newpvar1 2 newpvar1 newpvar1 newpvar1 newpvar2 newpvar2 newpvar2 newpvar1 newpvar2 ``` Does anybody know why it is like that? I probably do not understand the internal way python works with this `__dict__` so well...
2011/02/24
[ "https://Stackoverflow.com/questions/5104366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/632263/" ]
The other answer is right, your question is more about namespaces and references than about inheritance. All variables in Python are references, and all object instance is a namespace. So you can do: ``` class C(): def __init__(self, x): self.x = x class Shared(object): def __init__(self, value): self.value = value # instances: >>> shared1 = Shared(1) >>> shared2 = Shared(2) >>> c1 = C(shared1) >>> c2 = C(shared1) >>> c3 = C(shared2) >>> c4 = C(shared2) # c1 and c2 sharing a reference to shared1 >>> c1.x.value 1 >>> c2.x.value 1 # change c2.x will reflect on c1 >>> c2.x.value = 3 >>> c1.x.value 3 # but not on c3, because shared1 and shared2 are distinct namespaces >>> c3.x.value 2 ``` UPDATE: But watch out, it is easy to make a mistake: ``` >>> c4.x = 4 >>> c3.x.value 2 >>> c4.x.value Traceback (most recent call last): File "<interactive input>", line 1, in <module> AttributeError: 'int' object has no attribute 'value' >>> ``` I think the state of the art would be using [properties](http://docs.python.org/library/functions.html#property) to hide the [`__shared_instance`](http://docs.python.org/tutorial/classes.html#private-variables) in a private instance variable - so you can use c1.x instead of c1.x.value and avoid a typo like the example above.
Finally, I found a way to do it. The key point is to abandon the aim to obtain instances **c** with real **pvar** field, because it is impossible: Since it is the same **\_*init*\_()** function (the one being in class P) that processes to create the objects **pvar**, it isn't possible to create **pvar** in instances **c** that will points to the **pvar** in an instance **p** to mirror its value and that will also give the possibility to change this value of a **p**'s **pvar** each time a **c**'s **pvar**'s value will change. That makes too much contradictory conditions to verify. Consequently, since the instances **c** can't have a real **pvar** field, the best is to set up a mechanism controling the creation of ( with **\_*setattr*\_** ) and access to ( with **\_*getattr*\_** ) these **c**'s seemingly **pvar** objects to give the illusion that they exist. ``` class P(object): def __init__(self,pvar_arg,foo="^^^ "): self.pvar = pvar_arg self.cat = foo def printname(self): print self.name class C(P): def __init__(self,name,pobject,foo=''): self.__dict__['name'] = name P.__init__(self,None,pobject.cat+foo) C.dic[name] = pobject def __setattr__(self,xn,val): if xn!='pvar': self.__dict__[xn] = val elif self.name in C.dic: # During the creation of an instance c, # this condition is False because the instruction # C.dic[name] = pobject is written after # P.__init__(self,None,pobject.cat+foo). # Hence the value of pobject.pvar is preserved, # not changed with the value val being None # due to P.__init__(self,None,pobject.cat+foo) # that provokes self.pvar = pvar_arg and # consequently a call __setattr__(self,'pvar',None) C.dic[self.name].pvar = val def __getattribute__(self,xn): if xn=='pvar': return object.__getattribute__(C.dic[self.name],'pvar') else: return object.__getattribute__(self,xn) dic = {} p1 = P("1") p2 = P("2","QZX ") print '--- p1 = P("1") and p2 = P("2","QZX ") executed ---' print "p1.__dict__ ==",p1.__dict__ print "p2.__dict__ ==",p2.__dict__ print 'p1.pvar==',p1.pvar print 'p2.pvar==',p2.pvar c1a = C("c1a",p1,'sea') c1b = C("c1b",p1,'mountain') c1c = C("c1c",p1,'desert') c2a = C("c2a",p2,'banana') c2b = C("c2b",p2) c2c = C("c2c",p2,'pear') print '\n--- creations of c1a, c1b, c1c, c2a, c2b, c2c executed ---' print "p1.__dict__ ==",p1.__dict__ print "p2.__dict__ ==",p2.__dict__ print "c1a.__dict__ ==",c1a.__dict__ print "c1b.__dict__ ==",c1b.__dict__ print "c1c.__dict__ ==",c1c.__dict__ print "c2a.__dict__ ==",c2a.__dict__ print "c2b.__dict__ ==",c2b.__dict__ print "c2c.__dict__ ==",c2c.__dict__ print 'p1.pvar==',p1.pvar print 'p2.pvar==',p2.pvar print '(c1a.pvar, c1b.pvar, c1c.pvar)==',(c1a.pvar,c1b.pvar,c1c.pvar) print '(c2a.pvar, c2b.pvar, c2c.pvar)==',(c2a.pvar,c2b.pvar,c2c.pvar) c1a.pvar = "newpvar1" print '\n--- c1a.pvar = "newpvar1" executed ---' print 'p1.pvar==',p1.pvar print 'p2.pvar==',p2.pvar print '(c1a.pvar, c1b.pvar, c1c.pvar)==',(c1a.pvar,c1b.pvar,c1c.pvar) print '(c2a.pvar, c2b.pvar, c2c.pvar)==',(c2a.pvar,c2b.pvar,c2c.pvar) c2c.pvar = 45789 print '\n--- c2c.pvar = 45789 executed ---' print 'p1.pvar==',p1.pvar print 'p2.pvar==',p2.pvar print '(c1a.pvar, c1b.pvar, c1c.pvar)==',(c1a.pvar,c1b.pvar,c1c.pvar) print '(c2a.pvar, c2b.pvar, c2c.pvar)==',(c2a.pvar,c2b.pvar,c2c.pvar) ``` result ``` --- p1 = P("1") and p2 = P("2","QZX ") executed --- p1.__dict__ == {'cat': '^^^ ', 'pvar': '1'} p2.__dict__ == {'cat': 'QZX ', 'pvar': '2'} p1.pvar== 1 p2.pvar== 2 --- creations of c1a, c1b, c1c, c2a, c2b, c2c executed --- p1.__dict__ == {'cat': '^^^ ', 'pvar': '1'} p2.__dict__ == {'cat': 'QZX ', 'pvar': '2'} c1a.__dict__ == {'name': 'c1a', 'cat': '^^^ sea'} c1b.__dict__ == {'name': 'c1b', 'cat': '^^^ mountain'} c1c.__dict__ == {'name': 'c1c', 'cat': '^^^ desert'} c2a.__dict__ == {'name': 'c2a', 'cat': 'QZX banana'} c2b.__dict__ == {'name': 'c2b', 'cat': 'QZX '} c2c.__dict__ == {'name': 'c2c', 'cat': 'QZX pear'} p1.pvar== 1 p2.pvar== 2 (c1a.pvar, c1b.pvar, c1c.pvar)== ('1', '1', '1') (c2a.pvar, c2b.pvar, c2c.pvar)== ('2', '2', '2') --- c1a.pvar = "newpvar1" executed --- p1.pvar== newpvar1 p2.pvar== 2 (c1a.pvar, c1b.pvar, c1c.pvar)== ('newpvar1', 'newpvar1', 'newpvar1') (c2a.pvar, c2b.pvar, c2c.pvar)== ('2', '2', '2') --- c2c.pvar = 45789 executed --- p1.pvar== newpvar1 p2.pvar== 45789 (c1a.pvar, c1b.pvar, c1c.pvar)== ('newpvar1', 'newpvar1', 'newpvar1') (c2a.pvar, c2b.pvar, c2c.pvar)== (45789, 45789, 45789) ``` Remarks: 1. the attribute **name** must be defined before the instruction P.**init**(self,None,pobject.cat+foo) ------------------------------------- because the execution of this instruction calls `__setattr__(self,'pvar',"1")` that executes itself the instruction `C.dic[self.name].pvar = "1"` when `c1a = C("c1a",p1,'sea')` is executed, for example. AnHence this call needs **self.name** as key for dic. 2. I introduced **foo** and **cat** to justify the need to write the instruction P.**init**(self,None,pobject.cat+foo) ------------------------------------- otherwise, as no **pvar** is in fact defined into the instances **c** , this instuction wouldn't be useful. 3. There are two situations in which `__setattr__` is called: at the creation of an instance, and at the modifications of the attributes of an existing instance. When an instance is created, the value of **pvar** of the instance **p** must remain unaffected by the instruction `C.dic[self.name].pvar = None` . Hence the condition `elif self.name in C.dic:` In order that this condition gives a correct result, the instruction `C.dic[name] = pobject` must follow the call to `P.__init__(self,None,pobject.cat+foo)` . EDIT 1 I think it's better to write ``` def __setattr__(self,xn,val): if xn=='pvar': self.__class__.dic[self.name].pvar = val ``` than ``` def __setattr__(self,xn,val): if xn=='pvar': C.dic[self.name].pvar = val ``` In the first case, the interpreter has to search for the reference to the **self**'s class **C** ( that is to say under the name **'\_*class*\_'** ) in the namespace of self. In the second case, the interpreter must search for the same reference ( but under the name **'C'**) in the namespace of the level in which classes **P** and **C** are defined. This second namespace may be more more big than the limited namespace of an instance. In the first case, the name **'\_*class*\_'** is looked for as a key in the dictionary implementing the self's namespace. In the second, the name **'C'** is the key searched for in the dictionary of the level inclosing the classes **P** and **C**. The identity of these two objects can be verified with the function **id()** . . EDIT 2 There is another possibility for the `dic` object: instead of making it a class attribute of the class **C**, it can be defined in the outer scope of the class **C**. If this outer level is a module, then **dic** is a global object. ``` class P(object): def __init__(self,pvar,foo="^^^ "): self.pvar = pvar self.cat = foo def printname(self): print self.name class C(P): def __init__(self,name,pobject,foo=''): self.__dict__['name'] = name P.__init__(self,None,pobject.cat+foo) dic[name] = pobject def __setattr__(self,xn,val): if xn!='pvar': self.__dict__[xn] = val elif self.name in dic: # During the creation of an instance c, # this condition is False because the instruction # dic[name] = pobject is written after # P.__init__(self,None,pobject.cat+foo). # Hence the value of pobject.pvar is preserved, # not changed with the value val being None # due to P.__init__(self,None,pobject.cat+foo) # that provokes self.pvar = pvar_arg and # consequently a call __setattr__(self,'pvar',None) dic[self.name].pvar = val def __getattribute__(self,xn): if xn=='pvar': return object.__getattribute__(dic[self.name],'pvar') else: return object.__getattribute__(self,xn) dic = {} ``` The result is exactly the same Doing so, **dic** looses its OOish nature. . . EDIT 3 At last, there is still another way: instead of creating an illusory attribute **pvar** for each instance **c** with help of functions `__setattr__` and `__getattribute__` , it is better, according to me, to use a function with the dictionary **dic** as a default argument and that will replace them. ``` class P(object): def __init__(self,pvar,foo="^^^ "): self.pvar = pvar self.cat = foo def printname(self): print self.name class C(P): def __init__(self,name,pobject,foo=''): P.__init__(self,None,pobject.cat+foo) self.__dict__['name'] = name del self.pvar self.pvar(pobject) def pvar(self,x = None,dic = {}): if x.__class__==P: # a pobject dic[self.name] = x elif x: # a value dic[self.name].pvar = x else: # to return value return dic[self.name].pvar p1 = P("1") p2 = P("2","QZX ") print '--- p1 = P("1") and p2 = P("2","QZX ") executed ---' print "p1.__dict__ ==",p1.__dict__ print "p2.__dict__ ==",p2.__dict__ print 'p1.pvar==',p1.pvar print 'p2.pvar==',p2.pvar c1a = C("c1a",p1,'sea') c1b = C("c1b",p1,'mountain') c1c = C("c1c",p1,'desert') c2a = C("c2a",p2,'banana') c2b = C("c2b",p2) c2c = C("c2c",p2,'pear') print '\n--- creations of c1a, c1b, c1c, c2a, c2b, c2c executed ---' print "p1.__dict__ ==",p1.__dict__ print "p2.__dict__ ==",p2.__dict__ print "c1a.__dict__ ==",c1a.__dict__ print "c1b.__dict__ ==",c1b.__dict__ print "c1c.__dict__ ==",c1c.__dict__ print "c2a.__dict__ ==",c2a.__dict__ print "c2b.__dict__ ==",c2b.__dict__ print "c2c.__dict__ ==",c2c.__dict__ print 'p1.pvar==',p1.pvar print 'p2.pvar==',p2.pvar print '(c1a.pvar(),c1b.pvar(),c1c.pvar())==',(c1a.pvar(),c1b.pvar(),c1c.pvar()) print '(c2a.pvar(),c2b.pvar(),c2c.pvar())==',(c2a.pvar(),c2b.pvar(),c2c.pvar()) c1a.pvar("newpvar1") print '\n--- c1a.pvar("newpvar1") executed ---' print 'p1.pvar==',p1.pvar print 'p2.pvar==',p2.pvar print '(c1a.pvar(),c1b.pvar(),c1c.pvar())==',(c1a.pvar(),c1b.pvar(),c1c.pvar()) print '(c2a.pvar(),c2b.pvar(),c2c.pvar())==',(c2a.pvar(),c2b.pvar(),c2c.pvar()) c2c.pvar(45789) print '\n--- c2c.pvar(45789) ---' print 'p1.pvar==',p1.pvar print 'p2.pvar==',p2.pvar print '(c1a.pvar(),c1b.pvar(),c1c.pvar())==',(c1a.pvar(),c1b.pvar(),c1c.pvar()) print '(c2a.pvar(),c2b.pvar(),c2c.pvar())==',(c2a.pvar(),c2b.pvar(),c2c.pvar()) ``` Results are the same, only use of c.pvar() is slightly different: ``` --- p1 = P("1") and p2 = P("2","QZX ") executed --- p1.__dict__ == {'cat': '^^^ ', 'pvar': '1'} p2.__dict__ == {'cat': 'QZX ', 'pvar': '2'} p1.pvar== 1 p2.pvar== 2 --- creations of c1a, c1b, c1c, c2a, c2b, c2c executed --- p1.__dict__ == {'cat': '^^^ ', 'pvar': '1'} p2.__dict__ == {'cat': 'QZX ', 'pvar': '2'} c1a.__dict__ == {'cat': '^^^ sea', 'name': 'c1a'} c1b.__dict__ == {'cat': '^^^ mountain', 'name': 'c1b'} c1c.__dict__ == {'cat': '^^^ desert', 'name': 'c1c'} c2a.__dict__ == {'cat': 'QZX banana', 'name': 'c2a'} c2b.__dict__ == {'cat': 'QZX ', 'name': 'c2b'} c2c.__dict__ == {'cat': 'QZX pear', 'name': 'c2c'} p1.pvar== 1 p2.pvar== 2 (c1a.pvar(),c1b.pvar(),c1c.pvar())== ('1', '1', '1') (c2a.pvar(),c2b.pvar(),c2c.pvar())== ('2', '2', '2') --- c1a.pvar("newpvar1") executed --- p1.pvar== newpvar1 p2.pvar== 2 (c1a.pvar(),c1b.pvar(),c1c.pvar())== ('newpvar1', 'newpvar1', 'newpvar1') (c2a.pvar(),c2b.pvar(),c2c.pvar())== ('2', '2', '2') --- c2c.pvar(45789) --- p1.pvar== newpvar1 p2.pvar== 45789 (c1a.pvar(),c1b.pvar(),c1c.pvar())== ('newpvar1', 'newpvar1', 'newpvar1') (c2a.pvar(),c2b.pvar(),c2c.pvar())== (45789, 45789, 45789) ``` Note that in this last code **P**'s instances can't be values of **C**'instances because a **pobject** passed to a **c.pvar()** method will never be considered as a value.
72,509,585
I have information about places and purchases in a table, and I need to find the name of all the places where, for all the clients who purchased in that place, the total of their purchases is at least 70%. I've already found the answer on python, I've sum the number of purchases per client, then the purchases per client and place, and I've created a new column with the percentage. So I got something like this: | client\_id | place\_name | total purchase | detail purchase | percent | | --- | --- | --- | --- | --- | | 1 | place1 | 10 | 7 | 0.7 | | 1 | place2 | 10 | 3 | 0.3 | | 2 | place1 | 5 | 4 | 0.8 | | 2 | place3 | 5 | 1 | 0.2 | So, my answer should be place1, since all the purchases in that place all the percentage is > > = 70%. > > > I've developed this python code to solve it: ``` places = [] for i in place name: if (c[c["place_name"]==i]["percent"]>=0.7).all(): places.append(i) ``` but now I need to do it in SQl, but I'm not sure if there's a way to get a similar behavior with the function all in SQL I've been trying this: ``` SELECT place_name FROM c GROUP BY place_name HAVING total_purchase/detail_purchase >=0.7 ``` But, It doesn't work :c Any help?
2022/06/05
[ "https://Stackoverflow.com/questions/72509585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9535697/" ]
Schema and insert statements: ``` create table c(client_id int, place_name varchar(50), total_purchase int, detail_purchase int); insert into c values(1 ,'place1', 10, 7); insert into c values(1 ,'place2', 10, 3); insert into c values(2 ,'place1', 5, 4); insert into c values(2 ,'place3', 5, 1); ``` Query: ``` with cte as ( select client_id,place_name,total_purchase,detail_purchase,detail_purchase*1.0/total_purchase percent, count( client_id)over (partition by place_name) total_client from c a ) select place_name from cte where percent>=0.7 group by place_name having count(client_id)=max(total_client) ``` Output: | place\_name | | --- | | place1 | *db<>fiddle [here](https://dbfiddle.uk/?rdbms=postgres_14&fiddle=e458704de14ad6ba8de2ebeae631a7f0)*
If I understand your question correctly, you could just use a where statement ``` SELECT place_name FROM purchases where (detail_purchase/total_purchase) >=0.7 GROUP BY place_name ``` [db fiddle](https://www.db-fiddle.com/f/w4EVh4WrdPJWJBKzqJ8RQb/1)
72,509,585
I have information about places and purchases in a table, and I need to find the name of all the places where, for all the clients who purchased in that place, the total of their purchases is at least 70%. I've already found the answer on python, I've sum the number of purchases per client, then the purchases per client and place, and I've created a new column with the percentage. So I got something like this: | client\_id | place\_name | total purchase | detail purchase | percent | | --- | --- | --- | --- | --- | | 1 | place1 | 10 | 7 | 0.7 | | 1 | place2 | 10 | 3 | 0.3 | | 2 | place1 | 5 | 4 | 0.8 | | 2 | place3 | 5 | 1 | 0.2 | So, my answer should be place1, since all the purchases in that place all the percentage is > > = 70%. > > > I've developed this python code to solve it: ``` places = [] for i in place name: if (c[c["place_name"]==i]["percent"]>=0.7).all(): places.append(i) ``` but now I need to do it in SQl, but I'm not sure if there's a way to get a similar behavior with the function all in SQL I've been trying this: ``` SELECT place_name FROM c GROUP BY place_name HAVING total_purchase/detail_purchase >=0.7 ``` But, It doesn't work :c Any help?
2022/06/05
[ "https://Stackoverflow.com/questions/72509585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9535697/" ]
Here is a clean solution based on [group by](https://www.postgresql.org/docs/current/tutorial-agg.html) and [min](https://www.postgresql.org/docs/8.0/functions-aggregate.html) functions ``` select place_name from c group by place_name having min(percent)>=0.7 ``` | place\_name | | --- | | place1 | [Fiddle](https://dbfiddle.uk/?rdbms=postgres_13&fiddle=0d408d39c8d71a4f8baf33afbbfa49ba&hide=1)
If I understand your question correctly, you could just use a where statement ``` SELECT place_name FROM purchases where (detail_purchase/total_purchase) >=0.7 GROUP BY place_name ``` [db fiddle](https://www.db-fiddle.com/f/w4EVh4WrdPJWJBKzqJ8RQb/1)
39,448,135
I have an application generating a weird config file ``` app_id1 { key1 = val key2 = val ... } app_id2 { key1 = val key2 = val ... } ... ``` And I am struggling on how to parse this in python. The keys of each app may vary too. I can't change the application to generate the configuration file in some easily parsable format :) Any suggestions on how to do this pythonically ? I am thinking along the lines of dict of dict ``` conf = {'app_id1': {'key1' : 'val', 'key2' : 'val'}, 'app_id2' : {'key1' : 'val', 'key2' : 'val'} } ```
2016/09/12
[ "https://Stackoverflow.com/questions/39448135", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3821298/" ]
Based on the fact you said it had a button where you can view source, this sounds like a WYSIWIG (What you see is what you get) editor like CKeditor, TinyMCE, Froala, etc. They take standard HTML textarea elements and using Javascript and CSS convert them into more robust editors. They allow you to do simple text formatting in the textarea, upload images, view source, etc. They are used a lot in blogs and for content editing for people that don't write code but want to be able to manage and maintain content in web sites. For instance if you type a "paragraph" of text in one of these it will automatically wrap it with the appropriate `<p>` tags using Javascript. In your case you're adding content in this box, and it's simply applying the formatting to it with Javascript. It will do the same if you just type in the box, vs. copy/paste. Here are some links to WYSIWIG editors so you can learn more about how they function: <http://ckeditor.com/> <https://www.tinymce.com/> <https://www.froala.com/wysiwyg-editor> Fun Fact: The editor you used when you typed your question on Stack Overflow uses one of these. <https://meta.stackexchange.com/questions/121981/stackoverflow-official-wmd-editor>
It`s not much information, so I‘ll take a guess: For `<strong><em>`: The website could eventually use a div with the `contenteditable="true"` attribute ([more info on mdn](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/contenteditable)) as the input method. When you then paste in text from another application that already has markup like bold or italic, it‘s converted to html tags. The `<span lang="en-gb">` could come from the browser, another application or the website through analyzing the text and adding this.
16,158,221
I got this error: ``` [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] mod_wsgi (pid=19481): Exception occurred processing WSGI script '/home/projects/treeio/treeio.wsgi'. [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] Traceback (most recent call last): [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/wsgi.py", line 236, in __call__ [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] self.load_middleware() [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 53, in load_middleware [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] raise exceptions.ImproperlyConfigured('Error importing middleware %s: "%s"' % (mw_module, e)) [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] ImproperlyConfigured: Error importing middleware treeio.core.middleware.user: "No module named csrf.middleware" ``` I have Django 1.5.1 and Python 2.7.3. I am trying to install Tree.io. Any suggest? EDIT: ``` MIDDLEWARE_CLASSES = ( 'johnny.middleware.LocalStoreClearMiddleware', 'johnny.middleware.QueryCacheMiddleware', 'django.middleware.gzip.GZipMiddleware', 'treeio.core.middleware.domain.DomainMiddleware', 'treeio.core.middleware.user.SSLMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'treeio.core.middleware.user.AuthMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'treeio.core.middleware.chat.ChatAjaxMiddleware', "django.contrib.messages.middleware.MessageMiddleware", "treeio.core.middleware.modules.ModuleDetect", "minidetector.Middleware", "treeio.core.middleware.user.CommonMiddleware", "treeio.core.middleware.user.PopupMiddleware", "treeio.core.middleware.user.LanguageMiddleware",) ``` The SO: Ubuntu 12.04.2 LTS
2013/04/22
[ "https://Stackoverflow.com/questions/16158221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2309182/" ]
try `GROUP BY` with `GROUP_CONCAT` <http://www.mysqlperformanceblog.com/2006/09/04/group_concat-useful-group-by-extension/>
You could do this all in your query instead of relying on PHP. ``` Select item, group_concat(category) FROM yourtable GROUP BY Item ```
16,158,221
I got this error: ``` [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] mod_wsgi (pid=19481): Exception occurred processing WSGI script '/home/projects/treeio/treeio.wsgi'. [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] Traceback (most recent call last): [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/wsgi.py", line 236, in __call__ [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] self.load_middleware() [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 53, in load_middleware [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] raise exceptions.ImproperlyConfigured('Error importing middleware %s: "%s"' % (mw_module, e)) [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] ImproperlyConfigured: Error importing middleware treeio.core.middleware.user: "No module named csrf.middleware" ``` I have Django 1.5.1 and Python 2.7.3. I am trying to install Tree.io. Any suggest? EDIT: ``` MIDDLEWARE_CLASSES = ( 'johnny.middleware.LocalStoreClearMiddleware', 'johnny.middleware.QueryCacheMiddleware', 'django.middleware.gzip.GZipMiddleware', 'treeio.core.middleware.domain.DomainMiddleware', 'treeio.core.middleware.user.SSLMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'treeio.core.middleware.user.AuthMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'treeio.core.middleware.chat.ChatAjaxMiddleware', "django.contrib.messages.middleware.MessageMiddleware", "treeio.core.middleware.modules.ModuleDetect", "minidetector.Middleware", "treeio.core.middleware.user.CommonMiddleware", "treeio.core.middleware.user.PopupMiddleware", "treeio.core.middleware.user.LanguageMiddleware",) ``` The SO: Ubuntu 12.04.2 LTS
2013/04/22
[ "https://Stackoverflow.com/questions/16158221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2309182/" ]
try `GROUP BY` with `GROUP_CONCAT` <http://www.mysqlperformanceblog.com/2006/09/04/group_concat-useful-group-by-extension/>
Create an array of categories for each item: ``` while($results = mysql_fetch_array($raw_results)) { $items[$results['item']][] = $results['category']; } ``` Then use that to output your HTML: ``` foreach ($items as $itemName => $categories) { echo $itemName.'<br>'; echo 'Categories: '.implode(', ',$categories); } ```
16,158,221
I got this error: ``` [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] mod_wsgi (pid=19481): Exception occurred processing WSGI script '/home/projects/treeio/treeio.wsgi'. [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] Traceback (most recent call last): [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/wsgi.py", line 236, in __call__ [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] self.load_middleware() [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 53, in load_middleware [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] raise exceptions.ImproperlyConfigured('Error importing middleware %s: "%s"' % (mw_module, e)) [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] ImproperlyConfigured: Error importing middleware treeio.core.middleware.user: "No module named csrf.middleware" ``` I have Django 1.5.1 and Python 2.7.3. I am trying to install Tree.io. Any suggest? EDIT: ``` MIDDLEWARE_CLASSES = ( 'johnny.middleware.LocalStoreClearMiddleware', 'johnny.middleware.QueryCacheMiddleware', 'django.middleware.gzip.GZipMiddleware', 'treeio.core.middleware.domain.DomainMiddleware', 'treeio.core.middleware.user.SSLMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'treeio.core.middleware.user.AuthMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'treeio.core.middleware.chat.ChatAjaxMiddleware', "django.contrib.messages.middleware.MessageMiddleware", "treeio.core.middleware.modules.ModuleDetect", "minidetector.Middleware", "treeio.core.middleware.user.CommonMiddleware", "treeio.core.middleware.user.PopupMiddleware", "treeio.core.middleware.user.LanguageMiddleware",) ``` The SO: Ubuntu 12.04.2 LTS
2013/04/22
[ "https://Stackoverflow.com/questions/16158221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2309182/" ]
try `GROUP BY` with `GROUP_CONCAT` <http://www.mysqlperformanceblog.com/2006/09/04/group_concat-useful-group-by-extension/>
I would do something like this : ``` select id, item, group_concat(category) from Table1 group by id, item ``` [SQLFiddle](http://sqlfiddle.com/#!2/9e49f/2)
16,158,221
I got this error: ``` [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] mod_wsgi (pid=19481): Exception occurred processing WSGI script '/home/projects/treeio/treeio.wsgi'. [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] Traceback (most recent call last): [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/wsgi.py", line 236, in __call__ [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] self.load_middleware() [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 53, in load_middleware [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] raise exceptions.ImproperlyConfigured('Error importing middleware %s: "%s"' % (mw_module, e)) [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] ImproperlyConfigured: Error importing middleware treeio.core.middleware.user: "No module named csrf.middleware" ``` I have Django 1.5.1 and Python 2.7.3. I am trying to install Tree.io. Any suggest? EDIT: ``` MIDDLEWARE_CLASSES = ( 'johnny.middleware.LocalStoreClearMiddleware', 'johnny.middleware.QueryCacheMiddleware', 'django.middleware.gzip.GZipMiddleware', 'treeio.core.middleware.domain.DomainMiddleware', 'treeio.core.middleware.user.SSLMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'treeio.core.middleware.user.AuthMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'treeio.core.middleware.chat.ChatAjaxMiddleware', "django.contrib.messages.middleware.MessageMiddleware", "treeio.core.middleware.modules.ModuleDetect", "minidetector.Middleware", "treeio.core.middleware.user.CommonMiddleware", "treeio.core.middleware.user.PopupMiddleware", "treeio.core.middleware.user.LanguageMiddleware",) ``` The SO: Ubuntu 12.04.2 LTS
2013/04/22
[ "https://Stackoverflow.com/questions/16158221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2309182/" ]
try `GROUP BY` with `GROUP_CONCAT` <http://www.mysqlperformanceblog.com/2006/09/04/group_concat-useful-group-by-extension/>
If you do not have the ability to change the query that gets the data from the database you can use the PHP helper function `array_unique`. This function removes duplicate values from an array. While it is better to do this in MySQL, its not always possible for the developer to do this easily so this would help. Here is a link to the PHP manual on this function: <http://www.php.net/manual/en/function.array-unique.php>
16,158,221
I got this error: ``` [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] mod_wsgi (pid=19481): Exception occurred processing WSGI script '/home/projects/treeio/treeio.wsgi'. [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] Traceback (most recent call last): [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/wsgi.py", line 236, in __call__ [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] self.load_middleware() [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 53, in load_middleware [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] raise exceptions.ImproperlyConfigured('Error importing middleware %s: "%s"' % (mw_module, e)) [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] ImproperlyConfigured: Error importing middleware treeio.core.middleware.user: "No module named csrf.middleware" ``` I have Django 1.5.1 and Python 2.7.3. I am trying to install Tree.io. Any suggest? EDIT: ``` MIDDLEWARE_CLASSES = ( 'johnny.middleware.LocalStoreClearMiddleware', 'johnny.middleware.QueryCacheMiddleware', 'django.middleware.gzip.GZipMiddleware', 'treeio.core.middleware.domain.DomainMiddleware', 'treeio.core.middleware.user.SSLMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'treeio.core.middleware.user.AuthMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'treeio.core.middleware.chat.ChatAjaxMiddleware', "django.contrib.messages.middleware.MessageMiddleware", "treeio.core.middleware.modules.ModuleDetect", "minidetector.Middleware", "treeio.core.middleware.user.CommonMiddleware", "treeio.core.middleware.user.PopupMiddleware", "treeio.core.middleware.user.LanguageMiddleware",) ``` The SO: Ubuntu 12.04.2 LTS
2013/04/22
[ "https://Stackoverflow.com/questions/16158221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2309182/" ]
You could do this all in your query instead of relying on PHP. ``` Select item, group_concat(category) FROM yourtable GROUP BY Item ```
Create an array of categories for each item: ``` while($results = mysql_fetch_array($raw_results)) { $items[$results['item']][] = $results['category']; } ``` Then use that to output your HTML: ``` foreach ($items as $itemName => $categories) { echo $itemName.'<br>'; echo 'Categories: '.implode(', ',$categories); } ```
16,158,221
I got this error: ``` [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] mod_wsgi (pid=19481): Exception occurred processing WSGI script '/home/projects/treeio/treeio.wsgi'. [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] Traceback (most recent call last): [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/wsgi.py", line 236, in __call__ [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] self.load_middleware() [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 53, in load_middleware [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] raise exceptions.ImproperlyConfigured('Error importing middleware %s: "%s"' % (mw_module, e)) [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] ImproperlyConfigured: Error importing middleware treeio.core.middleware.user: "No module named csrf.middleware" ``` I have Django 1.5.1 and Python 2.7.3. I am trying to install Tree.io. Any suggest? EDIT: ``` MIDDLEWARE_CLASSES = ( 'johnny.middleware.LocalStoreClearMiddleware', 'johnny.middleware.QueryCacheMiddleware', 'django.middleware.gzip.GZipMiddleware', 'treeio.core.middleware.domain.DomainMiddleware', 'treeio.core.middleware.user.SSLMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'treeio.core.middleware.user.AuthMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'treeio.core.middleware.chat.ChatAjaxMiddleware', "django.contrib.messages.middleware.MessageMiddleware", "treeio.core.middleware.modules.ModuleDetect", "minidetector.Middleware", "treeio.core.middleware.user.CommonMiddleware", "treeio.core.middleware.user.PopupMiddleware", "treeio.core.middleware.user.LanguageMiddleware",) ``` The SO: Ubuntu 12.04.2 LTS
2013/04/22
[ "https://Stackoverflow.com/questions/16158221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2309182/" ]
You could do this all in your query instead of relying on PHP. ``` Select item, group_concat(category) FROM yourtable GROUP BY Item ```
If you do not have the ability to change the query that gets the data from the database you can use the PHP helper function `array_unique`. This function removes duplicate values from an array. While it is better to do this in MySQL, its not always possible for the developer to do this easily so this would help. Here is a link to the PHP manual on this function: <http://www.php.net/manual/en/function.array-unique.php>
16,158,221
I got this error: ``` [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] mod_wsgi (pid=19481): Exception occurred processing WSGI script '/home/projects/treeio/treeio.wsgi'. [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] Traceback (most recent call last): [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/wsgi.py", line 236, in __call__ [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] self.load_middleware() [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 53, in load_middleware [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] raise exceptions.ImproperlyConfigured('Error importing middleware %s: "%s"' % (mw_module, e)) [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] ImproperlyConfigured: Error importing middleware treeio.core.middleware.user: "No module named csrf.middleware" ``` I have Django 1.5.1 and Python 2.7.3. I am trying to install Tree.io. Any suggest? EDIT: ``` MIDDLEWARE_CLASSES = ( 'johnny.middleware.LocalStoreClearMiddleware', 'johnny.middleware.QueryCacheMiddleware', 'django.middleware.gzip.GZipMiddleware', 'treeio.core.middleware.domain.DomainMiddleware', 'treeio.core.middleware.user.SSLMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'treeio.core.middleware.user.AuthMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'treeio.core.middleware.chat.ChatAjaxMiddleware', "django.contrib.messages.middleware.MessageMiddleware", "treeio.core.middleware.modules.ModuleDetect", "minidetector.Middleware", "treeio.core.middleware.user.CommonMiddleware", "treeio.core.middleware.user.PopupMiddleware", "treeio.core.middleware.user.LanguageMiddleware",) ``` The SO: Ubuntu 12.04.2 LTS
2013/04/22
[ "https://Stackoverflow.com/questions/16158221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2309182/" ]
I would do something like this : ``` select id, item, group_concat(category) from Table1 group by id, item ``` [SQLFiddle](http://sqlfiddle.com/#!2/9e49f/2)
Create an array of categories for each item: ``` while($results = mysql_fetch_array($raw_results)) { $items[$results['item']][] = $results['category']; } ``` Then use that to output your HTML: ``` foreach ($items as $itemName => $categories) { echo $itemName.'<br>'; echo 'Categories: '.implode(', ',$categories); } ```
16,158,221
I got this error: ``` [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] mod_wsgi (pid=19481): Exception occurred processing WSGI script '/home/projects/treeio/treeio.wsgi'. [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] Traceback (most recent call last): [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/wsgi.py", line 236, in __call__ [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] self.load_middleware() [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 53, in load_middleware [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] raise exceptions.ImproperlyConfigured('Error importing middleware %s: "%s"' % (mw_module, e)) [Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] ImproperlyConfigured: Error importing middleware treeio.core.middleware.user: "No module named csrf.middleware" ``` I have Django 1.5.1 and Python 2.7.3. I am trying to install Tree.io. Any suggest? EDIT: ``` MIDDLEWARE_CLASSES = ( 'johnny.middleware.LocalStoreClearMiddleware', 'johnny.middleware.QueryCacheMiddleware', 'django.middleware.gzip.GZipMiddleware', 'treeio.core.middleware.domain.DomainMiddleware', 'treeio.core.middleware.user.SSLMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'treeio.core.middleware.user.AuthMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'treeio.core.middleware.chat.ChatAjaxMiddleware', "django.contrib.messages.middleware.MessageMiddleware", "treeio.core.middleware.modules.ModuleDetect", "minidetector.Middleware", "treeio.core.middleware.user.CommonMiddleware", "treeio.core.middleware.user.PopupMiddleware", "treeio.core.middleware.user.LanguageMiddleware",) ``` The SO: Ubuntu 12.04.2 LTS
2013/04/22
[ "https://Stackoverflow.com/questions/16158221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2309182/" ]
I would do something like this : ``` select id, item, group_concat(category) from Table1 group by id, item ``` [SQLFiddle](http://sqlfiddle.com/#!2/9e49f/2)
If you do not have the ability to change the query that gets the data from the database you can use the PHP helper function `array_unique`. This function removes duplicate values from an array. While it is better to do this in MySQL, its not always possible for the developer to do this easily so this would help. Here is a link to the PHP manual on this function: <http://www.php.net/manual/en/function.array-unique.php>
12,482,819
I have been working with Beaglebone lately and have a question. I have worked with TI microcontrollers before, setting the registers as I needed to. From what I understand, the Angstrom distro (the one that comes with the board) let to set the registers of the processor as you want (through the kernel and class folders from /sys). How can relate the files in Angstrom with the registers of the TI microprocessor? Also, how can I set the clock/timer for the PWM signals? I want to do it through a program in C. I have found libraries and programs written in python but they do not help me to understand what is really been set. I appreciate the help you could provide. Thanks in advance. gus
2012/09/18
[ "https://Stackoverflow.com/questions/12482819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1420553/" ]
After trying out a few variations this worked: ``` -:System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute ```
Make sure you add this filter inside **Attribute Filter**: ``` -:System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute ``` ![enter image description here](https://i.stack.imgur.com/Gw7tA.png)
41,009,009
I'm trying to create a function ``` rotate_character(char, rot) ``` that receives a character, "char" (a string with a length of 1), and an integer "rot". The function should return a new string with a length of 1, which is the result of rotating char by rot number of places to the right. So an input of "A" for char and "13" for rot would return ``` N ``` (with A having an initial value of 0, and B having an initial value of 1, etc). Capitalization should be maintained during rotation. I already created a function that returns the position of a letter in the alphabet by using a dictionary: ``` letter = input("Enter a letter: ") def alphabet_position(letter): alphabet_pos = {'A':0, 'a':0, 'B':1, 'b':1, 'C':2, 'c':2, 'D':3, 'd':3, 'E':4, 'e':4, 'F':5, 'f':5, 'G':6, 'g':6, 'H':7, 'h':7, 'I':8, 'i':8, 'J':9, 'j':9, 'K':10, 'k':10, 'L':11, 'l':11, 'M':12, 'm':12, 'N': 13, 'n':13, 'O':14, 'o':14, 'P':15, 'p':15, 'Q':16, 'q':16, 'R':17, 'r':17, 'S':18, 's':18, 'T':19, 't':19, 'U':20, 'u':20, 'V':21, 'v':21, 'W':22, 'w':22, 'X':23, 'x':23, 'Y':24, 'y':24, 'Z':25, 'z':25 } pos = alphabet_pos[letter] return pos ``` I figure that I can use this function to get the initial value of (char) before rotation. ``` def rotate_character(char, rot) initial_char = alphabet_position(char) final_char = initial_char + rot ``` But my problem is that, if initial\_char + rot is greater than 25, I need to wrap back to the beginning of the alphabet and continue counting. So an input of "w" (initial value of 22) + an input of 8 for rot should return ``` e ``` How do I say this using python? ``` if final_char > 25, start at the beginning of the list and continue counting ``` And do I necessarily need to use the dictionary that I created in the alphabet\_position function? [It was also suggested](https://stackoverflow.com/questions/41007646/python-function-that-receives-letter-returns-0-based-numerical-position-within) that I find the character number by using Python's built-in list of letters, like this: ``` import string letter = input('enter a letter: ') def alphabet_position(letter): letter = letter.lower() return list(string.ascii_lowercase).index(letter) return(alphabet_position(letter)) ``` I'm not sure which one of these is the better option to go with when you have to wrap while you're counting. Thanks for your help / suggestions! **EDIT**: Now my code looks like this: ``` letter = input("enter a letter") rotate = input("enter a number") def rotate(letter, rotate): letter = letter.lower() return chr((ord(letter) + rotate - 97) % 26 + 97) print(rotate(letter)) ``` **EDIT 2**: ``` def rotate(letter, number): letter = letter.lower() shift = 97 if letter.islower() else 65 return chr((ord(letter) + number - shift) % 26 + shift) letter = input('Enter a letter: ') number = int(eval(input('Enter a number: ') print(rotate(letter, number)) ``` gave me a ParseError: "ParseError: bad input on line 8" (the print line)
2016/12/07
[ "https://Stackoverflow.com/questions/41009009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3546086/" ]
``` def rotate(letter, rot): shift = 97 if letter.islower() else 65 return chr((ord(letter) + rot - shift) % 26 + shift) letter = input('Enter a letter: ') rot = int(input('Enter a number: ')) print(rotate(letter, rot)) ```
You can use the `string` module and then use the modulo operator to "wrap around" the end of the alphabet: ``` from string import lowercase def rotate_char(char, rot): i = lowercase.index(char) return lowercase[(i + rot) % 25] ```
39,606,112
I'm a beginner trying to write a program that will read in .exe files, .class files, or .pyc files and get the percentage of alphanumeric characters (a-z,A-Z,0-9). Here's what I have right now (I'm just trying to see if I can identify anything at the moment, not looking to count stuff yet): ``` chars_total = 0 chars_alphnum = 0 iterate = 1 with open("pythonfile.pyc", "rb") as f: byte = f.read(iterate) while byte != b"": chars_total += 1 print (byte) iterate +=1 byte = f.read(iterate) ``` This code prints out various bytes such as ``` b'\xe1WQ\x00' b'\x00\x00c\x00\x00' ``` but I'm having trouble with translating the bytes themselves. I've also tried `print (binascii.hexlify(byte))` after importing binascii which converts everything into alphanumeric characters, which seems to not quite be what I'm looking for. So am I just getting something severely mistaken or am I at least on the right track? Full disclaimer, this is related in small part to a homework assignment, but we have permission to use this site because neither the in class material nor the reading covers any coding at all. And yes, I have been trying to figure this out before I came on here.
2016/09/21
[ "https://Stackoverflow.com/questions/39606112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6856008/" ]
`viewWillLayoutSubviews` is called when view controller's view's bounds changed (usually happens when view loaded, or orientation changed, or if it's a child view controller, and its view was changed by the parent view controller), but before it's subview's bounds or position changes. You can override this method to make some changes to subview's bounds or position before the view layouts them. `layoutSubviews`, from Apple's [documentation](https://developer.apple.com/reference/uikit/uiview/1622482-layoutsubviews): > > You should override this method only if the autoresizing and constraint-based behaviors of the subviews do not offer the behavior you want > > > This method gets called when a layout update happens, either by changing the view's bounds explicitly or call `setNeedsLayout` or `layoutIfNeeded` on the view to force a layout update. Please remember that it will be called automatically by the OS, and you should never call it directly. It's quite rare that you need to override this method, cause usually the autoresizing or constraint will do the job for you.
You can call the `layoutSubviews()` of UIView when you are changing any constraint value which is inside the UIView and more then one element is effected by the constraint change. When you are performing some task by changing the constraint by taking an outlet of the constraint at runtime you can call this. But this is not a best practice. I suggest call `layoutIfNeeded()` instead of this `layoutSubviews()`. You need to use `viewWillLayoutSubviews()` function when you want to perform some task just before any element changes its size or position in the view controller. When you are going to make an application, those 2 functions are rarely used in worst case scenarios. This is as per my understanding. Thanks.
39,606,112
I'm a beginner trying to write a program that will read in .exe files, .class files, or .pyc files and get the percentage of alphanumeric characters (a-z,A-Z,0-9). Here's what I have right now (I'm just trying to see if I can identify anything at the moment, not looking to count stuff yet): ``` chars_total = 0 chars_alphnum = 0 iterate = 1 with open("pythonfile.pyc", "rb") as f: byte = f.read(iterate) while byte != b"": chars_total += 1 print (byte) iterate +=1 byte = f.read(iterate) ``` This code prints out various bytes such as ``` b'\xe1WQ\x00' b'\x00\x00c\x00\x00' ``` but I'm having trouble with translating the bytes themselves. I've also tried `print (binascii.hexlify(byte))` after importing binascii which converts everything into alphanumeric characters, which seems to not quite be what I'm looking for. So am I just getting something severely mistaken or am I at least on the right track? Full disclaimer, this is related in small part to a homework assignment, but we have permission to use this site because neither the in class material nor the reading covers any coding at all. And yes, I have been trying to figure this out before I came on here.
2016/09/21
[ "https://Stackoverflow.com/questions/39606112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6856008/" ]
There is no effective difference. One (`layoutSubviews`) is a message the runtime sends to the view, the other (`viewWillLayoutSubviews`) is a message the runtime sends to the view controller. The message to the view controller tells the view controller that its view is about to receive the view message! That's all. They go together.
You can call the `layoutSubviews()` of UIView when you are changing any constraint value which is inside the UIView and more then one element is effected by the constraint change. When you are performing some task by changing the constraint by taking an outlet of the constraint at runtime you can call this. But this is not a best practice. I suggest call `layoutIfNeeded()` instead of this `layoutSubviews()`. You need to use `viewWillLayoutSubviews()` function when you want to perform some task just before any element changes its size or position in the view controller. When you are going to make an application, those 2 functions are rarely used in worst case scenarios. This is as per my understanding. Thanks.
39,606,112
I'm a beginner trying to write a program that will read in .exe files, .class files, or .pyc files and get the percentage of alphanumeric characters (a-z,A-Z,0-9). Here's what I have right now (I'm just trying to see if I can identify anything at the moment, not looking to count stuff yet): ``` chars_total = 0 chars_alphnum = 0 iterate = 1 with open("pythonfile.pyc", "rb") as f: byte = f.read(iterate) while byte != b"": chars_total += 1 print (byte) iterate +=1 byte = f.read(iterate) ``` This code prints out various bytes such as ``` b'\xe1WQ\x00' b'\x00\x00c\x00\x00' ``` but I'm having trouble with translating the bytes themselves. I've also tried `print (binascii.hexlify(byte))` after importing binascii which converts everything into alphanumeric characters, which seems to not quite be what I'm looking for. So am I just getting something severely mistaken or am I at least on the right track? Full disclaimer, this is related in small part to a homework assignment, but we have permission to use this site because neither the in class material nor the reading covers any coding at all. And yes, I have been trying to figure this out before I came on here.
2016/09/21
[ "https://Stackoverflow.com/questions/39606112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6856008/" ]
There is no effective difference. One (`layoutSubviews`) is a message the runtime sends to the view, the other (`viewWillLayoutSubviews`) is a message the runtime sends to the view controller. The message to the view controller tells the view controller that its view is about to receive the view message! That's all. They go together.
`viewWillLayoutSubviews` is called when view controller's view's bounds changed (usually happens when view loaded, or orientation changed, or if it's a child view controller, and its view was changed by the parent view controller), but before it's subview's bounds or position changes. You can override this method to make some changes to subview's bounds or position before the view layouts them. `layoutSubviews`, from Apple's [documentation](https://developer.apple.com/reference/uikit/uiview/1622482-layoutsubviews): > > You should override this method only if the autoresizing and constraint-based behaviors of the subviews do not offer the behavior you want > > > This method gets called when a layout update happens, either by changing the view's bounds explicitly or call `setNeedsLayout` or `layoutIfNeeded` on the view to force a layout update. Please remember that it will be called automatically by the OS, and you should never call it directly. It's quite rare that you need to override this method, cause usually the autoresizing or constraint will do the job for you.
52,072,784
I am working on a positioning system. The input I have is a dict which will give us circles of radius d1 from point(x1,y1) and so on. The output I want is an array(similar to a 2D coordinate system) in which the intersecting area is marked 1 and rest is 0. I tried this: ``` xsize=3000 ysize=2000 lis={(x1,y1):d1,(x2,y2):d2,(x3,y3):d3} array=np.zeros((xsize,ysize)) for i in range(xsize-1): for j in range(ysize-1): for element in lis: if distance((i,j),element)<=(lis[element]): array[i][j]=1 else: array[i][j]=0 break def distance(p1,p2): return math.sqrt((p1[0]-p2[0])**2+(p1[1]-p2[1])**2) ``` The only problem is that the array is large and takes way too long(no. of loops is in 10 millions), especially on a raspberry pi, otherwise this works. Is there any way to do it using openCV and an image and then draw circles to get the intersecting area faster? It has to be python 2.x.
2018/08/29
[ "https://Stackoverflow.com/questions/52072784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10269207/" ]
As you are already using numpy, try to rewrite your operations in a vectorized fashion, instead of using loops. ``` # choose appropriate dtype for better perf dtype = np.float32 # take all indices in an array indices = np.indices((ysize, xsize), dtype=dtype).T points = np.array(list(lis.keys()), dtype=dtype) # squared distance from all indices to all points dist = (indices[..., np.newaxis] - points.T) ** 2 dist = dist.sum(axis=-2) # squared circle radii dist_thresh = np.array(list(lis.values()), dtype=dtype) ** 2 intersect = np.all(dist <= dist_thresh, axis=-1) ``` That's around 60x faster on my machine than the for loop version. It is still a brute-force version, doing possibly many needless computations for all coordinates. The circles are not given in the question, so it's hard to reason about them. If they cover a relatively small area, the problem will be solved much faster (still computationally, not analytically), if a smaller area is considered. For example instead of testing all coordinates, the intersection of the bounding boxes of the circles could be used, which may reduce the computational load considerably.
Thanks for the answers! I also found this: ``` pos=np.ones((xsize,ysize)) xx,yy=np.mgrid[:xsize,:ysize] for element in lis: circle=(xx-element[0])**2+(yy-element[1])**2 pos=np.logical_and(pos,(circle<(lis[element]**2))) #pos&circle<(lis[element]**2 doesn't work(I read somewhere it does) ``` I needed this array for marking when I reached my destination or not. ``` if pos[dest[0]][dest[1]]==1 #Reached ```
42,835,809
are there any tutorials available about `export_savedmodel` ? I have gone through [this article](https://www.tensorflow.org/versions/master/api_docs/python/contrib.learn/estimators) on tensorflow.org and [unittest code](https://github.com/tensorflow/tensorflow/blob/05d7f793ec5f04cd6b362abfef620a78fefdb35f/tensorflow/python/estimator/estimator_test.py) on github.com, and still have no idea about how to construct the parameter `serving_input_fn` of function `export_savedmodel`
2017/03/16
[ "https://Stackoverflow.com/questions/42835809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/456105/" ]
if you are using tensorflow straight from the master branch there's a module tensorflow.python.estimator.export that provides a function for that: ``` from tensorflow.python.estimator.export import export feature_spec = {'MY_FEATURE': tf.constant(2.0, shape=[1, 1])} serving_input_fn = export.build_raw_serving_input_receiver_fn(feature_spec) ``` Unfortunately at least for me it will not go further than that but I'm not sure if my model is really correct so maybe you have more luck than I do. Alternatively, there are the following functions for the current version installed from pypi: ``` serving_input_fn = tf.contrib.learn.utils.build_parsing_serving_input_fn(feature_spec) serving_input_fn = tf.contrib.learn.utils.build_default_serving_input_fn(feature_spec) ``` But I couldn't get them to work, too. Probably, I'm not understanding this correctly so I hope you'll have more luck. chris
You need to have tf.train.Example and tf.train.Feature and pass the input to input receiver function and invoke the model. You can take a look at this example <https://github.com/tettusud/tensorflow-examples/tree/master/estimators>
42,835,809
are there any tutorials available about `export_savedmodel` ? I have gone through [this article](https://www.tensorflow.org/versions/master/api_docs/python/contrib.learn/estimators) on tensorflow.org and [unittest code](https://github.com/tensorflow/tensorflow/blob/05d7f793ec5f04cd6b362abfef620a78fefdb35f/tensorflow/python/estimator/estimator_test.py) on github.com, and still have no idea about how to construct the parameter `serving_input_fn` of function `export_savedmodel`
2017/03/16
[ "https://Stackoverflow.com/questions/42835809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/456105/" ]
Do it like this: ``` your_feature_spec = { "some_feature": tf.FixedLenFeature([], dtype=tf.string, default_value=""), "some_feature": tf.VarLenFeature(dtype=tf.string), } def _serving_input_receiver_fn(): serialized_tf_example = tf.placeholder(dtype=tf.string, shape=None, name='input_example_tensor') # key (e.g. 'examples') should be same with the inputKey when you # buid the request for prediction receiver_tensors = {'examples': serialized_tf_example} features = tf.parse_example(serialized_tf_example, your_feature_spec) return tf.estimator.export.ServingInputReceiver(features, receiver_tensors) estimator.export_savedmodel(export_dir, _serving_input_receiver_fn) ``` Then you can request the served model with "predict" signature name by batch. Source: <https://www.tensorflow.org/guide/saved_model#prepare_serving_inputs>
if you are using tensorflow straight from the master branch there's a module tensorflow.python.estimator.export that provides a function for that: ``` from tensorflow.python.estimator.export import export feature_spec = {'MY_FEATURE': tf.constant(2.0, shape=[1, 1])} serving_input_fn = export.build_raw_serving_input_receiver_fn(feature_spec) ``` Unfortunately at least for me it will not go further than that but I'm not sure if my model is really correct so maybe you have more luck than I do. Alternatively, there are the following functions for the current version installed from pypi: ``` serving_input_fn = tf.contrib.learn.utils.build_parsing_serving_input_fn(feature_spec) serving_input_fn = tf.contrib.learn.utils.build_default_serving_input_fn(feature_spec) ``` But I couldn't get them to work, too. Probably, I'm not understanding this correctly so I hope you'll have more luck. chris
42,835,809
are there any tutorials available about `export_savedmodel` ? I have gone through [this article](https://www.tensorflow.org/versions/master/api_docs/python/contrib.learn/estimators) on tensorflow.org and [unittest code](https://github.com/tensorflow/tensorflow/blob/05d7f793ec5f04cd6b362abfef620a78fefdb35f/tensorflow/python/estimator/estimator_test.py) on github.com, and still have no idea about how to construct the parameter `serving_input_fn` of function `export_savedmodel`
2017/03/16
[ "https://Stackoverflow.com/questions/42835809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/456105/" ]
You have 2 options: Export your model to work with JSON dictionaries ------------------------------------------------ In my [mlengine-boilerplate repository](https://github.com/Fematich/mlengine-boilerplate/blob/master/trainer/task.py), I use this to export estimator models to Cloud ML Engine to easily use this with online predictions ([sample code for the predictions](https://github.com/Fematich/mlengine-boilerplate/blob/master/predictions/predict.py)). Essential part: ``` def serving_input_fn(): feature_placeholders = { 'id': tf.placeholder(tf.string, [None], name="id_placeholder"), 'feat': tf.placeholder(tf.float32, [None, FEAT_LEN], name="feat_placeholder"), #label is not required since serving is only used for inference } return input_fn_utils.InputFnOps( feature_placeholders, None, feature_placeholders) ``` Export your model to work with Tensorflow Examples -------------------------------------------------- [This tutorial](https://github.com/MtDersvan/tf_playground/blob/master/wide_and_deep_tutorial/wide_and_deep_basic_serving.md) shows how you can use `export_savedmodel` to serve the Wide & Deep Model implemented with estimators and how to feed Tensorflow examples into the exported model. The essential part: ``` from tensorflow.contrib.learn.python.learn.utils import input_fn_utils serving_input_fn = input_fn_utils.build_parsing_serving_input_fn(feature_spec) ```
You need to have tf.train.Example and tf.train.Feature and pass the input to input receiver function and invoke the model. You can take a look at this example <https://github.com/tettusud/tensorflow-examples/tree/master/estimators>
42,835,809
are there any tutorials available about `export_savedmodel` ? I have gone through [this article](https://www.tensorflow.org/versions/master/api_docs/python/contrib.learn/estimators) on tensorflow.org and [unittest code](https://github.com/tensorflow/tensorflow/blob/05d7f793ec5f04cd6b362abfef620a78fefdb35f/tensorflow/python/estimator/estimator_test.py) on github.com, and still have no idea about how to construct the parameter `serving_input_fn` of function `export_savedmodel`
2017/03/16
[ "https://Stackoverflow.com/questions/42835809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/456105/" ]
Do it like this: ``` your_feature_spec = { "some_feature": tf.FixedLenFeature([], dtype=tf.string, default_value=""), "some_feature": tf.VarLenFeature(dtype=tf.string), } def _serving_input_receiver_fn(): serialized_tf_example = tf.placeholder(dtype=tf.string, shape=None, name='input_example_tensor') # key (e.g. 'examples') should be same with the inputKey when you # buid the request for prediction receiver_tensors = {'examples': serialized_tf_example} features = tf.parse_example(serialized_tf_example, your_feature_spec) return tf.estimator.export.ServingInputReceiver(features, receiver_tensors) estimator.export_savedmodel(export_dir, _serving_input_receiver_fn) ``` Then you can request the served model with "predict" signature name by batch. Source: <https://www.tensorflow.org/guide/saved_model#prepare_serving_inputs>
You have 2 options: Export your model to work with JSON dictionaries ------------------------------------------------ In my [mlengine-boilerplate repository](https://github.com/Fematich/mlengine-boilerplate/blob/master/trainer/task.py), I use this to export estimator models to Cloud ML Engine to easily use this with online predictions ([sample code for the predictions](https://github.com/Fematich/mlengine-boilerplate/blob/master/predictions/predict.py)). Essential part: ``` def serving_input_fn(): feature_placeholders = { 'id': tf.placeholder(tf.string, [None], name="id_placeholder"), 'feat': tf.placeholder(tf.float32, [None, FEAT_LEN], name="feat_placeholder"), #label is not required since serving is only used for inference } return input_fn_utils.InputFnOps( feature_placeholders, None, feature_placeholders) ``` Export your model to work with Tensorflow Examples -------------------------------------------------- [This tutorial](https://github.com/MtDersvan/tf_playground/blob/master/wide_and_deep_tutorial/wide_and_deep_basic_serving.md) shows how you can use `export_savedmodel` to serve the Wide & Deep Model implemented with estimators and how to feed Tensorflow examples into the exported model. The essential part: ``` from tensorflow.contrib.learn.python.learn.utils import input_fn_utils serving_input_fn = input_fn_utils.build_parsing_serving_input_fn(feature_spec) ```
42,835,809
are there any tutorials available about `export_savedmodel` ? I have gone through [this article](https://www.tensorflow.org/versions/master/api_docs/python/contrib.learn/estimators) on tensorflow.org and [unittest code](https://github.com/tensorflow/tensorflow/blob/05d7f793ec5f04cd6b362abfef620a78fefdb35f/tensorflow/python/estimator/estimator_test.py) on github.com, and still have no idea about how to construct the parameter `serving_input_fn` of function `export_savedmodel`
2017/03/16
[ "https://Stackoverflow.com/questions/42835809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/456105/" ]
Do it like this: ``` your_feature_spec = { "some_feature": tf.FixedLenFeature([], dtype=tf.string, default_value=""), "some_feature": tf.VarLenFeature(dtype=tf.string), } def _serving_input_receiver_fn(): serialized_tf_example = tf.placeholder(dtype=tf.string, shape=None, name='input_example_tensor') # key (e.g. 'examples') should be same with the inputKey when you # buid the request for prediction receiver_tensors = {'examples': serialized_tf_example} features = tf.parse_example(serialized_tf_example, your_feature_spec) return tf.estimator.export.ServingInputReceiver(features, receiver_tensors) estimator.export_savedmodel(export_dir, _serving_input_receiver_fn) ``` Then you can request the served model with "predict" signature name by batch. Source: <https://www.tensorflow.org/guide/saved_model#prepare_serving_inputs>
You need to have tf.train.Example and tf.train.Feature and pass the input to input receiver function and invoke the model. You can take a look at this example <https://github.com/tettusud/tensorflow-examples/tree/master/estimators>
70,068,198
I have api like this : ![api](https://i.stack.imgur.com/dvcZ5.png) I want to call this api in python, this is my code : ``` def get_province(): headers = { 'Content-type': 'application/json', 'x-api-key': api_key } response = requests.get(url, headers=headers) return response.json() ``` But, i've got > > error 500 : Internal Server Error. > > > I think there's something wrong with the header. Can anyone help me?
2021/11/22
[ "https://Stackoverflow.com/questions/70068198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17480369/" ]
**No Need for a LOOP** Here is a little technique Gordon Linoff demonstrated some time ago. 1. Expand 2. Elimnate 3. Restore You can substitute any `ODD` combination of characters/strings pairs like `§§` and `||` **Example** ``` Select replace(replace(replace('my string to split',' ','><'),'<>',''),'><',' ') ``` or More Unique strings ``` Select replace(replace(replace('my string to split',' ','§§||'),'||§§',''),'§§||',' ') ``` **Results** ``` my string to split ```
use charindex <https://www.w3schools.com/sql/func_sqlserver_charindex.asp> in a looping structure and then use a variable to keep track of the index position.
14,444,012
I am writing a bit of `python` code where I had to check if all values in `list2` was present in `list1`, I did that by using `set(list2).difference(list1)` but that function was too slow with many items in the list. So I was thinking that `list1` could be a dictionary for fast lookup... So I would like to find a fast way to determent if a list has an item that isn't part of a dict performance wise is there any difference between ``` d = {1: 1, 2:2, 3:3} l = [3, 4, 5] for n in l: if not n in d: do_stuff ``` vs ``` for n in l: if not d[n]: do_stuff ``` and please if both of these are rubbish and you know something much quicker, tell me. Edit1: list1 or d can contain elements not in list2 but not the other way around.
2013/01/21
[ "https://Stackoverflow.com/questions/14444012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1376883/" ]
A fast way to achieve what you want will be using `all` and a generator comprehension. ``` s_list2 = set(list2) all_present = all(l in s_list2 for l in list1) ``` This will be advantageous in the case that some elements of list1 are not present in list2. Some timing. In the case where all values in the first list are contained in the second: ``` In [4]: l1 = range(100) In [5]: l2 = range(1000) In [6]: random.shuffle(l1) In [9]: random.shuffle(l2) In [20]: %timeit s2 = set(l2); all(l in s2 for l in l1) 10000 loops, best of 3: 26.4 us per loop In [21]: %timeit s1 = set(l1); s2 = set(l2); s1.issubset(s2) 10000 loops, best of 3: 25.3 us per loop ``` If we look at the case where some values in the first list are **not** present in the second: ``` In [2]: l1 = range(1000) In [3]: l2 = range(100) In [4]: random.shuffle(l1) In [5]: random.shuffle(l2) In [6]: sl2 = set(l2) In [8]: %timeit ss = set(l2); set(l1) & ss == ss 10000 loops, best of 3: 27.8 us per loop In [10]: %timeit s1 = set(l1); s2 = set(l2); s2.issubset(s1) 10000 loops, best of 3: 24.7 us per loop In [11]: %timeit sl2 = set(l2); all(l in sl2 for l in l1) 100000 loops, best of 3: 3.58 us per loop ``` You can see that this method is equivalent in performance to the `issubset` in the first case and is faster in the second case as it will short circuit and obviates the need to construct 2 intermediate sets (only requiring one). Having one large list and one small lists demonstrates the benefit of the gencomp method: ``` In [7]: l1 = range(10) In [8]: l2 = range(10000) In [9]: %timeit sl2 = set(l2); all(l in sl2 for l in l1) 1000 loops, best of 3: 230 us per loop In [10]: %timeit sl1 = set(l1); all(l in sl1 for l in l2) 1000000 loops, best of 3: 1.45 us per loop In [11]: %timeit s1 = set(l1); s2 = set(l2); s1.issubset(s2) 1000 loops, best of 3: 228 us per loop In [12]: %timeit s1 = set(l1); s2 = set(l2); s2.issubset(s1) 1000 loops, best of 3: 228 us per loop ```
You can convert the lists to sets and then use the method `issubset()` to check whether one is a subset of another set or not. ``` In [78]: import random In [79]: lis2=range(100) In [80]: random.shuffle(lis2) In [81]: lis1=range(1000) In [82]: random.shuffle(lis1) In [83]: s1=set(lis1) In [84]: all(l in s1 for l in lis2) Out[84]: True In [85]: %timeit all(l in s1 for l in lis2) 10000 loops, best of 3: 28.6 us per loop In [86]: %timeit s2=set(lis2);s2.issubset(s1) 100000 loops, best of 3: 12 us per loop In [87]: s2.issubset(s1) Out[87]: True ```
14,444,012
I am writing a bit of `python` code where I had to check if all values in `list2` was present in `list1`, I did that by using `set(list2).difference(list1)` but that function was too slow with many items in the list. So I was thinking that `list1` could be a dictionary for fast lookup... So I would like to find a fast way to determent if a list has an item that isn't part of a dict performance wise is there any difference between ``` d = {1: 1, 2:2, 3:3} l = [3, 4, 5] for n in l: if not n in d: do_stuff ``` vs ``` for n in l: if not d[n]: do_stuff ``` and please if both of these are rubbish and you know something much quicker, tell me. Edit1: list1 or d can contain elements not in list2 but not the other way around.
2013/01/21
[ "https://Stackoverflow.com/questions/14444012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1376883/" ]
A fast way to achieve what you want will be using `all` and a generator comprehension. ``` s_list2 = set(list2) all_present = all(l in s_list2 for l in list1) ``` This will be advantageous in the case that some elements of list1 are not present in list2. Some timing. In the case where all values in the first list are contained in the second: ``` In [4]: l1 = range(100) In [5]: l2 = range(1000) In [6]: random.shuffle(l1) In [9]: random.shuffle(l2) In [20]: %timeit s2 = set(l2); all(l in s2 for l in l1) 10000 loops, best of 3: 26.4 us per loop In [21]: %timeit s1 = set(l1); s2 = set(l2); s1.issubset(s2) 10000 loops, best of 3: 25.3 us per loop ``` If we look at the case where some values in the first list are **not** present in the second: ``` In [2]: l1 = range(1000) In [3]: l2 = range(100) In [4]: random.shuffle(l1) In [5]: random.shuffle(l2) In [6]: sl2 = set(l2) In [8]: %timeit ss = set(l2); set(l1) & ss == ss 10000 loops, best of 3: 27.8 us per loop In [10]: %timeit s1 = set(l1); s2 = set(l2); s2.issubset(s1) 10000 loops, best of 3: 24.7 us per loop In [11]: %timeit sl2 = set(l2); all(l in sl2 for l in l1) 100000 loops, best of 3: 3.58 us per loop ``` You can see that this method is equivalent in performance to the `issubset` in the first case and is faster in the second case as it will short circuit and obviates the need to construct 2 intermediate sets (only requiring one). Having one large list and one small lists demonstrates the benefit of the gencomp method: ``` In [7]: l1 = range(10) In [8]: l2 = range(10000) In [9]: %timeit sl2 = set(l2); all(l in sl2 for l in l1) 1000 loops, best of 3: 230 us per loop In [10]: %timeit sl1 = set(l1); all(l in sl1 for l in l2) 1000000 loops, best of 3: 1.45 us per loop In [11]: %timeit s1 = set(l1); s2 = set(l2); s1.issubset(s2) 1000 loops, best of 3: 228 us per loop In [12]: %timeit s1 = set(l1); s2 = set(l2); s2.issubset(s1) 1000 loops, best of 3: 228 us per loop ```
Sorting both lists and then walking through them together is O(n log n). i.e.: ``` l1.sort() l2.sort() j = 0 for i in range(0,len(l1)): while ((j < len(l2)) and (l1[i] == l2[j])): j = j+1 if (j == len(l2)): break if (l1[i] > l2[j]): break if (j == len(l2)): # all of l2 in l1 ``` Now in terms of time complexity, like I said this is O(n log n) because of the sorts (second loop is less than that at O(n)). However it may not be faster in python than the builtin set operations. You'd have to try it. [BTW, probably a more pythony way to do the last piece with comprehensions if I thought about it]
14,444,012
I am writing a bit of `python` code where I had to check if all values in `list2` was present in `list1`, I did that by using `set(list2).difference(list1)` but that function was too slow with many items in the list. So I was thinking that `list1` could be a dictionary for fast lookup... So I would like to find a fast way to determent if a list has an item that isn't part of a dict performance wise is there any difference between ``` d = {1: 1, 2:2, 3:3} l = [3, 4, 5] for n in l: if not n in d: do_stuff ``` vs ``` for n in l: if not d[n]: do_stuff ``` and please if both of these are rubbish and you know something much quicker, tell me. Edit1: list1 or d can contain elements not in list2 but not the other way around.
2013/01/21
[ "https://Stackoverflow.com/questions/14444012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1376883/" ]
You can convert the lists to sets and then use the method `issubset()` to check whether one is a subset of another set or not. ``` In [78]: import random In [79]: lis2=range(100) In [80]: random.shuffle(lis2) In [81]: lis1=range(1000) In [82]: random.shuffle(lis1) In [83]: s1=set(lis1) In [84]: all(l in s1 for l in lis2) Out[84]: True In [85]: %timeit all(l in s1 for l in lis2) 10000 loops, best of 3: 28.6 us per loop In [86]: %timeit s2=set(lis2);s2.issubset(s1) 100000 loops, best of 3: 12 us per loop In [87]: s2.issubset(s1) Out[87]: True ```
Sorting both lists and then walking through them together is O(n log n). i.e.: ``` l1.sort() l2.sort() j = 0 for i in range(0,len(l1)): while ((j < len(l2)) and (l1[i] == l2[j])): j = j+1 if (j == len(l2)): break if (l1[i] > l2[j]): break if (j == len(l2)): # all of l2 in l1 ``` Now in terms of time complexity, like I said this is O(n log n) because of the sorts (second loop is less than that at O(n)). However it may not be faster in python than the builtin set operations. You'd have to try it. [BTW, probably a more pythony way to do the last piece with comprehensions if I thought about it]
11,962,123
I am trying to make a query which I haven't been able to yet. My permanent view function is following: ``` function(doc) { if('llweb_result' in doc){ for(i in doc.llweb_result){ emit(doc.llweb_result[i].llweb_result, doc); } } } ``` Depending on the key, I filter the result. So, I need this key. Secondly, as you see, there is a for loop. This causes identical tuples in the result. However, I also need to do this for loop to check everything. In here, I just want to know how to eliminate identical tuples? I am using couchdb-python. My related code is: ``` result = {} result['0'] = self.dns_db.view('llweb/llweb_filter', None, key=0, limit = amount, startkey_docid = '000000052130') result['1'] = self.dns_db.view('llweb/llweb_filter', None, key=1, limit=amount) result['2'] = self.dns_db.view('llweb/llweb_filter', None, key=2, limit=amount) ``` As it is understood from key values, there are three different types of keys. I thought that I can extend the 'key' with [doc.\_id, llweb\_result]. I need a key like [\*, 2], but I don't know it is possible. Then, use reduce function to group them. This will definitely work, but at this time the problem is how to make a selection query by using only the values [0,1,2]. Edited in 16.08.12 Example for 'llweb\_result' property of a couchdb record: ``` "llweb_result": { "1": { "ip": "66.233.123.15", "domain": "domain.com", "llweb_result": 1 }, "0": { "ip": "66.235.132.118", "domain": "domain.com', "llweb_result": 1 } } ``` there is only one domain name in one record, but ther could be multiple ips for it. You can consider the record as a dns packet. I want to group records depending on llweb\_result (0,1,2). I will do a selection query for them(e.g. I fetch records which contains '1'). But for the example above, there will be two identical tuples in the result. Any help will be appriciated.
2012/08/14
[ "https://Stackoverflow.com/questions/11962123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1277280/" ]
If you get duplicate pairs in the query results, it means that you have the duplicate `doc.llweb_result[i].llweb_result` values in each document. You can change the view function to emit only one of these values (as the key). One way to do so would be: ``` function(doc) { if ('llweb_result' in doc) { distinct_values = {}; for (var i in doc.llweb_result) { distinct_values[doc.llweb_result[i].llweb_result] = true; } for(var dv in distinct_values) { emit(dv, doc); } } } ```
I don't know anything about `couchdb-python` but CouchDB supports either a single `key` or multiple `keys` in an array. So, take a look in your `couchdb-python` docs for how to supply `keys=[0,1,2]` as a parameter. Regarding getting just the unique values, take a look [at this section of *CouchDB The Definitive Guide*](http://guide.couchdb.org/draft/cookbook.html#unique) which explains how to add basically a NOOP reduce, so you can use `group=true`
7,045,371
I recently learned I could run a server with this command: ``` sudo python -m HTTPSimpleServer ``` **My question: how do I terminate this server when done with it?**
2011/08/12
[ "https://Stackoverflow.com/questions/7045371", "https://Stackoverflow.com", "https://Stackoverflow.com/users/873392/" ]
Type Control-C. Simple as that.
You might want to check the HttpServer class in [this servlet module](http://code.google.com/p/verse-quiz/source/browse/trunk/servlet.py) for a modification that allows the server to be quit. If the handler raises a SystemExit exception, the server will break from its serving. --- ``` class HttpServer(socketserver.ThreadingMixIn, http.server.HTTPServer): """Create a server with specified address and handler. A generic web server can be instantiated with this class. It will listen on the address given to its constructor and will use the handler class to process all incoming traffic. Running a server is greatly simplified.""" # We should not be binding to an # address that is already in use. allow_reuse_address = False @classmethod def main(cls, RequestHandlerClass, port=80): """Start server with handler on given port. This static method provides an easy way to start, run, and exit a HttpServer instance. The server will be executed if possible, and the computer's web browser will be directed to the address.""" try: server = cls(('', port), RequestHandlerClass) active = True except socket.error: active = False else: addr, port = server.socket.getsockname() print('Serving HTTP on', addr, 'port', port, '...') finally: port = '' if port == 80 else ':' + str(port) addr = 'http://localhost' + port + '/' webbrowser.open(addr) if active: try: server.serve_forever() except KeyboardInterrupt: print('Keyboard interrupt received: EXITING') finally: server.server_close() def handle_error(self, request, client_address): """Process exceptions raised by the RequestHandlerClass. Overriding this method is necessary for two different reasons: (1) SystemExit exceptions are incorrectly caught otherwise and (2) Socket errors should be silently passed in the server code""" klass, value = sys.exc_info()[:2] if klass is SystemExit: self.__exit = value self._BaseServer__serving = None elif issubclass(klass, socket.error): pass else: super().handle_error(request, client_address) def serve_forever(self, poll_interval=0.5): """Handle all incoming client requests forever. This method has been overridden so that SystemExit exceptions raised in the RequestHandlerClass can be re-raised after being caught in the handle_error method above. This allows servlet code to terminate server execution if so desired or required.""" super().serve_forever(poll_interval) if self._BaseServer__serving is None: raise self.__exit ```
2,706,129
I'm trying to speed up a python routine by writing it in C++, then using it using ctypes or cython. I'm brand new to c++. I'm using Microsoft Visual C++ Express as it's free. I plan to implement an expression tree, and a method to evaluate it in postfix order. The problem I run into right away is: ``` class Node { char *cargo; Node left; Node right; }; ``` I can't declare `left` or `right` as `Node` types.
2010/04/24
[ "https://Stackoverflow.com/questions/2706129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/169415/" ]
No, because the object would be infinitely large (because every `Node` has as members two other `Node` objects, which each have as members two other `Node` objects, which each... well, you get the point). You can, however, have a pointer to the class type as a member variable: ``` class Node { char *cargo; Node* left; // I'm not a Node; I'm just a pointer to a Node Node* right; // Same here }; ```
No, but it can have a reference or a pointer to itself: ``` class Node { Node *pnode; Node &rnode; }; ```
2,706,129
I'm trying to speed up a python routine by writing it in C++, then using it using ctypes or cython. I'm brand new to c++. I'm using Microsoft Visual C++ Express as it's free. I plan to implement an expression tree, and a method to evaluate it in postfix order. The problem I run into right away is: ``` class Node { char *cargo; Node left; Node right; }; ``` I can't declare `left` or `right` as `Node` types.
2010/04/24
[ "https://Stackoverflow.com/questions/2706129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/169415/" ]
No, because the object would be infinitely large (because every `Node` has as members two other `Node` objects, which each have as members two other `Node` objects, which each... well, you get the point). You can, however, have a pointer to the class type as a member variable: ``` class Node { char *cargo; Node* left; // I'm not a Node; I'm just a pointer to a Node Node* right; // Same here }; ```
Just for completeness, note that a class can contain a static instance of itself: ``` class A { static A a; }; ``` This is because static members are not actually stored in the class instances, so there is no recursion.
2,706,129
I'm trying to speed up a python routine by writing it in C++, then using it using ctypes or cython. I'm brand new to c++. I'm using Microsoft Visual C++ Express as it's free. I plan to implement an expression tree, and a method to evaluate it in postfix order. The problem I run into right away is: ``` class Node { char *cargo; Node left; Node right; }; ``` I can't declare `left` or `right` as `Node` types.
2010/04/24
[ "https://Stackoverflow.com/questions/2706129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/169415/" ]
No, because the object would be infinitely large (because every `Node` has as members two other `Node` objects, which each have as members two other `Node` objects, which each... well, you get the point). You can, however, have a pointer to the class type as a member variable: ``` class Node { char *cargo; Node* left; // I'm not a Node; I'm just a pointer to a Node Node* right; // Same here }; ```
Use a pointer, *& better initialized*: ``` class Node { char * cargo = nullptr; Node * left = nullptr; Node * right = nullptr; }; ``` **Modern C++** It is a better practice to use **smart-pointers** (unique\_ptr, shared\_ptr, etc.), instead of memory allocations by 'new': ``` #include <string> #include <memory> // For 'std::unique_ptr' class Node { public: std::string cargo; std::unique_ptr<Node> left; std::unique_ptr<Node> right; }; int main() { auto bt = std::make_unique<Node>(); (*bt).cargo = "Coffee"; (*bt).left = std::make_unique<Node>(); } ```
2,706,129
I'm trying to speed up a python routine by writing it in C++, then using it using ctypes or cython. I'm brand new to c++. I'm using Microsoft Visual C++ Express as it's free. I plan to implement an expression tree, and a method to evaluate it in postfix order. The problem I run into right away is: ``` class Node { char *cargo; Node left; Node right; }; ``` I can't declare `left` or `right` as `Node` types.
2010/04/24
[ "https://Stackoverflow.com/questions/2706129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/169415/" ]
Just for completeness, note that a class can contain a static instance of itself: ``` class A { static A a; }; ``` This is because static members are not actually stored in the class instances, so there is no recursion.
No, but it can have a reference or a pointer to itself: ``` class Node { Node *pnode; Node &rnode; }; ```
2,706,129
I'm trying to speed up a python routine by writing it in C++, then using it using ctypes or cython. I'm brand new to c++. I'm using Microsoft Visual C++ Express as it's free. I plan to implement an expression tree, and a method to evaluate it in postfix order. The problem I run into right away is: ``` class Node { char *cargo; Node left; Node right; }; ``` I can't declare `left` or `right` as `Node` types.
2010/04/24
[ "https://Stackoverflow.com/questions/2706129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/169415/" ]
No, but it can have a reference or a pointer to itself: ``` class Node { Node *pnode; Node &rnode; }; ```
Use a pointer, *& better initialized*: ``` class Node { char * cargo = nullptr; Node * left = nullptr; Node * right = nullptr; }; ``` **Modern C++** It is a better practice to use **smart-pointers** (unique\_ptr, shared\_ptr, etc.), instead of memory allocations by 'new': ``` #include <string> #include <memory> // For 'std::unique_ptr' class Node { public: std::string cargo; std::unique_ptr<Node> left; std::unique_ptr<Node> right; }; int main() { auto bt = std::make_unique<Node>(); (*bt).cargo = "Coffee"; (*bt).left = std::make_unique<Node>(); } ```
2,706,129
I'm trying to speed up a python routine by writing it in C++, then using it using ctypes or cython. I'm brand new to c++. I'm using Microsoft Visual C++ Express as it's free. I plan to implement an expression tree, and a method to evaluate it in postfix order. The problem I run into right away is: ``` class Node { char *cargo; Node left; Node right; }; ``` I can't declare `left` or `right` as `Node` types.
2010/04/24
[ "https://Stackoverflow.com/questions/2706129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/169415/" ]
Just for completeness, note that a class can contain a static instance of itself: ``` class A { static A a; }; ``` This is because static members are not actually stored in the class instances, so there is no recursion.
Use a pointer, *& better initialized*: ``` class Node { char * cargo = nullptr; Node * left = nullptr; Node * right = nullptr; }; ``` **Modern C++** It is a better practice to use **smart-pointers** (unique\_ptr, shared\_ptr, etc.), instead of memory allocations by 'new': ``` #include <string> #include <memory> // For 'std::unique_ptr' class Node { public: std::string cargo; std::unique_ptr<Node> left; std::unique_ptr<Node> right; }; int main() { auto bt = std::make_unique<Node>(); (*bt).cargo = "Coffee"; (*bt).left = std::make_unique<Node>(); } ```
48,490,382
Gnome desktop has 2 clipboards, the X.org (saves every selection) and the legacy one (CTRL+C). I am writing a simple python script to clear both clipboards, securely preferably, since it may be done after copy-pasting a password. The code that I have seen over here is this: ``` # empty X.org clipboard os.system("xclip -i /dev/null") # empty GNOME clipboard os.system("touch blank") os.system("xclip -selection clipboard blank") ``` Unfortunately this code creates a file named `blank` for some reason, so we have to remove it: ``` os.remove("blank") ``` However the main problem is that by calling both of these scripts, it leaves the `xclip` process open, even after I close the terminal. So we have 2 problems with this option: --------------------------------------- 1) It creates a blank file, which seems like a flawed method to me ------------------------------------------------------------------ 2) It leaves a process open, which could be a security hole. ------------------------------------------------------------ I also know about this method: ``` os.system("echo "" | xclip -selection clipboard") # empty clipboard ``` However this one leaves a `\n` newline character in the clipboard, so I would not call this method effective either. So how to do it properly then?
2018/01/28
[ "https://Stackoverflow.com/questions/48490382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9213435/" ]
I know three ways to clear the clipboard from Python. First using tkinter: ``` try: from Tkinter import Tk except ImportError: from tkinter import Tk r = Tk() r.withdraw() r.clipboard_clear() r.destroy() ``` Second with xclip, but I use xclip like this: ``` echo -n | xclip -selection clipboard ``` Does it create a new line? Finally, it's possible to user xsel: ``` xsel -bc ```
I have figured out: ``` #CLIPBOARD cleaner subprocess.run(["xsel","-bc"]) #PRIMARY cleaner subprocess.run(["xsel","-c"]) ``` This one cleans both buffers, and leaves no zombie processes at all. Thanks for everyone who suggested some of them.
48,490,382
Gnome desktop has 2 clipboards, the X.org (saves every selection) and the legacy one (CTRL+C). I am writing a simple python script to clear both clipboards, securely preferably, since it may be done after copy-pasting a password. The code that I have seen over here is this: ``` # empty X.org clipboard os.system("xclip -i /dev/null") # empty GNOME clipboard os.system("touch blank") os.system("xclip -selection clipboard blank") ``` Unfortunately this code creates a file named `blank` for some reason, so we have to remove it: ``` os.remove("blank") ``` However the main problem is that by calling both of these scripts, it leaves the `xclip` process open, even after I close the terminal. So we have 2 problems with this option: --------------------------------------- 1) It creates a blank file, which seems like a flawed method to me ------------------------------------------------------------------ 2) It leaves a process open, which could be a security hole. ------------------------------------------------------------ I also know about this method: ``` os.system("echo "" | xclip -selection clipboard") # empty clipboard ``` However this one leaves a `\n` newline character in the clipboard, so I would not call this method effective either. So how to do it properly then?
2018/01/28
[ "https://Stackoverflow.com/questions/48490382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9213435/" ]
Misconceptions ============== 1. GNOME doesn't "have clipboards"; *X11* has [selections and cut buffers](https://en.wikipedia.org/wiki/X_Window_selection). There are more than 2 of them, but mostly we worry about the selections `PRIMARY` and `CLIPBOARD`. Neither of them is "legacy". 2. You can't "securely" clear these (by writing something else into the memory they occupy), since they aren't stored in your process. Cut buffers (which *are* obsolete) are stored in the X server, and selections are stored (if anywhere) in the process providing them. (If there is a clipboard manager running, they may be stored in several places and be impossible to kill completely.) 3. `xclip` *has* to leave a background process running to serve the selection it sets to any processes requesting it. It's mostly useless when the selection is empty, but it does go away as soon as anything else is selected/copied, and it is surely not a security risk. 4. Never use `os.system` (or `system` in any language), except to run a shell command specified by the user (like `!` in `less`). It uses the shell (specifically, [`/bin/sh`](https://stackoverflow.com/questions/48122804/how-to-discard-the-output-from-a-system-command#comment83223373_48122847)), which (because it is meant for interactive use) requires various kinds of quoting to avoid misinterpretation of generated input, it [affects signal handling](https://stackoverflow.com/questions/34457955/perl-forward-sigint-to-parent-process-from-system-command), it can't set up the child's open files directly, and it makes it all too easy to ignore the exit status of the child. Tools ===== 1. There of course exist Python bindings for Xlib, including [manipulating selections](https://github.com/python-xlib/python-xlib/blob/master/examples/put_selection.py). Probably overkill if selection-clearing is your only use case. 2. Tkinter, as mentioned, probably supports this (Tk [certainly does](https://www.tcl.tk/man/tcl/TkCmd/selection.htm)), but I haven't found a reference for it. 3. `xclip` and `xsel`, as mentioned, are widely available (both are in the Ubuntu repositories, for instance). You [run external programs in Python](https://stackoverflow.com/questions/89228/calling-an-external-command-in-python) using [`subprocess`](https://docs.python.org/3/library/subprocess.html); in Python 3.5 or better it looks like one of ``` subprocess.run("xclip",stdin=subprocess.DEVNULL) subprocess.run(["xclip","-selection","clipboard"],input="") subprocess.run(["xsel","-c"]) ``` (The choice between `stdin` and `input` matters more if you don't immediately wait on the program to exit.) `xsel` has an explicit `--clear` option, which avoids the need for input and a background process. With any of these, you'll need to treat each of the two common selection types.
I have figured out: ``` #CLIPBOARD cleaner subprocess.run(["xsel","-bc"]) #PRIMARY cleaner subprocess.run(["xsel","-c"]) ``` This one cleans both buffers, and leaves no zombie processes at all. Thanks for everyone who suggested some of them.
40,942,338
I'm working on a python AWS Cognito implementation using boto3. `jwt.decode` on the IdToken yields a payload that's in the form of a dictionary, like so: ```py { "sub": "a uuid", "email_verified": True, "iss": "https://cognito-idp....", "phone_number_verified": False, "cognito:username": "19407ea0-a79d-11e6-9ce4-09487ca06884", "given_name": "Aron Filbert", "aud": "my client app", "token_use": "id", "auth_time": 1480547504, "nickname": "Aron Filbert", "phone_number": "+14025555555", "exp": 1480551104, "iat": 1480547504, "email": "my@email.com" } ``` So I designed a User class that consumes that dictionary. Works great, until I need to hit Cognito again and grab fresh user details to make sure nothing changed (say, from another device). My return payload from the `get_user()` call ends up looking like a list of dictionaries: ```py [ { "Name": "sub", "Value": "a uuid" }, { "Name": "email_verified", "Value": "true" }, { "Name": "phone_number_verified", "Value": "false" }, { "Name": "phone_number", "Value": "+114025555555" }, { "Name": "given_name", "Value": "Aron Filbert" }, { "Name": "email", "Value": "my@email.com" } ] ``` Since I might be hitting that `get_user()` Cognito endpoint a lot, I'm looking for an efficient way to grab JUST the values of each dictionary in the list and use them to form the keys:values of a new dictionary. Example: ```py { "sub": "a uuid", # From first list item "email_verified": True, # From next list item ... } ``` Being new to Python, I'm struggling with how to accomplish this elegantly and efficiently.
2016/12/02
[ "https://Stackoverflow.com/questions/40942338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/119041/" ]
As I noted in a comment, the bulk of your work can be done by a dict comprehension: ``` lst = get_user() # or something similar, lst is a list of dicts parsed_res = {k["Name"]:k["Value"] for k in lst} ``` This only differs from your expected output in that it contains `'true'` and `'false'` whereas you want bools in your final result. Well, the simplest solution is to define a function that does this conversion for you: ``` def boolify(inp): if inp=='true': return True elif inp=='false': return False else: return inp parsed_res = {k["Name"]:boolify(k["Value"]) for k in lst} ``` The same thing *could* be done in the comprehension itself, but it wouldn't be any clearer, nor efficient. This way you can do additional manipulations in your keys if you later realize that there are other stuff you want to do with your payload before storing.
A dictionary comprehension, as Andras answered above, is a simple, Pythonic one-liner for your case. Some style guidelines ([such as Google's](https://google.github.io/styleguide/pyguide.html?showone=List_Comprehensions#List_Comprehensions)), however, recommend against them if they introduce complex logic or take up more than two or three lines: > > Okay to use for simple cases. Each portion must fit on one line: > mapping expression, for clause, filter expression. Multiple for > clauses or filter expressions are not permitted. Use loops instead > when things get more complicated. > > > **Yes:** > > > > ```py > result = [] > for x in range(10): > for y in range(5): > if x * y > 10: > result.append((x, y)) > > for x in xrange(5): > for y in xrange(5): > if x != y: > for z in xrange(5): > if y != z: > yield (x, y, z) > > return ((x, complicated_transform(x)) > for x in long_generator_function(parameter) > if x is not None) > > squares = [x * x for x in range(10)] > > eat(jelly_bean for jelly_bean in jelly_beans > if jelly_bean.color == 'black') > > ``` > > **No:** > > > > ```py > result = [(x, y) for x in range(10) for y in range(5) if x * y > 10] > > return ((x, y, z) > for x in xrange(5) > for y in xrange(5) > if x != y > for z in xrange(5) > if y != z) > > ``` > > Dictionary comprehension is perfectly appropriate in your instance, but for the sake of completeness, this is a general method for performing operations with a couple of for-loops if you decide to do anything fancier: ```py for <dict> in <list>: for <key>, <value> in <dict>: # Perform any applicable operations. <new_dict>[<key>] = <value> ``` which comes out to... ```py user = get_user() user_info = {} for info in user: for name, value in info: n, v = info[name], info[value] if v.lowercase() == 'true': v = True else if v.lowercase() == 'false': v = False user_info[n] = v ```
67,448,604
I have a pandas DataFrame containing rows of nodes that I ultimately would like to *connect* and turn into a graph like object. For this, I first thought of converting this DataFrame to something that resembles an adjacency list, to later on easily create a graph from this. I have the following: A pandas Dataframe: ``` df = pd.DataFrame({"id": [0, 1, 2, 3, 4, 5, 6], "start": ["A", "B", "D", "A", "X", "F", "B"], "end": ["B", "C", "F", "G", "X", "X", "E"], "cases": [["c1", "c2", "c44"], ["c2", "c1", "c3"], ["c4"], ["c1", ], ["c1", "c7"], ["c4"], ["c44", "c7"]]}) ``` which looks like this: ``` id start end cases 0 0 A B [c1, c2, c44] 1 1 B C [c2, c1, c3] 2 2 D F [c4] 3 3 A G [c1] 4 4 X X [c1, c7] 5 5 F X [c4] 6 6 B E [c44, c7] ``` A function `directly_follows(i, j)` that returns true if the node in row `i` is followed by the node in row `j` (this wil later be a directed edge in a graph from node `i` to node `j`): ``` def directly_follows(row1, row2): return close(row1, row2) and case_overlap(row1, row2) def close(row1, row2): return row1["end"] == row2["start"] def case_overlap(row1, row2): return not set(row1["cases"]).isdisjoint(row2["cases"]) ``` Shortly, node `i` is followed by node `j` if the `end` value of node `i` is the same as the `start` value of node `j` and if their `cases` overlap Based on this `directly_follows` function, I want to create an extra column to my DataFrame `df` which acts as an adjacency list, containing for node `i` a list with the `id` values of nodes that follow `i` My desired result would thus be: ``` id start end cases adjacency_list 0 0 A B [c1, c2, c44] [1, 6] 1 1 B C [c2, c1, c3] [] 2 2 D F [c4] [5] 3 3 A G [c1] [] 4 4 X X [c1, c7] [] 5 5 F X [c4] [] 6 6 B E [c44, c7] [] ``` Basically I thought of first creating the column adjacency\_list as empty lists, and then looping through the rows of the Dataframe and if for row `i` and `j` directly\_follows(row\_i, row\_j) returns True, add the id of `j` to the adjacency list of `i`. I did it like this: ``` def connect(data): data["adjacency_list"] = np.empty((len(data), 0)).tolist() for i in range(len(data)): for j in range(len(data)): if i != j: if directly_follows(data.iloc[i], data.iloc[j]): data.iloc[i]["adjacency_list"] = data.iloc[i]["adjacency_list"].append(data.iloc[i]["id"]) ``` Now first, this returns an error ``` SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame ``` And secondly, I highly doubt this is the most pythonic and efficient way to solve this problem, since my actual DataFrame consists of about 9000 rows, which would give around 81 million comparisons. How to create the adjacency list in the least time consuming way? Is there maybe a faster or more elegant solution than mine?
2021/05/08
[ "https://Stackoverflow.com/questions/67448604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5560529/" ]
One option would be to apply the following function - it's not completely vectorised because Dataframes don't particularly like embedding mutable objects like lists, and I don't think you can apply set operations in a vectorised way. It does cut down the number of comparisons needed though. ``` def f(x): check = df[(x["end"] == df["start"])] return [ row["id"] for i, row in check.iterrows() if not set(row["cases"]).isdisjoint(x["cases"]) ] df["adjacency_list"] = df.apply(f, axis=1) ``` Or, as a big lambda function: ``` df["adjacency_list"] = df.apply( lambda x: [ row["id"] for i, row in df[(x["end"] == df["start"])].iterrows() if not set(row["cases"]).isdisjoint(x["cases"]) ], axis=1, ) ``` Output ------ ``` id start end cases adjacency_list 0 0 A B [c1, c2, c44] [1, 6] 1 1 B C [c2, c1, c3] [] 2 2 D F [c4] [5] 3 3 A G [c1] [] 4 4 X X [c1, c7] [4] 5 5 F X [c4] [] 6 6 B E [c44, c7] [] ```
TRY: ``` k=0 def test(x): global k k+=1 test_df = df[k:] return list(test_df[test_df['start'] == x].index) df['adjancy_matrix'] = df.end.apply(test,1) ``` **OUTPUT:** ``` id start end cases adjancy_matrix 0 0 A B [c1,c2,c44] [1, 6] 1 1 B C [c2,c1,c3] [] 2 2 D F [c4] [5] 3 3 A G [c1] [] 4 4 X X [c1,c7] [] 5 5 F X [c4] [] 6 6 B E [c44,c7] [] ```
67,448,604
I have a pandas DataFrame containing rows of nodes that I ultimately would like to *connect* and turn into a graph like object. For this, I first thought of converting this DataFrame to something that resembles an adjacency list, to later on easily create a graph from this. I have the following: A pandas Dataframe: ``` df = pd.DataFrame({"id": [0, 1, 2, 3, 4, 5, 6], "start": ["A", "B", "D", "A", "X", "F", "B"], "end": ["B", "C", "F", "G", "X", "X", "E"], "cases": [["c1", "c2", "c44"], ["c2", "c1", "c3"], ["c4"], ["c1", ], ["c1", "c7"], ["c4"], ["c44", "c7"]]}) ``` which looks like this: ``` id start end cases 0 0 A B [c1, c2, c44] 1 1 B C [c2, c1, c3] 2 2 D F [c4] 3 3 A G [c1] 4 4 X X [c1, c7] 5 5 F X [c4] 6 6 B E [c44, c7] ``` A function `directly_follows(i, j)` that returns true if the node in row `i` is followed by the node in row `j` (this wil later be a directed edge in a graph from node `i` to node `j`): ``` def directly_follows(row1, row2): return close(row1, row2) and case_overlap(row1, row2) def close(row1, row2): return row1["end"] == row2["start"] def case_overlap(row1, row2): return not set(row1["cases"]).isdisjoint(row2["cases"]) ``` Shortly, node `i` is followed by node `j` if the `end` value of node `i` is the same as the `start` value of node `j` and if their `cases` overlap Based on this `directly_follows` function, I want to create an extra column to my DataFrame `df` which acts as an adjacency list, containing for node `i` a list with the `id` values of nodes that follow `i` My desired result would thus be: ``` id start end cases adjacency_list 0 0 A B [c1, c2, c44] [1, 6] 1 1 B C [c2, c1, c3] [] 2 2 D F [c4] [5] 3 3 A G [c1] [] 4 4 X X [c1, c7] [] 5 5 F X [c4] [] 6 6 B E [c44, c7] [] ``` Basically I thought of first creating the column adjacency\_list as empty lists, and then looping through the rows of the Dataframe and if for row `i` and `j` directly\_follows(row\_i, row\_j) returns True, add the id of `j` to the adjacency list of `i`. I did it like this: ``` def connect(data): data["adjacency_list"] = np.empty((len(data), 0)).tolist() for i in range(len(data)): for j in range(len(data)): if i != j: if directly_follows(data.iloc[i], data.iloc[j]): data.iloc[i]["adjacency_list"] = data.iloc[i]["adjacency_list"].append(data.iloc[i]["id"]) ``` Now first, this returns an error ``` SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame ``` And secondly, I highly doubt this is the most pythonic and efficient way to solve this problem, since my actual DataFrame consists of about 9000 rows, which would give around 81 million comparisons. How to create the adjacency list in the least time consuming way? Is there maybe a faster or more elegant solution than mine?
2021/05/08
[ "https://Stackoverflow.com/questions/67448604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5560529/" ]
A self-join option: ```py df['adjacency_list'] = df.apply(lambda s: df[(df['start'] == s.end) & (df['id'] != s.id)].index.tolist(), axis=1) print(df) ``` Output: ``` id start end cases adjacency_list 0 0 A B [c1, c2, c44] [1, 6] 1 1 B C [c2, c1, c3] [] 2 2 D F [c4] [5] 3 3 A G [c1] [] 4 4 X X [c1, c7] [] 5 5 F X [c4] [4] 6 6 B E [c44, c7] [] ```
TRY: ``` k=0 def test(x): global k k+=1 test_df = df[k:] return list(test_df[test_df['start'] == x].index) df['adjancy_matrix'] = df.end.apply(test,1) ``` **OUTPUT:** ``` id start end cases adjancy_matrix 0 0 A B [c1,c2,c44] [1, 6] 1 1 B C [c2,c1,c3] [] 2 2 D F [c4] [5] 3 3 A G [c1] [] 4 4 X X [c1,c7] [] 5 5 F X [c4] [] 6 6 B E [c44,c7] [] ```
40,041,463
I installed OpenCV 3.1.0 and CUDA 8.0 in Ubuntu 16.04. When I check "nvcc --version" to check the CUDA version, it is 8.0. But when I try to compile a C++ OpenCV program I get the following error: ``` Could NOT find CUDA: Found unsuitable version "7.5", but required is exact version "8.0" (found /usr/local/cuda) ``` So OpenCV tells it founds version 7.5 when the only installed one is 8.0. Both CUDA and OpenCV work well toguether in python with no error. Any idea about what is happening?
2016/10/14
[ "https://Stackoverflow.com/questions/40041463", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4136920/" ]
I had a similar issue after upgrading from CUDA 8.0 to 9.1. When I compiled my code and got error "found unsuitable version (CUDA 8.0)". In my case, it's the problem of previous cmake files. Just deleted previous files generated by cmake and then it worked fine.
Environment Variables As part of the CUDA environment, you should add the following in the .bashrc file of your home folder. ``` export CUDA_HOME=/usr/local/cuda-7.5 export LD_LIBRARY_PATH=${CUDA_HOME}/lib64 PATH=${CUDA_HOME}/bin:${PATH} export PATH ```
40,041,463
I installed OpenCV 3.1.0 and CUDA 8.0 in Ubuntu 16.04. When I check "nvcc --version" to check the CUDA version, it is 8.0. But when I try to compile a C++ OpenCV program I get the following error: ``` Could NOT find CUDA: Found unsuitable version "7.5", but required is exact version "8.0" (found /usr/local/cuda) ``` So OpenCV tells it founds version 7.5 when the only installed one is 8.0. Both CUDA and OpenCV work well toguether in python with no error. Any idea about what is happening?
2016/10/14
[ "https://Stackoverflow.com/questions/40041463", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4136920/" ]
I had a similar issue after upgrading from CUDA 8.0 to 9.1. When I compiled my code and got error "found unsuitable version (CUDA 8.0)". In my case, it's the problem of previous cmake files. Just deleted previous files generated by cmake and then it worked fine.
try this: ``` cd /usr/local ls -l | grep cuda ``` if you see something like: ``` lrwxrwxrwx 1 root root 9 9 4 10:08 cuda -> cuda-7.5/ drwxr-xr-x 13 root root 4096 1 5 2017 cuda-7.5 drwxr-xr-x 14 root root 4096 7 27 17:24 cuda-8.0 ``` then: ``` sudo rm -rf cuda ln -s cuda-8.0 cuda ```
39,656,433
I need to download incoming attachment without past attachment from mail using Python Script. For example:If anyone send mail at this time(now) then just download that attachment only into local drive not past attachments. Please anyone help me to download attachment using python script or java.
2016/09/23
[ "https://Stackoverflow.com/questions/39656433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5693776/" ]
``` import email import imaplib import os class FetchEmail(): connection = None error = None mail_server="host_name" username="outlook_username" password="password" self.save_attachment(self,msg,download_folder) def __init__(self, mail_server, username, password): self.connection = imaplib.IMAP4_SSL(mail_server) self.connection.login(username, password) self.connection.select(readonly=False) # so we can mark mails as read def close_connection(self): """ Close the connection to the IMAP server """ self.connection.close() def save_attachment(self, msg, download_folder="/tmp"): """ Given a message, save its attachments to the specified download folder (default is /tmp) return: file path to attachment """ att_path = "No attachment found." for part in msg.walk(): if part.get_content_maintype() == 'multipart': continue if part.get('Content-Disposition') is None: continue filename = part.get_filename() att_path = os.path.join(download_folder, filename) if not os.path.isfile(att_path): fp = open(att_path, 'wb') fp.write(part.get_payload(decode=True)) fp.close() return att_path def fetch_unread_messages(self): """ Retrieve unread messages """ emails = [] (result, messages) = self.connection.search(None, 'UnSeen') if result == "OK": for message in messages[0].split(' '): try: ret, data = self.connection.fetch(message,'(RFC822)') except: print "No new emails to read." self.close_connection() exit() msg = email.message_from_string(data[0][1]) if isinstance(msg, str) == False: emails.append(msg) response, data = self.connection.store(message, '+FLAGS','\\Seen') return emails self.error = "Failed to retrieve emails." return emails ``` Above code works for me to download attachment. Hope this really helpful for any one.
``` import win32com.client #pip install pypiwin32 to work with windows operating sysytm import datetime import os # To get today's date in 'day-month-year' format(01-12-2017). dateToday=datetime.datetime.today() FormatedDate=('{:02d}'.format(dateToday.day)+'-'+'{:02d}'.format(dateToday.month)+'-'+'{:04d}'.format(dateToday.year)) # Creating an object for the outlook application. outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") # Creating an object to access Inbox of the outlook. inbox=outlook.GetDefaultFolder(6) # Creating an object to access items inside the inbox of outlook. messages=inbox.Items def save_attachments(subject,which_item,file_name): # To iterate through inbox emails using inbox.Items object. for message in messages: if (message.Subject == subject): body_content = message.body # Creating an object for the message.Attachments. attachment = message.Attachments # To check which item is selected among the attacments. print (message.Attachments.Item(which_item)) # To iterate through email items using message.Attachments object. for attachment in message.Attachments: # To save the perticular attachment at the desired location in your hard disk. attachment.SaveAsFile(os.path.join("D:\Script\Monitoring",file_name)) break ```
39,656,433
I need to download incoming attachment without past attachment from mail using Python Script. For example:If anyone send mail at this time(now) then just download that attachment only into local drive not past attachments. Please anyone help me to download attachment using python script or java.
2016/09/23
[ "https://Stackoverflow.com/questions/39656433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5693776/" ]
``` import email import imaplib import os class FetchEmail(): connection = None error = None mail_server="host_name" username="outlook_username" password="password" self.save_attachment(self,msg,download_folder) def __init__(self, mail_server, username, password): self.connection = imaplib.IMAP4_SSL(mail_server) self.connection.login(username, password) self.connection.select(readonly=False) # so we can mark mails as read def close_connection(self): """ Close the connection to the IMAP server """ self.connection.close() def save_attachment(self, msg, download_folder="/tmp"): """ Given a message, save its attachments to the specified download folder (default is /tmp) return: file path to attachment """ att_path = "No attachment found." for part in msg.walk(): if part.get_content_maintype() == 'multipart': continue if part.get('Content-Disposition') is None: continue filename = part.get_filename() att_path = os.path.join(download_folder, filename) if not os.path.isfile(att_path): fp = open(att_path, 'wb') fp.write(part.get_payload(decode=True)) fp.close() return att_path def fetch_unread_messages(self): """ Retrieve unread messages """ emails = [] (result, messages) = self.connection.search(None, 'UnSeen') if result == "OK": for message in messages[0].split(' '): try: ret, data = self.connection.fetch(message,'(RFC822)') except: print "No new emails to read." self.close_connection() exit() msg = email.message_from_string(data[0][1]) if isinstance(msg, str) == False: emails.append(msg) response, data = self.connection.store(message, '+FLAGS','\\Seen') return emails self.error = "Failed to retrieve emails." return emails ``` Above code works for me to download attachment. Hope this really helpful for any one.
If you want to download the attachment from the outlook application from a particular sender and with a specific subject. The below code may be helpful. ``` import win32com.client import os from datetime import datetime, timedelta outlook = win32com.client.Dispatch('outlook.application') mapi = outlook.GetNamespace("MAPI") for account in mapi.Accounts: print(account.DeliveryStore.DisplayName) #outlook account inbox = mapi.GetDefaultFolder(6) #Inbox folder inbox = inbox.Folders["your folder"] #Folder inside Inbox Folder messages = inbox.Items received_dt = datetime.now() - timedelta(days=1) received_dt = received_dt.strftime('%m/%d/%Y %H:%M %p') email_sender = 'sender@outlook.com' email_subject = 'Subject of mail' messages = messages.Restrict("[ReceivedTime] >= '"+received_dt+"'") #save to current directory outputDir = os.getcwd() try: for message in list(messages): if email_subject == message.subject and message.SenderEmailAddress == email_sender and message.ReceivedTime.strftime('%Y-%m-%d') == _date: try: s = message.sender for attachment in message.Attachments: attachment.SaveASFile(os.path.join(outputDir, attachment.FileName)) print(f"attachment {attachment.FileName} from {s} saved") except Exception as e: print("Error when saving the attachment:" + str(e)) except Exception as e: print("Error when processing emails messages:" + str(e)) ```
39,656,433
I need to download incoming attachment without past attachment from mail using Python Script. For example:If anyone send mail at this time(now) then just download that attachment only into local drive not past attachments. Please anyone help me to download attachment using python script or java.
2016/09/23
[ "https://Stackoverflow.com/questions/39656433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5693776/" ]
The below code helps by downloading the attachments from outlook emails that are * '*Unread*' (and changes the mail to Read.) or from '*Today's*' date. * without altering the file name. Just pass the '*Subject*' argument. ``` import datetime import os import win32com.client path = os.path.expanduser("~/Desktop/Attachments") today = datetime.date.today() outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") inbox = outlook.GetDefaultFolder(6) messages = inbox.Items def saveattachemnts(subject): for message in messages: if message.Subject == subject and message.Unread or message.Senton.date() == today: # body_content = message.body attachments = message.Attachments attachment = attachments.Item(1) for attachment in message.Attachments: attachment.SaveAsFile(os.path.join(path, str(attachment))) if message.Subject == subject and message.Unread: message.Unread = False break ```
``` import win32com.client #pip install pypiwin32 to work with windows operating sysytm import datetime import os # To get today's date in 'day-month-year' format(01-12-2017). dateToday=datetime.datetime.today() FormatedDate=('{:02d}'.format(dateToday.day)+'-'+'{:02d}'.format(dateToday.month)+'-'+'{:04d}'.format(dateToday.year)) # Creating an object for the outlook application. outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") # Creating an object to access Inbox of the outlook. inbox=outlook.GetDefaultFolder(6) # Creating an object to access items inside the inbox of outlook. messages=inbox.Items def save_attachments(subject,which_item,file_name): # To iterate through inbox emails using inbox.Items object. for message in messages: if (message.Subject == subject): body_content = message.body # Creating an object for the message.Attachments. attachment = message.Attachments # To check which item is selected among the attacments. print (message.Attachments.Item(which_item)) # To iterate through email items using message.Attachments object. for attachment in message.Attachments: # To save the perticular attachment at the desired location in your hard disk. attachment.SaveAsFile(os.path.join("D:\Script\Monitoring",file_name)) break ```
39,656,433
I need to download incoming attachment without past attachment from mail using Python Script. For example:If anyone send mail at this time(now) then just download that attachment only into local drive not past attachments. Please anyone help me to download attachment using python script or java.
2016/09/23
[ "https://Stackoverflow.com/questions/39656433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5693776/" ]
``` import win32com.client #pip install pypiwin32 to work with windows operating sysytm import datetime import os # To get today's date in 'day-month-year' format(01-12-2017). dateToday=datetime.datetime.today() FormatedDate=('{:02d}'.format(dateToday.day)+'-'+'{:02d}'.format(dateToday.month)+'-'+'{:04d}'.format(dateToday.year)) # Creating an object for the outlook application. outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") # Creating an object to access Inbox of the outlook. inbox=outlook.GetDefaultFolder(6) # Creating an object to access items inside the inbox of outlook. messages=inbox.Items def save_attachments(subject,which_item,file_name): # To iterate through inbox emails using inbox.Items object. for message in messages: if (message.Subject == subject): body_content = message.body # Creating an object for the message.Attachments. attachment = message.Attachments # To check which item is selected among the attacments. print (message.Attachments.Item(which_item)) # To iterate through email items using message.Attachments object. for attachment in message.Attachments: # To save the perticular attachment at the desired location in your hard disk. attachment.SaveAsFile(os.path.join("D:\Script\Monitoring",file_name)) break ```
If you want to download the attachment from the outlook application from a particular sender and with a specific subject. The below code may be helpful. ``` import win32com.client import os from datetime import datetime, timedelta outlook = win32com.client.Dispatch('outlook.application') mapi = outlook.GetNamespace("MAPI") for account in mapi.Accounts: print(account.DeliveryStore.DisplayName) #outlook account inbox = mapi.GetDefaultFolder(6) #Inbox folder inbox = inbox.Folders["your folder"] #Folder inside Inbox Folder messages = inbox.Items received_dt = datetime.now() - timedelta(days=1) received_dt = received_dt.strftime('%m/%d/%Y %H:%M %p') email_sender = 'sender@outlook.com' email_subject = 'Subject of mail' messages = messages.Restrict("[ReceivedTime] >= '"+received_dt+"'") #save to current directory outputDir = os.getcwd() try: for message in list(messages): if email_subject == message.subject and message.SenderEmailAddress == email_sender and message.ReceivedTime.strftime('%Y-%m-%d') == _date: try: s = message.sender for attachment in message.Attachments: attachment.SaveASFile(os.path.join(outputDir, attachment.FileName)) print(f"attachment {attachment.FileName} from {s} saved") except Exception as e: print("Error when saving the attachment:" + str(e)) except Exception as e: print("Error when processing emails messages:" + str(e)) ```
39,656,433
I need to download incoming attachment without past attachment from mail using Python Script. For example:If anyone send mail at this time(now) then just download that attachment only into local drive not past attachments. Please anyone help me to download attachment using python script or java.
2016/09/23
[ "https://Stackoverflow.com/questions/39656433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5693776/" ]
The below code helps by downloading the attachments from outlook emails that are * '*Unread*' (and changes the mail to Read.) or from '*Today's*' date. * without altering the file name. Just pass the '*Subject*' argument. ``` import datetime import os import win32com.client path = os.path.expanduser("~/Desktop/Attachments") today = datetime.date.today() outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") inbox = outlook.GetDefaultFolder(6) messages = inbox.Items def saveattachemnts(subject): for message in messages: if message.Subject == subject and message.Unread or message.Senton.date() == today: # body_content = message.body attachments = message.Attachments attachment = attachments.Item(1) for attachment in message.Attachments: attachment.SaveAsFile(os.path.join(path, str(attachment))) if message.Subject == subject and message.Unread: message.Unread = False break ```
If you want to download the attachment from the outlook application from a particular sender and with a specific subject. The below code may be helpful. ``` import win32com.client import os from datetime import datetime, timedelta outlook = win32com.client.Dispatch('outlook.application') mapi = outlook.GetNamespace("MAPI") for account in mapi.Accounts: print(account.DeliveryStore.DisplayName) #outlook account inbox = mapi.GetDefaultFolder(6) #Inbox folder inbox = inbox.Folders["your folder"] #Folder inside Inbox Folder messages = inbox.Items received_dt = datetime.now() - timedelta(days=1) received_dt = received_dt.strftime('%m/%d/%Y %H:%M %p') email_sender = 'sender@outlook.com' email_subject = 'Subject of mail' messages = messages.Restrict("[ReceivedTime] >= '"+received_dt+"'") #save to current directory outputDir = os.getcwd() try: for message in list(messages): if email_subject == message.subject and message.SenderEmailAddress == email_sender and message.ReceivedTime.strftime('%Y-%m-%d') == _date: try: s = message.sender for attachment in message.Attachments: attachment.SaveASFile(os.path.join(outputDir, attachment.FileName)) print(f"attachment {attachment.FileName} from {s} saved") except Exception as e: print("Error when saving the attachment:" + str(e)) except Exception as e: print("Error when processing emails messages:" + str(e)) ```
70,580,711
How can I change my slurm script below so that each python job gets a unique GPU? The node had 4 GPUs, I would like to run 1 python job per each GPU. The problem is that all jobs use the first GPU and other GPUs are idle. ``` #!/bin/bash #SBATCH --qos=maxjobs #SBATCH -N 1 #SBATCH --exclusive for i in `seq 0 3`; do cd ${i} srun python gpu_code.py & cd .. done wait ```
2022/01/04
[ "https://Stackoverflow.com/questions/70580711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7242276/" ]
If the solution proposed by @Iagows doesn't work for you, have a look at this: [flutter\_launcher\_icons-issues](https://github.com/fluttercommunity/flutter_launcher_icons/issues/324#issuecomment-1005736502)
The issue is explained in the readme of the plugin, section "Dependency incompatible". It says ``` Because flutter_launcher_icons >=0.9.0 depends on args 2.0.0 and flutter_native_splash 1.2.0 depends on args ^2.1.1, flutter_launcher_icons >=0.9.0 is incompatible with flutter_native_splash 1.2.0. And because no versions of flutter_native_splash match >1.2.0 <2.0.0, flutter_launcher_icons >=0.9.0 is incompatible with flutter_native_splash ^1.2.0. So, because enstack depends on both flutter_native_splash ^1.2.0 and flutter_launcher_icons ^0.9.0, version solving failed. pub get failed ``` The solution is given in as cryptic a manner as the description above, but the simple hack given by @deffo worked for me. <https://github.com/fluttercommunity/flutter_launcher_icons/issues/324#issuecomment-1013611137> What you do is that you skip the version solving done when the plugin reads `build.gradle` and you force `minSdkVersion` to be whatever version you prefer. It's a hack but since you generate automatically the app icons only once and for all, who cares? :-) BTW, the following solution seems cleaner but I didn't test it: <https://github.com/fluttercommunity/flutter_launcher_icons/issues/262#issuecomment-877653847>
70,580,711
How can I change my slurm script below so that each python job gets a unique GPU? The node had 4 GPUs, I would like to run 1 python job per each GPU. The problem is that all jobs use the first GPU and other GPUs are idle. ``` #!/bin/bash #SBATCH --qos=maxjobs #SBATCH -N 1 #SBATCH --exclusive for i in `seq 0 3`; do cd ${i} srun python gpu_code.py & cd .. done wait ```
2022/01/04
[ "https://Stackoverflow.com/questions/70580711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7242276/" ]
Inside file: ~/flutter/.pub-cache/hosted/pub.dartlang.org/flutter\_launcher\_icons-0.9.2/lib/android.dart Replace Line: ``` final String minSdk = line.replaceAll(RegExp(r'[^\d]'), ''); To this: final String minSdk = "21"; // line.replaceAll(RegExp(r'[^\d]'), ''); ``` Save the file and then run: ``` flutter pub get flutter pub run flutter_launcher_icons:main ``` Source : <https://github.com/fluttercommunity/flutter_launcher_icons/issues/324>
The issue is explained in the readme of the plugin, section "Dependency incompatible". It says ``` Because flutter_launcher_icons >=0.9.0 depends on args 2.0.0 and flutter_native_splash 1.2.0 depends on args ^2.1.1, flutter_launcher_icons >=0.9.0 is incompatible with flutter_native_splash 1.2.0. And because no versions of flutter_native_splash match >1.2.0 <2.0.0, flutter_launcher_icons >=0.9.0 is incompatible with flutter_native_splash ^1.2.0. So, because enstack depends on both flutter_native_splash ^1.2.0 and flutter_launcher_icons ^0.9.0, version solving failed. pub get failed ``` The solution is given in as cryptic a manner as the description above, but the simple hack given by @deffo worked for me. <https://github.com/fluttercommunity/flutter_launcher_icons/issues/324#issuecomment-1013611137> What you do is that you skip the version solving done when the plugin reads `build.gradle` and you force `minSdkVersion` to be whatever version you prefer. It's a hack but since you generate automatically the app icons only once and for all, who cares? :-) BTW, the following solution seems cleaner but I didn't test it: <https://github.com/fluttercommunity/flutter_launcher_icons/issues/262#issuecomment-877653847>
70,580,711
How can I change my slurm script below so that each python job gets a unique GPU? The node had 4 GPUs, I would like to run 1 python job per each GPU. The problem is that all jobs use the first GPU and other GPUs are idle. ``` #!/bin/bash #SBATCH --qos=maxjobs #SBATCH -N 1 #SBATCH --exclusive for i in `seq 0 3`; do cd ${i} srun python gpu_code.py & cd .. done wait ```
2022/01/04
[ "https://Stackoverflow.com/questions/70580711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7242276/" ]
Thanks to this [answer](https://github.com/fluttercommunity/flutter_launcher_icons/issues/324#issuecomment-1057617130), I was able to fix the issue!
The issue is explained in the readme of the plugin, section "Dependency incompatible". It says ``` Because flutter_launcher_icons >=0.9.0 depends on args 2.0.0 and flutter_native_splash 1.2.0 depends on args ^2.1.1, flutter_launcher_icons >=0.9.0 is incompatible with flutter_native_splash 1.2.0. And because no versions of flutter_native_splash match >1.2.0 <2.0.0, flutter_launcher_icons >=0.9.0 is incompatible with flutter_native_splash ^1.2.0. So, because enstack depends on both flutter_native_splash ^1.2.0 and flutter_launcher_icons ^0.9.0, version solving failed. pub get failed ``` The solution is given in as cryptic a manner as the description above, but the simple hack given by @deffo worked for me. <https://github.com/fluttercommunity/flutter_launcher_icons/issues/324#issuecomment-1013611137> What you do is that you skip the version solving done when the plugin reads `build.gradle` and you force `minSdkVersion` to be whatever version you prefer. It's a hack but since you generate automatically the app icons only once and for all, who cares? :-) BTW, the following solution seems cleaner but I didn't test it: <https://github.com/fluttercommunity/flutter_launcher_icons/issues/262#issuecomment-877653847>
70,580,711
How can I change my slurm script below so that each python job gets a unique GPU? The node had 4 GPUs, I would like to run 1 python job per each GPU. The problem is that all jobs use the first GPU and other GPUs are idle. ``` #!/bin/bash #SBATCH --qos=maxjobs #SBATCH -N 1 #SBATCH --exclusive for i in `seq 0 3`; do cd ${i} srun python gpu_code.py & cd .. done wait ```
2022/01/04
[ "https://Stackoverflow.com/questions/70580711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7242276/" ]
Thanks to this [answer](https://github.com/fluttercommunity/flutter_launcher_icons/issues/324#issuecomment-1057617130), I was able to fix the issue!
Inside file: ~/flutter/.pub-cache/hosted/pub.dartlang.org/flutter\_launcher\_icons-0.9.2/lib/android.dart Replace Line: ``` final String minSdk = line.replaceAll(RegExp(r'[^\d]'), ''); To this: final String minSdk = "21"; // line.replaceAll(RegExp(r'[^\d]'), ''); ``` Save the file and then run: ``` flutter pub get flutter pub run flutter_launcher_icons:main ``` Source : <https://github.com/fluttercommunity/flutter_launcher_icons/issues/324>
70,580,711
How can I change my slurm script below so that each python job gets a unique GPU? The node had 4 GPUs, I would like to run 1 python job per each GPU. The problem is that all jobs use the first GPU and other GPUs are idle. ``` #!/bin/bash #SBATCH --qos=maxjobs #SBATCH -N 1 #SBATCH --exclusive for i in `seq 0 3`; do cd ${i} srun python gpu_code.py & cd .. done wait ```
2022/01/04
[ "https://Stackoverflow.com/questions/70580711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7242276/" ]
I just had the same problem and solved doing this in `android/app/build.gradle`. Changed: ``` minSdkVersion flutter.minSdkVersion targetSdkVersion flutter.targetSdkVersion ``` To: ``` minSdkVersion 26 targetSdkVersion 30 ``` [Source](https://github.com/fluttercommunity/flutter_launcher_icons/issues/88) [Edit] After that, I could not run on emulator, so I changed back the gradle file (without running flutter\_launcher\_icon again). Now I have the app running and the icons are right.
Thanks to this [answer](https://github.com/fluttercommunity/flutter_launcher_icons/issues/324#issuecomment-1057617130), I was able to fix the issue!
70,580,711
How can I change my slurm script below so that each python job gets a unique GPU? The node had 4 GPUs, I would like to run 1 python job per each GPU. The problem is that all jobs use the first GPU and other GPUs are idle. ``` #!/bin/bash #SBATCH --qos=maxjobs #SBATCH -N 1 #SBATCH --exclusive for i in `seq 0 3`; do cd ${i} srun python gpu_code.py & cd .. done wait ```
2022/01/04
[ "https://Stackoverflow.com/questions/70580711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7242276/" ]
I just had the same problem and solved doing this in `android/app/build.gradle`. Changed: ``` minSdkVersion flutter.minSdkVersion targetSdkVersion flutter.targetSdkVersion ``` To: ``` minSdkVersion 26 targetSdkVersion 30 ``` [Source](https://github.com/fluttercommunity/flutter_launcher_icons/issues/88) [Edit] After that, I could not run on emulator, so I changed back the gradle file (without running flutter\_launcher\_icon again). Now I have the app running and the icons are right.
The issue is explained in the readme of the plugin, section "Dependency incompatible". It says ``` Because flutter_launcher_icons >=0.9.0 depends on args 2.0.0 and flutter_native_splash 1.2.0 depends on args ^2.1.1, flutter_launcher_icons >=0.9.0 is incompatible with flutter_native_splash 1.2.0. And because no versions of flutter_native_splash match >1.2.0 <2.0.0, flutter_launcher_icons >=0.9.0 is incompatible with flutter_native_splash ^1.2.0. So, because enstack depends on both flutter_native_splash ^1.2.0 and flutter_launcher_icons ^0.9.0, version solving failed. pub get failed ``` The solution is given in as cryptic a manner as the description above, but the simple hack given by @deffo worked for me. <https://github.com/fluttercommunity/flutter_launcher_icons/issues/324#issuecomment-1013611137> What you do is that you skip the version solving done when the plugin reads `build.gradle` and you force `minSdkVersion` to be whatever version you prefer. It's a hack but since you generate automatically the app icons only once and for all, who cares? :-) BTW, the following solution seems cleaner but I didn't test it: <https://github.com/fluttercommunity/flutter_launcher_icons/issues/262#issuecomment-877653847>
70,580,711
How can I change my slurm script below so that each python job gets a unique GPU? The node had 4 GPUs, I would like to run 1 python job per each GPU. The problem is that all jobs use the first GPU and other GPUs are idle. ``` #!/bin/bash #SBATCH --qos=maxjobs #SBATCH -N 1 #SBATCH --exclusive for i in `seq 0 3`; do cd ${i} srun python gpu_code.py & cd .. done wait ```
2022/01/04
[ "https://Stackoverflow.com/questions/70580711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7242276/" ]
Thanks to this [answer](https://github.com/fluttercommunity/flutter_launcher_icons/issues/324#issuecomment-1057617130), I was able to fix the issue!
I just changed the package version in `pubspec.yaml` and that solved the problem for me. ```yaml dependencies: flutter_launcher_icons: ^0.10.0 ```
70,580,711
How can I change my slurm script below so that each python job gets a unique GPU? The node had 4 GPUs, I would like to run 1 python job per each GPU. The problem is that all jobs use the first GPU and other GPUs are idle. ``` #!/bin/bash #SBATCH --qos=maxjobs #SBATCH -N 1 #SBATCH --exclusive for i in `seq 0 3`; do cd ${i} srun python gpu_code.py & cd .. done wait ```
2022/01/04
[ "https://Stackoverflow.com/questions/70580711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7242276/" ]
Thanks to this [answer](https://github.com/fluttercommunity/flutter_launcher_icons/issues/324#issuecomment-1057617130), I was able to fix the issue!
If the solution proposed by @Iagows doesn't work for you, have a look at this: [flutter\_launcher\_icons-issues](https://github.com/fluttercommunity/flutter_launcher_icons/issues/324#issuecomment-1005736502)
70,580,711
How can I change my slurm script below so that each python job gets a unique GPU? The node had 4 GPUs, I would like to run 1 python job per each GPU. The problem is that all jobs use the first GPU and other GPUs are idle. ``` #!/bin/bash #SBATCH --qos=maxjobs #SBATCH -N 1 #SBATCH --exclusive for i in `seq 0 3`; do cd ${i} srun python gpu_code.py & cd .. done wait ```
2022/01/04
[ "https://Stackoverflow.com/questions/70580711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7242276/" ]
I just had the same problem and solved doing this in `android/app/build.gradle`. Changed: ``` minSdkVersion flutter.minSdkVersion targetSdkVersion flutter.targetSdkVersion ``` To: ``` minSdkVersion 26 targetSdkVersion 30 ``` [Source](https://github.com/fluttercommunity/flutter_launcher_icons/issues/88) [Edit] After that, I could not run on emulator, so I changed back the gradle file (without running flutter\_launcher\_icon again). Now I have the app running and the icons are right.
I just changed the package version in `pubspec.yaml` and that solved the problem for me. ```yaml dependencies: flutter_launcher_icons: ^0.10.0 ```
70,580,711
How can I change my slurm script below so that each python job gets a unique GPU? The node had 4 GPUs, I would like to run 1 python job per each GPU. The problem is that all jobs use the first GPU and other GPUs are idle. ``` #!/bin/bash #SBATCH --qos=maxjobs #SBATCH -N 1 #SBATCH --exclusive for i in `seq 0 3`; do cd ${i} srun python gpu_code.py & cd .. done wait ```
2022/01/04
[ "https://Stackoverflow.com/questions/70580711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7242276/" ]
I just changed the package version in `pubspec.yaml` and that solved the problem for me. ```yaml dependencies: flutter_launcher_icons: ^0.10.0 ```
The issue is explained in the readme of the plugin, section "Dependency incompatible". It says ``` Because flutter_launcher_icons >=0.9.0 depends on args 2.0.0 and flutter_native_splash 1.2.0 depends on args ^2.1.1, flutter_launcher_icons >=0.9.0 is incompatible with flutter_native_splash 1.2.0. And because no versions of flutter_native_splash match >1.2.0 <2.0.0, flutter_launcher_icons >=0.9.0 is incompatible with flutter_native_splash ^1.2.0. So, because enstack depends on both flutter_native_splash ^1.2.0 and flutter_launcher_icons ^0.9.0, version solving failed. pub get failed ``` The solution is given in as cryptic a manner as the description above, but the simple hack given by @deffo worked for me. <https://github.com/fluttercommunity/flutter_launcher_icons/issues/324#issuecomment-1013611137> What you do is that you skip the version solving done when the plugin reads `build.gradle` and you force `minSdkVersion` to be whatever version you prefer. It's a hack but since you generate automatically the app icons only once and for all, who cares? :-) BTW, the following solution seems cleaner but I didn't test it: <https://github.com/fluttercommunity/flutter_launcher_icons/issues/262#issuecomment-877653847>
60,548,289
I don't know why I am getting this error. Below is the code I am using. **settings.py** ``` TEMPLATE_DIRS = (os.path.join(os.path.dirname(BASE_DIR), "mysite", "static", "templates"),) ``` **urls.py** ``` from django.urls import path from django.conf.urls import include, url from django.contrib.auth import views as auth_views from notes import views as notes_views urlpatterns = [ url(r'^$', notes_views.home, name='home'), url(r'^admin/', admin.site.urls), ]``` **views.py** `def home(request): notes = Note.objects template = loader.get_template('note.html') context = {'notes': notes} return render(request, 'templates/note.html', context)` NOTE : I am following this tutorial - https://pythonspot.com/django-tutorial-building-a-note-taking-app/ ```
2020/03/05
[ "https://Stackoverflow.com/questions/60548289", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5227269/" ]
The problem comes from the "this" scope. Either you have to bind the function you're using in the class. ``` constructor( props ){ super( props ); this.resetTimer = this.resetTimer.bind(this); } ``` A second option is to use arrow functions when you declare your functions in order to maintain the scope of "this" on the class. ``` resetTimer = () => { this.setState(initialState); } ```
instead of writing ``` `resetTimer() { this.setState(initialState); }` ``` use arrow function `const resetTimer=()=> { this.setState(initialState); }` this will work
60,548,289
I don't know why I am getting this error. Below is the code I am using. **settings.py** ``` TEMPLATE_DIRS = (os.path.join(os.path.dirname(BASE_DIR), "mysite", "static", "templates"),) ``` **urls.py** ``` from django.urls import path from django.conf.urls import include, url from django.contrib.auth import views as auth_views from notes import views as notes_views urlpatterns = [ url(r'^$', notes_views.home, name='home'), url(r'^admin/', admin.site.urls), ]``` **views.py** `def home(request): notes = Note.objects template = loader.get_template('note.html') context = {'notes': notes} return render(request, 'templates/note.html', context)` NOTE : I am following this tutorial - https://pythonspot.com/django-tutorial-building-a-note-taking-app/ ```
2020/03/05
[ "https://Stackoverflow.com/questions/60548289", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5227269/" ]
instead of writing ``` `resetTimer() { this.setState(initialState); }` ``` use arrow function `const resetTimer=()=> { this.setState(initialState); }` this will work
You have to bind the method call with the event as suggested by other users If you don't bind the method, It will be always be called with the re-render First approach Inside constructor `this.methodName = this.bind.methodName(this);` Inside render() ``` render(){ return( <button onClick={this.methodName}></button> ) } ``` Second approach ``` render(){ return( <button onClick={()=>this.methodName()}></button> ) } ``` Third approach ``` methodName = () => { //scope } render(){ return( <button onClick={this.methodName}></button> ) } ``` The third type is not available for older versions of react you have to use class experimental plugin for that, In that case you should always you the first approach The second approach should always be used when you need to pass a parameter otherwise don't use that Also please note If you just write ``` <button onClick={this.methodName()}></button> ``` That means you are calling the method, but without binding it with event i.e. whether you click or not the method will always be called
60,548,289
I don't know why I am getting this error. Below is the code I am using. **settings.py** ``` TEMPLATE_DIRS = (os.path.join(os.path.dirname(BASE_DIR), "mysite", "static", "templates"),) ``` **urls.py** ``` from django.urls import path from django.conf.urls import include, url from django.contrib.auth import views as auth_views from notes import views as notes_views urlpatterns = [ url(r'^$', notes_views.home, name='home'), url(r'^admin/', admin.site.urls), ]``` **views.py** `def home(request): notes = Note.objects template = loader.get_template('note.html') context = {'notes': notes} return render(request, 'templates/note.html', context)` NOTE : I am following this tutorial - https://pythonspot.com/django-tutorial-building-a-note-taking-app/ ```
2020/03/05
[ "https://Stackoverflow.com/questions/60548289", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5227269/" ]
The problem comes from the "this" scope. Either you have to bind the function you're using in the class. ``` constructor( props ){ super( props ); this.resetTimer = this.resetTimer.bind(this); } ``` A second option is to use arrow functions when you declare your functions in order to maintain the scope of "this" on the class. ``` resetTimer = () => { this.setState(initialState); } ```
**second Solution** - this is because you have not bind the function and calling it in the click event Please refer [Handling events](https://reactjs.org/docs/handling-events.html) So add this line inside the constructor ``` this.resetTimer = this.resetTimer.bind(); ``` I hope this solves your problem :)
60,548,289
I don't know why I am getting this error. Below is the code I am using. **settings.py** ``` TEMPLATE_DIRS = (os.path.join(os.path.dirname(BASE_DIR), "mysite", "static", "templates"),) ``` **urls.py** ``` from django.urls import path from django.conf.urls import include, url from django.contrib.auth import views as auth_views from notes import views as notes_views urlpatterns = [ url(r'^$', notes_views.home, name='home'), url(r'^admin/', admin.site.urls), ]``` **views.py** `def home(request): notes = Note.objects template = loader.get_template('note.html') context = {'notes': notes} return render(request, 'templates/note.html', context)` NOTE : I am following this tutorial - https://pythonspot.com/django-tutorial-building-a-note-taking-app/ ```
2020/03/05
[ "https://Stackoverflow.com/questions/60548289", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5227269/" ]
The problem comes from the "this" scope. Either you have to bind the function you're using in the class. ``` constructor( props ){ super( props ); this.resetTimer = this.resetTimer.bind(this); } ``` A second option is to use arrow functions when you declare your functions in order to maintain the scope of "this" on the class. ``` resetTimer = () => { this.setState(initialState); } ```
You have to bind the method call with the event as suggested by other users If you don't bind the method, It will be always be called with the re-render First approach Inside constructor `this.methodName = this.bind.methodName(this);` Inside render() ``` render(){ return( <button onClick={this.methodName}></button> ) } ``` Second approach ``` render(){ return( <button onClick={()=>this.methodName()}></button> ) } ``` Third approach ``` methodName = () => { //scope } render(){ return( <button onClick={this.methodName}></button> ) } ``` The third type is not available for older versions of react you have to use class experimental plugin for that, In that case you should always you the first approach The second approach should always be used when you need to pass a parameter otherwise don't use that Also please note If you just write ``` <button onClick={this.methodName()}></button> ``` That means you are calling the method, but without binding it with event i.e. whether you click or not the method will always be called