qid
int64
46k
74.7M
question
stringlengths
54
37.8k
date
stringlengths
10
10
metadata
sequencelengths
3
3
response_j
stringlengths
17
26k
response_k
stringlengths
26
26k
718,040
<http://pypi.python.org/pypi/simplejson> I am just diving into the Python world and want to make a simple twitter application which requires the installation of simplejson but not sure how I can set it up and get it working.. I am on a Windows System
2009/04/04
[ "https://Stackoverflow.com/questions/718040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32372/" ]
I would recommend [EasyInstall](http://pypi.python.org/pypi/setuptools#windows), a package management application for Python. Once you've installed EasyInstall, you should be able to go to a command window and type: ``` easy_install simplejson ``` This may require putting easy\_install.exe on your PATH first, I don't remember if the EasyInstall setup does this for you (something like `C:\Python25\Scripts`).
Download the source code, unzip it to and directory, and execute python setup.py install.
718,040
<http://pypi.python.org/pypi/simplejson> I am just diving into the Python world and want to make a simple twitter application which requires the installation of simplejson but not sure how I can set it up and get it working.. I am on a Windows System
2009/04/04
[ "https://Stackoverflow.com/questions/718040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32372/" ]
I would recommend [EasyInstall](http://pypi.python.org/pypi/setuptools#windows), a package management application for Python. Once you've installed EasyInstall, you should be able to go to a command window and type: ``` easy_install simplejson ``` This may require putting easy\_install.exe on your PATH first, I don't remember if the EasyInstall setup does this for you (something like `C:\Python25\Scripts`).
You can import json as simplejson like this: ``` import json as simplejson ``` and keep backward compatibility.
718,040
<http://pypi.python.org/pypi/simplejson> I am just diving into the Python world and want to make a simple twitter application which requires the installation of simplejson but not sure how I can set it up and get it working.. I am on a Windows System
2009/04/04
[ "https://Stackoverflow.com/questions/718040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32372/" ]
I would recommend [EasyInstall](http://pypi.python.org/pypi/setuptools#windows), a package management application for Python. Once you've installed EasyInstall, you should be able to go to a command window and type: ``` easy_install simplejson ``` This may require putting easy\_install.exe on your PATH first, I don't remember if the EasyInstall setup does this for you (something like `C:\Python25\Scripts`).
Really simple way is: ``` pip install simplejson ```
718,040
<http://pypi.python.org/pypi/simplejson> I am just diving into the Python world and want to make a simple twitter application which requires the installation of simplejson but not sure how I can set it up and get it working.. I am on a Windows System
2009/04/04
[ "https://Stackoverflow.com/questions/718040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32372/" ]
If you have Python 2.6 installed then you already have simplejson - just import `json`; it's the same thing.
Download the source code, unzip it to and directory, and execute python setup.py install.
718,040
<http://pypi.python.org/pypi/simplejson> I am just diving into the Python world and want to make a simple twitter application which requires the installation of simplejson but not sure how I can set it up and get it working.. I am on a Windows System
2009/04/04
[ "https://Stackoverflow.com/questions/718040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32372/" ]
If you have Python 2.6 installed then you already have simplejson - just import `json`; it's the same thing.
You can import json as simplejson like this: ``` import json as simplejson ``` and keep backward compatibility.
718,040
<http://pypi.python.org/pypi/simplejson> I am just diving into the Python world and want to make a simple twitter application which requires the installation of simplejson but not sure how I can set it up and get it working.. I am on a Windows System
2009/04/04
[ "https://Stackoverflow.com/questions/718040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32372/" ]
Really simple way is: ``` pip install simplejson ```
If you have Python 2.6 installed then you already have simplejson - just import `json`; it's the same thing.
718,040
<http://pypi.python.org/pypi/simplejson> I am just diving into the Python world and want to make a simple twitter application which requires the installation of simplejson but not sure how I can set it up and get it working.. I am on a Windows System
2009/04/04
[ "https://Stackoverflow.com/questions/718040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32372/" ]
You can import json as simplejson like this: ``` import json as simplejson ``` and keep backward compatibility.
Download the source code, unzip it to and directory, and execute python setup.py install.
718,040
<http://pypi.python.org/pypi/simplejson> I am just diving into the Python world and want to make a simple twitter application which requires the installation of simplejson but not sure how I can set it up and get it working.. I am on a Windows System
2009/04/04
[ "https://Stackoverflow.com/questions/718040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32372/" ]
Really simple way is: ``` pip install simplejson ```
Download the source code, unzip it to and directory, and execute python setup.py install.
718,040
<http://pypi.python.org/pypi/simplejson> I am just diving into the Python world and want to make a simple twitter application which requires the installation of simplejson but not sure how I can set it up and get it working.. I am on a Windows System
2009/04/04
[ "https://Stackoverflow.com/questions/718040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32372/" ]
Really simple way is: ``` pip install simplejson ```
You can import json as simplejson like this: ``` import json as simplejson ``` and keep backward compatibility.
16,330,838
I would like to split a string by ':' and ' ' characters. However, i would like to ignore two spaces ' ' and two colons '::'. for e.g. ``` text = "s:11011 i:11010 ::110011 :110010 d:11000" ``` should split into ``` [s,11011,i,11010,:,110011, ,110010,d,11000] ``` after following the Regular Expressions HOWTO on the python website, i managed to comeup with the following ``` regx= re.compile('([\s:]|[^\s\s]|[^::])') regx.split(text) ``` However this does not work as intended as it splits on the : and spaces, but it still includes the ':' and ' ' in the split. ``` [s,:,11011, ,i,:,11010, ,:,:,110011, , :,110010, ,d,:,11000] ``` How can I fix this? **EDIT:** In case of a double space, i only want one space to appear
2013/05/02
[ "https://Stackoverflow.com/questions/16330838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1753000/" ]
Note this assumes that your data has format like `X:101010`: ``` >>> re.findall(r'(.+?):(.+?)\b ?',text) [('s', '11011'), ('i', '11010'), (':', '110011'), (' ', '110010'), ('d', '11000')] ``` Then `chain` them up: ``` >>> list(itertools.chain(*_)) ['s', '11011', 'i', '11010', ':', '110011', ' ', '110010', 'd', '11000'] ```
``` >>> text = "s:11011 i:11010 ::110011 :110010 d:11000" >>> [x for x in re.split(r":(:)?|\s(\s)?", text) if x] ['s', '11011', 'i', '11010', ':', '110011', ' ', '110010', 'd', '11000'] ```
16,330,838
I would like to split a string by ':' and ' ' characters. However, i would like to ignore two spaces ' ' and two colons '::'. for e.g. ``` text = "s:11011 i:11010 ::110011 :110010 d:11000" ``` should split into ``` [s,11011,i,11010,:,110011, ,110010,d,11000] ``` after following the Regular Expressions HOWTO on the python website, i managed to comeup with the following ``` regx= re.compile('([\s:]|[^\s\s]|[^::])') regx.split(text) ``` However this does not work as intended as it splits on the : and spaces, but it still includes the ':' and ' ' in the split. ``` [s,:,11011, ,i,:,11010, ,:,:,110011, , :,110010, ,d,:,11000] ``` How can I fix this? **EDIT:** In case of a double space, i only want one space to appear
2013/05/02
[ "https://Stackoverflow.com/questions/16330838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1753000/" ]
Note this assumes that your data has format like `X:101010`: ``` >>> re.findall(r'(.+?):(.+?)\b ?',text) [('s', '11011'), ('i', '11010'), (':', '110011'), (' ', '110010'), ('d', '11000')] ``` Then `chain` them up: ``` >>> list(itertools.chain(*_)) ['s', '11011', 'i', '11010', ':', '110011', ' ', '110010', 'd', '11000'] ```
Use the regex `(?<=\d) |:(?=\d)` to split: ``` >>> text = "s:11011 i:11010 ::110011 :110010 d:11000" >>> result = re.split(r"(?<=\d) |:(?=\d)", text) >>> result ['s', '11011', 'i', '11010', ':', '110011', ' ', '110010', 'd', '11000'] ``` This will split on: `(?<=\d)` a space, when there is a digit on the left. To check this I use a [lookbehind assertion](http://www.regular-expressions.info/lookaround.html). `:(?=\d)` a colon, when there is a digit on the right. To check this I use a [lookahead assertion](http://www.regular-expressions.info/lookaround.html).
16,330,838
I would like to split a string by ':' and ' ' characters. However, i would like to ignore two spaces ' ' and two colons '::'. for e.g. ``` text = "s:11011 i:11010 ::110011 :110010 d:11000" ``` should split into ``` [s,11011,i,11010,:,110011, ,110010,d,11000] ``` after following the Regular Expressions HOWTO on the python website, i managed to comeup with the following ``` regx= re.compile('([\s:]|[^\s\s]|[^::])') regx.split(text) ``` However this does not work as intended as it splits on the : and spaces, but it still includes the ':' and ' ' in the split. ``` [s,:,11011, ,i,:,11010, ,:,:,110011, , :,110010, ,d,:,11000] ``` How can I fix this? **EDIT:** In case of a double space, i only want one space to appear
2013/05/02
[ "https://Stackoverflow.com/questions/16330838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1753000/" ]
Note this assumes that your data has format like `X:101010`: ``` >>> re.findall(r'(.+?):(.+?)\b ?',text) [('s', '11011'), ('i', '11010'), (':', '110011'), (' ', '110010'), ('d', '11000')] ``` Then `chain` them up: ``` >>> list(itertools.chain(*_)) ['s', '11011', 'i', '11010', ':', '110011', ' ', '110010', 'd', '11000'] ```
Have a look at this pattern: ``` ([a-z\:\s])\:(\d+) ``` It will give you the same array you are expecting. No need to use split, just access the matches you have returned by the regex engine. Hope it helps!
16,330,838
I would like to split a string by ':' and ' ' characters. However, i would like to ignore two spaces ' ' and two colons '::'. for e.g. ``` text = "s:11011 i:11010 ::110011 :110010 d:11000" ``` should split into ``` [s,11011,i,11010,:,110011, ,110010,d,11000] ``` after following the Regular Expressions HOWTO on the python website, i managed to comeup with the following ``` regx= re.compile('([\s:]|[^\s\s]|[^::])') regx.split(text) ``` However this does not work as intended as it splits on the : and spaces, but it still includes the ':' and ' ' in the split. ``` [s,:,11011, ,i,:,11010, ,:,:,110011, , :,110010, ,d,:,11000] ``` How can I fix this? **EDIT:** In case of a double space, i only want one space to appear
2013/05/02
[ "https://Stackoverflow.com/questions/16330838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1753000/" ]
``` >>> text = "s:11011 i:11010 ::110011 :110010 d:11000" >>> [x for x in re.split(r":(:)?|\s(\s)?", text) if x] ['s', '11011', 'i', '11010', ':', '110011', ' ', '110010', 'd', '11000'] ```
Have a look at this pattern: ``` ([a-z\:\s])\:(\d+) ``` It will give you the same array you are expecting. No need to use split, just access the matches you have returned by the regex engine. Hope it helps!
16,330,838
I would like to split a string by ':' and ' ' characters. However, i would like to ignore two spaces ' ' and two colons '::'. for e.g. ``` text = "s:11011 i:11010 ::110011 :110010 d:11000" ``` should split into ``` [s,11011,i,11010,:,110011, ,110010,d,11000] ``` after following the Regular Expressions HOWTO on the python website, i managed to comeup with the following ``` regx= re.compile('([\s:]|[^\s\s]|[^::])') regx.split(text) ``` However this does not work as intended as it splits on the : and spaces, but it still includes the ':' and ' ' in the split. ``` [s,:,11011, ,i,:,11010, ,:,:,110011, , :,110010, ,d,:,11000] ``` How can I fix this? **EDIT:** In case of a double space, i only want one space to appear
2013/05/02
[ "https://Stackoverflow.com/questions/16330838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1753000/" ]
Use the regex `(?<=\d) |:(?=\d)` to split: ``` >>> text = "s:11011 i:11010 ::110011 :110010 d:11000" >>> result = re.split(r"(?<=\d) |:(?=\d)", text) >>> result ['s', '11011', 'i', '11010', ':', '110011', ' ', '110010', 'd', '11000'] ``` This will split on: `(?<=\d)` a space, when there is a digit on the left. To check this I use a [lookbehind assertion](http://www.regular-expressions.info/lookaround.html). `:(?=\d)` a colon, when there is a digit on the right. To check this I use a [lookahead assertion](http://www.regular-expressions.info/lookaround.html).
Have a look at this pattern: ``` ([a-z\:\s])\:(\d+) ``` It will give you the same array you are expecting. No need to use split, just access the matches you have returned by the regex engine. Hope it helps!
65,856,151
I am using anaconda and python 3.8. Now some of my codes need to be run with python 2. so I create a separate python 2.7 environment in conda like below: after that, I installed spyder, then launcher spyder amd spyder is showing I am still using python 3.8 how do i do to use python 2.7 in spyder with a new environment? Thanks ``` conda create -n py27 python=2.7 ipykernel conda activate py27 pip install spyder ```
2021/01/23
[ "https://Stackoverflow.com/questions/65856151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9983652/" ]
According to the documentation [here](https://docs.anaconda.com/anaconda/user-guide/tasks/switch-environment/), this should create a python2.7 virtual environment (29 April 2021) with spyder installed. I verified that spyder version 3.3.6 is python2.7 compatible ``` conda create -y -n py27 python=2.7 spyder=3.3.6 ``` However, I could not run `spyder` in the `py27` environment due to conflicts that `conda` failed to catch. The workaround shown by [asanganuwan](https://github.com/asanganuwan) on this [Spyder Github Issue](https://github.com/spyder-ide/spyder/issues/13510#issuecomment-754392635) page worked for me also > > Found a workaround to use Spyder on python 2.7. > > > > ``` > setup two virtual environments for Python 2.7 and 3.6. > Launce anaconda navigator and install spyder 3.3.6 on both the environments > Launch spyder on the environment with Python 3.6 > Preferences-->Python Interpreter --> set the Python path for 2.7 > Restart Spyder > Done! > > ``` > > So my recommendation is next run ``` conda create -y -n py36 python=3.6 spyder=3.3.6 conda activate py36 spyder ``` And follow the last three instructions from asanganuwan. Also you should use the `conda` package manager as much as possible since it is smarter with managing requirements. When I try to use `pip install spyder` after activating the environment, it warns of version conflicts and fails to start.
You can manage environments from Ananconda's Navigator. <https://docs.anaconda.com/anaconda/navigator/getting-started/#navigator-managing-environments>
65,856,151
I am using anaconda and python 3.8. Now some of my codes need to be run with python 2. so I create a separate python 2.7 environment in conda like below: after that, I installed spyder, then launcher spyder amd spyder is showing I am still using python 3.8 how do i do to use python 2.7 in spyder with a new environment? Thanks ``` conda create -n py27 python=2.7 ipykernel conda activate py27 pip install spyder ```
2021/01/23
[ "https://Stackoverflow.com/questions/65856151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9983652/" ]
I suggest to first search for an anaconda 2.7 version you want, then install it explicitly, this will make resolving much faster, give you a "stable" anaconda and allow you more control while installing all anaconda packages: First: ``` conda search anaconda ``` Then select a version that has 27, in my case: ``` # Name Version Build Channel anaconda custom py27_0 pkgs/main anaconda custom py27_1 pkgs/main anaconda custom py27h689e5c3_0 pkgs/main anaconda custom py35_1 pkgs/main ............ anaconda 5.3.1 py27_0 pkgs/main anaconda 5.3.1 py37_0 pkgs/main ............ anaconda 2019.10 py27_0 pkgs/main ............ ``` I went with: ``` conda create -n py2 Python=2.7 anaconda==5.3.1 -y ```
You can manage environments from Ananconda's Navigator. <https://docs.anaconda.com/anaconda/navigator/getting-started/#navigator-managing-environments>
65,856,151
I am using anaconda and python 3.8. Now some of my codes need to be run with python 2. so I create a separate python 2.7 environment in conda like below: after that, I installed spyder, then launcher spyder amd spyder is showing I am still using python 3.8 how do i do to use python 2.7 in spyder with a new environment? Thanks ``` conda create -n py27 python=2.7 ipykernel conda activate py27 pip install spyder ```
2021/01/23
[ "https://Stackoverflow.com/questions/65856151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9983652/" ]
According to the documentation [here](https://docs.anaconda.com/anaconda/user-guide/tasks/switch-environment/), this should create a python2.7 virtual environment (29 April 2021) with spyder installed. I verified that spyder version 3.3.6 is python2.7 compatible ``` conda create -y -n py27 python=2.7 spyder=3.3.6 ``` However, I could not run `spyder` in the `py27` environment due to conflicts that `conda` failed to catch. The workaround shown by [asanganuwan](https://github.com/asanganuwan) on this [Spyder Github Issue](https://github.com/spyder-ide/spyder/issues/13510#issuecomment-754392635) page worked for me also > > Found a workaround to use Spyder on python 2.7. > > > > ``` > setup two virtual environments for Python 2.7 and 3.6. > Launce anaconda navigator and install spyder 3.3.6 on both the environments > Launch spyder on the environment with Python 3.6 > Preferences-->Python Interpreter --> set the Python path for 2.7 > Restart Spyder > Done! > > ``` > > So my recommendation is next run ``` conda create -y -n py36 python=3.6 spyder=3.3.6 conda activate py36 spyder ``` And follow the last three instructions from asanganuwan. Also you should use the `conda` package manager as much as possible since it is smarter with managing requirements. When I try to use `pip install spyder` after activating the environment, it warns of version conflicts and fails to start.
**I guess you are on previous pip;** 1. Use `which pip` command to find out your current pip environment. 2. Modify your **.bash** file and set another new environment variable for your new pip. 3. Source your **.bash** file. 4. Try to install **spyder** by using new pip env variable; something like `pipX install spyder`
65,856,151
I am using anaconda and python 3.8. Now some of my codes need to be run with python 2. so I create a separate python 2.7 environment in conda like below: after that, I installed spyder, then launcher spyder amd spyder is showing I am still using python 3.8 how do i do to use python 2.7 in spyder with a new environment? Thanks ``` conda create -n py27 python=2.7 ipykernel conda activate py27 pip install spyder ```
2021/01/23
[ "https://Stackoverflow.com/questions/65856151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9983652/" ]
I suggest to first search for an anaconda 2.7 version you want, then install it explicitly, this will make resolving much faster, give you a "stable" anaconda and allow you more control while installing all anaconda packages: First: ``` conda search anaconda ``` Then select a version that has 27, in my case: ``` # Name Version Build Channel anaconda custom py27_0 pkgs/main anaconda custom py27_1 pkgs/main anaconda custom py27h689e5c3_0 pkgs/main anaconda custom py35_1 pkgs/main ............ anaconda 5.3.1 py27_0 pkgs/main anaconda 5.3.1 py37_0 pkgs/main ............ anaconda 2019.10 py27_0 pkgs/main ............ ``` I went with: ``` conda create -n py2 Python=2.7 anaconda==5.3.1 -y ```
**I guess you are on previous pip;** 1. Use `which pip` command to find out your current pip environment. 2. Modify your **.bash** file and set another new environment variable for your new pip. 3. Source your **.bash** file. 4. Try to install **spyder** by using new pip env variable; something like `pipX install spyder`
65,856,151
I am using anaconda and python 3.8. Now some of my codes need to be run with python 2. so I create a separate python 2.7 environment in conda like below: after that, I installed spyder, then launcher spyder amd spyder is showing I am still using python 3.8 how do i do to use python 2.7 in spyder with a new environment? Thanks ``` conda create -n py27 python=2.7 ipykernel conda activate py27 pip install spyder ```
2021/01/23
[ "https://Stackoverflow.com/questions/65856151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9983652/" ]
According to the documentation [here](https://docs.anaconda.com/anaconda/user-guide/tasks/switch-environment/), this should create a python2.7 virtual environment (29 April 2021) with spyder installed. I verified that spyder version 3.3.6 is python2.7 compatible ``` conda create -y -n py27 python=2.7 spyder=3.3.6 ``` However, I could not run `spyder` in the `py27` environment due to conflicts that `conda` failed to catch. The workaround shown by [asanganuwan](https://github.com/asanganuwan) on this [Spyder Github Issue](https://github.com/spyder-ide/spyder/issues/13510#issuecomment-754392635) page worked for me also > > Found a workaround to use Spyder on python 2.7. > > > > ``` > setup two virtual environments for Python 2.7 and 3.6. > Launce anaconda navigator and install spyder 3.3.6 on both the environments > Launch spyder on the environment with Python 3.6 > Preferences-->Python Interpreter --> set the Python path for 2.7 > Restart Spyder > Done! > > ``` > > So my recommendation is next run ``` conda create -y -n py36 python=3.6 spyder=3.3.6 conda activate py36 spyder ``` And follow the last three instructions from asanganuwan. Also you should use the `conda` package manager as much as possible since it is smarter with managing requirements. When I try to use `pip install spyder` after activating the environment, it warns of version conflicts and fails to start.
I suggest to first search for an anaconda 2.7 version you want, then install it explicitly, this will make resolving much faster, give you a "stable" anaconda and allow you more control while installing all anaconda packages: First: ``` conda search anaconda ``` Then select a version that has 27, in my case: ``` # Name Version Build Channel anaconda custom py27_0 pkgs/main anaconda custom py27_1 pkgs/main anaconda custom py27h689e5c3_0 pkgs/main anaconda custom py35_1 pkgs/main ............ anaconda 5.3.1 py27_0 pkgs/main anaconda 5.3.1 py37_0 pkgs/main ............ anaconda 2019.10 py27_0 pkgs/main ............ ``` I went with: ``` conda create -n py2 Python=2.7 anaconda==5.3.1 -y ```
8,638,880
I've come across an interesting behavior with Python 3 that I don't understand. I've understood that with the built-in immutable types like str, int, etc, that not only are two variables of the same value (both contain 'x') equal, they are literally the same object, which allows the use of the `is` operator. However, when I use the input() function, it seems to create a string object that is NOT the same object, but does have the same value. Here's my python interactive prompt of this: ``` $ python Python 3.2 (r32:88452, Feb 20 2011, 11:12:31) [GCC 4.2.1 (Apple Inc. build 5664)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> x = input() test >>> y = 'test' >>> x is y False >>> x == y True >>> id(x) 4301225744 >>> id(y) 4301225576 ``` Why is this?
2011/12/26
[ "https://Stackoverflow.com/questions/8638880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/206349/" ]
> > I've understood that with the built-in immutable types like str, int, etc, that not only are two variables of the same value (both contain 'x') equal, they are literally the same object, which allows the use of the is operator. > > > This is your misconception: concerning the `int`s and `long`s, that is valid only for a few values; with strings of any kind, it may be true concerning the strings of one module, but not otherwise. But [there is a builtin function `intern()`](http://docs.python.org/library/functions.html#intern) which interns any given string.
This is a properly behavior. ``` x == y #True because they have a the same value x is y #False because x isn't reference to y id(x) == id(y) #False because as the above ``` But: ``` x = input() y = x #rewrite reference of x to another variable y == x and x is y and id(x) == id(y) #True ```
8,638,880
I've come across an interesting behavior with Python 3 that I don't understand. I've understood that with the built-in immutable types like str, int, etc, that not only are two variables of the same value (both contain 'x') equal, they are literally the same object, which allows the use of the `is` operator. However, when I use the input() function, it seems to create a string object that is NOT the same object, but does have the same value. Here's my python interactive prompt of this: ``` $ python Python 3.2 (r32:88452, Feb 20 2011, 11:12:31) [GCC 4.2.1 (Apple Inc. build 5664)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> x = input() test >>> y = 'test' >>> x is y False >>> x == y True >>> id(x) 4301225744 >>> id(y) 4301225576 ``` Why is this?
2011/12/26
[ "https://Stackoverflow.com/questions/8638880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/206349/" ]
This is a properly behavior. ``` x == y #True because they have a the same value x is y #False because x isn't reference to y id(x) == id(y) #False because as the above ``` But: ``` x = input() y = x #rewrite reference of x to another variable y == x and x is y and id(x) == id(y) #True ```
Values that are the same are **not** guaranteed to be the same instance. That's merely an optimization that you can't rely on. There aren't very many times that using `is` is appropriate, use `==` instead.
8,638,880
I've come across an interesting behavior with Python 3 that I don't understand. I've understood that with the built-in immutable types like str, int, etc, that not only are two variables of the same value (both contain 'x') equal, they are literally the same object, which allows the use of the `is` operator. However, when I use the input() function, it seems to create a string object that is NOT the same object, but does have the same value. Here's my python interactive prompt of this: ``` $ python Python 3.2 (r32:88452, Feb 20 2011, 11:12:31) [GCC 4.2.1 (Apple Inc. build 5664)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> x = input() test >>> y = 'test' >>> x is y False >>> x == y True >>> id(x) 4301225744 >>> id(y) 4301225576 ``` Why is this?
2011/12/26
[ "https://Stackoverflow.com/questions/8638880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/206349/" ]
This is a properly behavior. ``` x == y #True because they have a the same value x is y #False because x isn't reference to y id(x) == id(y) #False because as the above ``` But: ``` x = input() y = x #rewrite reference of x to another variable y == x and x is y and id(x) == id(y) #True ```
> > I've understood that with the built-in immutable types like str, int, etc, that not only are two variables of the same value (both contain 'x') equal, they are literally the same object > > > No, that is not guaranteed, in the same way that if I speak of an orange that is physically indistinguishable from the one you are holding, it is not guaranteed that I don't have some other orange in mind that simply happens to look identical.
8,638,880
I've come across an interesting behavior with Python 3 that I don't understand. I've understood that with the built-in immutable types like str, int, etc, that not only are two variables of the same value (both contain 'x') equal, they are literally the same object, which allows the use of the `is` operator. However, when I use the input() function, it seems to create a string object that is NOT the same object, but does have the same value. Here's my python interactive prompt of this: ``` $ python Python 3.2 (r32:88452, Feb 20 2011, 11:12:31) [GCC 4.2.1 (Apple Inc. build 5664)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> x = input() test >>> y = 'test' >>> x is y False >>> x == y True >>> id(x) 4301225744 >>> id(y) 4301225576 ``` Why is this?
2011/12/26
[ "https://Stackoverflow.com/questions/8638880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/206349/" ]
> > I've understood that with the built-in immutable types like str, int, etc, that not only are two variables of the same value (both contain 'x') equal, they are literally the same object, which allows the use of the is operator. > > > This is your misconception: concerning the `int`s and `long`s, that is valid only for a few values; with strings of any kind, it may be true concerning the strings of one module, but not otherwise. But [there is a builtin function `intern()`](http://docs.python.org/library/functions.html#intern) which interns any given string.
Values that are the same are **not** guaranteed to be the same instance. That's merely an optimization that you can't rely on. There aren't very many times that using `is` is appropriate, use `==` instead.
8,638,880
I've come across an interesting behavior with Python 3 that I don't understand. I've understood that with the built-in immutable types like str, int, etc, that not only are two variables of the same value (both contain 'x') equal, they are literally the same object, which allows the use of the `is` operator. However, when I use the input() function, it seems to create a string object that is NOT the same object, but does have the same value. Here's my python interactive prompt of this: ``` $ python Python 3.2 (r32:88452, Feb 20 2011, 11:12:31) [GCC 4.2.1 (Apple Inc. build 5664)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> x = input() test >>> y = 'test' >>> x is y False >>> x == y True >>> id(x) 4301225744 >>> id(y) 4301225576 ``` Why is this?
2011/12/26
[ "https://Stackoverflow.com/questions/8638880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/206349/" ]
> > I've understood that with the built-in immutable types like str, int, etc, that not only are two variables of the same value (both contain 'x') equal, they are literally the same object, which allows the use of the is operator. > > > This is your misconception: concerning the `int`s and `long`s, that is valid only for a few values; with strings of any kind, it may be true concerning the strings of one module, but not otherwise. But [there is a builtin function `intern()`](http://docs.python.org/library/functions.html#intern) which interns any given string.
This is because of an implementation detail - you can't rely on `is` returning `True` in general. Try this script: ``` x = 'test' y = 'test' print('%r: \'x == y\' is %s, \'x is y\' is %s' % (x, x == y, x is y)) x = 'testtest' y = 'testtest' print('%r: \'x == y\' is %s, \'x is y\' is %s' % (x, x == y, x is y)) for i in range(1, 100): x = 'test' * i y = 'test' * i print('%d: %r: \'x == y\' is %s, \'x is y\' is %s' % (i, x, x == y, x is y)) if x is not y: break ``` This prints ``` 'test': 'x == y' is True, 'x is y' is True 'testtest': 'x == y' is True, 'x is y' is True 1: 'test': 'x == y' is True, 'x is y' is True 2: 'testtest': 'x == y' is True, 'x is y' is False ``` On Jython, `is` returns `False` even in the first print.
8,638,880
I've come across an interesting behavior with Python 3 that I don't understand. I've understood that with the built-in immutable types like str, int, etc, that not only are two variables of the same value (both contain 'x') equal, they are literally the same object, which allows the use of the `is` operator. However, when I use the input() function, it seems to create a string object that is NOT the same object, but does have the same value. Here's my python interactive prompt of this: ``` $ python Python 3.2 (r32:88452, Feb 20 2011, 11:12:31) [GCC 4.2.1 (Apple Inc. build 5664)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> x = input() test >>> y = 'test' >>> x is y False >>> x == y True >>> id(x) 4301225744 >>> id(y) 4301225576 ``` Why is this?
2011/12/26
[ "https://Stackoverflow.com/questions/8638880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/206349/" ]
> > I've understood that with the built-in immutable types like str, int, etc, that not only are two variables of the same value (both contain 'x') equal, they are literally the same object, which allows the use of the is operator. > > > This is your misconception: concerning the `int`s and `long`s, that is valid only for a few values; with strings of any kind, it may be true concerning the strings of one module, but not otherwise. But [there is a builtin function `intern()`](http://docs.python.org/library/functions.html#intern) which interns any given string.
> > I've understood that with the built-in immutable types like str, int, etc, that not only are two variables of the same value (both contain 'x') equal, they are literally the same object > > > No, that is not guaranteed, in the same way that if I speak of an orange that is physically indistinguishable from the one you are holding, it is not guaranteed that I don't have some other orange in mind that simply happens to look identical.
8,638,880
I've come across an interesting behavior with Python 3 that I don't understand. I've understood that with the built-in immutable types like str, int, etc, that not only are two variables of the same value (both contain 'x') equal, they are literally the same object, which allows the use of the `is` operator. However, when I use the input() function, it seems to create a string object that is NOT the same object, but does have the same value. Here's my python interactive prompt of this: ``` $ python Python 3.2 (r32:88452, Feb 20 2011, 11:12:31) [GCC 4.2.1 (Apple Inc. build 5664)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> x = input() test >>> y = 'test' >>> x is y False >>> x == y True >>> id(x) 4301225744 >>> id(y) 4301225576 ``` Why is this?
2011/12/26
[ "https://Stackoverflow.com/questions/8638880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/206349/" ]
This is because of an implementation detail - you can't rely on `is` returning `True` in general. Try this script: ``` x = 'test' y = 'test' print('%r: \'x == y\' is %s, \'x is y\' is %s' % (x, x == y, x is y)) x = 'testtest' y = 'testtest' print('%r: \'x == y\' is %s, \'x is y\' is %s' % (x, x == y, x is y)) for i in range(1, 100): x = 'test' * i y = 'test' * i print('%d: %r: \'x == y\' is %s, \'x is y\' is %s' % (i, x, x == y, x is y)) if x is not y: break ``` This prints ``` 'test': 'x == y' is True, 'x is y' is True 'testtest': 'x == y' is True, 'x is y' is True 1: 'test': 'x == y' is True, 'x is y' is True 2: 'testtest': 'x == y' is True, 'x is y' is False ``` On Jython, `is` returns `False` even in the first print.
Values that are the same are **not** guaranteed to be the same instance. That's merely an optimization that you can't rely on. There aren't very many times that using `is` is appropriate, use `==` instead.
8,638,880
I've come across an interesting behavior with Python 3 that I don't understand. I've understood that with the built-in immutable types like str, int, etc, that not only are two variables of the same value (both contain 'x') equal, they are literally the same object, which allows the use of the `is` operator. However, when I use the input() function, it seems to create a string object that is NOT the same object, but does have the same value. Here's my python interactive prompt of this: ``` $ python Python 3.2 (r32:88452, Feb 20 2011, 11:12:31) [GCC 4.2.1 (Apple Inc. build 5664)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> x = input() test >>> y = 'test' >>> x is y False >>> x == y True >>> id(x) 4301225744 >>> id(y) 4301225576 ``` Why is this?
2011/12/26
[ "https://Stackoverflow.com/questions/8638880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/206349/" ]
This is because of an implementation detail - you can't rely on `is` returning `True` in general. Try this script: ``` x = 'test' y = 'test' print('%r: \'x == y\' is %s, \'x is y\' is %s' % (x, x == y, x is y)) x = 'testtest' y = 'testtest' print('%r: \'x == y\' is %s, \'x is y\' is %s' % (x, x == y, x is y)) for i in range(1, 100): x = 'test' * i y = 'test' * i print('%d: %r: \'x == y\' is %s, \'x is y\' is %s' % (i, x, x == y, x is y)) if x is not y: break ``` This prints ``` 'test': 'x == y' is True, 'x is y' is True 'testtest': 'x == y' is True, 'x is y' is True 1: 'test': 'x == y' is True, 'x is y' is True 2: 'testtest': 'x == y' is True, 'x is y' is False ``` On Jython, `is` returns `False` even in the first print.
> > I've understood that with the built-in immutable types like str, int, etc, that not only are two variables of the same value (both contain 'x') equal, they are literally the same object > > > No, that is not guaranteed, in the same way that if I speak of an orange that is physically indistinguishable from the one you are holding, it is not guaranteed that I don't have some other orange in mind that simply happens to look identical.
9,887,224
Does apache or nginx must be installed before I can run my PHP files in browser? Django itself has a run-server for testing python codes.Is there any similar way to test PHP files?
2012/03/27
[ "https://Stackoverflow.com/questions/9887224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1188895/" ]
Your options is: * Install web server, as you said. * Use [web server](http://php.net/manual/en/features.commandline.webserver.php), as JohnP suggested. * Install php-cli, run your script from console, save output to html file and open it in a browser. Actually, you can't normally "run" php files in browser. Browser can only send requests to server and display script's output.
Yes. You need something like nginx or Apache. Either install one of those (on say your local machine). **OR**, see JohnP's comment - a new feature released recently.
9,887,224
Does apache or nginx must be installed before I can run my PHP files in browser? Django itself has a run-server for testing python codes.Is there any similar way to test PHP files?
2012/03/27
[ "https://Stackoverflow.com/questions/9887224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1188895/" ]
There is a [built in web server](http://php.net/manual/en/features.commandline.webserver.php) from php 5.4. Before PHP 5.4 you must install a web server to execute php files in browser
Yes. You need something like nginx or Apache. Either install one of those (on say your local machine). **OR**, see JohnP's comment - a new feature released recently.
2,765,664
I have got some code to pass in a variable into a script from the command line. I can pass any value into `function` for the `var` arg. The problem is that when I put `function` into a class the variable doesn't get read into `function`. The script is: ``` import sys, os def function(var): print var class function_call(object): def __init__(self, sysArgs): try: self.function = None self.args = [] self.modulePath = sysArgs[0] self.moduleDir, tail = os.path.split(self.modulePath) self.moduleName, ext = os.path.splitext(tail) __import__(self.moduleName) self.module = sys.modules[self.moduleName] if len(sysArgs) > 1: self.functionName = sysArgs[1] self.function = self.module.__dict__[self.functionName] self.args = sysArgs[2:] except Exception, e: sys.stderr.write("%s %s\n" % ("PythonCall#__init__", e)) def execute(self): try: if self.function: self.function(*self.args) except Exception, e: sys.stderr.write("%s %s\n" % ("PythonCall#execute", e)) if __name__=="__main__": function_call(sys.argv).execute() ``` This works by entering `./function <function> <arg1 arg2 ....>`. The problem is that I want to to select the function I want that is in a class rather than just a function by itself. The code I have tried is the same except that `function(var):` is in a class. I was hoping for some ideas on how to modify my `function_call` class to accept this. If i want to pass in the value `Hello` I run the script like so -- `python function_call.py function Hello`. This then prints the `var` variable as `Hello`. By entering the variable into the command lines I can then use this variable throughout the code. If the script was a bunch of functions I could just select the function using this code but I would like to select the functions inside a particular class. Instead of `python function.py function hello` I could enter the class in as well eg. `python function.py A function hello`. Also I have encounter that I have problem's saving the value for use outside the function. If anyone could solve this I would appreciate it very much. `_________________________________________________________________________________` Amended code. This is the code that work's for me now. ``` class A: def __init__(self): self.project = sys.argv[2] def run(self, *sysArgs): pass def funct(self): print self.project class function_call(object): def __init__(self, sysArgs): try: self.function = None self.args = [] self.modulePath = sysArgs[0] self.moduleDir, tail = os.path.split(self.modulePath) self.moduleName, ext = os.path.splitext(tail) __import__(self.moduleName) self.module = sys.modules[self.moduleName] if len(sysArgs) > 1: self.functionName = sysArgs[1] self.function = getattr(A(), sysArgs[1])(*sysArgs[2:]) self.args = sysArgs[2:] except Exception, e: sys.stderr.write("%s %s\n" % ("PythonCall#__init__", e)) def execute(self): try: if self.function: self.function(*self.args) except Exception, e: sys.stderr.write("%s %s\n" % ("PythonCall#execute", e)) if __name__=="__main__": function_call(sys.argv).execute() inst_A = A() inst_A.funct() ``` Thanks for all the help.
2010/05/04
[ "https://Stackoverflow.com/questions/2765664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/234435/" ]
you might find [`getattr`](http://docs.python.org/library/functions.html#getattr) useful: ``` >>> argv = ['function.py', 'run', 'Hello'] >>> class A: def run(self, *args): print(*args) >>> getattr(A(), argv[1])(*argv[2:]) Hello ```
It sounds like rather than: ``` self.function = self.module.__dict__[self.functionName] ``` you want to do something like (as @SilentGhost mentioned): ``` self.function = getattr(some_class, self.functionName) ``` The tricky thing with retrieving a method on a class (not an object instance) is that you are going to get back an unbound method. You will need to pass an instance of some\_class as the first argument when you call self.function. Alternately, if you are defining the class in question, you can use classmethod or [staticmethod](http://docs.python.org/library/functions.html#staticmethod) to make sure that some\_class.function\_you\_want\_to\_pick will return a bound function.
65,661,996
How Do I pass values say `12,32,34` to formula `x+y+z` in python without assigning manually? I have tried using `**args` but the results is `None`. ``` def myFormula(*args): lambda x, y: x+y+z(*args) print(myFormula(1,2,3)) ```
2021/01/11
[ "https://Stackoverflow.com/questions/65661996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14911024/" ]
try this: ```py formula = lambda x,y,z: x+y+z print(formula(1,2,3)) ``` there is no need to use \*args there. here is an example of using a function for a formula ```py # a = (v - u)/t acceleration = lambda v, u, t: (v - u)/t print(acceleration(23, 12, 5) ```
Just use `sum`: ``` print(sum([1, 2, 3])) ``` Output: ``` 6 ``` If you want a `def` try this: ``` def myFormula(*args): return sum(args) print(myFormula(1, 2, 3)) ``` Output: ``` 6 ```
65,661,996
How Do I pass values say `12,32,34` to formula `x+y+z` in python without assigning manually? I have tried using `**args` but the results is `None`. ``` def myFormula(*args): lambda x, y: x+y+z(*args) print(myFormula(1,2,3)) ```
2021/01/11
[ "https://Stackoverflow.com/questions/65661996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14911024/" ]
try this: ```py formula = lambda x,y,z: x+y+z print(formula(1,2,3)) ``` there is no need to use \*args there. here is an example of using a function for a formula ```py # a = (v - u)/t acceleration = lambda v, u, t: (v - u)/t print(acceleration(23, 12, 5) ```
A regular function doesn't require doing any manual assignments: ``` def myFormula(x,y,z): return sum((x,y,z)) print(myFormula(1,2,3)) ``` You can handle an arbitrary number of arguments in this situation like this: ``` def myFormula(*args): return sum(args) print(myFormula(1,2,3,4)) ```
65,661,996
How Do I pass values say `12,32,34` to formula `x+y+z` in python without assigning manually? I have tried using `**args` but the results is `None`. ``` def myFormula(*args): lambda x, y: x+y+z(*args) print(myFormula(1,2,3)) ```
2021/01/11
[ "https://Stackoverflow.com/questions/65661996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14911024/" ]
A regular function doesn't require doing any manual assignments: ``` def myFormula(x,y,z): return sum((x,y,z)) print(myFormula(1,2,3)) ``` You can handle an arbitrary number of arguments in this situation like this: ``` def myFormula(*args): return sum(args) print(myFormula(1,2,3,4)) ```
Just use `sum`: ``` print(sum([1, 2, 3])) ``` Output: ``` 6 ``` If you want a `def` try this: ``` def myFormula(*args): return sum(args) print(myFormula(1, 2, 3)) ``` Output: ``` 6 ```
55,929,577
I'm trying to run a python program in the online IDE SourceLair. I've written a line of code that simply prints hello, but I am embarrassed to say I can't figure out how to RUN the program. I have the console, web server, and terminal available on the IDE already pulled up. I just don't know how to start the program. I've tried it on Mac OSX and Chrome OS, and neither work. I don't know if anyone has experience with this IDE, but I can hope. Thanks!!
2019/04/30
[ "https://Stackoverflow.com/questions/55929577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11434891/" ]
Can I ask you why you are using SourceLair? Well I just figured it out in about 2 mins....its the same as using any other editor for python. All you have to do is to run it in the terminal. python (nameoffile).py
Antonis from SourceLair here. In SourceLair, you get a fully featured terminal, plus a web server for running your Python applications. For simple files, as you correctly found out, all you have to do is save the file and run it through your terminal, using `python <your-file.py>`. If you want to run a complete web server, you can check out our server configuration guide here: <https://help.sourcelair.com/webserver/configure-your-web-server/> Happy hacking!
60,099,737
I have a compiled a dataframe that contains USGS streamflow data at several different streamgages. Now I want to create a Gantt chart similar to [this](https://stackoverflow.com/questions/31820578/how-to-plot-stacked-event-duration-gantt-charts-using-python-pandas). Currently, my data has columns as site names and a date index as rows. Here is a sample of my [data](https://drive.google.com/file/d/1KHokKsjAIuCS8lNVRJ9NQJzk0-5q6JYA/view?usp=sharing). The problem with the Gantt chart example I linked is that my data has gaps between the start and end dates that would normally define the horizontal time-lines. Many of the examples I found only account for the start and end date, but not missing values that may be in between. How do I account for the gaps where there is no data (blanks or nan in those slots for values) for some of the sites? First, I have a plot that shows where the missing data is. ``` import missingno as msno msno.bar(dfp) ``` [![Missing Streamflow Gage Data](https://i.stack.imgur.com/obRn8.png)](https://i.stack.imgur.com/obRn8.png) Now, I want time on the x-axis and a horizontal line on the y-axis that tracks when the sites contain data at those times. I know how to do this the brute force way, which would mean manually picking out the start and end dates where there is valid data (which I made up below). ``` from datetime import datetime import pandas as pd import matplotlib.pyplot as plt import matplotlib.dates as dt df=[('RIO GRANDE AT EMBUDO, NM','2015-7-22','2015-12-7'), ('RIO GRANDE AT EMBUDO, NM','2016-1-22','2016-8-5'), ('RIO GRANDE DEL RANCHO NEAR TALPA, NM','2014-12-10','2015-12-14'), ('RIO GRANDE DEL RANCHO NEAR TALPA, NM','2017-1-10','2017-11-25'), ('RIO GRANDE AT OTOWI BRIDGE, NM','2015-8-17','2017-8-21'), ('RIO GRANDE BLW TAOS JUNCTION BRIDGE NEAR TAOS, NM','2015-9-1','2016-6-1'), ('RIO GRANDE NEAR CERRO, NM','2016-1-2','2016-3-15'), ] df=pd.DataFrame(data=df) df.columns = ['A', 'Beg', 'End'] df['Beg'] = pd.to_datetime(df['Beg']) df['End'] = pd.to_datetime(df['End']) fig = plt.figure(figsize=(10,8)) ax = fig.add_subplot(111) ax = ax.xaxis_date() ax = plt.hlines(df['A'], dt.date2num(df['Beg']), dt.date2num(df['End'])) ``` [![enter image description here](https://i.stack.imgur.com/ZvJUV.png)](https://i.stack.imgur.com/ZvJUV.png) How do I make a figure (like the one shown above) with the dataframe I provided as an example? Ideally I want to avoid the brute force method. **Please note:** values of zero are considered valid data points. Thank you in advance for your feedback!
2020/02/06
[ "https://Stackoverflow.com/questions/60099737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10382580/" ]
The reason this is happening is because you have pd.MultiIndex column headers. I can tell you have MultiIndex column headers by tuples in your column names from pd.DataFrame.info() results. See this example below: ``` df = pd.DataFrame(np.random.randint(100,999,(5,5))) #create a dataframe df.columns = pd.MultiIndex.from_arrays([['A','B','C','D','E'],['max','min','max','min','max']]) #create multi index column headers type(df['A'] - df['E']) ``` Output: ``` pandas.core.frame.DataFrame ``` ***Note*** The type of the return even though you are subtracting one column from another column. You expected a pd.Series, but this is returning a dataframe. You have a couple of options to solving this. Option 1 use [`squeeze`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.squeeze.html): ------------------------------------------------------------------------------------------------------------------- ``` type((df['A'] - df['E']).squeeze()) pandas.core.series.Series ``` Option 2 flatten your column headers before: -------------------------------------------- ``` df.columns = df.columns.map('_'.join) type(df['A_max'] - df['E_max']) ``` Output: ``` pandas.core.series.Series ``` Now, you can apply .dt datetime accessor to your series. `type` is important to know the object you are working with.
Well, as @EdChum said above, .dt is a pd.DataFrame attribute, not a pd.Series method. If you want to get the date difference, use the `apply()` pd.Dataframe method.
16,247,002
I have a script using DaemonRunner to create a daemon process with a pid file. The problem is that if someone tried to start it without stopping the currently running process, it will silently fail. What's the best way to detect an existing process and alert the user to stop it first? Is it as easy as checking the pidfile? My code is similar to this example: ``` #!/usr/bin/python import time from daemon import runner class App(): def __init__(self): self.stdin_path = '/dev/null' self.stdout_path = '/dev/tty' self.stderr_path = '/dev/tty' self.pidfile_path = '/tmp/foo.pid' self.pidfile_timeout = 5 def run(self): while True: print("Howdy! Gig'em! Whoop!") time.sleep(10) app = App() daemon_runner = runner.DaemonRunner(app) daemon_runner.do_action() ``` To see my actual code, look at investor.py in: <https://github.com/jgillick/LendingClubAutoInvestor>
2013/04/27
[ "https://Stackoverflow.com/questions/16247002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/629195/" ]
since DaemonRunner handles its own lockfile, it's more wisely to refer to that one, to be sure you can't mess up. Maybe this block can help you with that: Add `from lockfile import LockTimeout` to the beginning of the script and surround `daemon_runner.doaction()` like this ``` try: daemon_runner.do_action() except LockTimeout: print "Error: couldn't aquire lock" #you can exit here or try something else ```
This is the solution that I decided to use: ``` lockfile = runner.make_pidlockfile('/tmp/myapp.pid', 1) if lockfile.is_locked(): print 'It looks like a daemon is already running!' exit() app = App() daemon_runner = runner.DaemonRunner(app) daemon_runner.do_action() ``` Is this a best practice or is there a better way?
7,554,576
i am tryig to execute a sample python program through monkey runner command prompt and it is throwing an error ``` Can't open specified script file Usage: monkeyrunner [options] SCRIPT_FILE -s MonkeyServer IP Address. -p MonkeyServer TCP Port. -v MonkeyServer Logging level (ALL, FINEST, FINER, FINE, CONFIG, INFO, WARNING, SEVERE, OFF) ``` Exception in thread "main" java.lang.NullPointerException so any one can guide me how to resolve this one
2011/09/26
[ "https://Stackoverflow.com/questions/7554576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/946040/" ]
scriptfile should be a full path file name try below `monkeyrunner c:\test_script\first.py`
Under all unix/linux families OS the sha bang syntax can be used. Edit the first line of your script with the results of the following command: ``` which monkeyrunner ``` for example, if monkeyrunner (usually provided with android sdk) has been installed under /usr/local/bin/sdk write: ``` #!/usr/local/bin/sdk/tools/monkeyrunner ``` or even use "env" ``` #!/usr/bin/env monkeyrunner ``` then set you script file as executable ``` chmod +x <script> ``` You can now launch your script from the shell.
7,554,576
i am tryig to execute a sample python program through monkey runner command prompt and it is throwing an error ``` Can't open specified script file Usage: monkeyrunner [options] SCRIPT_FILE -s MonkeyServer IP Address. -p MonkeyServer TCP Port. -v MonkeyServer Logging level (ALL, FINEST, FINER, FINE, CONFIG, INFO, WARNING, SEVERE, OFF) ``` Exception in thread "main" java.lang.NullPointerException so any one can guide me how to resolve this one
2011/09/26
[ "https://Stackoverflow.com/questions/7554576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/946040/" ]
scriptfile should be a full path file name try below `monkeyrunner c:\test_script\first.py`
I met the same things as you did, I resolved by using "monkeyrunner" command under tools, and your script file should be a full path name. It looks like the directory “tools” is the main directory of MonnkeyRunner. I am depressed that I can't run my script files by pydev IDE directly.
7,554,576
i am tryig to execute a sample python program through monkey runner command prompt and it is throwing an error ``` Can't open specified script file Usage: monkeyrunner [options] SCRIPT_FILE -s MonkeyServer IP Address. -p MonkeyServer TCP Port. -v MonkeyServer Logging level (ALL, FINEST, FINER, FINE, CONFIG, INFO, WARNING, SEVERE, OFF) ``` Exception in thread "main" java.lang.NullPointerException so any one can guide me how to resolve this one
2011/09/26
[ "https://Stackoverflow.com/questions/7554576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/946040/" ]
scriptfile should be a full path file name try below `monkeyrunner c:\test_script\first.py`
try using something like ``` ...\tools>monkeyrunner -v ALL first.py ``` where `first.py` was my sample python script which I copied into tools folder of android SDK (the place where `monkeyrunner.bat` is located)
7,554,576
i am tryig to execute a sample python program through monkey runner command prompt and it is throwing an error ``` Can't open specified script file Usage: monkeyrunner [options] SCRIPT_FILE -s MonkeyServer IP Address. -p MonkeyServer TCP Port. -v MonkeyServer Logging level (ALL, FINEST, FINER, FINE, CONFIG, INFO, WARNING, SEVERE, OFF) ``` Exception in thread "main" java.lang.NullPointerException so any one can guide me how to resolve this one
2011/09/26
[ "https://Stackoverflow.com/questions/7554576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/946040/" ]
Under all unix/linux families OS the sha bang syntax can be used. Edit the first line of your script with the results of the following command: ``` which monkeyrunner ``` for example, if monkeyrunner (usually provided with android sdk) has been installed under /usr/local/bin/sdk write: ``` #!/usr/local/bin/sdk/tools/monkeyrunner ``` or even use "env" ``` #!/usr/bin/env monkeyrunner ``` then set you script file as executable ``` chmod +x <script> ``` You can now launch your script from the shell.
monkeyrunner.bat `cygpath -w $(pwd)/monkey.py`
7,554,576
i am tryig to execute a sample python program through monkey runner command prompt and it is throwing an error ``` Can't open specified script file Usage: monkeyrunner [options] SCRIPT_FILE -s MonkeyServer IP Address. -p MonkeyServer TCP Port. -v MonkeyServer Logging level (ALL, FINEST, FINER, FINE, CONFIG, INFO, WARNING, SEVERE, OFF) ``` Exception in thread "main" java.lang.NullPointerException so any one can guide me how to resolve this one
2011/09/26
[ "https://Stackoverflow.com/questions/7554576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/946040/" ]
scriptfile should be a full path file name try below `monkeyrunner c:\test_script\first.py`
monkeyrunner.bat `cygpath -w $(pwd)/monkey.py`
7,554,576
i am tryig to execute a sample python program through monkey runner command prompt and it is throwing an error ``` Can't open specified script file Usage: monkeyrunner [options] SCRIPT_FILE -s MonkeyServer IP Address. -p MonkeyServer TCP Port. -v MonkeyServer Logging level (ALL, FINEST, FINER, FINE, CONFIG, INFO, WARNING, SEVERE, OFF) ``` Exception in thread "main" java.lang.NullPointerException so any one can guide me how to resolve this one
2011/09/26
[ "https://Stackoverflow.com/questions/7554576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/946040/" ]
try using something like ``` ...\tools>monkeyrunner -v ALL first.py ``` where `first.py` was my sample python script which I copied into tools folder of android SDK (the place where `monkeyrunner.bat` is located)
It looks not make sense to switch working directory to Android SDK folder but just for obtain some relative references path for itself. It means you have to specify the full path for your script file and the PNG image files you want to save or compare to. A better way is modify few lines in the "monkeyrunner.bat" under your SDK folder as below. This will use your current path as working directory, so, no necessary to use full path file name. ``` rem don't modify the caller's environment setlocal rem Set up prog to be the path of this script, including following symlinks, rem and set up progdir to be the fully-qualified pathname of its directory. set prog=%~f0 rem Change current directory and drive to where the script is, to avoid rem issues with directories containing whitespaces. rem cd /d %~dp0 rem Check we have a valid Java.exe in the path. set java_exe= call %~sdp0\lib\find_java.bat if not defined java_exe goto :EOF set jarfile=monkeyrunner.jar set frameworkdir= set libdir= if exist %frameworkdir%%jarfile% goto JarFileOk set frameworkdir=%~sdp0\lib\ if exist %frameworkdir%%jarfile% goto JarFileOk set frameworkdir=%~sdp0\..\framework\ :JarFileOk set jarpath=%frameworkdir%%jarfile% if not defined ANDROID_SWT goto QueryArch set swt_path=%ANDROID_SWT% goto SwtDone :QueryArch for /f %%a in ('%java_exe% -jar %frameworkdir%archquery.jar') do set swt_path=%frameworkdir%%%a :SwtDone if exist %swt_path% goto SetPath echo SWT folder '%swt_path%' does not exist. echo Please set ANDROID_SWT to point to the folder containing swt.jar for your platform. exit /B :SetPath call %java_exe% -Xmx512m -Djava.ext.dirs=%frameworkdir%;%swt_path% -Dcom.android.monkeyrunner.bindir=%frameworkdir%\..\..\platform-tools\ -jar %jarpath% %* ```
7,554,576
i am tryig to execute a sample python program through monkey runner command prompt and it is throwing an error ``` Can't open specified script file Usage: monkeyrunner [options] SCRIPT_FILE -s MonkeyServer IP Address. -p MonkeyServer TCP Port. -v MonkeyServer Logging level (ALL, FINEST, FINER, FINE, CONFIG, INFO, WARNING, SEVERE, OFF) ``` Exception in thread "main" java.lang.NullPointerException so any one can guide me how to resolve this one
2011/09/26
[ "https://Stackoverflow.com/questions/7554576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/946040/" ]
Under all unix/linux families OS the sha bang syntax can be used. Edit the first line of your script with the results of the following command: ``` which monkeyrunner ``` for example, if monkeyrunner (usually provided with android sdk) has been installed under /usr/local/bin/sdk write: ``` #!/usr/local/bin/sdk/tools/monkeyrunner ``` or even use "env" ``` #!/usr/bin/env monkeyrunner ``` then set you script file as executable ``` chmod +x <script> ``` You can now launch your script from the shell.
It looks not make sense to switch working directory to Android SDK folder but just for obtain some relative references path for itself. It means you have to specify the full path for your script file and the PNG image files you want to save or compare to. A better way is modify few lines in the "monkeyrunner.bat" under your SDK folder as below. This will use your current path as working directory, so, no necessary to use full path file name. ``` rem don't modify the caller's environment setlocal rem Set up prog to be the path of this script, including following symlinks, rem and set up progdir to be the fully-qualified pathname of its directory. set prog=%~f0 rem Change current directory and drive to where the script is, to avoid rem issues with directories containing whitespaces. rem cd /d %~dp0 rem Check we have a valid Java.exe in the path. set java_exe= call %~sdp0\lib\find_java.bat if not defined java_exe goto :EOF set jarfile=monkeyrunner.jar set frameworkdir= set libdir= if exist %frameworkdir%%jarfile% goto JarFileOk set frameworkdir=%~sdp0\lib\ if exist %frameworkdir%%jarfile% goto JarFileOk set frameworkdir=%~sdp0\..\framework\ :JarFileOk set jarpath=%frameworkdir%%jarfile% if not defined ANDROID_SWT goto QueryArch set swt_path=%ANDROID_SWT% goto SwtDone :QueryArch for /f %%a in ('%java_exe% -jar %frameworkdir%archquery.jar') do set swt_path=%frameworkdir%%%a :SwtDone if exist %swt_path% goto SetPath echo SWT folder '%swt_path%' does not exist. echo Please set ANDROID_SWT to point to the folder containing swt.jar for your platform. exit /B :SetPath call %java_exe% -Xmx512m -Djava.ext.dirs=%frameworkdir%;%swt_path% -Dcom.android.monkeyrunner.bindir=%frameworkdir%\..\..\platform-tools\ -jar %jarpath% %* ```
7,554,576
i am tryig to execute a sample python program through monkey runner command prompt and it is throwing an error ``` Can't open specified script file Usage: monkeyrunner [options] SCRIPT_FILE -s MonkeyServer IP Address. -p MonkeyServer TCP Port. -v MonkeyServer Logging level (ALL, FINEST, FINER, FINE, CONFIG, INFO, WARNING, SEVERE, OFF) ``` Exception in thread "main" java.lang.NullPointerException so any one can guide me how to resolve this one
2011/09/26
[ "https://Stackoverflow.com/questions/7554576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/946040/" ]
Under all unix/linux families OS the sha bang syntax can be used. Edit the first line of your script with the results of the following command: ``` which monkeyrunner ``` for example, if monkeyrunner (usually provided with android sdk) has been installed under /usr/local/bin/sdk write: ``` #!/usr/local/bin/sdk/tools/monkeyrunner ``` or even use "env" ``` #!/usr/bin/env monkeyrunner ``` then set you script file as executable ``` chmod +x <script> ``` You can now launch your script from the shell.
I met the same things as you did, I resolved by using "monkeyrunner" command under tools, and your script file should be a full path name. It looks like the directory “tools” is the main directory of MonnkeyRunner. I am depressed that I can't run my script files by pydev IDE directly.
7,554,576
i am tryig to execute a sample python program through monkey runner command prompt and it is throwing an error ``` Can't open specified script file Usage: monkeyrunner [options] SCRIPT_FILE -s MonkeyServer IP Address. -p MonkeyServer TCP Port. -v MonkeyServer Logging level (ALL, FINEST, FINER, FINE, CONFIG, INFO, WARNING, SEVERE, OFF) ``` Exception in thread "main" java.lang.NullPointerException so any one can guide me how to resolve this one
2011/09/26
[ "https://Stackoverflow.com/questions/7554576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/946040/" ]
try using something like ``` ...\tools>monkeyrunner -v ALL first.py ``` where `first.py` was my sample python script which I copied into tools folder of android SDK (the place where `monkeyrunner.bat` is located)
I met the same things as you did, I resolved by using "monkeyrunner" command under tools, and your script file should be a full path name. It looks like the directory “tools” is the main directory of MonnkeyRunner. I am depressed that I can't run my script files by pydev IDE directly.
7,554,576
i am tryig to execute a sample python program through monkey runner command prompt and it is throwing an error ``` Can't open specified script file Usage: monkeyrunner [options] SCRIPT_FILE -s MonkeyServer IP Address. -p MonkeyServer TCP Port. -v MonkeyServer Logging level (ALL, FINEST, FINER, FINE, CONFIG, INFO, WARNING, SEVERE, OFF) ``` Exception in thread "main" java.lang.NullPointerException so any one can guide me how to resolve this one
2011/09/26
[ "https://Stackoverflow.com/questions/7554576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/946040/" ]
scriptfile should be a full path file name try below `monkeyrunner c:\test_script\first.py`
It looks not make sense to switch working directory to Android SDK folder but just for obtain some relative references path for itself. It means you have to specify the full path for your script file and the PNG image files you want to save or compare to. A better way is modify few lines in the "monkeyrunner.bat" under your SDK folder as below. This will use your current path as working directory, so, no necessary to use full path file name. ``` rem don't modify the caller's environment setlocal rem Set up prog to be the path of this script, including following symlinks, rem and set up progdir to be the fully-qualified pathname of its directory. set prog=%~f0 rem Change current directory and drive to where the script is, to avoid rem issues with directories containing whitespaces. rem cd /d %~dp0 rem Check we have a valid Java.exe in the path. set java_exe= call %~sdp0\lib\find_java.bat if not defined java_exe goto :EOF set jarfile=monkeyrunner.jar set frameworkdir= set libdir= if exist %frameworkdir%%jarfile% goto JarFileOk set frameworkdir=%~sdp0\lib\ if exist %frameworkdir%%jarfile% goto JarFileOk set frameworkdir=%~sdp0\..\framework\ :JarFileOk set jarpath=%frameworkdir%%jarfile% if not defined ANDROID_SWT goto QueryArch set swt_path=%ANDROID_SWT% goto SwtDone :QueryArch for /f %%a in ('%java_exe% -jar %frameworkdir%archquery.jar') do set swt_path=%frameworkdir%%%a :SwtDone if exist %swt_path% goto SetPath echo SWT folder '%swt_path%' does not exist. echo Please set ANDROID_SWT to point to the folder containing swt.jar for your platform. exit /B :SetPath call %java_exe% -Xmx512m -Djava.ext.dirs=%frameworkdir%;%swt_path% -Dcom.android.monkeyrunner.bindir=%frameworkdir%\..\..\platform-tools\ -jar %jarpath% %* ```
21,302,971
I initially had `python 2.7.3` i downloaded from the sourcee and did `make install` and after downloading i run `python` but again my system is showing `2.7.3` I didn't get any error while installing
2014/01/23
[ "https://Stackoverflow.com/questions/21302971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3113427/" ]
Since you are on Ubuntu, I recommend following the steps outlined [here](http://heliumhq.com/docs/installing_python_2.7.5_on_ubuntu) to install a new Python version. The steps there are for Python 2.7.5 but should be equally applicable to Python 2.7.6.
The version you installed is probably in /usr/local/bin/python . Try calling it with the complete path. You may want to change your path settings or remove the previously installed version using your package manager if it was installed by the system.
59,987,601
Good morning! I am trying to remove duplicate rows from a csv file with panda. I have 2 files, A.csv and B.csv I want to delete all rows in A that exist in B. File A.csv: ``` Pedro,10,rojo Mirta,15,azul Jose,5,violeta ``` File B.csv: ``` Pedro, ignacio, fernando, federico, ``` Output file output.csv: ``` Mirta,15,azul Jose,5,violeta ``` try to join the files and then apply ``` cat A.csv B.csv > output.csv ``` and run this program in python: ``` import pandas as pd df = pd.read_csv('output.csv') df.drop_duplicates(inplace=True) df.to_csv('final.csv', index=False) ```
2020/01/30
[ "https://Stackoverflow.com/questions/59987601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12814128/" ]
Search based on Many-to-Many Relationship ========================================= Talking about articles and authors, when each article may have many authors, let's say you are going to search based on a `term` and find *Articles where the article name or article abstract contains the term or one of the authors of the article have the term in their first name or their last name.* **EF 6 - Many-To-May without entity class for Relationship** You can handle these cases in a Linq query using `Any`, the same way that you can handle in a SQL query using `EXISTS`: ``` Where(article=> article.Title.Contains(term) || article.Abstract.Contains(term) || article.Authors.Any(author => author.FirstName.Contains(term) || author.LastName.Contains(searchTerm))) ``` It doesn't exactly generate the following SQL Query, but the logic is quite similar to having the following in SQL: ``` FROM Articles WHERE (Articles.Title LIKE '%' + @Term + '%') OR (Articles.Abstract LIKE '%' + @Term + '%') OR EXISTS (SELECT * FROM Authors WHERE (Authors.FirstName LIKE '%' + @Term + '%') OR (Authors.LastName LIKE '%' + @Term + '%')) ``` **EF CORE - Many-To-May with entity class for Relationship** At the moment, Many-to-Many relationships without an entity class to represent the join table are not yet supported. You can handle these cases in a Linq query using `Any`, the same way that you can handle in a SQL query using `EXISTS` + `Join`: ``` .Where(article => article.Title.Contains(model.SearchTerm) || article.Abstract.Contains(model.SearchTerm) || article.ArticlesAuthors.Any(au => (au.Author.FirstName).Contains(model.SearchTerm) || (au.Author.LastName).Contains(model.SearchTerm))) ``` It doesn't exactly generate the following SQL Query, but the logic is quite similar to having the following in SQL: ``` FROM Articles WHERE (Articles.Title LIKE '%' + @Term + '%') OR (Articles.Abstract LIKE '%' + @Term + '%') OR EXISTS (SELECT * FROM ArticlesAuthors INNER JOIN Authors ON ArticlesAuthors.AuthorId = Authors.Id WHERE ((Authors.FirstName LIKE '%' + @Term + '%') OR (Authors.LastName LIKE '%'+ @Term + '%')) AND (Articles.Id = ArticlesAuthors.ArticleId)) ``` EF 6 - Example ============== The question is a bit cluttered including search sort and a lot of code and needs more focus. To make it more useful and more understandable for you and feature readers, I'll use a simpler model with fewer properties and easier to understand. As you can see in the EF diagram, the `ArticlesAuthors` table has not been shown in diagram because it's a many-to-many relationship containing just Id columns of other entities without any extra fields [![enter image description here](https://i.stack.imgur.com/kXiXd.png)](https://i.stack.imgur.com/kXiXd.png) ### Search Logic We want to find articles based on a `SerachTerm`, `PublishDateFrom` and `PublishDateTo`: * If the title or abstract of article contains the term, article should be part of the result. * If the combination of first name and last name of an author of the article contains the term, article should be part of the result. * If the publish date is greater than or equal to `PublishDateFrom`, article should be part of the result, also if the publish date is less than or equal to `PublishDateTo`, article should be part of the result. Here is a model for search: ``` public class ArticlesSearchModel { public string SearchTerm { get; set; } public DateTime? PublishDateFrom { get; set; } public DateTime? PublishDateTo { get; set; } } ``` Here is the code for search: > > Please note: `Inculde` doesn't have anything to do with search and > it's just for including the the related entities in output result. > > > ``` public class ArticlesBusinessLogic { public IEnumerable<Article> Search(ArticlesSearchModel model) { using (var db = new ArticlesDBEntities()) { var result = db.Articles.Include(x => x.Authors).AsQueryable(); if (model == null) return result.ToList(); if (!string.IsNullOrEmpty(model.SearchTerm)) result = result.Where(article => ( article.Title.Contains(model.SearchTerm) || article.Abstract.Contains(model.SearchTerm) || article.Authors.Any(author => (author.FirstName + " " + author.LastName).Contains(model.SearchTerm)) )); if (model.PublishDateFrom.HasValue) result = result.Where(x => x.PublishDate >= model.PublishDateFrom); if (model.PublishDateFrom.HasValue) result = result.Where(x => x.PublishDate <= model.PublishDateTo); return result.ToList(); } } } ``` EF CORE - Example ================= As I mentioned above, at the moment, Many-to-Many relationships without an entity class to represent the join table are not yet supported, so the model using EF CORE will be: [![enter image description here](https://i.stack.imgur.com/oUwmZ.png)](https://i.stack.imgur.com/oUwmZ.png) Here is the code for search: > > Please note: `Inculde` doesn't have anything to do with search and > it's just for including the the related entities in output result. > > > ``` public IEnumerable<Article> Search(ArticlesSearchModel model) { using (var db = new ArticlesDbContext()) { var result = db.Articles.Include(x=>x.ArticleAuthor) .ThenInclude(x=>x.Author) .AsQueryable(); if (model == null) return result; if (!string.IsNullOrEmpty(model.SearchTerm)) { result = result.Where(article => ( article.Title.Contains(model.SearchTerm) || article.Abstract.Contains(model.SearchTerm) || article.ArticleAuthor.Any(au => (au.Author.FirstName + " " + au.Author.LastName) .Contains(model.SearchTerm)) )); } if (model.PublishDateFrom.HasValue) { result = result.Where(x => x.PublishDate >= model.PublishDateFrom); } if (model.PublishDateFrom.HasValue) { result = result.Where(x => x.PublishDate <= model.PublishDateTo); } return result.ToList(); } } ```
You are doing a lot of things wrong : 1. you can not use `.ToString()` on classes or lists. so first you have to remove or change these lines. for example : ```cs sort = sort.Where(s => OfficerIDs.ToString().Contains(searchString)); sort = sort.OrderBy(s => officerList.ToString()).ThenBy(s => s.EventDate); sort = sort.OrderByDescending(s => officerList.ToString()).ThenBy(s => s.EventDate); ``` 2. you are almost loading the entire data from your database tables every time your page loads or your search or sorting changed. Of course, having paging makes this problem a little fuzzy here 3. you are not using entity framework to load your relational data so you can not write a query that loads what you need or what user searched for. (you are fetching data from the database on separate parts) --- I know this is not what you looking for but honestly, I tried to answer your question and help you solved the problem but I ended up rewriting whole things again ... you should break your problem into smaller pieces and ask a more conceptual question.
3,870,312
I am trying to solve problem related to model inheritance in Django. I have four relevant models: `Order`, `OrderItem` which has ForeignKey to `Order` and then there is `Orderable` model which is model inheritance superclass to children models like `Fee`, `RentedProduct` etc. In python, it goes like this (posting only relevant parts): ``` class Orderable(models.Model): real_content_type = models.ForeignKey(ContentType, editable=False) objects = OrderableManager() available_types = [] def save(self, *args, **kwargs): """ Saves instance and stores information about concrete class. """ self.real_content_type = ContentType.objects.get_for_model(type(self)) super(Orderable, self).save(*args, **kwargs) def cast(self): """ Casts instance to the most concrete class in inheritance hierarchy possible. """ return self.real_content_type.get_object_for_this_type(pk=self.pk) @staticmethod def register_type(type): Orderable.available_types.append(type) @staticmethod def get_types(): return Orderable.available_types class RentedProduct(Orderable): """ Represent a product which is rented to be part of an order """ start_at = models.ForeignKey(Storage, related_name='starting_products', verbose_name=_('Start at')) real_start_at = models.ForeignKey(Storage, null=True, related_name='real_starting_products', verbose_name=_('Real start at')) finish_at = models.ForeignKey(Storage, related_name='finishing_products', verbose_name=_('Finish at')) real_finish_at = models.ForeignKey(Storage, null=True, related_name='real_finishing_products', verbose_name=_('Real finish at')) target = models.ForeignKey(Product, verbose_name=_('Product')) Orderable.register_type(RentedProduct) class OrderItem(BaseItem): unit_price = models.DecimalField(max_digits=8, decimal_places=2, verbose_name=_('Unit price')) count = models.PositiveIntegerField(default=0, verbose_name=_('Count')) order = models.ForeignKey('Order', related_name='items', verbose_name=_('Order')) discounts = models.ManyToManyField(DiscountDescription, related_name='order_items', through=OrderItemDiscounts, blank=True, verbose_name=_('Discounts')) target = models.ForeignKey(Orderable, related_name='ordered_items', verbose_name=_('Target')) class Meta: unique_together = ('order', 'target') ``` I would like to have an inline tied to Order model to enable editing OrderItems. Problem is, that the target field in OrderItem points to Orderable (not the concrete class which one can get by calling Orderable's `cast` method) and the form in inline is therefore not complete. Does anyone have an idea, how to create at least a bit user-friendly interface for this? Can it be solved by Django admin inlines only, or you would suggest creating special user interface? Thanks in advance for any tips.
2010/10/06
[ "https://Stackoverflow.com/questions/3870312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/303184/" ]
Try inherit OrderItemInlineAdmin's Form a define your own Form there. But fingers crossed for that.
I'm looking for a solid answer to this very thing, but you should check out FeinCMS. They are doing this quite well. See, for example, the FeinCMS [inline editor](https://github.com/matthiask/feincms/blob/master/feincms/admin/item_editor.py). I need to figure out how to adapt this to my code.
34,910,115
I'd like to make this more efficient but I can't figure out how to turn this into a python list comprehension. ``` coupons = [] for source in sources: for coupon in source: if coupon.code_used not in coupons: coupons.append(coupon.code_used) ```
2016/01/20
[ "https://Stackoverflow.com/questions/34910115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3977548/" ]
You cannot access the list you currently creating, but if the order is not important you can use a `set`: ``` coupons = set(coupon.code_used for source in sources for coupon in source) ```
``` used_codes = set(coupon.code_used for source in sources for coupon in source) ```
34,910,115
I'd like to make this more efficient but I can't figure out how to turn this into a python list comprehension. ``` coupons = [] for source in sources: for coupon in source: if coupon.code_used not in coupons: coupons.append(coupon.code_used) ```
2016/01/20
[ "https://Stackoverflow.com/questions/34910115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3977548/" ]
``` used_codes = set(coupon.code_used for source in sources for coupon in source) ```
I'm going to assume that the order of the resulting list is unimportant, because then we can just use a set to eliminate duplicates. ``` coupons = list(set(coupon.code_used for source in sources for coupon in source)) ``` This uses a generator expression, with the `for` clauses appearing in the same order as in the nested loop, to extract all the codes. The `set` keeps only unique codes, and `list` creates a list (arbitrarily ordered) from the set.
34,910,115
I'd like to make this more efficient but I can't figure out how to turn this into a python list comprehension. ``` coupons = [] for source in sources: for coupon in source: if coupon.code_used not in coupons: coupons.append(coupon.code_used) ```
2016/01/20
[ "https://Stackoverflow.com/questions/34910115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3977548/" ]
``` used_codes = set(coupon.code_used for source in sources for coupon in source) ```
``` coupons = {x for x in (y.code_used for y in coupon for coupon in sources)} ``` you are actually looking for a `set`
34,910,115
I'd like to make this more efficient but I can't figure out how to turn this into a python list comprehension. ``` coupons = [] for source in sources: for coupon in source: if coupon.code_used not in coupons: coupons.append(coupon.code_used) ```
2016/01/20
[ "https://Stackoverflow.com/questions/34910115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3977548/" ]
You cannot access the list you currently creating, but if the order is not important you can use a `set`: ``` coupons = set(coupon.code_used for source in sources for coupon in source) ```
I'm going to assume that the order of the resulting list is unimportant, because then we can just use a set to eliminate duplicates. ``` coupons = list(set(coupon.code_used for source in sources for coupon in source)) ``` This uses a generator expression, with the `for` clauses appearing in the same order as in the nested loop, to extract all the codes. The `set` keeps only unique codes, and `list` creates a list (arbitrarily ordered) from the set.
34,910,115
I'd like to make this more efficient but I can't figure out how to turn this into a python list comprehension. ``` coupons = [] for source in sources: for coupon in source: if coupon.code_used not in coupons: coupons.append(coupon.code_used) ```
2016/01/20
[ "https://Stackoverflow.com/questions/34910115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3977548/" ]
You cannot access the list you currently creating, but if the order is not important you can use a `set`: ``` coupons = set(coupon.code_used for source in sources for coupon in source) ```
``` coupons = {x for x in (y.code_used for y in coupon for coupon in sources)} ``` you are actually looking for a `set`
34,910,115
I'd like to make this more efficient but I can't figure out how to turn this into a python list comprehension. ``` coupons = [] for source in sources: for coupon in source: if coupon.code_used not in coupons: coupons.append(coupon.code_used) ```
2016/01/20
[ "https://Stackoverflow.com/questions/34910115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3977548/" ]
I'm going to assume that the order of the resulting list is unimportant, because then we can just use a set to eliminate duplicates. ``` coupons = list(set(coupon.code_used for source in sources for coupon in source)) ``` This uses a generator expression, with the `for` clauses appearing in the same order as in the nested loop, to extract all the codes. The `set` keeps only unique codes, and `list` creates a list (arbitrarily ordered) from the set.
``` coupons = {x for x in (y.code_used for y in coupon for coupon in sources)} ``` you are actually looking for a `set`
40,674,526
I'm having trouble deploying my app to heroku, I'm using the heroku\_deploy.sh from documentation and get ``` Deploying Heroku Version 82d8ec66d98120ae24c89b88dc75e4d1c225461e Traceback (most recent call last): File "<string>", line 1, in <module> KeyError: 'source_blob' Traceback (most recent call last): File "<string>", line 1, in <module> KeyError: 'source_blob' curl: no URL specified! curl: try 'curl --help' or 'curl --manual' for more information Traceback (most recent call last): File "<string>", line 1, in <module> KeyError: 'output_stream_url' curl: try 'curl --help' or 'curl --manual' for more information ``` I'm using a custom docker image, but It has python on it, anything else I should make sure exists?
2016/11/18
[ "https://Stackoverflow.com/questions/40674526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/67505/" ]
If you want to destroy the window when its closed just specifiy ``` closeAction : 'destroy' ``` instead of ``` closeAction : 'hide' ``` If doing so ExtJS destroys, and thus removes, all items completely. Additional, if specifying `destroy` as close action you will not need the additional listener (`onCardLayoutWindowBeforeHide`) to remove all items. If you create the window again it will be build from scratch (see [Sencha Fiddle](https://fiddle.sencha.com/#view/editor&fiddle/1knk)).
### Thanks to oberbics and Evan Trimboli I solve the problem, just because I assign a rownumberer like this: > > new Ext.grid.RowNumberer({width: 40}), > > > however, when I replace it with xtype config, it works well. > > {xtype: 'rownumberer'} > > > ``` Ext.define('MyWebServer.view.qualityassign.AllocateStrategy',{ extend : 'Ext.panel.Panel', xtype : 'allocate-strategy', layout : 'fit', requires: [ 'Ext.grid.column.Action', 'Ext.ProgressBarWidget', 'Ext.slider.Widget' ], reference : 'allocatestrategypanel', controller : 'allocatestrategy', viewModel : { data : { } }, listeners : { beforerender : 'onAllocateStrategyPanelBeforeRender', scope : 'controller' }, header : { xtype : 'container', html : '<p>Step 4 of 4 Choose allocate strategy</p>' }, initComponent : function() { var me = this; me.items = this.createItems(); me.callParent(); }, createItems : function() { var me = this; return [{ xtype : 'grid', reference : 'allocatestrategygrid', frame : true, viewConfig : { loadMask: true }, store : { type : 'allocate' }, dockedItems : [{ xtype : 'toolbar', dock : 'bottom', items : [{ xtype : 'toolbar', itemId : 'allocatestrategygrid-topbar', dock : 'top', items : [{ xtype : 'combo', reference : 'selectgroupcombo', fieldLabel : 'qualityinspectorgrp', labelWidth : 30, editable : false, triggerAction : 'all', valueField : 'sGroupGuid', displayField : 'sGroupName', forceSelection : true, store : { type : 'selectgroup' }, listeners : { select : 'onSelectGroupComboSelect', scope : 'controller' } }] }], columns : { xtype : 'gridcolumn', defaults: { align : 'center', width : 100, menuDisabled: true }, items : [ **new Ext.grid.RowNumberer({width: 40}),** { text : 'agentId', dataIndex : 'qualInspId' }, { text : 'agentName', dataIndex : 'qualInspName' }, { text : 'percent', xtype : 'widgetcolumn', width : 120, widget : { bind : '{record.percent}', xtype : 'progressbarwidget', textTpl: [ '{percent:number("0")}%' ] } }, { text : '', xtype : 'widgetcolumn', width : 120, widget : { xtype : 'numberfield', editable : false, bind : '{record.percent}', maxValue : 0.99, minValue : 0, step : 0.01, maxLength : 4, minLength : 1, autoFitErrors: false } }, { text : '', xtype : 'widgetcolumn', width : 120, flex : 1, widget : { xtype : 'sliderwidget', minValue : 0, maxValue : 1, bind : '{record.percent}', publishOnComplete : false, decimalPrecision : 2 } } ] } }]; } ```
5,445,166
I am developing a 3d shooter game that I would like to run on Computers/Phones/Tablets and would like some help to choose which engine to use. * I would like to write the application once and port it over to Android/iOS/windows/mac with ease. * I would like to make the application streamable over the internet. * The engine needs some physics(collision detection) as well as 3d rendering capabilities * I would prefer to use a scripting language such as Javascript or Python to Java or C++(although I would be willing to learn these if it is the best option) -My desire is to use an engine that is Code-based and not GUI-based, an engine that is more like a library which I can import into my Python files(for instance) than an application which forces me to rely on its GUI to import assets and establish relationships between them. > > > > > > > > > > > > This desire stems from my recent experience with Unity3d and Blender. The way I had designed my code required me to write dozens of disorganized scripts to control various objects. I cannot help but think that if I had written my program in a series of python files that I would be able to do a neater, faster job. > > > > > > > > > > > > > > > > > > I'd appreciate any suggestions. The closest thing to what I want is Panda3d, but I had a difficult time working with textures, and I am not convinced that my application can be made easily available to mobile phone/device users. If there is a similar option that you can think about, I'd appreciate the tip.
2011/03/26
[ "https://Stackoverflow.com/questions/5445166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/509895/" ]
You've mentioned iOS -- that pretty much limits you to going native or using web stack. Since native is not what you want (because that'd be different for each platform you mention), you can go JavaScript. The ideal thing for that would be WebGL, but support is still experimental and not available in phone systems. You can still use one of JS libraries built on top of 2D `<canvas>`. You can't expect great performance from that though. You can find examples here: <http://www.javascriptgaming.com/>
Well I see you've checked Unity3D already, but I can't think of any other engines work on PC, Telephones and via streaming internet that suport 3D (for 2D check EXEN or any others). I'm also pretty sure that you can use Unity code-based, and it supports a couple of different languages, but for Unity to work you can't just import unity.dll (for example) into your code, no you have to use your code into unity so that unity can make it work on all these different platforms.
5,445,166
I am developing a 3d shooter game that I would like to run on Computers/Phones/Tablets and would like some help to choose which engine to use. * I would like to write the application once and port it over to Android/iOS/windows/mac with ease. * I would like to make the application streamable over the internet. * The engine needs some physics(collision detection) as well as 3d rendering capabilities * I would prefer to use a scripting language such as Javascript or Python to Java or C++(although I would be willing to learn these if it is the best option) -My desire is to use an engine that is Code-based and not GUI-based, an engine that is more like a library which I can import into my Python files(for instance) than an application which forces me to rely on its GUI to import assets and establish relationships between them. > > > > > > > > > > > > This desire stems from my recent experience with Unity3d and Blender. The way I had designed my code required me to write dozens of disorganized scripts to control various objects. I cannot help but think that if I had written my program in a series of python files that I would be able to do a neater, faster job. > > > > > > > > > > > > > > > > > > I'd appreciate any suggestions. The closest thing to what I want is Panda3d, but I had a difficult time working with textures, and I am not convinced that my application can be made easily available to mobile phone/device users. If there is a similar option that you can think about, I'd appreciate the tip.
2011/03/26
[ "https://Stackoverflow.com/questions/5445166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/509895/" ]
For the requirements that you have Unity3d is probably one of your best bets. As roy said there aren't any other 3D engines out there that will span that wide a range of platforms. Why do you think that going to a completely code based system would save you from creating a variety of classes with various responsibilities ? The coding effort and the amount of code and classes will stay the same. The only thing that does change is the way that you interact with the system that you are producing. With any large scale system you will quickly run into hundreds of files. I am just finishing up a smaller sized unity project 3-4 month coding including learning unity it runs at 10k lines of code plus another 8k from external libraries and over 100 classes. But this amount wasn't driven by how unity works it was driven by the requirements of the project. While coding this I have learned a lot about how unity runs and what kind of patterns it requires and will be able to come up with better solutions for the next project. Look back at what you did and think about how you can organize it better. I think it is a save bet to say that you will need about the same amount of code with any other system to achieve a similar result. The advantages that unity does have are a good multiplattform support and a excellent asset pipeline. Importing and utilising art assets, 2D, 3D and audio is for me one of the most onerous tasks of this kind of development and it is extremely well supported in unity.
Well I see you've checked Unity3D already, but I can't think of any other engines work on PC, Telephones and via streaming internet that suport 3D (for 2D check EXEN or any others). I'm also pretty sure that you can use Unity code-based, and it supports a couple of different languages, but for Unity to work you can't just import unity.dll (for example) into your code, no you have to use your code into unity so that unity can make it work on all these different platforms.
5,445,166
I am developing a 3d shooter game that I would like to run on Computers/Phones/Tablets and would like some help to choose which engine to use. * I would like to write the application once and port it over to Android/iOS/windows/mac with ease. * I would like to make the application streamable over the internet. * The engine needs some physics(collision detection) as well as 3d rendering capabilities * I would prefer to use a scripting language such as Javascript or Python to Java or C++(although I would be willing to learn these if it is the best option) -My desire is to use an engine that is Code-based and not GUI-based, an engine that is more like a library which I can import into my Python files(for instance) than an application which forces me to rely on its GUI to import assets and establish relationships between them. > > > > > > > > > > > > This desire stems from my recent experience with Unity3d and Blender. The way I had designed my code required me to write dozens of disorganized scripts to control various objects. I cannot help but think that if I had written my program in a series of python files that I would be able to do a neater, faster job. > > > > > > > > > > > > > > > > > > I'd appreciate any suggestions. The closest thing to what I want is Panda3d, but I had a difficult time working with textures, and I am not convinced that my application can be made easily available to mobile phone/device users. If there is a similar option that you can think about, I'd appreciate the tip.
2011/03/26
[ "https://Stackoverflow.com/questions/5445166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/509895/" ]
For the requirements that you have Unity3d is probably one of your best bets. As roy said there aren't any other 3D engines out there that will span that wide a range of platforms. Why do you think that going to a completely code based system would save you from creating a variety of classes with various responsibilities ? The coding effort and the amount of code and classes will stay the same. The only thing that does change is the way that you interact with the system that you are producing. With any large scale system you will quickly run into hundreds of files. I am just finishing up a smaller sized unity project 3-4 month coding including learning unity it runs at 10k lines of code plus another 8k from external libraries and over 100 classes. But this amount wasn't driven by how unity works it was driven by the requirements of the project. While coding this I have learned a lot about how unity runs and what kind of patterns it requires and will be able to come up with better solutions for the next project. Look back at what you did and think about how you can organize it better. I think it is a save bet to say that you will need about the same amount of code with any other system to achieve a similar result. The advantages that unity does have are a good multiplattform support and a excellent asset pipeline. Importing and utilising art assets, 2D, 3D and audio is for me one of the most onerous tasks of this kind of development and it is extremely well supported in unity.
You've mentioned iOS -- that pretty much limits you to going native or using web stack. Since native is not what you want (because that'd be different for each platform you mention), you can go JavaScript. The ideal thing for that would be WebGL, but support is still experimental and not available in phone systems. You can still use one of JS libraries built on top of 2D `<canvas>`. You can't expect great performance from that though. You can find examples here: <http://www.javascriptgaming.com/>
34,755,636
I am trying to show time series lines representing an effort amount using matplotlib and pandas. I've got my DF's to all to overlay in one plot, however when I do python seems to strip the x axis of the date and input some numbers. (I'm not sure where these come from but at a guess, not all days contain the same data so python has reverted to using an index id number). If I plot any one of these they come up with date on the x-axis. Any hints or solutions to make the x axis show date for the multiple plot would be much appreciated. This is the single figure plot with time axis: [![single figure plot with time axis](https://i.stack.imgur.com/P954I.png)](https://i.stack.imgur.com/P954I.png) Code I'm using to plot is ``` fig = pl.figure() ax = fig.add_subplot(111) ax.plot(b342,color='black') ax.plot(b343,color='blue') ax.plot(b344,color='red') ax.plot(b345,color='green') ax.plot(b346,color='pink') ax.plot(fi,color='yellow') plt.show() ``` This is the multiple plot fig with weird x axis: [![multiple plots without time axis](https://i.stack.imgur.com/kqLwz.png)](https://i.stack.imgur.com/kqLwz.png)
2016/01/12
[ "https://Stackoverflow.com/questions/34755636", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3509416/" ]
When you use `getClass().getResource(...)` you are loading a resource, not specifying a path to a file. In the case where the class loader loads classes from the file system, these essentially equate to the same thing, and it does actually work (though even then there's no technical reason it has to). When the class loader is loading classes by other mechanisms (and probably in all cases anyway), then it's important to pay attention to the Java [specifications for a resource](https://docs.oracle.com/javase/8/docs/technotes/guides/lang/resources.html). In particular, note: > > **Resources, names, and contexts** > > > A resource is identified by a string consisting of a sequence of > substrings, delimited by slashes (/), followed by a resource name. > ***Each substring must be a valid Java identifier.*** The resource name is of the form shortName or shortName.extension. Both shortName > and extension must be Java identifiers. > > > (My emphasis.) Since `..` is not a valid Java identifier, there's no guarantee of this resource being resolvable. It happens that the file system class loader resolves this in the way you expect, which is why it works in your IDE, but the implementation of `getResource(...)` in the jar class loader does not implement this in the way you are hoping. Try ``` FXMLLoader loader = new FXMLLoader(getClass().getResource("/sm/customer/CustomerHome.fxml")); ``` --- Using controller locations to load FXML: ---------------------------------------- Since you have organized your code so that each FXML is in the same package as its corresponding controller file (which I think is a sensible way to do things), you could also leverage this in loading the FXML: just load the FXML "relative to its controller": ``` FXMLLoader loader = new FXMLLoader(CustomerHomeCtrl.class.getResource("CustomerHome.fxml")); ``` This seems fairly natural in this setup, and the compiler will check that you have the package name for `CustomerHomeCtrl` correct at the point where you import the class. It also makes it easy to refactor: for example suppose you wanted to split `sm.admin` into multiple subpackages. In Eclipse you would create the subpackages, drag and drop the FXML and controllers to the appropriate subpackages, and the import statements would automatically be updated: there would be no further changes needed. In the case where the path is specified in the `getResource(...)`, all those would have to be changed by hand.
A bit late but this can maybe help someone. If you are using IntelliJ, your `resources` folder may not be marked as THE resources folder, which has the following icon: [![enter image description here](https://i.stack.imgur.com/LWBaw.png)](https://i.stack.imgur.com/LWBaw.png) This is the way I fixed it: [![enter image description here](https://i.stack.imgur.com/OdqfM.png)](https://i.stack.imgur.com/OdqfM.png)
14,722,788
I'm the author of [doctest](https://github.com/davidchambers/doctest), quick and dirty [doctests](http://docs.python.org/2/library/doctest.html) for JavaScript and CoffeeScript. I'd like to make the library less dirty by using a JavaScript parser rather than regular expressions to locate comments. I'd like to use [Esprima](http://esprima.org/) or [Acorn](https://github.com/marijnh/acorn) to do the following: 1. Create an AST 2. Walk the tree, and for each comment node: 1. Create an AST from the comment node's text 2. Replace the comment node in the main tree with this subtree **Input:** ``` !function() { // > toUsername("Jesper Nøhr") // "jespernhr" var toUsername = function(text) { return ('' + text).replace(/\W/g, '').toLowerCase() } }() ``` **Output:** ``` !function() { doctest.input(function() { return toUsername("Jesper Nøhr") }); doctest.output(4, function() { return "jespernhr" }); var toUsername = function(text) { return ('' + text).replace(/\W/g, '').toLowerCase() } }() ``` I don't know how to do this. Acorn provides a [walker](https://github.com/marijnh/acorn/blob/master/util/walk.js) which takes a node type and a function, and walks the tree invoking the function each time a node of the specified type is encountered. This seems promising, but doesn't apply to comments. With Esprima I can use `esprima.parse(input, {comment: true, loc: true}).comments` to get the comments, but I'm not sure how to update the tree.
2013/02/06
[ "https://Stackoverflow.com/questions/14722788", "https://Stackoverflow.com", "https://Stackoverflow.com/users/312785/" ]
Most AST-producing parsers throw away comments. I don't know what Esprima or Acorn do, but that might be the issue. .... in fact, Esprima lists comment capture as a current bug: <http://code.google.com/p/esprima/issues/detail?id=197> ... Acorn's code is right there in GitHub. It appears to throw comments away, too. So, looks like you get to fix either parser to capture the comments first, at which point your task should be straightforward, or, you're stuck. Our DMS Software Reengineering Toolkit has JavaScript parsers that capture comments, in the tree. It also has language *substring* parsers, that could be used to parse the comment text into JavaScript ASTs of whatever type the comment represents (e.g, function declaration, expression, variable declaration, ...), and the support machinery to graft such new ASTs into the main tree. If you are going to manipulate ASTs, this substring capability is likely important: most parsers won't parse arbitrary language fragments, they are wired only to parse "whole programs". For DMS, there are no comment nodes to replace; there are comments associated with ASTs nodes, so the grafting process is a little trickier than just "replace comment nodes". Still pretty easy. I'll observe that most parsers (including these) read the source and break it into tokens by using or applying the equivalent of a regular expressions. So, if you are already using these to locate comments (that means using them to locate \*non\*comments to throw away, as well, e.g., you need to recognize string literals that contain comment-like text and ignore them), you are doing as well as the parsers would do anyway in terms of *finding* the comments. And if all you want to do is to replace them exactly with their content, echoing the source stream with the comment prefix/suffix /\* \*/ stripped will do apparantly exactly what you want, so all this parsing machinery seems like overkill.
You can already use Esprima to achieve what you want: 1. Parse the code, get the comments (as an array). 2. Iterate over the comments, see if each is what you are interested in. 3. If you need to transform the comment, note its range. Collect all transformations. 4. Apply the transformation back-to-first so that the ranges are not shifted. The trick is here not change the AST. Simply apply the text change as if you are doing a typical search replace on the source string directly. Because the position of the replacement might shift, you need to collect everything and then do it from the last one. For an example on how to carry out such a transformation, take a look at my blog post ["From double-quotes to single-quotes"](http://ariya.ofilabs.com/2012/02/from-double-quotes-to-single-quotes.html) (it deals with string quotes but the principle remains the same). Last but not least, you might want to use a slightly higher-level utility such as [Rocambole](https://github.com/millermedeiros/rocambole).
48,548,878
I'm running Django 1.11 with Python 3.4 on Ubuntu 14.04.5 Moving my development code to the test server and running into some strange errors. Can anyone see what is wrong from the traceback? I'm very new to linux and have made the mistake of developing on a Windows machine on this first go around. I have since created a virtualbox copy of the test and production servers to develop on, but I'm hoping I can salvage what's up on the test server now. I think my app is looking in the correct directory for this environment, but I am a Django, Python and linux noob. Any direction would be very helpful. \*\*UPDATE: I added models.py and migration for relevant app. Also, I was using sqlite on dev machine and am using postgreSQL on test server (like a fool). Thanks! staff\_manager/models.py ``` # -*- coding: utf-8 -*- from __future__ import unicode_literals # Create your models here. from django.db import models from django.utils.encoding import python_2_unicode_compatible from smrt.settings import DATE_INPUT_FORMATS class OrganizationTitle(models.Model): def __str__(self): return "{}".format(self.organization_title_name) organization_title_name = models.CharField(max_length=150, unique=True) class ClassificationTitle(models.Model): def __str__(self): return "{}".format(self.classification_title_name) classification_title_name = models.CharField(max_length=150, unique=True) class WorkingTitle(models.Model): def __str__(self): return "{}".format(self.working_title_name) working_title_name = models.CharField(max_length=150, unique=True) class Category(models.Model): def __str__(self): return "{}".format(self.category_name) category_name = models.CharField(max_length=150, unique=True) class Department(models.Model): def __str__(self): return "{}".format(self.department_name) department_name = models.CharField(max_length=150, unique=True) class Employee(models.Model): first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) org_title = models.ForeignKey(OrganizationTitle, blank=True, null=True, on_delete=models.SET_NULL) manager = models.ForeignKey('self', blank=True, null=True, on_delete=models.SET_NULL) manager_email = models.EmailField(max_length=50, blank=True, null=True) hire_date = models.DateField(blank=True, null=True) classification_title = models.ForeignKey(ClassificationTitle, blank=True, null=True, on_delete=models.SET_NULL) working_title = models.ForeignKey(WorkingTitle, blank=True, null=True, on_delete=models.SET_NULL) email_address = models.EmailField(max_length=250, blank=False, unique=True, error_messages={'unique': 'An account with this email exist.', 'required': 'Please provide an email address.'}) category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.SET_NULL) is_substitute = models.BooleanField(default=False) department = models.ForeignKey(Department, blank=True, null=True, on_delete=models.SET_NULL) is_active = models.BooleanField(default=True) is_manager = models.BooleanField(default=False) class Meta: ordering = ('is_active', 'last_name',) def __str__(self): return "{}".format(self.first_name + ' ' + self.last_name) def __iter__(self): return iter([ self.email_address, self.last_name, self.first_name, self.org_title, self.manager, self.manager.email_address, self.hire_date, self.classification_title, self.working_title, self.email_address, self.category, self.is_substitute, self.department ]) def save(self, *args, **kwargs): for field_name in ['first_name', 'last_name']: val = getattr(self, field_name, False) if val: setattr(self, field_name, val.capitalize()) super(Employee, self).save(*args, **kwargs) ``` MIGRATION staff\_manager.0003\_auto\_20180131\_1756: ``` # -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2018-01-31 17:56 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('staff_manager', '0002_auto_20171127_2244'), ] operations = [ migrations.CreateModel( name='Category', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('category_name', models.CharField(max_length=150, unique=True)), ], ), migrations.CreateModel( name='ClassificationTitle', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('classification_title_name', models.CharField(max_length=150, unique=True)), ], ), migrations.CreateModel( name='Department', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('department_name', models.CharField(max_length=150, unique=True)), ], ), migrations.CreateModel( name='OrganizationTitle', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('organization_title_name', models.CharField(max_length=150, unique=True)), ], ), migrations.CreateModel( name='WorkingTitle', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('working_title_name', models.CharField(max_length=150, unique=True)), ], ), migrations.AlterField( model_name='employee', name='category', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='staff_manager.Category'), ), migrations.AlterField( model_name='employee', name='classification_title', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='staff_manager.ClassificationTitle'), ), migrations.AlterField( model_name='employee', name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='staff_manager.Department'), ), migrations.AlterField( model_name='employee', name='email_address', field=models.EmailField(error_messages={'required': 'Please provide an email address.', 'unique': 'An account with this email exist.'}, max_length=250, unique=True), ), migrations.AlterField( model_name='employee', name='first_name', field=models.CharField(max_length=150), ), migrations.AlterField( model_name='employee', name='hire_date', field=models.DateField(blank=True, null=True), ), migrations.AlterField( model_name='employee', name='last_name', field=models.CharField(max_length=150), ), migrations.AlterField( model_name='employee', name='manager', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='staff_manager.Employee'), ), migrations.AlterField( model_name='employee', name='manager_email', field=models.EmailField(blank=True, max_length=50, null=True), ), migrations.AlterField( model_name='employee', name='org_title', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='staff_manager.OrganizationTitle'), ), migrations.AlterField( model_name='employee', name='working_title', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='staff_manager.WorkingTitle'), ), ] ``` TRACEBACK: ``` Operations to perform: Apply all migrations: admin, auth, contenttypes, csvimport, sessions, staff_manager Running migrations: Applying staff_manager.0003_auto_20180131_1756...Traceback (most recent call last): File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) psycopg2.DataError: invalid input syntax for integer: "test" The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/migrations/migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/migrations/operations/fields.py", line 216, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 515, in alter_field old_db_params, new_db_params, strict) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/postgresql/schema.py", line 112, in _alter_field new_db_params, strict, File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 684, in _alter_field params, File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 120, in execute cursor.execute(sql, params) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/utils.py", line 80, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) django.db.utils.DataError: invalid input syntax for integer: "test" (django_env_1) www-root@Server:~/envs/django_env_1/smrt$ ^C (django_env_1) www-root@Server:~/envs/django_env_1/smrt$ django.db.utils.DataError: invalid input syntax for integer: "test"django.db.utils.DataError: invalid input syntax for integer: "test" ```
2018/01/31
[ "https://Stackoverflow.com/questions/48548878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3541909/" ]
The issue is likely related to [this open bug](https://code.djangoproject.com/ticket/25012) in Django. You have some test data in one of the fields that you are now converting to a ForeignKey. For instance, maybe `department` used to be a `CharField` and you added an employee who has "test" as their `department` value. Now you're trying to change `department` from a CharField to a ForeignKey. The issue is that Django is trying to convert the previous value "test" into a relational value (integer) for the ForeignKey. I can think of a few good solutions: * If this is just a test database, just reset your database and run the migration on a clean database * If you need to migrate the existing data, figure out what field has the "test" value. Then try something similar to the solution given in the bug report: ``` ``` from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('documents', '0042_auto_19700101-0000'), ] operations = [ migrations.RunSQL('ALTER TABLE documents_document_tags ALTER tag_id TYPE varchar(32);'), ] ```
The simplest way that works for me is changing the foreign key to a character field, Make migrations, migrate. Then change back the field to be a foreign key. This way, you will force a database alteration which is very important
48,548,878
I'm running Django 1.11 with Python 3.4 on Ubuntu 14.04.5 Moving my development code to the test server and running into some strange errors. Can anyone see what is wrong from the traceback? I'm very new to linux and have made the mistake of developing on a Windows machine on this first go around. I have since created a virtualbox copy of the test and production servers to develop on, but I'm hoping I can salvage what's up on the test server now. I think my app is looking in the correct directory for this environment, but I am a Django, Python and linux noob. Any direction would be very helpful. \*\*UPDATE: I added models.py and migration for relevant app. Also, I was using sqlite on dev machine and am using postgreSQL on test server (like a fool). Thanks! staff\_manager/models.py ``` # -*- coding: utf-8 -*- from __future__ import unicode_literals # Create your models here. from django.db import models from django.utils.encoding import python_2_unicode_compatible from smrt.settings import DATE_INPUT_FORMATS class OrganizationTitle(models.Model): def __str__(self): return "{}".format(self.organization_title_name) organization_title_name = models.CharField(max_length=150, unique=True) class ClassificationTitle(models.Model): def __str__(self): return "{}".format(self.classification_title_name) classification_title_name = models.CharField(max_length=150, unique=True) class WorkingTitle(models.Model): def __str__(self): return "{}".format(self.working_title_name) working_title_name = models.CharField(max_length=150, unique=True) class Category(models.Model): def __str__(self): return "{}".format(self.category_name) category_name = models.CharField(max_length=150, unique=True) class Department(models.Model): def __str__(self): return "{}".format(self.department_name) department_name = models.CharField(max_length=150, unique=True) class Employee(models.Model): first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) org_title = models.ForeignKey(OrganizationTitle, blank=True, null=True, on_delete=models.SET_NULL) manager = models.ForeignKey('self', blank=True, null=True, on_delete=models.SET_NULL) manager_email = models.EmailField(max_length=50, blank=True, null=True) hire_date = models.DateField(blank=True, null=True) classification_title = models.ForeignKey(ClassificationTitle, blank=True, null=True, on_delete=models.SET_NULL) working_title = models.ForeignKey(WorkingTitle, blank=True, null=True, on_delete=models.SET_NULL) email_address = models.EmailField(max_length=250, blank=False, unique=True, error_messages={'unique': 'An account with this email exist.', 'required': 'Please provide an email address.'}) category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.SET_NULL) is_substitute = models.BooleanField(default=False) department = models.ForeignKey(Department, blank=True, null=True, on_delete=models.SET_NULL) is_active = models.BooleanField(default=True) is_manager = models.BooleanField(default=False) class Meta: ordering = ('is_active', 'last_name',) def __str__(self): return "{}".format(self.first_name + ' ' + self.last_name) def __iter__(self): return iter([ self.email_address, self.last_name, self.first_name, self.org_title, self.manager, self.manager.email_address, self.hire_date, self.classification_title, self.working_title, self.email_address, self.category, self.is_substitute, self.department ]) def save(self, *args, **kwargs): for field_name in ['first_name', 'last_name']: val = getattr(self, field_name, False) if val: setattr(self, field_name, val.capitalize()) super(Employee, self).save(*args, **kwargs) ``` MIGRATION staff\_manager.0003\_auto\_20180131\_1756: ``` # -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2018-01-31 17:56 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('staff_manager', '0002_auto_20171127_2244'), ] operations = [ migrations.CreateModel( name='Category', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('category_name', models.CharField(max_length=150, unique=True)), ], ), migrations.CreateModel( name='ClassificationTitle', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('classification_title_name', models.CharField(max_length=150, unique=True)), ], ), migrations.CreateModel( name='Department', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('department_name', models.CharField(max_length=150, unique=True)), ], ), migrations.CreateModel( name='OrganizationTitle', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('organization_title_name', models.CharField(max_length=150, unique=True)), ], ), migrations.CreateModel( name='WorkingTitle', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('working_title_name', models.CharField(max_length=150, unique=True)), ], ), migrations.AlterField( model_name='employee', name='category', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='staff_manager.Category'), ), migrations.AlterField( model_name='employee', name='classification_title', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='staff_manager.ClassificationTitle'), ), migrations.AlterField( model_name='employee', name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='staff_manager.Department'), ), migrations.AlterField( model_name='employee', name='email_address', field=models.EmailField(error_messages={'required': 'Please provide an email address.', 'unique': 'An account with this email exist.'}, max_length=250, unique=True), ), migrations.AlterField( model_name='employee', name='first_name', field=models.CharField(max_length=150), ), migrations.AlterField( model_name='employee', name='hire_date', field=models.DateField(blank=True, null=True), ), migrations.AlterField( model_name='employee', name='last_name', field=models.CharField(max_length=150), ), migrations.AlterField( model_name='employee', name='manager', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='staff_manager.Employee'), ), migrations.AlterField( model_name='employee', name='manager_email', field=models.EmailField(blank=True, max_length=50, null=True), ), migrations.AlterField( model_name='employee', name='org_title', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='staff_manager.OrganizationTitle'), ), migrations.AlterField( model_name='employee', name='working_title', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='staff_manager.WorkingTitle'), ), ] ``` TRACEBACK: ``` Operations to perform: Apply all migrations: admin, auth, contenttypes, csvimport, sessions, staff_manager Running migrations: Applying staff_manager.0003_auto_20180131_1756...Traceback (most recent call last): File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) psycopg2.DataError: invalid input syntax for integer: "test" The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/migrations/migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/migrations/operations/fields.py", line 216, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 515, in alter_field old_db_params, new_db_params, strict) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/postgresql/schema.py", line 112, in _alter_field new_db_params, strict, File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 684, in _alter_field params, File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 120, in execute cursor.execute(sql, params) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/utils.py", line 80, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) django.db.utils.DataError: invalid input syntax for integer: "test" (django_env_1) www-root@Server:~/envs/django_env_1/smrt$ ^C (django_env_1) www-root@Server:~/envs/django_env_1/smrt$ django.db.utils.DataError: invalid input syntax for integer: "test"django.db.utils.DataError: invalid input syntax for integer: "test" ```
2018/01/31
[ "https://Stackoverflow.com/questions/48548878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3541909/" ]
The issue is likely related to [this open bug](https://code.djangoproject.com/ticket/25012) in Django. You have some test data in one of the fields that you are now converting to a ForeignKey. For instance, maybe `department` used to be a `CharField` and you added an employee who has "test" as their `department` value. Now you're trying to change `department` from a CharField to a ForeignKey. The issue is that Django is trying to convert the previous value "test" into a relational value (integer) for the ForeignKey. I can think of a few good solutions: * If this is just a test database, just reset your database and run the migration on a clean database * If you need to migrate the existing data, figure out what field has the "test" value. Then try something similar to the solution given in the bug report: ``` ``` from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('documents', '0042_auto_19700101-0000'), ] operations = [ migrations.RunSQL('ALTER TABLE documents_document_tags ALTER tag_id TYPE varchar(32);'), ] ```
In my case @YPCrumble was correct and it was caused after I changed a field from a StreamField to a CharField. The quickest solution I found was to open up my DB on a GUI (Postico in my case) and overwrite the values from JSON to the default value. This meant setting every existing fields values to 1, in my situation. This let the migration run as intended, without issue.
48,548,878
I'm running Django 1.11 with Python 3.4 on Ubuntu 14.04.5 Moving my development code to the test server and running into some strange errors. Can anyone see what is wrong from the traceback? I'm very new to linux and have made the mistake of developing on a Windows machine on this first go around. I have since created a virtualbox copy of the test and production servers to develop on, but I'm hoping I can salvage what's up on the test server now. I think my app is looking in the correct directory for this environment, but I am a Django, Python and linux noob. Any direction would be very helpful. \*\*UPDATE: I added models.py and migration for relevant app. Also, I was using sqlite on dev machine and am using postgreSQL on test server (like a fool). Thanks! staff\_manager/models.py ``` # -*- coding: utf-8 -*- from __future__ import unicode_literals # Create your models here. from django.db import models from django.utils.encoding import python_2_unicode_compatible from smrt.settings import DATE_INPUT_FORMATS class OrganizationTitle(models.Model): def __str__(self): return "{}".format(self.organization_title_name) organization_title_name = models.CharField(max_length=150, unique=True) class ClassificationTitle(models.Model): def __str__(self): return "{}".format(self.classification_title_name) classification_title_name = models.CharField(max_length=150, unique=True) class WorkingTitle(models.Model): def __str__(self): return "{}".format(self.working_title_name) working_title_name = models.CharField(max_length=150, unique=True) class Category(models.Model): def __str__(self): return "{}".format(self.category_name) category_name = models.CharField(max_length=150, unique=True) class Department(models.Model): def __str__(self): return "{}".format(self.department_name) department_name = models.CharField(max_length=150, unique=True) class Employee(models.Model): first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) org_title = models.ForeignKey(OrganizationTitle, blank=True, null=True, on_delete=models.SET_NULL) manager = models.ForeignKey('self', blank=True, null=True, on_delete=models.SET_NULL) manager_email = models.EmailField(max_length=50, blank=True, null=True) hire_date = models.DateField(blank=True, null=True) classification_title = models.ForeignKey(ClassificationTitle, blank=True, null=True, on_delete=models.SET_NULL) working_title = models.ForeignKey(WorkingTitle, blank=True, null=True, on_delete=models.SET_NULL) email_address = models.EmailField(max_length=250, blank=False, unique=True, error_messages={'unique': 'An account with this email exist.', 'required': 'Please provide an email address.'}) category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.SET_NULL) is_substitute = models.BooleanField(default=False) department = models.ForeignKey(Department, blank=True, null=True, on_delete=models.SET_NULL) is_active = models.BooleanField(default=True) is_manager = models.BooleanField(default=False) class Meta: ordering = ('is_active', 'last_name',) def __str__(self): return "{}".format(self.first_name + ' ' + self.last_name) def __iter__(self): return iter([ self.email_address, self.last_name, self.first_name, self.org_title, self.manager, self.manager.email_address, self.hire_date, self.classification_title, self.working_title, self.email_address, self.category, self.is_substitute, self.department ]) def save(self, *args, **kwargs): for field_name in ['first_name', 'last_name']: val = getattr(self, field_name, False) if val: setattr(self, field_name, val.capitalize()) super(Employee, self).save(*args, **kwargs) ``` MIGRATION staff\_manager.0003\_auto\_20180131\_1756: ``` # -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2018-01-31 17:56 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('staff_manager', '0002_auto_20171127_2244'), ] operations = [ migrations.CreateModel( name='Category', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('category_name', models.CharField(max_length=150, unique=True)), ], ), migrations.CreateModel( name='ClassificationTitle', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('classification_title_name', models.CharField(max_length=150, unique=True)), ], ), migrations.CreateModel( name='Department', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('department_name', models.CharField(max_length=150, unique=True)), ], ), migrations.CreateModel( name='OrganizationTitle', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('organization_title_name', models.CharField(max_length=150, unique=True)), ], ), migrations.CreateModel( name='WorkingTitle', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('working_title_name', models.CharField(max_length=150, unique=True)), ], ), migrations.AlterField( model_name='employee', name='category', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='staff_manager.Category'), ), migrations.AlterField( model_name='employee', name='classification_title', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='staff_manager.ClassificationTitle'), ), migrations.AlterField( model_name='employee', name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='staff_manager.Department'), ), migrations.AlterField( model_name='employee', name='email_address', field=models.EmailField(error_messages={'required': 'Please provide an email address.', 'unique': 'An account with this email exist.'}, max_length=250, unique=True), ), migrations.AlterField( model_name='employee', name='first_name', field=models.CharField(max_length=150), ), migrations.AlterField( model_name='employee', name='hire_date', field=models.DateField(blank=True, null=True), ), migrations.AlterField( model_name='employee', name='last_name', field=models.CharField(max_length=150), ), migrations.AlterField( model_name='employee', name='manager', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='staff_manager.Employee'), ), migrations.AlterField( model_name='employee', name='manager_email', field=models.EmailField(blank=True, max_length=50, null=True), ), migrations.AlterField( model_name='employee', name='org_title', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='staff_manager.OrganizationTitle'), ), migrations.AlterField( model_name='employee', name='working_title', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='staff_manager.WorkingTitle'), ), ] ``` TRACEBACK: ``` Operations to perform: Apply all migrations: admin, auth, contenttypes, csvimport, sessions, staff_manager Running migrations: Applying staff_manager.0003_auto_20180131_1756...Traceback (most recent call last): File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) psycopg2.DataError: invalid input syntax for integer: "test" The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/migrations/migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/migrations/operations/fields.py", line 216, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 515, in alter_field old_db_params, new_db_params, strict) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/postgresql/schema.py", line 112, in _alter_field new_db_params, strict, File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 684, in _alter_field params, File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 120, in execute cursor.execute(sql, params) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/utils.py", line 80, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) django.db.utils.DataError: invalid input syntax for integer: "test" (django_env_1) www-root@Server:~/envs/django_env_1/smrt$ ^C (django_env_1) www-root@Server:~/envs/django_env_1/smrt$ django.db.utils.DataError: invalid input syntax for integer: "test"django.db.utils.DataError: invalid input syntax for integer: "test" ```
2018/01/31
[ "https://Stackoverflow.com/questions/48548878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3541909/" ]
The issue is likely related to [this open bug](https://code.djangoproject.com/ticket/25012) in Django. You have some test data in one of the fields that you are now converting to a ForeignKey. For instance, maybe `department` used to be a `CharField` and you added an employee who has "test" as their `department` value. Now you're trying to change `department` from a CharField to a ForeignKey. The issue is that Django is trying to convert the previous value "test" into a relational value (integer) for the ForeignKey. I can think of a few good solutions: * If this is just a test database, just reset your database and run the migration on a clean database * If you need to migrate the existing data, figure out what field has the "test" value. Then try something similar to the solution given in the bug report: ``` ``` from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('documents', '0042_auto_19700101-0000'), ] operations = [ migrations.RunSQL('ALTER TABLE documents_document_tags ALTER tag_id TYPE varchar(32);'), ] ```
In my case, I have the same issue on the development. This command works for me. ``` python manage.py flush ``` Make sure it removes all data from the database. Run this command, it will delete all data from the database and run migration again. ``` python manage.py migrate ```
48,548,878
I'm running Django 1.11 with Python 3.4 on Ubuntu 14.04.5 Moving my development code to the test server and running into some strange errors. Can anyone see what is wrong from the traceback? I'm very new to linux and have made the mistake of developing on a Windows machine on this first go around. I have since created a virtualbox copy of the test and production servers to develop on, but I'm hoping I can salvage what's up on the test server now. I think my app is looking in the correct directory for this environment, but I am a Django, Python and linux noob. Any direction would be very helpful. \*\*UPDATE: I added models.py and migration for relevant app. Also, I was using sqlite on dev machine and am using postgreSQL on test server (like a fool). Thanks! staff\_manager/models.py ``` # -*- coding: utf-8 -*- from __future__ import unicode_literals # Create your models here. from django.db import models from django.utils.encoding import python_2_unicode_compatible from smrt.settings import DATE_INPUT_FORMATS class OrganizationTitle(models.Model): def __str__(self): return "{}".format(self.organization_title_name) organization_title_name = models.CharField(max_length=150, unique=True) class ClassificationTitle(models.Model): def __str__(self): return "{}".format(self.classification_title_name) classification_title_name = models.CharField(max_length=150, unique=True) class WorkingTitle(models.Model): def __str__(self): return "{}".format(self.working_title_name) working_title_name = models.CharField(max_length=150, unique=True) class Category(models.Model): def __str__(self): return "{}".format(self.category_name) category_name = models.CharField(max_length=150, unique=True) class Department(models.Model): def __str__(self): return "{}".format(self.department_name) department_name = models.CharField(max_length=150, unique=True) class Employee(models.Model): first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) org_title = models.ForeignKey(OrganizationTitle, blank=True, null=True, on_delete=models.SET_NULL) manager = models.ForeignKey('self', blank=True, null=True, on_delete=models.SET_NULL) manager_email = models.EmailField(max_length=50, blank=True, null=True) hire_date = models.DateField(blank=True, null=True) classification_title = models.ForeignKey(ClassificationTitle, blank=True, null=True, on_delete=models.SET_NULL) working_title = models.ForeignKey(WorkingTitle, blank=True, null=True, on_delete=models.SET_NULL) email_address = models.EmailField(max_length=250, blank=False, unique=True, error_messages={'unique': 'An account with this email exist.', 'required': 'Please provide an email address.'}) category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.SET_NULL) is_substitute = models.BooleanField(default=False) department = models.ForeignKey(Department, blank=True, null=True, on_delete=models.SET_NULL) is_active = models.BooleanField(default=True) is_manager = models.BooleanField(default=False) class Meta: ordering = ('is_active', 'last_name',) def __str__(self): return "{}".format(self.first_name + ' ' + self.last_name) def __iter__(self): return iter([ self.email_address, self.last_name, self.first_name, self.org_title, self.manager, self.manager.email_address, self.hire_date, self.classification_title, self.working_title, self.email_address, self.category, self.is_substitute, self.department ]) def save(self, *args, **kwargs): for field_name in ['first_name', 'last_name']: val = getattr(self, field_name, False) if val: setattr(self, field_name, val.capitalize()) super(Employee, self).save(*args, **kwargs) ``` MIGRATION staff\_manager.0003\_auto\_20180131\_1756: ``` # -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2018-01-31 17:56 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('staff_manager', '0002_auto_20171127_2244'), ] operations = [ migrations.CreateModel( name='Category', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('category_name', models.CharField(max_length=150, unique=True)), ], ), migrations.CreateModel( name='ClassificationTitle', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('classification_title_name', models.CharField(max_length=150, unique=True)), ], ), migrations.CreateModel( name='Department', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('department_name', models.CharField(max_length=150, unique=True)), ], ), migrations.CreateModel( name='OrganizationTitle', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('organization_title_name', models.CharField(max_length=150, unique=True)), ], ), migrations.CreateModel( name='WorkingTitle', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('working_title_name', models.CharField(max_length=150, unique=True)), ], ), migrations.AlterField( model_name='employee', name='category', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='staff_manager.Category'), ), migrations.AlterField( model_name='employee', name='classification_title', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='staff_manager.ClassificationTitle'), ), migrations.AlterField( model_name='employee', name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='staff_manager.Department'), ), migrations.AlterField( model_name='employee', name='email_address', field=models.EmailField(error_messages={'required': 'Please provide an email address.', 'unique': 'An account with this email exist.'}, max_length=250, unique=True), ), migrations.AlterField( model_name='employee', name='first_name', field=models.CharField(max_length=150), ), migrations.AlterField( model_name='employee', name='hire_date', field=models.DateField(blank=True, null=True), ), migrations.AlterField( model_name='employee', name='last_name', field=models.CharField(max_length=150), ), migrations.AlterField( model_name='employee', name='manager', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='staff_manager.Employee'), ), migrations.AlterField( model_name='employee', name='manager_email', field=models.EmailField(blank=True, max_length=50, null=True), ), migrations.AlterField( model_name='employee', name='org_title', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='staff_manager.OrganizationTitle'), ), migrations.AlterField( model_name='employee', name='working_title', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='staff_manager.WorkingTitle'), ), ] ``` TRACEBACK: ``` Operations to perform: Apply all migrations: admin, auth, contenttypes, csvimport, sessions, staff_manager Running migrations: Applying staff_manager.0003_auto_20180131_1756...Traceback (most recent call last): File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) psycopg2.DataError: invalid input syntax for integer: "test" The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/migrations/migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/migrations/operations/fields.py", line 216, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 515, in alter_field old_db_params, new_db_params, strict) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/postgresql/schema.py", line 112, in _alter_field new_db_params, strict, File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 684, in _alter_field params, File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 120, in execute cursor.execute(sql, params) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/utils.py", line 80, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) django.db.utils.DataError: invalid input syntax for integer: "test" (django_env_1) www-root@Server:~/envs/django_env_1/smrt$ ^C (django_env_1) www-root@Server:~/envs/django_env_1/smrt$ django.db.utils.DataError: invalid input syntax for integer: "test"django.db.utils.DataError: invalid input syntax for integer: "test" ```
2018/01/31
[ "https://Stackoverflow.com/questions/48548878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3541909/" ]
The issue is likely related to [this open bug](https://code.djangoproject.com/ticket/25012) in Django. You have some test data in one of the fields that you are now converting to a ForeignKey. For instance, maybe `department` used to be a `CharField` and you added an employee who has "test" as their `department` value. Now you're trying to change `department` from a CharField to a ForeignKey. The issue is that Django is trying to convert the previous value "test" into a relational value (integer) for the ForeignKey. I can think of a few good solutions: * If this is just a test database, just reset your database and run the migration on a clean database * If you need to migrate the existing data, figure out what field has the "test" value. Then try something similar to the solution given in the bug report: ``` ``` from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('documents', '0042_auto_19700101-0000'), ] operations = [ migrations.RunSQL('ALTER TABLE documents_document_tags ALTER tag_id TYPE varchar(32);'), ] ```
In my case error was thith replace `IntegerField` to `TextField in file migartion file migration: ``` # Generated by Django 3.1.3 on 2020-12-03 11:19 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('adminPanel', '0028_auto_20201203_1117'), ] operations = [ migrations.RemoveField( model_name='myuser', name='balance', ), migrations.AlterField( model_name='myuser', name='bot_admin_chat_id', field=models.IntegerField(default=0), ), ] ``` I change `IntegerField` to `TextField` & python manage.py migrate After that, I remove my column in models, makemigration & migrate After that, I do thth my model that ever I want.
48,548,878
I'm running Django 1.11 with Python 3.4 on Ubuntu 14.04.5 Moving my development code to the test server and running into some strange errors. Can anyone see what is wrong from the traceback? I'm very new to linux and have made the mistake of developing on a Windows machine on this first go around. I have since created a virtualbox copy of the test and production servers to develop on, but I'm hoping I can salvage what's up on the test server now. I think my app is looking in the correct directory for this environment, but I am a Django, Python and linux noob. Any direction would be very helpful. \*\*UPDATE: I added models.py and migration for relevant app. Also, I was using sqlite on dev machine and am using postgreSQL on test server (like a fool). Thanks! staff\_manager/models.py ``` # -*- coding: utf-8 -*- from __future__ import unicode_literals # Create your models here. from django.db import models from django.utils.encoding import python_2_unicode_compatible from smrt.settings import DATE_INPUT_FORMATS class OrganizationTitle(models.Model): def __str__(self): return "{}".format(self.organization_title_name) organization_title_name = models.CharField(max_length=150, unique=True) class ClassificationTitle(models.Model): def __str__(self): return "{}".format(self.classification_title_name) classification_title_name = models.CharField(max_length=150, unique=True) class WorkingTitle(models.Model): def __str__(self): return "{}".format(self.working_title_name) working_title_name = models.CharField(max_length=150, unique=True) class Category(models.Model): def __str__(self): return "{}".format(self.category_name) category_name = models.CharField(max_length=150, unique=True) class Department(models.Model): def __str__(self): return "{}".format(self.department_name) department_name = models.CharField(max_length=150, unique=True) class Employee(models.Model): first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) org_title = models.ForeignKey(OrganizationTitle, blank=True, null=True, on_delete=models.SET_NULL) manager = models.ForeignKey('self', blank=True, null=True, on_delete=models.SET_NULL) manager_email = models.EmailField(max_length=50, blank=True, null=True) hire_date = models.DateField(blank=True, null=True) classification_title = models.ForeignKey(ClassificationTitle, blank=True, null=True, on_delete=models.SET_NULL) working_title = models.ForeignKey(WorkingTitle, blank=True, null=True, on_delete=models.SET_NULL) email_address = models.EmailField(max_length=250, blank=False, unique=True, error_messages={'unique': 'An account with this email exist.', 'required': 'Please provide an email address.'}) category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.SET_NULL) is_substitute = models.BooleanField(default=False) department = models.ForeignKey(Department, blank=True, null=True, on_delete=models.SET_NULL) is_active = models.BooleanField(default=True) is_manager = models.BooleanField(default=False) class Meta: ordering = ('is_active', 'last_name',) def __str__(self): return "{}".format(self.first_name + ' ' + self.last_name) def __iter__(self): return iter([ self.email_address, self.last_name, self.first_name, self.org_title, self.manager, self.manager.email_address, self.hire_date, self.classification_title, self.working_title, self.email_address, self.category, self.is_substitute, self.department ]) def save(self, *args, **kwargs): for field_name in ['first_name', 'last_name']: val = getattr(self, field_name, False) if val: setattr(self, field_name, val.capitalize()) super(Employee, self).save(*args, **kwargs) ``` MIGRATION staff\_manager.0003\_auto\_20180131\_1756: ``` # -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2018-01-31 17:56 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('staff_manager', '0002_auto_20171127_2244'), ] operations = [ migrations.CreateModel( name='Category', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('category_name', models.CharField(max_length=150, unique=True)), ], ), migrations.CreateModel( name='ClassificationTitle', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('classification_title_name', models.CharField(max_length=150, unique=True)), ], ), migrations.CreateModel( name='Department', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('department_name', models.CharField(max_length=150, unique=True)), ], ), migrations.CreateModel( name='OrganizationTitle', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('organization_title_name', models.CharField(max_length=150, unique=True)), ], ), migrations.CreateModel( name='WorkingTitle', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('working_title_name', models.CharField(max_length=150, unique=True)), ], ), migrations.AlterField( model_name='employee', name='category', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='staff_manager.Category'), ), migrations.AlterField( model_name='employee', name='classification_title', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='staff_manager.ClassificationTitle'), ), migrations.AlterField( model_name='employee', name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='staff_manager.Department'), ), migrations.AlterField( model_name='employee', name='email_address', field=models.EmailField(error_messages={'required': 'Please provide an email address.', 'unique': 'An account with this email exist.'}, max_length=250, unique=True), ), migrations.AlterField( model_name='employee', name='first_name', field=models.CharField(max_length=150), ), migrations.AlterField( model_name='employee', name='hire_date', field=models.DateField(blank=True, null=True), ), migrations.AlterField( model_name='employee', name='last_name', field=models.CharField(max_length=150), ), migrations.AlterField( model_name='employee', name='manager', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='staff_manager.Employee'), ), migrations.AlterField( model_name='employee', name='manager_email', field=models.EmailField(blank=True, max_length=50, null=True), ), migrations.AlterField( model_name='employee', name='org_title', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='staff_manager.OrganizationTitle'), ), migrations.AlterField( model_name='employee', name='working_title', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='staff_manager.WorkingTitle'), ), ] ``` TRACEBACK: ``` Operations to perform: Apply all migrations: admin, auth, contenttypes, csvimport, sessions, staff_manager Running migrations: Applying staff_manager.0003_auto_20180131_1756...Traceback (most recent call last): File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) psycopg2.DataError: invalid input syntax for integer: "test" The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/migrations/migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/migrations/operations/fields.py", line 216, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 515, in alter_field old_db_params, new_db_params, strict) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/postgresql/schema.py", line 112, in _alter_field new_db_params, strict, File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 684, in _alter_field params, File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 120, in execute cursor.execute(sql, params) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/utils.py", line 80, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) django.db.utils.DataError: invalid input syntax for integer: "test" (django_env_1) www-root@Server:~/envs/django_env_1/smrt$ ^C (django_env_1) www-root@Server:~/envs/django_env_1/smrt$ django.db.utils.DataError: invalid input syntax for integer: "test"django.db.utils.DataError: invalid input syntax for integer: "test" ```
2018/01/31
[ "https://Stackoverflow.com/questions/48548878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3541909/" ]
In my case, I have the same issue on the development. This command works for me. ``` python manage.py flush ``` Make sure it removes all data from the database. Run this command, it will delete all data from the database and run migration again. ``` python manage.py migrate ```
The simplest way that works for me is changing the foreign key to a character field, Make migrations, migrate. Then change back the field to be a foreign key. This way, you will force a database alteration which is very important
48,548,878
I'm running Django 1.11 with Python 3.4 on Ubuntu 14.04.5 Moving my development code to the test server and running into some strange errors. Can anyone see what is wrong from the traceback? I'm very new to linux and have made the mistake of developing on a Windows machine on this first go around. I have since created a virtualbox copy of the test and production servers to develop on, but I'm hoping I can salvage what's up on the test server now. I think my app is looking in the correct directory for this environment, but I am a Django, Python and linux noob. Any direction would be very helpful. \*\*UPDATE: I added models.py and migration for relevant app. Also, I was using sqlite on dev machine and am using postgreSQL on test server (like a fool). Thanks! staff\_manager/models.py ``` # -*- coding: utf-8 -*- from __future__ import unicode_literals # Create your models here. from django.db import models from django.utils.encoding import python_2_unicode_compatible from smrt.settings import DATE_INPUT_FORMATS class OrganizationTitle(models.Model): def __str__(self): return "{}".format(self.organization_title_name) organization_title_name = models.CharField(max_length=150, unique=True) class ClassificationTitle(models.Model): def __str__(self): return "{}".format(self.classification_title_name) classification_title_name = models.CharField(max_length=150, unique=True) class WorkingTitle(models.Model): def __str__(self): return "{}".format(self.working_title_name) working_title_name = models.CharField(max_length=150, unique=True) class Category(models.Model): def __str__(self): return "{}".format(self.category_name) category_name = models.CharField(max_length=150, unique=True) class Department(models.Model): def __str__(self): return "{}".format(self.department_name) department_name = models.CharField(max_length=150, unique=True) class Employee(models.Model): first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) org_title = models.ForeignKey(OrganizationTitle, blank=True, null=True, on_delete=models.SET_NULL) manager = models.ForeignKey('self', blank=True, null=True, on_delete=models.SET_NULL) manager_email = models.EmailField(max_length=50, blank=True, null=True) hire_date = models.DateField(blank=True, null=True) classification_title = models.ForeignKey(ClassificationTitle, blank=True, null=True, on_delete=models.SET_NULL) working_title = models.ForeignKey(WorkingTitle, blank=True, null=True, on_delete=models.SET_NULL) email_address = models.EmailField(max_length=250, blank=False, unique=True, error_messages={'unique': 'An account with this email exist.', 'required': 'Please provide an email address.'}) category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.SET_NULL) is_substitute = models.BooleanField(default=False) department = models.ForeignKey(Department, blank=True, null=True, on_delete=models.SET_NULL) is_active = models.BooleanField(default=True) is_manager = models.BooleanField(default=False) class Meta: ordering = ('is_active', 'last_name',) def __str__(self): return "{}".format(self.first_name + ' ' + self.last_name) def __iter__(self): return iter([ self.email_address, self.last_name, self.first_name, self.org_title, self.manager, self.manager.email_address, self.hire_date, self.classification_title, self.working_title, self.email_address, self.category, self.is_substitute, self.department ]) def save(self, *args, **kwargs): for field_name in ['first_name', 'last_name']: val = getattr(self, field_name, False) if val: setattr(self, field_name, val.capitalize()) super(Employee, self).save(*args, **kwargs) ``` MIGRATION staff\_manager.0003\_auto\_20180131\_1756: ``` # -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2018-01-31 17:56 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('staff_manager', '0002_auto_20171127_2244'), ] operations = [ migrations.CreateModel( name='Category', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('category_name', models.CharField(max_length=150, unique=True)), ], ), migrations.CreateModel( name='ClassificationTitle', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('classification_title_name', models.CharField(max_length=150, unique=True)), ], ), migrations.CreateModel( name='Department', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('department_name', models.CharField(max_length=150, unique=True)), ], ), migrations.CreateModel( name='OrganizationTitle', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('organization_title_name', models.CharField(max_length=150, unique=True)), ], ), migrations.CreateModel( name='WorkingTitle', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('working_title_name', models.CharField(max_length=150, unique=True)), ], ), migrations.AlterField( model_name='employee', name='category', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='staff_manager.Category'), ), migrations.AlterField( model_name='employee', name='classification_title', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='staff_manager.ClassificationTitle'), ), migrations.AlterField( model_name='employee', name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='staff_manager.Department'), ), migrations.AlterField( model_name='employee', name='email_address', field=models.EmailField(error_messages={'required': 'Please provide an email address.', 'unique': 'An account with this email exist.'}, max_length=250, unique=True), ), migrations.AlterField( model_name='employee', name='first_name', field=models.CharField(max_length=150), ), migrations.AlterField( model_name='employee', name='hire_date', field=models.DateField(blank=True, null=True), ), migrations.AlterField( model_name='employee', name='last_name', field=models.CharField(max_length=150), ), migrations.AlterField( model_name='employee', name='manager', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='staff_manager.Employee'), ), migrations.AlterField( model_name='employee', name='manager_email', field=models.EmailField(blank=True, max_length=50, null=True), ), migrations.AlterField( model_name='employee', name='org_title', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='staff_manager.OrganizationTitle'), ), migrations.AlterField( model_name='employee', name='working_title', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='staff_manager.WorkingTitle'), ), ] ``` TRACEBACK: ``` Operations to perform: Apply all migrations: admin, auth, contenttypes, csvimport, sessions, staff_manager Running migrations: Applying staff_manager.0003_auto_20180131_1756...Traceback (most recent call last): File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) psycopg2.DataError: invalid input syntax for integer: "test" The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/migrations/migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/migrations/operations/fields.py", line 216, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 515, in alter_field old_db_params, new_db_params, strict) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/postgresql/schema.py", line 112, in _alter_field new_db_params, strict, File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 684, in _alter_field params, File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 120, in execute cursor.execute(sql, params) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/utils.py", line 80, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) django.db.utils.DataError: invalid input syntax for integer: "test" (django_env_1) www-root@Server:~/envs/django_env_1/smrt$ ^C (django_env_1) www-root@Server:~/envs/django_env_1/smrt$ django.db.utils.DataError: invalid input syntax for integer: "test"django.db.utils.DataError: invalid input syntax for integer: "test" ```
2018/01/31
[ "https://Stackoverflow.com/questions/48548878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3541909/" ]
In my case, I have the same issue on the development. This command works for me. ``` python manage.py flush ``` Make sure it removes all data from the database. Run this command, it will delete all data from the database and run migration again. ``` python manage.py migrate ```
In my case @YPCrumble was correct and it was caused after I changed a field from a StreamField to a CharField. The quickest solution I found was to open up my DB on a GUI (Postico in my case) and overwrite the values from JSON to the default value. This meant setting every existing fields values to 1, in my situation. This let the migration run as intended, without issue.
48,548,878
I'm running Django 1.11 with Python 3.4 on Ubuntu 14.04.5 Moving my development code to the test server and running into some strange errors. Can anyone see what is wrong from the traceback? I'm very new to linux and have made the mistake of developing on a Windows machine on this first go around. I have since created a virtualbox copy of the test and production servers to develop on, but I'm hoping I can salvage what's up on the test server now. I think my app is looking in the correct directory for this environment, but I am a Django, Python and linux noob. Any direction would be very helpful. \*\*UPDATE: I added models.py and migration for relevant app. Also, I was using sqlite on dev machine and am using postgreSQL on test server (like a fool). Thanks! staff\_manager/models.py ``` # -*- coding: utf-8 -*- from __future__ import unicode_literals # Create your models here. from django.db import models from django.utils.encoding import python_2_unicode_compatible from smrt.settings import DATE_INPUT_FORMATS class OrganizationTitle(models.Model): def __str__(self): return "{}".format(self.organization_title_name) organization_title_name = models.CharField(max_length=150, unique=True) class ClassificationTitle(models.Model): def __str__(self): return "{}".format(self.classification_title_name) classification_title_name = models.CharField(max_length=150, unique=True) class WorkingTitle(models.Model): def __str__(self): return "{}".format(self.working_title_name) working_title_name = models.CharField(max_length=150, unique=True) class Category(models.Model): def __str__(self): return "{}".format(self.category_name) category_name = models.CharField(max_length=150, unique=True) class Department(models.Model): def __str__(self): return "{}".format(self.department_name) department_name = models.CharField(max_length=150, unique=True) class Employee(models.Model): first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) org_title = models.ForeignKey(OrganizationTitle, blank=True, null=True, on_delete=models.SET_NULL) manager = models.ForeignKey('self', blank=True, null=True, on_delete=models.SET_NULL) manager_email = models.EmailField(max_length=50, blank=True, null=True) hire_date = models.DateField(blank=True, null=True) classification_title = models.ForeignKey(ClassificationTitle, blank=True, null=True, on_delete=models.SET_NULL) working_title = models.ForeignKey(WorkingTitle, blank=True, null=True, on_delete=models.SET_NULL) email_address = models.EmailField(max_length=250, blank=False, unique=True, error_messages={'unique': 'An account with this email exist.', 'required': 'Please provide an email address.'}) category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.SET_NULL) is_substitute = models.BooleanField(default=False) department = models.ForeignKey(Department, blank=True, null=True, on_delete=models.SET_NULL) is_active = models.BooleanField(default=True) is_manager = models.BooleanField(default=False) class Meta: ordering = ('is_active', 'last_name',) def __str__(self): return "{}".format(self.first_name + ' ' + self.last_name) def __iter__(self): return iter([ self.email_address, self.last_name, self.first_name, self.org_title, self.manager, self.manager.email_address, self.hire_date, self.classification_title, self.working_title, self.email_address, self.category, self.is_substitute, self.department ]) def save(self, *args, **kwargs): for field_name in ['first_name', 'last_name']: val = getattr(self, field_name, False) if val: setattr(self, field_name, val.capitalize()) super(Employee, self).save(*args, **kwargs) ``` MIGRATION staff\_manager.0003\_auto\_20180131\_1756: ``` # -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2018-01-31 17:56 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('staff_manager', '0002_auto_20171127_2244'), ] operations = [ migrations.CreateModel( name='Category', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('category_name', models.CharField(max_length=150, unique=True)), ], ), migrations.CreateModel( name='ClassificationTitle', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('classification_title_name', models.CharField(max_length=150, unique=True)), ], ), migrations.CreateModel( name='Department', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('department_name', models.CharField(max_length=150, unique=True)), ], ), migrations.CreateModel( name='OrganizationTitle', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('organization_title_name', models.CharField(max_length=150, unique=True)), ], ), migrations.CreateModel( name='WorkingTitle', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('working_title_name', models.CharField(max_length=150, unique=True)), ], ), migrations.AlterField( model_name='employee', name='category', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='staff_manager.Category'), ), migrations.AlterField( model_name='employee', name='classification_title', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='staff_manager.ClassificationTitle'), ), migrations.AlterField( model_name='employee', name='department', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='staff_manager.Department'), ), migrations.AlterField( model_name='employee', name='email_address', field=models.EmailField(error_messages={'required': 'Please provide an email address.', 'unique': 'An account with this email exist.'}, max_length=250, unique=True), ), migrations.AlterField( model_name='employee', name='first_name', field=models.CharField(max_length=150), ), migrations.AlterField( model_name='employee', name='hire_date', field=models.DateField(blank=True, null=True), ), migrations.AlterField( model_name='employee', name='last_name', field=models.CharField(max_length=150), ), migrations.AlterField( model_name='employee', name='manager', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='staff_manager.Employee'), ), migrations.AlterField( model_name='employee', name='manager_email', field=models.EmailField(blank=True, max_length=50, null=True), ), migrations.AlterField( model_name='employee', name='org_title', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='staff_manager.OrganizationTitle'), ), migrations.AlterField( model_name='employee', name='working_title', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='staff_manager.WorkingTitle'), ), ] ``` TRACEBACK: ``` Operations to perform: Apply all migrations: admin, auth, contenttypes, csvimport, sessions, staff_manager Running migrations: Applying staff_manager.0003_auto_20180131_1756...Traceback (most recent call last): File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) psycopg2.DataError: invalid input syntax for integer: "test" The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/migrations/migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/migrations/operations/fields.py", line 216, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 515, in alter_field old_db_params, new_db_params, strict) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/postgresql/schema.py", line 112, in _alter_field new_db_params, strict, File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 684, in _alter_field params, File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 120, in execute cursor.execute(sql, params) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/utils.py", line 80, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) django.db.utils.DataError: invalid input syntax for integer: "test" (django_env_1) www-root@Server:~/envs/django_env_1/smrt$ ^C (django_env_1) www-root@Server:~/envs/django_env_1/smrt$ django.db.utils.DataError: invalid input syntax for integer: "test"django.db.utils.DataError: invalid input syntax for integer: "test" ```
2018/01/31
[ "https://Stackoverflow.com/questions/48548878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3541909/" ]
In my case, I have the same issue on the development. This command works for me. ``` python manage.py flush ``` Make sure it removes all data from the database. Run this command, it will delete all data from the database and run migration again. ``` python manage.py migrate ```
In my case error was thith replace `IntegerField` to `TextField in file migartion file migration: ``` # Generated by Django 3.1.3 on 2020-12-03 11:19 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('adminPanel', '0028_auto_20201203_1117'), ] operations = [ migrations.RemoveField( model_name='myuser', name='balance', ), migrations.AlterField( model_name='myuser', name='bot_admin_chat_id', field=models.IntegerField(default=0), ), ] ``` I change `IntegerField` to `TextField` & python manage.py migrate After that, I remove my column in models, makemigration & migrate After that, I do thth my model that ever I want.
45,073,617
I am use AWS with REL 7. the default EC2 mico instance has already install python. but it encounter below error when i try to install pip by yum. sudo yum install pip ==================== Loaded plugins: amazon-id, rhui-lb, search-disabled-repos No package pip available. Error: Nothing to do Anyone advise on how to install pip with yum?
2017/07/13
[ "https://Stackoverflow.com/questions/45073617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8035222/" ]
To install pip3.6 in Amazon Linux., there is no python36-pip. If you install python34-pip, it will also install python34 and point to it. The best option that worked for me is the following: ``` #Download get-pip to current directory. It won't install anything, as of now curl -O https://bootstrap.pypa.io/get-pip.py #Use python3.6 to install pip python3 get-pip.py #this will install pip3 and pip3.6 ``` Based on your preference, if you like to install them for all users, you may choose to run it as 'sudo'
The above answers seem to apply to python3 not python2 I'm running an instance where the default Python is 2.7 ``` python --version Python 2.7.14 ``` I just tried to python-pip but it gave me pip for 2.6 To install pip for python 2.7 I installed the package pyton27-pip ``` sudo yum -y install python27-pip ``` That seemed to work for me.
45,073,617
I am use AWS with REL 7. the default EC2 mico instance has already install python. but it encounter below error when i try to install pip by yum. sudo yum install pip ==================== Loaded plugins: amazon-id, rhui-lb, search-disabled-repos No package pip available. Error: Nothing to do Anyone advise on how to install pip with yum?
2017/07/13
[ "https://Stackoverflow.com/questions/45073617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8035222/" ]
if you have already installed python you might want to install pip by: sudo yum install python("version")-pip for example: ``` sudo yum install python34-pip ```
In my case is using docker with AmazonLinux2 image and python 2.7, I have to enable epel first : <https://aws.amazon.com/premiumsupport/knowledge-center/ec2-enable-epel/> Then install by using `yum install python-pip` (because I'm using root user).
45,073,617
I am use AWS with REL 7. the default EC2 mico instance has already install python. but it encounter below error when i try to install pip by yum. sudo yum install pip ==================== Loaded plugins: amazon-id, rhui-lb, search-disabled-repos No package pip available. Error: Nothing to do Anyone advise on how to install pip with yum?
2017/07/13
[ "https://Stackoverflow.com/questions/45073617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8035222/" ]
if you have already installed python you might want to install pip by: sudo yum install python("version")-pip for example: ``` sudo yum install python34-pip ```
There are different ways but this seems to be promising for me. ``` sudo yum install python3-pip ``` I prefer **searching any package name first** and then enter full name which I want to **install**. ``` yum search pip ``` this will give you results if any package with name `pip`. Check if your installation is valid by `pip3 --version` which should print latest installed version on your system.
45,073,617
I am use AWS with REL 7. the default EC2 mico instance has already install python. but it encounter below error when i try to install pip by yum. sudo yum install pip ==================== Loaded plugins: amazon-id, rhui-lb, search-disabled-repos No package pip available. Error: Nothing to do Anyone advise on how to install pip with yum?
2017/07/13
[ "https://Stackoverflow.com/questions/45073617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8035222/" ]
You can see what is available by executing ``` yum search pip ``` In my case I see ``` ... python2-pip.noarch : A tool for installing and managing Python 2 packages python3-pip.noarch : A tool for installing and managing Python3 packages ``` So, you can install the version that you need. Since the default instance seems to have Python 2 installed, you probably want `python2-pip`. Thus: ``` sudo yum install python2-pip ``` and away you go.
There are different ways but this seems to be promising for me. ``` sudo yum install python3-pip ``` I prefer **searching any package name first** and then enter full name which I want to **install**. ``` yum search pip ``` this will give you results if any package with name `pip`. Check if your installation is valid by `pip3 --version` which should print latest installed version on your system.
45,073,617
I am use AWS with REL 7. the default EC2 mico instance has already install python. but it encounter below error when i try to install pip by yum. sudo yum install pip ==================== Loaded plugins: amazon-id, rhui-lb, search-disabled-repos No package pip available. Error: Nothing to do Anyone advise on how to install pip with yum?
2017/07/13
[ "https://Stackoverflow.com/questions/45073617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8035222/" ]
To install pip3.6 in Amazon Linux., there is no python36-pip. If you install python34-pip, it will also install python34 and point to it. The best option that worked for me is the following: ``` #Download get-pip to current directory. It won't install anything, as of now curl -O https://bootstrap.pypa.io/get-pip.py #Use python3.6 to install pip python3 get-pip.py #this will install pip3 and pip3.6 ``` Based on your preference, if you like to install them for all users, you may choose to run it as 'sudo'
There are different ways but this seems to be promising for me. ``` sudo yum install python3-pip ``` I prefer **searching any package name first** and then enter full name which I want to **install**. ``` yum search pip ``` this will give you results if any package with name `pip`. Check if your installation is valid by `pip3 --version` which should print latest installed version on your system.
45,073,617
I am use AWS with REL 7. the default EC2 mico instance has already install python. but it encounter below error when i try to install pip by yum. sudo yum install pip ==================== Loaded plugins: amazon-id, rhui-lb, search-disabled-repos No package pip available. Error: Nothing to do Anyone advise on how to install pip with yum?
2017/07/13
[ "https://Stackoverflow.com/questions/45073617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8035222/" ]
The following worked for me on Amazon Linux AMI 2: `sudo yum -y install python-pip`
I ran into this problem as well. I am using the AWS RHEL 7.5 image. ``` $ cat /etc/system-release Red Hat Enterprise Linux Server release 7.5 (Maipo) ``` I enabled the `extras` and `optional` repos: ``` sudo yum-config-manager --enable rhui-REGION-rhel-server-extras rhui-REGION-rhel-server-optional ``` But `sudo yum search pip` still did not show any relevant packages. I downloaded the `pip` bootstrap installer and installed from there (see [Installing with get-pip.py](https://pip.pypa.io/en/stable/installing/#installing-with-get-pip-py)): ``` sudo curl -O https://bootstrap.pypa.io/get-pip.py sudo python get-pip.py ``` Note that many `pip` packages will require additional `yum` packages as well, e.g.: * `gcc` * `python-devel`
45,073,617
I am use AWS with REL 7. the default EC2 mico instance has already install python. but it encounter below error when i try to install pip by yum. sudo yum install pip ==================== Loaded plugins: amazon-id, rhui-lb, search-disabled-repos No package pip available. Error: Nothing to do Anyone advise on how to install pip with yum?
2017/07/13
[ "https://Stackoverflow.com/questions/45073617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8035222/" ]
The following worked for me on Amazon Linux AMI 2: `sudo yum -y install python-pip`
The above answers seem to apply to python3 not python2 I'm running an instance where the default Python is 2.7 ``` python --version Python 2.7.14 ``` I just tried to python-pip but it gave me pip for 2.6 To install pip for python 2.7 I installed the package pyton27-pip ``` sudo yum -y install python27-pip ``` That seemed to work for me.
45,073,617
I am use AWS with REL 7. the default EC2 mico instance has already install python. but it encounter below error when i try to install pip by yum. sudo yum install pip ==================== Loaded plugins: amazon-id, rhui-lb, search-disabled-repos No package pip available. Error: Nothing to do Anyone advise on how to install pip with yum?
2017/07/13
[ "https://Stackoverflow.com/questions/45073617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8035222/" ]
Install python and then install pip ``` sudo yum install python34-pip ```
The above answers seem to apply to python3 not python2 I'm running an instance where the default Python is 2.7 ``` python --version Python 2.7.14 ``` I just tried to python-pip but it gave me pip for 2.6 To install pip for python 2.7 I installed the package pyton27-pip ``` sudo yum -y install python27-pip ``` That seemed to work for me.
45,073,617
I am use AWS with REL 7. the default EC2 mico instance has already install python. but it encounter below error when i try to install pip by yum. sudo yum install pip ==================== Loaded plugins: amazon-id, rhui-lb, search-disabled-repos No package pip available. Error: Nothing to do Anyone advise on how to install pip with yum?
2017/07/13
[ "https://Stackoverflow.com/questions/45073617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8035222/" ]
You can see what is available by executing ``` yum search pip ``` In my case I see ``` ... python2-pip.noarch : A tool for installing and managing Python 2 packages python3-pip.noarch : A tool for installing and managing Python3 packages ``` So, you can install the version that you need. Since the default instance seems to have Python 2 installed, you probably want `python2-pip`. Thus: ``` sudo yum install python2-pip ``` and away you go.
if you have already installed python you might want to install pip by: sudo yum install python("version")-pip for example: ``` sudo yum install python34-pip ```
45,073,617
I am use AWS with REL 7. the default EC2 mico instance has already install python. but it encounter below error when i try to install pip by yum. sudo yum install pip ==================== Loaded plugins: amazon-id, rhui-lb, search-disabled-repos No package pip available. Error: Nothing to do Anyone advise on how to install pip with yum?
2017/07/13
[ "https://Stackoverflow.com/questions/45073617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8035222/" ]
You can see what is available by executing ``` yum search pip ``` In my case I see ``` ... python2-pip.noarch : A tool for installing and managing Python 2 packages python3-pip.noarch : A tool for installing and managing Python3 packages ``` So, you can install the version that you need. Since the default instance seems to have Python 2 installed, you probably want `python2-pip`. Thus: ``` sudo yum install python2-pip ``` and away you go.
Install python and then install pip ``` sudo yum install python34-pip ```
53,093,487
How can I specify multi-stage build with in a `docker-compose.yml`? For each variant (e.g. dev, prod...) I have a multi-stage build with 2 docker files: * dev: `Dockerfile.base` + `Dockerfile.dev` * or prod: `Dockerfile.base` + `Dockerfile.prod` File `Dockerfile.base` (common for all variants): ``` FROM python:3.6 RUN apt-get update && apt-get upgrade -y RUN pip install pipenv pip COPY Pipfile ./ # some more common configuration... ``` File `Dockerfile.dev`: ``` FROM flaskapp:base RUN pipenv install --system --skip-lock --dev ENV FLASK_ENV development ENV FLASK_DEBUG 1 ``` File `Dockerfile.prod`: ``` FROM flaskapp:base RUN pipenv install --system --skip-lock ENV FLASK_ENV production ``` Without docker-compose, I can build as: ``` # Building dev docker build --tag flaskapp:base -f Dockerfile.base . docker build --tag flaskapp:dev -f Dockerfile.dev . # or building prod docker build --tag flaskapp:base -f Dockerfile.base . docker build --tag flaskapp:dev -f Dockerfile.dev . ``` According to the [compose-file doc](https://docs.docker.com/compose/compose-file/#build), I can specify a Dockerfile to build. ``` # docker-compose.yml version: '3' services: webapp: build: context: ./dir dockerfile: Dockerfile-alternate ``` But how can I specify 2 Dockerfiles in `docker-compose.yml` (for multi-stage build)?
2018/10/31
[ "https://Stackoverflow.com/questions/53093487", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3858883/" ]
As mentioned in the comments, a multi-stage build involves a single Dockerfile to perform multiple stages. What you have is a common base image. You could convert these to a non-traditional multi-stage build with a syntax like (I say non-traditional because you do not perform any copying between the layers and instead use just the from line to pick from a prior stage): ``` FROM python:3.6 as base RUN apt-get update && apt-get upgrade -y RUN pip install pipenv pip COPY Pipfile ./ # some more common configuration... FROM base as dev RUN pipenv install --system --skip-lock --dev ENV FLASK_ENV development ENV FLASK_DEBUG 1 FROM base as prod RUN pipenv install --system --skip-lock ENV FLASK_ENV production ``` Then you can build one stage or another using the `--target` syntax to build, or a compose file like: ``` # docker-compose.yml version: '3.4' services: webapp: build: context: ./dir dockerfile: Dockerfile target: prod ``` The biggest downside is the current build engine will go through every stage until it reaches the target. Build caching can mean that's only a sub-second process. And BuildKit which is coming out of experimental in 18.09 and will need upstream support from docker-compose will be more intelligent about only running the needed commands to get your desired target built. All that said, I believe this is trying to fit a square peg in a round hole. The docker-compose developer is encouraging users to move away from doing the build within the compose file itself since it's not supported in swarm mode. Instead, the recommended solution is to perform builds with a CI/CD build server, and push those images to a registry. Then you can run the same compose file with `docker-compose` or `docker stack deploy` or even some k8s equivalents, without needing to redesign your workflow.
you can use as well concating of docker-compose files, with including both `dockerfile` pointing to your existing dockerfiles and run `docker-compose -f docker-compose.yml -f docker-compose.prod.yml build`
37,871,964
I am calling a second python script that is written for the command line from within my script using ``` os.system('insert command line arguments here') ``` this works fine and runs the second script in the terminal. I would like this not to be output in the terminal and simply have access to the lists and variables that are being printed. Is this possible using os.system? Or, do I need to use something else?
2016/06/17
[ "https://Stackoverflow.com/questions/37871964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1244051/" ]
You have a [circular import](http://effbot.org/zone/import-confusion.htm#circular-imports): `models.py` is importing `db` from core, and `core.py` is importing `User` from models You should move this line: ``` from users.models import User ``` to the bottom of `core.py`. That way when `models.py` tries to import `db` from `core`, it will be defined (since it is past that point)
It works when you import user from .models in django with version 2 and above
34,113,000
I have the following python Numpy function; it is able to take X, an array with an arbitrary number of columns and rows, and output a Y value predicted by a least squares function. What is the Math.Net equivalent for such a function? Here is the Python code: ``` newdataX = np.ones([dataX.shape[0],dataX.shape[1]+1]) newdataX[:,0:dataX.shape[1]]=dataX # build and save the model self.model_coefs, residuals, rank, s = np.linalg.lstsq(newdataX, dataY) ```
2015/12/06
[ "https://Stackoverflow.com/questions/34113000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3834415/" ]
I think you are looking for the functions on this page: <http://numerics.mathdotnet.com/api/MathNet.Numerics.LinearRegression/MultipleRegression.htm> You have a few options to solve : * Normal Equations : `MultipleRegression.NormalEquations(x, y)` * QR Decomposition : `MultipleRegression.QR(x, y)` * SVD : `MultipleRegression.SVD(x, y)` Normal equations are faster but less numerically stable while SVD is the most numerically stable but the slowest.
You can call numpy from .NET using pythonnet (C# CODE BELOW IS COPIED FROM GITHUB): The only "funky" part right now with pythonnet is passing numpy arrays. It is possible to convert them to Python lists at the interface, though this reduces performance for some situations. <https://github.com/pythonnet/pythonnet/tree/develop> ``` static void Main(string[] args) { using (Py.GIL()) { dynamic np = Py.Import("numpy"); dynamic sin = np.sin; Console.WriteLine(np.cos(np.pi*2)); Console.WriteLine(sin(5)); double c = np.cos(5) + sin(5); Console.WriteLine(c); dynamic a = np.array(new List<float> { 1, 2, 3 }); dynamic b = np.array(new List<float> { 6, 5, 4 }, Py.kw("dtype", np.int32)); Console.WriteLine(a.dtype); Console.WriteLine(b.dtype); Console.WriteLine(a * b); Console.ReadKey(); } } ``` outputs: ``` 1.0 -0.958924274663 -0.6752620892 float64 int32 [ 6. 10. 12.] ``` Here is example using F# posted on github: <https://github.com/pythonnet/pythonnet/issues/112> ``` open Python.Runtime open FSharp.Interop.Dynamic open System.Collections.Generic [<EntryPoint>] let main argv = //set up for garbage collection? use gil = Py.GIL() //----- //NUMPY //import numpy let np = Py.Import("numpy") //call a numpy function dynamically let sinResult = np?sin(5) //make a python list the hard way let list = new Python.Runtime.PyList() list.Append( new PyFloat(4.0) ) list.Append( new PyFloat(5.0) ) //run the python list through np.array dynamically let a = np?array( list ) let sumA = np?sum(a) //again, but use a keyword to change the type let b = np?array( list, Py.kw("dtype", np?int32 ) ) let sumAB = np?add(a,b) let SeqToPyFloat ( aSeq : float seq ) = let list = new Python.Runtime.PyList() aSeq |> Seq.iter( fun x -> list.Append( new PyFloat(x))) list //Worth making some convenience functions (see below for why) let a2 = np?array( [|1.0;2.0;3.0|] |> SeqToPyFloat ) //-------------------- //Problematic cases: these run but don't give good results //make a np.array from a generic list let list2 = [|1;2;3|] |> ResizeArray let c = np?array( list2 ) printfn "%A" c //gives type not value in debugger //make a np.array from an array let d = np?array( [|1;2;3|] ) printfn "%A" d //gives type not value in debugger //use a np.array in a function let sumD = np?sum(d) //gives type not value in debugger //let sumCD = np?add(d,d) // this will crash //can't use primitive f# operators on the np.arrays without throwing an exception; seems //to work in c# https://github.com/tonyroberts/pythonnet //develop branch //let e = d + 1 //----- //NLTK //import nltk let nltk = Py.Import("nltk") let sentence = "I am happy" let tokens = nltk?word_tokenize(sentence) let tags = nltk?pos_tag(tokens) let taggedWords = nltk?corpus?brown?tagged_words() let taggedWordsNews = nltk?corpus?brown?tagged_words(Py.kw("categories", "news") ) printfn "%A" taggedWordsNews let tlp = nltk?sem?logic?LogicParser(Py.kw("type_check",true)) let parsed = tlp?parse("walk(angus)") printfn "%A" parsed?argument 0 // return an integer exit code ```
27,914,930
I'm trying to install OpenStack python novaclient using pip install python-novaclient This task fails: netifaces.c:185:6 #error You need to add code for your platform I have no idea what code it wants. Does anyone understand this?
2015/01/13
[ "https://Stackoverflow.com/questions/27914930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/518012/" ]
This has to do with the order that libraries are imported in the netifaces setup.py and is fixed in version 10.3+ (which you need to install from source). Here's how to install 10.4 (current latest release): ``` mkdir -p /tmp/install/netifaces/ cd /tmp/install/netifaces && wget -O "netifaces-0.10.4.tar.gz" "https://pypi.python.org/packages/source/n/netifaces/netifaces-0.10.4.tar.gz#md5=36da76e2cfadd24cc7510c2c0012eb1e" tar xvzf netifaces-0.10.4.tar.gz cd netifaces-0.10.4 && python setup.py install ```
I landed on this question while doing something similar: ``` pip install rackspace-novaclient ``` And this is what my error looked like: ``` Command "/usr/bin/python -c "import setuptools, tokenize;__file__='/tmp/pip-build-G5GwYu/netifaces/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-Jugr2a-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-G5GwYu/netifaces ``` After reading the entire output logs, I realized I was missing "gcc" and just needed to install it. On CentOS 7, my fix was: ``` yum -y install gcc && pip install rackspace-novaclient ```
27,914,930
I'm trying to install OpenStack python novaclient using pip install python-novaclient This task fails: netifaces.c:185:6 #error You need to add code for your platform I have no idea what code it wants. Does anyone understand this?
2015/01/13
[ "https://Stackoverflow.com/questions/27914930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/518012/" ]
I also had this problem, and resolved by `sudo yum install python-devel python-pip sudo yum -y install gcc`
This has to do with the order that libraries are imported in the netifaces setup.py and is fixed in version 10.3+ (which you need to install from source). Here's how to install 10.4 (current latest release): ``` mkdir -p /tmp/install/netifaces/ cd /tmp/install/netifaces && wget -O "netifaces-0.10.4.tar.gz" "https://pypi.python.org/packages/source/n/netifaces/netifaces-0.10.4.tar.gz#md5=36da76e2cfadd24cc7510c2c0012eb1e" tar xvzf netifaces-0.10.4.tar.gz cd netifaces-0.10.4 && python setup.py install ```
27,914,930
I'm trying to install OpenStack python novaclient using pip install python-novaclient This task fails: netifaces.c:185:6 #error You need to add code for your platform I have no idea what code it wants. Does anyone understand this?
2015/01/13
[ "https://Stackoverflow.com/questions/27914930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/518012/" ]
Same issue in awx\_task container in AWX project (Centos 7), trying to execute ``` pip install python-openstackclient ``` Error was: ``` Command "/usr/bin/python2 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-LTchWP/netifaces/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-86uBIZ-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-LTchWP/netifaces/ ``` Solved with: ``` yum install python-devel python-pip gcc ``` Hope it will help someone!
This has to do with the order that libraries are imported in the netifaces setup.py and is fixed in version 10.3+ (which you need to install from source). Here's how to install 10.4 (current latest release): ``` mkdir -p /tmp/install/netifaces/ cd /tmp/install/netifaces && wget -O "netifaces-0.10.4.tar.gz" "https://pypi.python.org/packages/source/n/netifaces/netifaces-0.10.4.tar.gz#md5=36da76e2cfadd24cc7510c2c0012eb1e" tar xvzf netifaces-0.10.4.tar.gz cd netifaces-0.10.4 && python setup.py install ```
27,914,930
I'm trying to install OpenStack python novaclient using pip install python-novaclient This task fails: netifaces.c:185:6 #error You need to add code for your platform I have no idea what code it wants. Does anyone understand this?
2015/01/13
[ "https://Stackoverflow.com/questions/27914930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/518012/" ]
I also had this problem, and resolved by `sudo yum install python-devel python-pip sudo yum -y install gcc`
I landed on this question while doing something similar: ``` pip install rackspace-novaclient ``` And this is what my error looked like: ``` Command "/usr/bin/python -c "import setuptools, tokenize;__file__='/tmp/pip-build-G5GwYu/netifaces/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-Jugr2a-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-G5GwYu/netifaces ``` After reading the entire output logs, I realized I was missing "gcc" and just needed to install it. On CentOS 7, my fix was: ``` yum -y install gcc && pip install rackspace-novaclient ```
27,914,930
I'm trying to install OpenStack python novaclient using pip install python-novaclient This task fails: netifaces.c:185:6 #error You need to add code for your platform I have no idea what code it wants. Does anyone understand this?
2015/01/13
[ "https://Stackoverflow.com/questions/27914930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/518012/" ]
Same issue in awx\_task container in AWX project (Centos 7), trying to execute ``` pip install python-openstackclient ``` Error was: ``` Command "/usr/bin/python2 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-LTchWP/netifaces/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-86uBIZ-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-LTchWP/netifaces/ ``` Solved with: ``` yum install python-devel python-pip gcc ``` Hope it will help someone!
I landed on this question while doing something similar: ``` pip install rackspace-novaclient ``` And this is what my error looked like: ``` Command "/usr/bin/python -c "import setuptools, tokenize;__file__='/tmp/pip-build-G5GwYu/netifaces/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-Jugr2a-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-G5GwYu/netifaces ``` After reading the entire output logs, I realized I was missing "gcc" and just needed to install it. On CentOS 7, my fix was: ``` yum -y install gcc && pip install rackspace-novaclient ```
71,870,864
I'm writing a python tool with modules at different 'levels': * A low-level module, that can do everything, with a bit of work * A higher level module, with added "sugar" and helper functions I would like to be able to share function signatures from the low-level module to the higher one, so that intellisense works with both modules. > > In the following examples, I'm using the `width` and `height` parameters as placeholders for a pretty long list of arguments (around 30). > > > I could do everything explicitly. This works, the interface is what I want, and intellisense works; but it's very tedious, error prone and a nightmare to maintain: ```py # high level function, wraps/uses the low level one def create_rectangles(count, width=10, height=10): return [create_rectangle(width=width, height=height) for _ in range(count)] # low level function def create_rectangle(width=10, height=10): print(f"the rectangle is {width} wide and {height} high") create_rectangles(3, width=10, height=5) ``` I could create a class to hold the lower function's parameters. It's very readable, intellisense works, but the interface in clunky: ```py class RectOptions: def __init__(self, width=10, height=10) -> None: self.width = width self.height = height def create_rectangles(count, rectangle_options:RectOptions): return [create_rectangle(rectangle_options) for _ in range(count)] def create_rectangle(options:RectOptions): print(f"the rectangle is {options.width} wide and {options.height} high") # needing to create an instance for a function call feels clunky... create_rectangles(3, RectOptions(width=10, height=3)) ``` I could simply use `**kwargs`. It's concise and allows a good interface, but it breaks intellisense and is not very readable: ```py def create_rectangles(count, **kwargs): return [create_rectangle(**kwargs) for _ in range(count)] def create_rectangle(width, height): print(f"the rectangle is {width} wide and {height} high") create_rectangles(3, width=10, height=3) ``` What I would like is something that has the advantages of kwargs but with better readability/typing/intellisense support: ```py # pseudo-python class RectOptions: def __init__(self, width=10, height=10) -> None: self.width = width self.height = height # The '**' operator would add properties from rectangle_options to the function signature # We could even 'inherit' parameters from multiple sources, and error in case of conflict def create_rectangles(count, **rectangle_options:RectOptions): return [create_rectangle(rectangle_options) for idx in range(count)] def create_rectangle(options:RectOptions): print(f"the rectangle is {options.width} wide and {options.height} high") create_rectangles(3, width=10, height=3) ``` I could use code generation, but I'm not very familiar with that, and it seems like it would add a lot of complexity. While looking for a solution, I stumbled upon this [reddit post](https://www.reddit.com/r/Python/comments/8kmzfw/new_to_the_python_but_read_a_lot_of_codebases_and/). From what I understand, what I'm looking for is not currently possible, but I really hope I'm wrong about that I've tried the the [docstring\_expander](https://pypi.org/project/docstring-expander/) pip package, since it looks like it's meant to solve this problem, but it didn't do anything for me (I might be using it wrong...) I don't think this matters but just in case: I'm using vscode 1.59 and python 3.9.9
2022/04/14
[ "https://Stackoverflow.com/questions/71870864", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2486378/" ]
While `args` [won't be null](https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/program-structure/main-command-line#command-line-arguments) (See the green **Tip** box in the link), it might be an Array of length 0. So `args[0]` doesn't exist because it refers to the first item in the array, which doesn't have any items. If you are really setting it in "command line arguments" in Visual Studio and are really using debug mode - see [this answer](https://stackoverflow.com/a/54189058/939213). Basically - make sure it's all on "Any CPU". **EDIT** Change ``` string[] inputArray = input.Split(); ``` to ``` string[] inputArray = input.ToCharArray(); ```
How do you start Main function (program)? Do you pass arguments to Main function? If not, lenght of your args array is 0 (you don't have any fields in that array).
71,870,864
I'm writing a python tool with modules at different 'levels': * A low-level module, that can do everything, with a bit of work * A higher level module, with added "sugar" and helper functions I would like to be able to share function signatures from the low-level module to the higher one, so that intellisense works with both modules. > > In the following examples, I'm using the `width` and `height` parameters as placeholders for a pretty long list of arguments (around 30). > > > I could do everything explicitly. This works, the interface is what I want, and intellisense works; but it's very tedious, error prone and a nightmare to maintain: ```py # high level function, wraps/uses the low level one def create_rectangles(count, width=10, height=10): return [create_rectangle(width=width, height=height) for _ in range(count)] # low level function def create_rectangle(width=10, height=10): print(f"the rectangle is {width} wide and {height} high") create_rectangles(3, width=10, height=5) ``` I could create a class to hold the lower function's parameters. It's very readable, intellisense works, but the interface in clunky: ```py class RectOptions: def __init__(self, width=10, height=10) -> None: self.width = width self.height = height def create_rectangles(count, rectangle_options:RectOptions): return [create_rectangle(rectangle_options) for _ in range(count)] def create_rectangle(options:RectOptions): print(f"the rectangle is {options.width} wide and {options.height} high") # needing to create an instance for a function call feels clunky... create_rectangles(3, RectOptions(width=10, height=3)) ``` I could simply use `**kwargs`. It's concise and allows a good interface, but it breaks intellisense and is not very readable: ```py def create_rectangles(count, **kwargs): return [create_rectangle(**kwargs) for _ in range(count)] def create_rectangle(width, height): print(f"the rectangle is {width} wide and {height} high") create_rectangles(3, width=10, height=3) ``` What I would like is something that has the advantages of kwargs but with better readability/typing/intellisense support: ```py # pseudo-python class RectOptions: def __init__(self, width=10, height=10) -> None: self.width = width self.height = height # The '**' operator would add properties from rectangle_options to the function signature # We could even 'inherit' parameters from multiple sources, and error in case of conflict def create_rectangles(count, **rectangle_options:RectOptions): return [create_rectangle(rectangle_options) for idx in range(count)] def create_rectangle(options:RectOptions): print(f"the rectangle is {options.width} wide and {options.height} high") create_rectangles(3, width=10, height=3) ``` I could use code generation, but I'm not very familiar with that, and it seems like it would add a lot of complexity. While looking for a solution, I stumbled upon this [reddit post](https://www.reddit.com/r/Python/comments/8kmzfw/new_to_the_python_but_read_a_lot_of_codebases_and/). From what I understand, what I'm looking for is not currently possible, but I really hope I'm wrong about that I've tried the the [docstring\_expander](https://pypi.org/project/docstring-expander/) pip package, since it looks like it's meant to solve this problem, but it didn't do anything for me (I might be using it wrong...) I don't think this matters but just in case: I'm using vscode 1.59 and python 3.9.9
2022/04/14
[ "https://Stackoverflow.com/questions/71870864", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2486378/" ]
While `args` [won't be null](https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/program-structure/main-command-line#command-line-arguments) (See the green **Tip** box in the link), it might be an Array of length 0. So `args[0]` doesn't exist because it refers to the first item in the array, which doesn't have any items. If you are really setting it in "command line arguments" in Visual Studio and are really using debug mode - see [this answer](https://stackoverflow.com/a/54189058/939213). Basically - make sure it's all on "Any CPU". **EDIT** Change ``` string[] inputArray = input.Split(); ``` to ``` string[] inputArray = input.ToCharArray(); ```
You are checking `input.Length` but you are *accessing* `inputArray[i]`.
71,870,864
I'm writing a python tool with modules at different 'levels': * A low-level module, that can do everything, with a bit of work * A higher level module, with added "sugar" and helper functions I would like to be able to share function signatures from the low-level module to the higher one, so that intellisense works with both modules. > > In the following examples, I'm using the `width` and `height` parameters as placeholders for a pretty long list of arguments (around 30). > > > I could do everything explicitly. This works, the interface is what I want, and intellisense works; but it's very tedious, error prone and a nightmare to maintain: ```py # high level function, wraps/uses the low level one def create_rectangles(count, width=10, height=10): return [create_rectangle(width=width, height=height) for _ in range(count)] # low level function def create_rectangle(width=10, height=10): print(f"the rectangle is {width} wide and {height} high") create_rectangles(3, width=10, height=5) ``` I could create a class to hold the lower function's parameters. It's very readable, intellisense works, but the interface in clunky: ```py class RectOptions: def __init__(self, width=10, height=10) -> None: self.width = width self.height = height def create_rectangles(count, rectangle_options:RectOptions): return [create_rectangle(rectangle_options) for _ in range(count)] def create_rectangle(options:RectOptions): print(f"the rectangle is {options.width} wide and {options.height} high") # needing to create an instance for a function call feels clunky... create_rectangles(3, RectOptions(width=10, height=3)) ``` I could simply use `**kwargs`. It's concise and allows a good interface, but it breaks intellisense and is not very readable: ```py def create_rectangles(count, **kwargs): return [create_rectangle(**kwargs) for _ in range(count)] def create_rectangle(width, height): print(f"the rectangle is {width} wide and {height} high") create_rectangles(3, width=10, height=3) ``` What I would like is something that has the advantages of kwargs but with better readability/typing/intellisense support: ```py # pseudo-python class RectOptions: def __init__(self, width=10, height=10) -> None: self.width = width self.height = height # The '**' operator would add properties from rectangle_options to the function signature # We could even 'inherit' parameters from multiple sources, and error in case of conflict def create_rectangles(count, **rectangle_options:RectOptions): return [create_rectangle(rectangle_options) for idx in range(count)] def create_rectangle(options:RectOptions): print(f"the rectangle is {options.width} wide and {options.height} high") create_rectangles(3, width=10, height=3) ``` I could use code generation, but I'm not very familiar with that, and it seems like it would add a lot of complexity. While looking for a solution, I stumbled upon this [reddit post](https://www.reddit.com/r/Python/comments/8kmzfw/new_to_the_python_but_read_a_lot_of_codebases_and/). From what I understand, what I'm looking for is not currently possible, but I really hope I'm wrong about that I've tried the the [docstring\_expander](https://pypi.org/project/docstring-expander/) pip package, since it looks like it's meant to solve this problem, but it didn't do anything for me (I might be using it wrong...) I don't think this matters but just in case: I'm using vscode 1.59 and python 3.9.9
2022/04/14
[ "https://Stackoverflow.com/questions/71870864", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2486378/" ]
You are checking `input.Length` but you are *accessing* `inputArray[i]`.
How do you start Main function (program)? Do you pass arguments to Main function? If not, lenght of your args array is 0 (you don't have any fields in that array).
56,695,227
I'm using `tf.estimator` API with TensorFlow 1.13 on Google AI Platform to build a DNN Binary Classifier. For some reason I don't get a `eval` graph but I do get a `training` graph. Here are two different methods for performing training. The first is the normal python method and the second is using GCP AI Platform in local mode. Notice in either method, the evaluation is simply a dot for what appears to be the final result. I was expecting a plot similar to training where it would be a curve. Lastly, I show the relevant model code for the performance metric. **Normal python notebook method:** [![enter image description here](https://i.stack.imgur.com/vAdF1.png)](https://i.stack.imgur.com/vAdF1.png) ``` %%bash #echo ${PYTHONPATH}:${PWD}/${MODEL_NAME} export PYTHONPATH=${PYTHONPATH}:${PWD}/${MODEL_NAME} python -m trainer.task \ --train_data_paths="${PWD}/samples/train_sounds*" \ --eval_data_paths=${PWD}/samples/valid_sounds.csv \ --output_dir=${PWD}/${TRAINING_DIR} \ --hidden_units="175" \ --train_steps=5000 --job-dir=./tmp ``` **Local gcloud (GCP) ai-platform method:** [![enter image description here](https://i.stack.imgur.com/ZPxVQ.png)](https://i.stack.imgur.com/ZPxVQ.png) ``` %%bash OUTPUT_DIR=${PWD}/${TRAINING_DIR} echo "OUTPUT_DIR=${OUTPUT_DIR}" echo "train_data_paths=${PWD}/${TRAINING_DATA_DIR}/train_sounds*" gcloud ai-platform local train \ --module-name=trainer.task \ --package-path=${PWD}/${MODEL_NAME}/trainer \ -- \ --train_data_paths="${PWD}/${TRAINING_DATA_DIR}/train_sounds*" \ --eval_data_paths=${PWD}/${TRAINING_DATA_DIR}/valid_sounds.csv \ --hidden_units="175" \ --train_steps=5000 \ --output_dir=${OUTPUT_DIR} ``` **The performance metric code** ``` estimator = tf.contrib.estimator.add_metrics(estimator, my_auc) ``` And ``` # This is from the tensorflow website for adding metrics for a DNNClassifier # https://www.tensorflow.org/api_docs/python/tf/metrics/auc def my_auc(features, labels, predictions): return { #'auc': tf.metrics.auc( labels, predictions['logistic'], weights=features['weight']) #'auc': tf.metrics.auc( labels, predictions['logistic'], weights=features[LABEL]) # 'auc': tf.metrics.auc( labels, predictions['logistic']) 'auc': tf.metrics.auc( labels, predictions['class_ids']), 'accuracy': tf.metrics.accuracy( labels, predictions['class_ids']) } ``` **The method used during train and evaluate** ``` eval_spec = tf.estimator.EvalSpec( input_fn = read_dataset( filename = args['eval_data_paths'], mode = tf.estimator.ModeKeys.EVAL, batch_size = args['eval_batch_size']), steps=100, throttle_secs=10, exporters = exporter) # addition of throttle_secs=10 above and this # below as a result of one of the suggested answers. # The result is that these mods do no print the final # evaluation graph much less the intermediate results tf.estimator.RunConfig(save_checkpoints_steps=10) tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec) ``` **The DNN binary classifier using tf.estimator** ``` estimator = tf.estimator.DNNClassifier( model_dir = model_dir, feature_columns = final_columns, hidden_units=hidden_units, n_classes=2) ``` **screenshot of file in model\_trained/eval dir.** Only this one file is in this directory. It is named model\_trained/eval/events.out.tfevents.1561296248.myhostname.local and looks like [![enter image description here](https://i.stack.imgur.com/QoC9O.png)](https://i.stack.imgur.com/QoC9O.png)
2019/06/20
[ "https://Stackoverflow.com/questions/56695227", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1008596/" ]
With the comment and suggestions as well as tweaking the parameters, here is the result which works for me. The code to start the tensorboard, train the model etc. Using ------- to denote a notebook cell --- ``` %%bash # clean model output dirs # This is so that the trained model is deleted output_dir=${PWD}/${TRAINING_DIR} echo ${output_dir} rm -rf ${output_dir} ``` --- ``` # start tensorboard def tb(logdir="logs", port=6006, open_tab=True, sleep=2): import subprocess proc = subprocess.Popen( "exec " + "tensorboard --logdir={0} --port={1}".format(logdir, port), shell=True) if open_tab: import time time.sleep(sleep) import webbrowser webbrowser.open("http://127.0.0.1:{}/".format(port)) return proc cwd = os.getcwd() output_dir=cwd + '/' + TRAINING_DIR print(output_dir) server1 = tb(logdir=output_dir) ``` --- ``` %%bash # The model run config is hard coded to checkpoint every 500 steps # #echo ${PYTHONPATH}:${PWD}/${MODEL_NAME} export PYTHONPATH=${PYTHONPATH}:${PWD}/${MODEL_NAME} python -m trainer.task \ --train_data_paths="${PWD}/samples/train_sounds*" \ --eval_data_paths=${PWD}/samples/valid_sounds.csv \ --output_dir=${PWD}/${TRAINING_DIR} \ --hidden_units="175" \ --train_batch_size=10 \ --eval_batch_size=100 \ --eval_steps=1000 \ --min_eval_frequency=15 \ --train_steps=20000 --job-dir=./tmp ``` The relevant model code ``` # This hard codes the checkpoints to be # every 500 training steps? estimator = tf.estimator.DNNClassifier( model_dir = model_dir, feature_columns = final_columns, hidden_units=hidden_units, config=tf.estimator.RunConfig(save_checkpoints_steps=500), n_classes=2) # trainspec to tell the estimator how to get training data train_spec = tf.estimator.TrainSpec( input_fn = read_dataset( filename = args['train_data_paths'], mode = tf.estimator.ModeKeys.TRAIN, # make sure you use the dataset api batch_size = args['train_batch_size']), max_steps = args['train_steps']) # max_steps allows a resume exporter = tf.estimator.LatestExporter(name = 'exporter', serving_input_receiver_fn = serving_input_fn) eval_spec = tf.estimator.EvalSpec( input_fn = read_dataset( filename = args['eval_data_paths'], mode = tf.estimator.ModeKeys.EVAL, batch_size = args['eval_batch_size']), steps=args['eval_steps'], throttle_secs = args['min_eval_frequency'], exporters = exporter) tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec) ``` The resultant graphs [![enter image description here](https://i.stack.imgur.com/Lr5w4.png)](https://i.stack.imgur.com/Lr5w4.png) [![enter image description here](https://i.stack.imgur.com/QjZVj.png)](https://i.stack.imgur.com/QjZVj.png)
In `estimator.train_and_evaluate()` you specify a `train_spec` and an `eval_spec`. The `eval_spec` often has a different input function (e.g. development evaluation dataset, non-shuffled) Every N steps, a checkpoint from the train process is saved, and the eval process loads those same weights and runs according to the `eval_spec`. Those eval summaries are logged under the step number of the checkpoint, so you are able to compare train vs test performance. In your case, evaluation produces only a single point on the graph for each call to evaluate. This point contains the average over the entire evaluation call. Take a look at [this](https://github.com/tensorflow/tensorflow/issues/18858) similar issue: I would modify `tf.estimator.EvalSpec` with `throttle_secs` small value (Default is 600) and `save_checkpoints_steps` in `tf.estimator.RunConfig` to an small value as well: `tf.estimator.RunConfig(save_checkpoints_steps=SOME_SMALL_VALUE_TO_VERIFY)` [![enter image description here](https://i.stack.imgur.com/2arND.png)](https://i.stack.imgur.com/2arND.png)
71,276,514
I had everything working fine, then out of nowhere I keep getting this ``` PS C:\Users\rygra\Documents\Ryan Projects\totalwine-product-details-scraper> ensurepip ensurepip : The term 'ensurepip' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + ensurepip + ~~~~~~~~~ + CategoryInfo : ObjectNotFound: (ensurepip:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException PS C:\Users\rygra\Documents\Ryan Projects\totalwine-product-details-scraper> py get-pip.py C:\Users\rygra\AppData\Local\Programs\Python\Python310\python.exe: can't open file 'C:\\Users\\rygra\\Documents\\Ryan Projects\\totalwine-product-details-scraper\\get-pip.py': [Errno 2] No such file or directory PS C:\Users\rygra\Documents\Ryan Projects\totalwine-product-details-scraper> ``` How do I resolve this issue?
2022/02/26
[ "https://Stackoverflow.com/questions/71276514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18312732/" ]
Add param `android:exported` in `AndroidManifest.xml` file under `activity` Like below code: ``` <activity android:name=".MainActivity" android:exported="true"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> ``` Add `android:exported="true"` for Launcher activity and `android:exported="false"` to other activities.
Goto **AndroidManifest.xml** and add the following line to each activity ``` <activity android:name=".MainActivity" android:exported="true" /> ```
12,755,804
I am trying to run a python script on my mac .I am getting the error :- > > ImportError: No module named opengl.opengl > > > I googled a bit and found that I was missing pyopengl .I installed pip.I go to the directory pip-1.0 and then say > > sudo pip install pyopengl > > > and it installs correctly I believe because I got this > > Successfully installed pyopengl Cleaning up... > > > at the end. I rerun the script but i am still getting the same error .Can someone tell me what I might be missing? Thanks!
2012/10/06
[ "https://Stackoverflow.com/questions/12755804", "https://Stackoverflow.com", "https://Stackoverflow.com/users/592667/" ]
Is it in the PYTHON-PATH? Maybe try something like this: ``` import sys sys.path.append(opengl-dir) import opengl.opengl ``` Replace the opengl-dir with the directory that you have installed in... Maybe try what RocketDonkey is suggesting... I don't know, really...
Thanks guys! I figured it out.It was infact a separate module which I needed to copy over to the "site-packages" location and it worked fine.So in summary no issues with the path just that the appropriate module was not there.
11,713,871
I am playing with Heroku to test how good it is for Django apps. I created a simple project with two actions: 1. return simple hello world 2. generate image and send it as response I used `siege -c10 -t30s` to test both Django dev server and gunicorn (both running on Heroku). These are my results: **Simple hello world** - django dev ``` Lifting the server siege... done. Transactions: 376 hits Availability: 100.00 % Elapsed time: 29.75 secs Data transferred: 0.00 MB Response time: 0.29 secs Transaction rate: 12.64 trans/sec Throughput: 0.00 MB/sec Concurrency: 3.65 Successful transactions: 376 Failed transactions: 0 Longest transaction: 0.50 Shortest transaction: 0.26 ``` - gunicorn ``` Lifting the server siege... done. Transactions: 357 hits Availability: 100.00 % Elapsed time: 29.27 secs Data transferred: 0.00 MB Response time: 0.27 secs Transaction rate: 12.20 trans/sec Throughput: 0.00 MB/sec Concurrency: 3.34 Successful transactions: 357 Failed transactions: 0 Longest transaction: 0.34 Shortest transaction: 0.26 ``` **generating images** - django dev ``` Lifting the server siege... done. Transactions: 144 hits Availability: 100.00 % Elapsed time: 29.91 secs Data transferred: 0.15 MB Response time: 1.52 secs Transaction rate: 4.81 trans/sec Throughput: 0.01 MB/sec Concurrency: 7.32 Successful transactions: 144 Failed transactions: 0 Longest transaction: 4.14 Shortest transaction: 1.13 ``` - gunicorn ``` Lifting the server siege... done. Transactions: 31 hits Availability: 100.00 % Elapsed time: 29.42 secs Data transferred: 0.05 MB Response time: 7.39 secs Transaction rate: 1.05 trans/sec Throughput: 0.00 MB/sec Concurrency: 7.78 Successful transactions: 31 Failed transactions: 0 Longest transaction: 9.13 Shortest transaction: 1.19 ``` I used - Django 1.4 - Gunicorn 0.14.6 - venv Why is gunicorn so slow? //UPDATE Both tests were running in Heroku envirenment dev server means standard django server - it can be ran by `python manage.py runserver` it is described [here](https://devcenter.heroku.com/articles/django#using_a_different_wsgi_server).
2012/07/29
[ "https://Stackoverflow.com/questions/11713871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/513686/" ]
Are settings the same? Django 1.4 dev server is multithreaded by default and there is only 1 sync worker in gunicorn default config.
You're going to have to set up [application profiling](http://docs.python.org/library/profile.html) to gain some insight into where exactly the problem is located.
11,713,871
I am playing with Heroku to test how good it is for Django apps. I created a simple project with two actions: 1. return simple hello world 2. generate image and send it as response I used `siege -c10 -t30s` to test both Django dev server and gunicorn (both running on Heroku). These are my results: **Simple hello world** - django dev ``` Lifting the server siege... done. Transactions: 376 hits Availability: 100.00 % Elapsed time: 29.75 secs Data transferred: 0.00 MB Response time: 0.29 secs Transaction rate: 12.64 trans/sec Throughput: 0.00 MB/sec Concurrency: 3.65 Successful transactions: 376 Failed transactions: 0 Longest transaction: 0.50 Shortest transaction: 0.26 ``` - gunicorn ``` Lifting the server siege... done. Transactions: 357 hits Availability: 100.00 % Elapsed time: 29.27 secs Data transferred: 0.00 MB Response time: 0.27 secs Transaction rate: 12.20 trans/sec Throughput: 0.00 MB/sec Concurrency: 3.34 Successful transactions: 357 Failed transactions: 0 Longest transaction: 0.34 Shortest transaction: 0.26 ``` **generating images** - django dev ``` Lifting the server siege... done. Transactions: 144 hits Availability: 100.00 % Elapsed time: 29.91 secs Data transferred: 0.15 MB Response time: 1.52 secs Transaction rate: 4.81 trans/sec Throughput: 0.01 MB/sec Concurrency: 7.32 Successful transactions: 144 Failed transactions: 0 Longest transaction: 4.14 Shortest transaction: 1.13 ``` - gunicorn ``` Lifting the server siege... done. Transactions: 31 hits Availability: 100.00 % Elapsed time: 29.42 secs Data transferred: 0.05 MB Response time: 7.39 secs Transaction rate: 1.05 trans/sec Throughput: 0.00 MB/sec Concurrency: 7.78 Successful transactions: 31 Failed transactions: 0 Longest transaction: 9.13 Shortest transaction: 1.19 ``` I used - Django 1.4 - Gunicorn 0.14.6 - venv Why is gunicorn so slow? //UPDATE Both tests were running in Heroku envirenment dev server means standard django server - it can be ran by `python manage.py runserver` it is described [here](https://devcenter.heroku.com/articles/django#using_a_different_wsgi_server).
2012/07/29
[ "https://Stackoverflow.com/questions/11713871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/513686/" ]
Are settings the same? Django 1.4 dev server is multithreaded by default and there is only 1 sync worker in gunicorn default config.
Maybe the speed of your Internet connection is a bottleneck? Downloading data from Heroku is obviously slower than moving it through localhost (I assume django dev server is run at localhost). This may explain why benchmarks with small responses (hellowords) are equally fast and the benchmarks with large responses (images) are slow for Heroku.
45,877,080
I'm trying to create a dropdown menu in HTML using info from a python script. I've gotten it to work thus far, however, the html dropdown displays all 4 values in the lists as 4 options. Current: **Option 1:** Red, Blue, Black Orange; **Option 2:** Red, Blue, Black, Orange etc. (Screenshot in link) [Current](https://i.stack.imgur.com/8w0tz.png) Desired: **Option 1:** Red **Option 2:** Blue etc. How do I make it so that the python list is separated? dropdown.py ``` from flask import Flask, render_template, request app = Flask(__name__) app.debug = True @app.route('/', methods=['GET']) def dropdown(): colours = ['Red', 'Blue', 'Black', 'Orange'] return render_template('test.html', colours=colours) if __name__ == "__main__": app.run() ``` test.html ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Dropdown</title> </head> <body> <select name= colours method="GET" action="/"> {% for colour in colours %} <option value= "{{colour}}" SELECTED>{{colours}}</option>" {% endfor %} </select> </body> </html> ```
2017/08/25
[ "https://Stackoverflow.com/questions/45877080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8515504/" ]
you have a typo, replace `colours` to `colour` ``` <option value= "{{colour}}" SELECTED>{{colours}}</option>" ``` replace to ``` <option value= "{{colour}}" SELECTED>{{ colour }}</option>" <!-- ^^^^ --> ```
You need to use `{{colour}}` in both places (instead of `{{colours}}` in the second place): ``` <select name="colour" method="GET" action="/"> {% for colour in colours %} <option value="{{colour}}" SELECTED>{{colour}}</option>" {% endfor %} </select> ``` Note that using `selected` inside the loop will add `selected` attribute to all options and the last one will be selected, what you need to do is the following: ``` <select name="colour" method="GET" action="/"> <option value="{{colours[0]}}" selected>{{colours[0]}}</option> {% for colour in colours[1:] %} <option value="{{colour}}">{{colour}}</option> {% endfor %} </select> ```
37,691,552
I have the following code that is leveraging multiprocessing to iterate through a large list and find a match. How can I get all processes to stop once a match is found in any one processes? I have seen examples but I none of them seem to fit into what I am doing here. ``` #!/usr/bin/env python3.5 import sys, itertools, multiprocessing, functools alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ12234567890!@#$%^&*?,()-=+[]/;" num_parts = 4 part_size = len(alphabet) // num_parts def do_job(first_bits): for x in itertools.product(first_bits, *itertools.repeat(alphabet, num_parts-1)): # CHECK FOR MATCH HERE print(''.join(x)) # EXIT ALL PROCESSES IF MATCH FOUND if __name__ == '__main__': pool = multiprocessing.Pool(processes=4) results = [] for i in range(num_parts): if i == num_parts - 1: first_bit = alphabet[part_size * i :] else: first_bit = alphabet[part_size * i : part_size * (i+1)] pool.apply_async(do_job, (first_bit,)) pool.close() pool.join() ``` Thanks for your time. **UPDATE 1:** I have implemented the changes suggested in the great approach by @ShadowRanger and it is nearly working the way I want it to. So I have added some logging to give an indication of progress and put a 'test' key in there to match. I want to be able to increase/decrease the iNumberOfProcessors independently of the num\_parts. At this stage when I have them both at 4 everything works as expected, 4 processes spin up (one extra for the console). When I change the iNumberOfProcessors = 6, 6 processes spin up but only for of them have any CPU usage. So it appears 2 are idle. Where as my previous solution above, I was able to set the number of cores higher without increasing the num\_parts, and all of the processes would get used. [![enter image description here](https://i.stack.imgur.com/YjNj4.png)](https://i.stack.imgur.com/YjNj4.png) I am not sure about how to refactor this new approach to give me the same functionality. Can you have a look and give me some direction with the refactoring needed to be able to set iNumberOfProcessors and num\_parts independently from each other and still have all processes used? Here is the updated code: ``` #!/usr/bin/env python3.5 import sys, itertools, multiprocessing, functools alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ12234567890!@#$%^&*?,()-=+[]/;" num_parts = 4 part_size = len(alphabet) // num_parts iProgressInterval = 10000 iNumberOfProcessors = 6 def do_job(first_bits): iAttemptNumber = 0 iLastProgressUpdate = 0 for x in itertools.product(first_bits, *itertools.repeat(alphabet, num_parts-1)): sKey = ''.join(x) iAttemptNumber = iAttemptNumber + 1 if iLastProgressUpdate + iProgressInterval <= iAttemptNumber: iLastProgressUpdate = iLastProgressUpdate + iProgressInterval print("Attempt#:", iAttemptNumber, "Key:", sKey) if sKey == 'test': print("KEY FOUND!! Attempt#:", iAttemptNumber, "Key:", sKey) return True def get_part(i): if i == num_parts - 1: first_bit = alphabet[part_size * i :] else: first_bit = alphabet[part_size * i : part_size * (i+1)] return first_bit if __name__ == '__main__': # with statement with Py3 multiprocessing.Pool terminates when block exits with multiprocessing.Pool(processes = iNumberOfProcessors) as pool: # Don't need special case for final block; slices can for gotmatch in pool.imap_unordered(do_job, map(get_part, range(num_parts))): if gotmatch: break else: print("No matches found") ``` **UPDATE 2:** Ok here is my attempt at trying @noxdafox suggestion. I have put together the following based on the link he provided with his suggestion. Unfortunately when I run it I get the error: ... line 322, in apply\_async raise ValueError("Pool not running") ValueError: Pool not running Can anyone give me some direction on how to get this working. Basically the issue is that my first attempt did multiprocessing but did not support canceling all processes once a match was found. My second attempt (based on @ShadowRanger suggestion) solved that problem, but broke the functionality of being able to scale the number of processes and num\_parts size independently, which is something my first attempt could do. My third attempt (based on @noxdafox suggestion), throws the error outlined above. If anyone can give me some direction on how to maintain the functionality of my first attempt (being able to scale the number of processes and num\_parts size independently), and add the functionality of canceling all processes once a match was found it would be much appreciated. Thank you for your time. Here is the code from my third attempt based on @noxdafox suggestion: ``` #!/usr/bin/env python3.5 import sys, itertools, multiprocessing, functools alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ12234567890!@#$%^&*?,()-=+[]/;" num_parts = 4 part_size = len(alphabet) // num_parts iProgressInterval = 10000 iNumberOfProcessors = 4 def find_match(first_bits): iAttemptNumber = 0 iLastProgressUpdate = 0 for x in itertools.product(first_bits, *itertools.repeat(alphabet, num_parts-1)): sKey = ''.join(x) iAttemptNumber = iAttemptNumber + 1 if iLastProgressUpdate + iProgressInterval <= iAttemptNumber: iLastProgressUpdate = iLastProgressUpdate + iProgressInterval print("Attempt#:", iAttemptNumber, "Key:", sKey) if sKey == 'test': print("KEY FOUND!! Attempt#:", iAttemptNumber, "Key:", sKey) return True def get_part(i): if i == num_parts - 1: first_bit = alphabet[part_size * i :] else: first_bit = alphabet[part_size * i : part_size * (i+1)] return first_bit def grouper(iterable, n, fillvalue=None): args = [iter(iterable)] * n return itertools.zip_longest(*args, fillvalue=fillvalue) class Worker(): def __init__(self, workers): self.workers = workers def callback(self, result): if result: self.pool.terminate() def do_job(self): print(self.workers) pool = multiprocessing.Pool(processes=self.workers) for part in grouper(alphabet, part_size): pool.apply_async(do_job, (part,), callback=self.callback) pool.close() pool.join() print("All Jobs Queued") if __name__ == '__main__': w = Worker(4) w.do_job() ```
2016/06/08
[ "https://Stackoverflow.com/questions/37691552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2109254/" ]
You can check [this question](https://stackoverflow.com/questions/33447055/python-multiprocess-pool-how-to-exit-the-script-when-one-of-the-worker-process/33450972#33450972) to see an implementation example solving your problem. This works also with concurrent.futures pool. Just replace the `map` method with `apply_async` and iterated over your list from the caller. Something like this. ``` for part in grouper(alphabet, part_size): pool.apply_async(do_job, part, callback=self.callback) ``` [grouper recipe](https://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks)
`multiprocessing` isn't really designed to cancel tasks, but you can simulate it for your particular case by using `pool.imap_unordered` and terminating the pool when you get a hit: ``` def do_job(first_bits): for x in itertools.product(first_bits, *itertools.repeat(alphabet, num_parts-1)): # CHECK FOR MATCH HERE print(''.join(x)) if match: return True # If we exit loop without a match, function implicitly returns falsy None for us # Factor out part getting to simplify imap_unordered use def get_part(i): if i == num_parts - 1: first_bit = alphabet[part_size * i :] else: first_bit = alphabet[part_size * i : part_size * (i+1)] if __name__ == '__main__': # with statement with Py3 multiprocessing.Pool terminates when block exits with multiprocessing.Pool(processes=4) as pool: # Don't need special case for final block; slices can for gotmatch in pool.imap_unordered(do_job, map(get_part, range(num_parts))): if gotmatch: break else: print("No matches found") ``` This will run `do_job` for each part, returning results as fast as it can get them. When a worker returns `True`, the loop breaks, and the `with` statement for the `Pool` is exited, `terminate`-ing the `Pool` (dropping all work in progress). Note that while this works, it's kind of abusing `multiprocessing`; it won't handle canceling individual tasks without terminating the whole `Pool`. If you need more fine grained task cancellation, you'll want to look at [`concurrent.futures`](https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Future.cancel), but even there, it can only cancel undispatched tasks; once they're running, they can't be cancelled without terminating the `Executor` or using a side-band means of termination (having the task poll some interprocess object intermittently to determine if it should continue running).
21,995,255
i'm trying to use BeautifulSoup on my NAS, that is the model in the title, but i am not able to install it, with the `ipkg list` there isn't a package named BeautifulSoup. On my NAS i have this version of python: ``` Python 2.5.6 (r256:88840, Feb 16 2012, 08:51:29) [GCC 3.4.3 20041021 (prerelease)] on linux2 ``` So i think i have to use the version 3 of Beautiful soup, so i have two question: 1) anyone knows how i can install it? 2) if i can't install this module i can import directly the BeautifulSoup.py file directly in my script? if yes how i can do? thanks
2014/02/24
[ "https://Stackoverflow.com/questions/21995255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/678833/" ]
In this case I suppose that you can't even install pip to manage your Python dependencies. One way of doing so would be to download the source from <http://www.crummy.com/software/BeautifulSoup/bs3/download//3.x/>, download the tarball for your preferred version. Once done, unzip it cd into the folder and type: ``` $ python setup.py install ```
You can if you install python3 from the package manager: ``` ashton@NASty:~/bin/three/$ pip install beautifulsoup4 -- user Requirement already satisfied: beautifulsoup4 in /volume1/@appstore/py3k/usr/local/lib/python3.5/site-packages (4.8.0) Requirement already satisfied: soupsieve>=1.2 in /volume1/@appstore/py3k/usr/local/lib/python3.5/site-packages (from beautifulsoup4) (1.9.2) ```
39,215,663
I think I have the same issue as [here on SO.](https://stackoverflow.com/questions/28323644/flask-sqlalchemy-backref-not-working) Using python 3.5, flask-sqlalchemy, and sqlite. I am trying to establish a one (User) to many (Post) relationship. ``` class User(db_blog.Model): id = db_blog.Column(db_blog.Integer, primary_key=True) nickname = db_blog.Column(db_blog.String(64), index=True, unique=True) email = db_blog.Column(db_blog.String(120), unique=True) posts = db_blog.relationship('Post', backref='author', lazy='dynamic') def __repr__(self): return '<User: {0}>'.format(self.nickname) class Post(db_blog.Model): id = db_blog.Column(db_blog.Integer, primary_key=True) body = db_blog.Column(db_blog.String(2500)) title = db_blog.Column(db_blog.String(140)) user_id = db_blog.Column(db_blog.Integer, db_blog.ForeignKey('user.id')) def __init__(self, body, title, **kwargs): self.body = body self.title = title def __repr__(self): return '<Title: {0}\nPost: {1}\nAuthor: {2}>'.format(self.title, self.body, self.author) ``` Author is None. ``` >>> u = User(nickname="John Doe", email="jdoe@email.com") >>> u <User: John Doe> >>> db_blog.session.add(u) >>> db_blog.session.commit() >>> u = User.query.get(1) >>> u <User: John Doe> >>> p = Post(body="Body of post", title="Title of Post", author=u) >>> p <Title: Title of Post Post: Body of post Author: None> #Here I expect- "Author: John Doe>" ``` I get the same result after session add/commit of the post and so can't find the post author.
2016/08/29
[ "https://Stackoverflow.com/questions/39215663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5795832/" ]
If you add the newly created `post` to the `posts` attribute of the user, it will work: ``` >>> u = User(nickname="John Doe", email="jdoe@email.com") >>> u <User: John Doe> >>> db_blog.session.add(u) >>> p = Post(body="Body of post", title="Title of Post") >>> p <Title: Title of Post Post: Body of post Author: None> >>> db_blog.session.add(p) >>> db_blog.session.commit() >>> u.posts.append(p) >>> p <Title: Title of Post Post: Body of post Author: <User: John Doe>> >>> p.author <User: John Doe> ``` The reason your code doesn't work as-is, is because you've defined an `__init__` constructor for your `Post` class, and this doesn't consider the `author` field at all, so Python doesn't know what to do with that `author` parameter.
You added your own `__init__` to `Post`. While it accepts keyword arguments, it does nothing with them. You can either update it to use them ``` def __init__(self, body, title, **kwargs): self.body = body self.title = title for k, v in kwargs: setattr(self, k, v) ``` Or, ideally, you can just remove the method and let SQLAlchemy handle it for you.
15,481,808
I'm trying to set the figure size with `fig1.set_size_inches(5.5,3)` on python, but the plot produces a fig where the x label is not completely visibile. The figure itself has the size I need, but it seems like the axis inside is too tall, and the x label just doesn't fit anymore. here is my code: ``` fig1 = plt.figure() fig1.set_size_inches(5.5,4) fig1.set_dpi(300) ax = fig1.add_subplot(111) ax.grid(True,which='both') ax.hist(driveDistance,100) ax.set_xlabel('Driven Distance in km') ax.set_ylabel('Frequency') fig1.savefig('figure1_distance.png') ``` and here is the result file: ![image with 5.5x3 inch](https://i.stack.imgur.com/HMiQJ.png)
2013/03/18
[ "https://Stackoverflow.com/questions/15481808", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1862909/" ]
You could order the save method to take the artist of the x-label into consideration. This is done with the bbox\_extra\_artists and the tight layout. The resulting code would be: ``` import matplotlib.pyplot as plt fig1 = plt.figure() fig1.set_size_inches(5.5,4) fig1.set_dpi(300) ax = fig1.add_subplot(111) ax.grid(True,which='both') ax.hist(driveDistance,100) xlabel = ax.set_xlabel('Driven Distance in km') ax.set_ylabel('Frequency') fig1.savefig('figure1_distance.png', bbox_extra_artists=[xlabel], bbox_inches='tight') ```
It works for me if I initialize the figure with the `figsize` and `dpi` as `kwargs`: ``` from numpy import random from matplotlib import pyplot as plt driveDistance = random.exponential(size=100) fig1 = plt.figure(figsize=(5.5,4),dpi=300) ax = fig1.add_subplot(111) ax.grid(True,which='both') ax.hist(driveDistance,100) ax.set_xlabel('Driven Distance in km') ax.set_ylabel('Frequency') fig1.savefig('figure1_distance.png') ``` ![driveDistance](https://i.stack.imgur.com/QhxE9.png)
42,903,036
I am trying to find any way possible to get a SharePoint list in Python. I was able to connect to SharePoint and get the XML data using Rest API via this video: <https://www.youtube.com/watch?v=dvFbVPDQYyk>... but not sure how to get the list data into python. The ultimate goal will be to get the SharePoint data and import into SSMS daily. Here is what I have so far.. ``` import requests from requests_ntlm import HttpNtlmAuth url='URL would go here' username='username would go here' password='password would go here' r=requests.get(url, auth=HttpNtlmAuth(username,password),verify=False) ``` I believe these would be the next steps. I really only need help getting the data from SharePoint in Excel/CSV format preferably and should be fine from there. But any recommendations would be helpful.. ``` #PARSE XML VIA REST API #PRINT INTO DATAFRAME AND CONVERT INTO CSV #IMPORT INTO SQL SERVER #EMAIL RESULTS ```
2017/03/20
[ "https://Stackoverflow.com/questions/42903036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7418496/" ]
``` from shareplum import Site from requests_ntlm import HttpNtlmAuth server_url = "https://sharepoint.xxx.com/" site_url = server_url + "sites/org/" auth = HttpNtlmAuth('xxx\\user', 'pwd') site = Site(site_url, auth=auth, verify_ssl=False) sp_list = site.List('list name in my share point') data = sp_list.GetListItems('All Items', rowlimit=200) ```
I know this doesn't directly answer your question (and you probably have an answer by now) but I would give the [SharePlum](https://pypi.org/project/SharePlum/) library a try. It should hopefully [simplify](https://shareplum.readthedocs.io/en/latest/index.html) the process you have for interacting with SharePoint. Also, I am not sure if you have a requirement to export the data into a csv but, you can [connect directly to SQL Server](https://stackoverflow.com/a/33787509/9350722) and insert your data more directly. I would have just added this into the comments but don't have a high enough reputation yet.