content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
ImportError with Pylons/SQLAlchemy and MySQL
Firstly, I should say I'm completely new to Pylons, trying to learn web development with Python after coming from a PHP/MySQL background. I've seen similar questions to this problem, but mine is kind of a reverse version.
I've been following the Pylons book (pylonsbook.com) to setup my application and get the following error:
ImportError: libmysqlclient_r.so.15: cannot open shared object file: No such file or directory
Other questions I've seen relate to the user having an older version of libmysqlclient_r.so.15, whereas I seem to have v16 installed.
Any suggestions as to what I can/should do would be greatly appreciated. Entire output is below.
(env)eclipse@eclipse31:/var/www/python/SimpleSite$ paster setup-app development.ini
Running setup_config() from simplesite.websetup
Traceback (most recent call last):
File "/var/www/python/env/bin/paster", line 8, in <module>
load_entry_point('PasteScript==1.7.3', 'console_scripts', 'paster')()
File "/var/www/python/env/lib/python2.6/site-packages/PasteScript-1.7.3-py2.6.egg/paste/script/command.py", line 84, in run
invoke(command, command_name, options, args[1:])
File "/var/www/python/env/lib/python2.6/site-packages/PasteScript-1.7.3-py2.6.egg/paste/script/command.py", line 123, in invoke
exit_code = runner.run(args)
File "/var/www/python/env/lib/python2.6/site-packages/PasteScript-1.7.3-py2.6.egg/paste/script/appinstall.py", line 68, in run
return super(AbstractInstallCommand, self).run(new_args)
File "/var/www/python/env/lib/python2.6/site-packages/PasteScript-1.7.3-py2.6.egg/paste/script/command.py", line 218, in run
result = self.command()
File "/var/www/python/env/lib/python2.6/site-packages/PasteScript-1.7.3-py2.6.egg/paste/script/appinstall.py", line 456, in command
self, config_file, section, self.sysconfig_install_vars(installer))
File "/var/www/python/env/lib/python2.6/site-packages/PasteScript-1.7.3-py2.6.egg/paste/script/appinstall.py", line 598, in setup_config
mod.setup_app, command, filename, section, vars)
File "/var/www/python/env/lib/python2.6/site-packages/PasteScript-1.7.3-py2.6.egg/paste/script/appinstall.py", line 612, in _call_setup_app
func(command, conf, vars)
File "/var/www/python/SimpleSite/simplesite/websetup.py", line 16, in setup_app
load_environment(conf.global_conf, conf.local_conf)
File "/var/www/python/SimpleSite/simplesite/config/environment.py", line 48, in load_environment
engine = engine_from_config(config, 'sqlalchemy.')
File "/var/www/python/env/lib/python2.6/site-packages/SQLAlchemy-0.5.8-py2.6.egg/sqlalchemy/engine/__init__.py", line 241, in engine_from_config
return create_engine(url, **opts)
File "/var/www/python/env/lib/python2.6/site-packages/SQLAlchemy-0.5.8-py2.6.egg/sqlalchemy/engine/__init__.py", line 223, in create_engine
return strategy.create(*args, **kwargs)
File "/var/www/python/env/lib/python2.6/site-packages/SQLAlchemy-0.5.8-py2.6.egg/sqlalchemy/engine/strategies.py", line 62, in create
dbapi = dialect_cls.dbapi(**dbapi_args)
File "/var/www/python/env/lib/python2.6/site-packages/SQLAlchemy-0.5.8-py2.6.egg/sqlalchemy/databases/mysql.py", line 1456, in dbapi
import MySQLdb as mysql
File "/var/www/python/env/lib/python2.6/site-packages/MySQL_python-1.2.3c1-py2.6-linux-i686.egg/MySQLdb/__init__.py", line 19, in <module>
File "/var/www/python/env/lib/python2.6/site-packages/MySQL_python-1.2.3c1-py2.6-linux-i686.egg/_mysql.py", line 7, in <module>
File "/var/www/python/env/lib/python2.6/site-packages/MySQL_python-1.2.3c1-py2.6-linux-i686.egg/_mysql.py", line 6, in __bootstrap__
ImportError: libmysqlclient_r.so.15: cannot open shared object file: No such file or directory
A:
Either install the .so.15 version of the library, or find or build MySQLdb against .so.16.
A:
I had the same error, although I was working with Django. I'm using Ubuntu Lucid (10.04) and a solution that worked for me was to delete (or rename) the MySQL_python-1.2.3c1-py2.6-linux-i686.egg directory and install python-mysqldb, if you don't have it yet.
The reason seems to be that MySQL_Python binary egg is linked directly to libmysqlclient_15.so, and this library has been replaced by libmysqlclient_16.so in Lucid.
I had found this solution in: http://github.com/rafpaf/OpenHatch
| ImportError with Pylons/SQLAlchemy and MySQL | Firstly, I should say I'm completely new to Pylons, trying to learn web development with Python after coming from a PHP/MySQL background. I've seen similar questions to this problem, but mine is kind of a reverse version.
I've been following the Pylons book (pylonsbook.com) to setup my application and get the following error:
ImportError: libmysqlclient_r.so.15: cannot open shared object file: No such file or directory
Other questions I've seen relate to the user having an older version of libmysqlclient_r.so.15, whereas I seem to have v16 installed.
Any suggestions as to what I can/should do would be greatly appreciated. Entire output is below.
(env)eclipse@eclipse31:/var/www/python/SimpleSite$ paster setup-app development.ini
Running setup_config() from simplesite.websetup
Traceback (most recent call last):
File "/var/www/python/env/bin/paster", line 8, in <module>
load_entry_point('PasteScript==1.7.3', 'console_scripts', 'paster')()
File "/var/www/python/env/lib/python2.6/site-packages/PasteScript-1.7.3-py2.6.egg/paste/script/command.py", line 84, in run
invoke(command, command_name, options, args[1:])
File "/var/www/python/env/lib/python2.6/site-packages/PasteScript-1.7.3-py2.6.egg/paste/script/command.py", line 123, in invoke
exit_code = runner.run(args)
File "/var/www/python/env/lib/python2.6/site-packages/PasteScript-1.7.3-py2.6.egg/paste/script/appinstall.py", line 68, in run
return super(AbstractInstallCommand, self).run(new_args)
File "/var/www/python/env/lib/python2.6/site-packages/PasteScript-1.7.3-py2.6.egg/paste/script/command.py", line 218, in run
result = self.command()
File "/var/www/python/env/lib/python2.6/site-packages/PasteScript-1.7.3-py2.6.egg/paste/script/appinstall.py", line 456, in command
self, config_file, section, self.sysconfig_install_vars(installer))
File "/var/www/python/env/lib/python2.6/site-packages/PasteScript-1.7.3-py2.6.egg/paste/script/appinstall.py", line 598, in setup_config
mod.setup_app, command, filename, section, vars)
File "/var/www/python/env/lib/python2.6/site-packages/PasteScript-1.7.3-py2.6.egg/paste/script/appinstall.py", line 612, in _call_setup_app
func(command, conf, vars)
File "/var/www/python/SimpleSite/simplesite/websetup.py", line 16, in setup_app
load_environment(conf.global_conf, conf.local_conf)
File "/var/www/python/SimpleSite/simplesite/config/environment.py", line 48, in load_environment
engine = engine_from_config(config, 'sqlalchemy.')
File "/var/www/python/env/lib/python2.6/site-packages/SQLAlchemy-0.5.8-py2.6.egg/sqlalchemy/engine/__init__.py", line 241, in engine_from_config
return create_engine(url, **opts)
File "/var/www/python/env/lib/python2.6/site-packages/SQLAlchemy-0.5.8-py2.6.egg/sqlalchemy/engine/__init__.py", line 223, in create_engine
return strategy.create(*args, **kwargs)
File "/var/www/python/env/lib/python2.6/site-packages/SQLAlchemy-0.5.8-py2.6.egg/sqlalchemy/engine/strategies.py", line 62, in create
dbapi = dialect_cls.dbapi(**dbapi_args)
File "/var/www/python/env/lib/python2.6/site-packages/SQLAlchemy-0.5.8-py2.6.egg/sqlalchemy/databases/mysql.py", line 1456, in dbapi
import MySQLdb as mysql
File "/var/www/python/env/lib/python2.6/site-packages/MySQL_python-1.2.3c1-py2.6-linux-i686.egg/MySQLdb/__init__.py", line 19, in <module>
File "/var/www/python/env/lib/python2.6/site-packages/MySQL_python-1.2.3c1-py2.6-linux-i686.egg/_mysql.py", line 7, in <module>
File "/var/www/python/env/lib/python2.6/site-packages/MySQL_python-1.2.3c1-py2.6-linux-i686.egg/_mysql.py", line 6, in __bootstrap__
ImportError: libmysqlclient_r.so.15: cannot open shared object file: No such file or directory
| [
"Either install the .so.15 version of the library, or find or build MySQLdb against .so.16.\n",
"I had the same error, although I was working with Django. I'm using Ubuntu Lucid (10.04) and a solution that worked for me was to delete (or rename) the MySQL_python-1.2.3c1-py2.6-linux-i686.egg directory and install ... | [
2,
0
] | [] | [] | [
"mysql",
"pylons",
"python",
"sqlalchemy"
] | stackoverflow_0002649262_mysql_pylons_python_sqlalchemy.txt |
Q:
How much faster is Python 2.7's new IO library compared to earlier versions?
The Python 2.7 update note says:
A new version of the io library, rewritten in C for performance.
I've played with Python 2.7 a bit, but I don't see any performance gain:
>>> from timeit import Timer
>>> t = Timer('f = open("E:\\db.txt", "r"); f.read(); f.close()')
>>> t.timeit(10000)
And the result:
Python 2.6.5 -- 12.879124022745913
Python 2.7 -- 12.905614540395504
Am I doing it wrong?
A:
If you look at http://docs.python.org/library/io.html, the open() method in the io module isn't used by default for opening files in python 2.x. It was only in python 3.x which makes open() use io.open(). Try:
from timeit import Timer
t = Timer('f = io.open("E:\\db.txt", "r"); f.read(); f.close()', 'import io')
t.timeit(10000)
| How much faster is Python 2.7's new IO library compared to earlier versions? | The Python 2.7 update note says:
A new version of the io library, rewritten in C for performance.
I've played with Python 2.7 a bit, but I don't see any performance gain:
>>> from timeit import Timer
>>> t = Timer('f = open("E:\\db.txt", "r"); f.read(); f.close()')
>>> t.timeit(10000)
And the result:
Python 2.6.5 -- 12.879124022745913
Python 2.7 -- 12.905614540395504
Am I doing it wrong?
| [
"If you look at http://docs.python.org/library/io.html, the open() method in the io module isn't used by default for opening files in python 2.x. It was only in python 3.x which makes open() use io.open(). Try:\nfrom timeit import Timer\nt = Timer('f = io.open(\"E:\\\\db.txt\", \"r\"); f.read(); f.close()', 'import... | [
4
] | [] | [] | [
"io",
"python",
"python_2.7"
] | stackoverflow_0003412931_io_python_python_2.7.txt |
Q:
Dynamic linking and Python SWIG (C++) works in C++ fails in python
I have a library for which I have created a python wrapper using SWIG. The library itself accepts user provided functions which are in an .so file that is dynamically linked. At the moment I'm dealing with one that I have created myself and have managed to get the dynamic linking working... in C++. When I attempt to run it in python I get undefined symbol errors. These symbols are ones that are not present in the provided .so file but are present in the main program (essentially they are the functions that allow the provided module to access data from the main program).
I do not get any errors running a short test program in C++, but a short test program in python with this wrapper (that worked previously) fails. I can't think of an explanation as to why it would fail in C++ and not in the python. What worries me slightly is the idea that the C++ isn't working properly but isn't telling me, and the python is picking up errors that the C++ isn't. Yet the result returned by the C++ is accurate, so this seems unlikely.
Any thoughts how this is possible and hence how I could fix it?
Thanks.
Update:
I have added this code to the top of the program:
import dl
sys.setdlopenflags(dl.RTLD_NOW | dl.RTLD_GLOBAL)
This gets rid of the runtime error, but unfortunately allows a second problem to arise (still due to linking). The functions that are being called from within the dynamically linked library that are part of the main program are not returning the correct values. They are returning 0. What's more it's evident that they are not even being run at all. The question becomes what is actually being run, why is it different to the C++, and how do I fix THAT?
Thanks again.
Update- A potentially clearer explanation
Python imports a module, which is my C++ library that has been wrapped by SWIG. This C++ library uses dlopen and dlsym to obtain functions from a user provided .so file. The user provided file calls to functions that are part of the C++ library in order to do it's job. The function calls from the .so file to the C++ library are the part that is failing, that is they fail to call the function and simply return 0. However this failure only occurs when the test code is written in python. C++ test code that uses the library works fine.
A:
A solution is to make sure that python is preloading the C++ main library in the global scope.
This is not a very elegant solution, and I don't want to do it, but it makes it work for the moment.
After a little poking around here and recognising the LD_LIBRARY_PATH environment variable that I have to set every time I start the terminal in order for it to even find the main C++ library that has been SWIGed, I noticed the LD_PRELOAD environment variable. Upon setting this to the filename of the main C++ library the program worked.
I suspect this is because it "can be used to selectively override functions in other shared libraries".
If anyone comes up with a better answer than setting environment variables it'd be awesome, as I'm not sure how portable this is.
Edit: The original problem is that the functions that the user provided library is looking for are not in the global scope. In order to fix this simply using python's "dl.open" to open the main library's .so file, using dl.RTLD_NOW and dl.RTLD_GLOBAL.
Success!
A:
The python interpreter is probably loading your wrapper .so without making it's symbols available to other dynamic link libraries (to avoid symbol conflicts). Try adding the following lines just before importing your wrapper:
import dl
sys.setdlopenflags(dl.RTLD_NOW | dl.RTLD_GLOBAL)
| Dynamic linking and Python SWIG (C++) works in C++ fails in python | I have a library for which I have created a python wrapper using SWIG. The library itself accepts user provided functions which are in an .so file that is dynamically linked. At the moment I'm dealing with one that I have created myself and have managed to get the dynamic linking working... in C++. When I attempt to run it in python I get undefined symbol errors. These symbols are ones that are not present in the provided .so file but are present in the main program (essentially they are the functions that allow the provided module to access data from the main program).
I do not get any errors running a short test program in C++, but a short test program in python with this wrapper (that worked previously) fails. I can't think of an explanation as to why it would fail in C++ and not in the python. What worries me slightly is the idea that the C++ isn't working properly but isn't telling me, and the python is picking up errors that the C++ isn't. Yet the result returned by the C++ is accurate, so this seems unlikely.
Any thoughts how this is possible and hence how I could fix it?
Thanks.
Update:
I have added this code to the top of the program:
import dl
sys.setdlopenflags(dl.RTLD_NOW | dl.RTLD_GLOBAL)
This gets rid of the runtime error, but unfortunately allows a second problem to arise (still due to linking). The functions that are being called from within the dynamically linked library that are part of the main program are not returning the correct values. They are returning 0. What's more it's evident that they are not even being run at all. The question becomes what is actually being run, why is it different to the C++, and how do I fix THAT?
Thanks again.
Update- A potentially clearer explanation
Python imports a module, which is my C++ library that has been wrapped by SWIG. This C++ library uses dlopen and dlsym to obtain functions from a user provided .so file. The user provided file calls to functions that are part of the C++ library in order to do it's job. The function calls from the .so file to the C++ library are the part that is failing, that is they fail to call the function and simply return 0. However this failure only occurs when the test code is written in python. C++ test code that uses the library works fine.
| [
"A solution is to make sure that python is preloading the C++ main library in the global scope.\nThis is not a very elegant solution, and I don't want to do it, but it makes it work for the moment.\nAfter a little poking around here and recognising the LD_LIBRARY_PATH environment variable that I have to set every t... | [
2,
1
] | [] | [] | [
"c++",
"dynamic_linking",
"python",
"swig"
] | stackoverflow_0003396966_c++_dynamic_linking_python_swig.txt |
Q:
Controlling a C# Winforms GUI with IronPython
So I made a Winforms GUI in Visual Studio using C#, but for the project I am working on I want the majority of the code to be written in Python. I am hoping to have the "engine" written in python (for portability), and then have the application interface be something I can swap out.
I made the C# project compile to a .dll, and was able to import the classes into an IronPython script and start the GUI fine.
The problem is that running the GUI stops the execution of the Python script unless I put it into a separate thread. However, if I put the GUI into a separate thread and try and use the original python thread to change state information, I get an exception about modifying a control from a different thread than what created it.
Is there any good way to communicate with the GUI thread or a way to accomplish what I am trying to do?
The C# driver of the GUI:
public class Program
{
private static MainWindow window;
[STAThread]
static void Main()
{
Program.RunGUI();
}
public static void RunGUI()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
window = new MainWindow();
Application.Run(window);
}
public static void SetState(GameState state)
{
window.State = state;
}
}
And the python script:
import clr
clr.AddReferenceToFile("TG.Model.dll")
clr.AddReferenceToFile("TG.UI.dll")
from TG.Model import GameState
from TG.UI import Program
import thread
import time
def main():
print "Hello!"
state = GameState()
print state.CharacterName
print dir(Program)
thread.start_new_thread(Program.RunGUI, ())
#Program.RunGUI()
time.sleep(2)
Program.SetState(state)
raw_input()
if __name__ == "__main__":
main()
A:
Put everything after the call to Program.RunGUI() in an event handler.
C#:
public static void RunGUI(EventHandler onLoad)
{
...
window = new MainWindow();
window.Load += onLoad;
Application.Run(window);
window.Load -= onLoad; //removes handler in case RunGUI() is called again
}
Python:
def onload(sender, args):
time.sleep(2)
Program.SetState(state)
raw_input()
def main():
...
Program.RunGUI(onload)
A:
Controls have thread affinity, and can only be accessed by the thread that created them.
There is a BackgroundWorker object that handles passing data between threads rather nicely.
A:
If you want to modify GUI from within a thread other than GUI's thread, you must use Invoke method.
| Controlling a C# Winforms GUI with IronPython | So I made a Winforms GUI in Visual Studio using C#, but for the project I am working on I want the majority of the code to be written in Python. I am hoping to have the "engine" written in python (for portability), and then have the application interface be something I can swap out.
I made the C# project compile to a .dll, and was able to import the classes into an IronPython script and start the GUI fine.
The problem is that running the GUI stops the execution of the Python script unless I put it into a separate thread. However, if I put the GUI into a separate thread and try and use the original python thread to change state information, I get an exception about modifying a control from a different thread than what created it.
Is there any good way to communicate with the GUI thread or a way to accomplish what I am trying to do?
The C# driver of the GUI:
public class Program
{
private static MainWindow window;
[STAThread]
static void Main()
{
Program.RunGUI();
}
public static void RunGUI()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
window = new MainWindow();
Application.Run(window);
}
public static void SetState(GameState state)
{
window.State = state;
}
}
And the python script:
import clr
clr.AddReferenceToFile("TG.Model.dll")
clr.AddReferenceToFile("TG.UI.dll")
from TG.Model import GameState
from TG.UI import Program
import thread
import time
def main():
print "Hello!"
state = GameState()
print state.CharacterName
print dir(Program)
thread.start_new_thread(Program.RunGUI, ())
#Program.RunGUI()
time.sleep(2)
Program.SetState(state)
raw_input()
if __name__ == "__main__":
main()
| [
"Put everything after the call to Program.RunGUI() in an event handler.\nC#:\npublic static void RunGUI(EventHandler onLoad)\n{ \n ...\n\n window = new MainWindow();\n window.Load += onLoad;\n Application.Run(window);\n window.Load -= onLoad; //removes handler in case RunGUI() is called again\n}\n\... | [
3,
1,
0
] | [] | [] | [
"c#",
"ironpython",
"python",
"winforms"
] | stackoverflow_0003402366_c#_ironpython_python_winforms.txt |
Q:
Forms not getting submitted with MECHANIZE in PYTHON!
from mechanize import *
import cookielib
from BeautifulSoup import BeautifulSoup
br = Browser()
br.open('http://casesearch.courts.state.md.us/inquiry/inquiry-index.jsp')
br.select_form(name="main")
br.find_control(name="disclaimer").selected = True
reponse = br.submit()
print reponse.read()
The Above is my code. Now I expect it to show the HTML of this http://casesearch.courts.state.md.us/inquiry/processDisclaimer.jis but it is not doing so instead returning the HTML of the same page. I do not get why?
A:
Add .items[0]:
br.find_control(name="disclaimer").items[0].selected
A fuller code snippet looks like this:
import mechanize
br = mechanize.Browser()
br.open('http://casesearch.courts.state.md.us/inquiry/inquiry-index.jsp')
br.select_form(name="main")
br.find_control(name="disclaimer").items[0].selected = True
reponse = br.submit()
print reponse.read()
A:
You're skipping some bits. I'm surprised it's not exploding.
reponse = br.submit()
print reponse.read()
should be:
br.submit() # returns nothing
print br.response().read()
| Forms not getting submitted with MECHANIZE in PYTHON! | from mechanize import *
import cookielib
from BeautifulSoup import BeautifulSoup
br = Browser()
br.open('http://casesearch.courts.state.md.us/inquiry/inquiry-index.jsp')
br.select_form(name="main")
br.find_control(name="disclaimer").selected = True
reponse = br.submit()
print reponse.read()
The Above is my code. Now I expect it to show the HTML of this http://casesearch.courts.state.md.us/inquiry/processDisclaimer.jis but it is not doing so instead returning the HTML of the same page. I do not get why?
| [
"Add .items[0]:\nbr.find_control(name=\"disclaimer\").items[0].selected\n\nA fuller code snippet looks like this:\nimport mechanize\n\nbr = mechanize.Browser()\nbr.open('http://casesearch.courts.state.md.us/inquiry/inquiry-index.jsp')\nbr.select_form(name=\"main\")\nbr.find_control(name=\"disclaimer\").items[0].sel... | [
1,
0
] | [] | [] | [
"mechanize",
"python"
] | stackoverflow_0003413585_mechanize_python.txt |
Q:
What's Python equivalent to or equals expression, to get return foo or foo = 'bar' working?
I'd like to do something like:
def get_foo():
return self._foo or self._foo = Bar()
I am looking for the cleanest way to do it. Is it possible with or equals?
My attempts failed:
>>> foo = None
>>> foo or 'bar'
'bar'
>>> foo
>>> foo or foo = 'bar'
File "<stdin>", line 1
SyntaxError: can't assign to operator
>>> foo or (foo = 'bar')
File "<stdin>", line 1
foo or (foo = 'bar')
^
SyntaxError: invalid syntax
A:
In Python, you cannot use assignments in expressions. So you have to do the assignment and the return statement on two different lines:
def get_foo(self):
self._foo = self._foo or Bar()
return self._foo
But in general, it's better to write it out:
def get_foo(self):
if not self._foo:
self._foo = Bar()
return self._foo
A:
Python's assignment operator doesn't pass through the assigned value, primarily because in other languages it has proven to be a fruitful generator of accidental =/== bugs. Instead you have to be explicit:
def get_foo(self):
if self._foo is None:
self._foo= Bar()
return self._foo
You can make an expression with side-effects if you really want to:
def set_foo(self, v):
self._foo= v
return v
return self._foo or self.set_foo(Bar())
but it's generally considered a Bad Thing.
| What's Python equivalent to or equals expression, to get return foo or foo = 'bar' working? | I'd like to do something like:
def get_foo():
return self._foo or self._foo = Bar()
I am looking for the cleanest way to do it. Is it possible with or equals?
My attempts failed:
>>> foo = None
>>> foo or 'bar'
'bar'
>>> foo
>>> foo or foo = 'bar'
File "<stdin>", line 1
SyntaxError: can't assign to operator
>>> foo or (foo = 'bar')
File "<stdin>", line 1
foo or (foo = 'bar')
^
SyntaxError: invalid syntax
| [
"In Python, you cannot use assignments in expressions. So you have to do the assignment and the return statement on two different lines:\ndef get_foo(self):\n self._foo = self._foo or Bar()\n return self._foo\n\nBut in general, it's better to write it out:\ndef get_foo(self):\n if not self._foo:\n ... | [
6,
4
] | [
"I might be wrong, but this looks like a job for the ||= operator.\ndef get_foo():\n return self._foo |= Bar()\n\nMy Perl is rusty at best, but ||= seems to return an R-value, so the return should work.\nEdit: Woopsie, this is Python. It doesn't have a ||=. Bummer.\nThen I'd use the simulated ternary operator:\nde... | [
-2
] | [
"python"
] | stackoverflow_0003413702_python.txt |
Q:
Postgres raises a "ACTIVE SQL TRANSACTION" (Errcode: 25001)
I use psycopg2 for accessing my postgres database in python. My function should create a new database, the code looks like this:
def createDB(host, username, dbname):
adminuser = settings.DB_ADMIN_USER
adminpass = settings.DB_ADMIN_PASS
try:
conn=psycopg2.connect(user=adminuser, password=adminpass, host=host)
cur = conn.cursor()
cur.execute("CREATE DATABASE %s OWNER %s" % (nospecial(dbname), nospecial(username)))
conn.commit()
except Exception, e:
raise e
finally:
cur.close()
conn.close()
def nospecial(s):
pattern = re.compile('[^a-zA-Z0-9_]+')
return pattern.sub('', s)
When I call createDB my postgres server throws an error:
CREATE DATABASE cannot run inside a transaction block
with the errorcode 25001 which stands for "ACTIVE SQL TRANSACTION".
I'm pretty sure that there is no other connection running at the same time and every connection I used before calling createDB is shut down.
A:
It looks like your cursor() is actually a transaction:
http://initd.org/psycopg/docs/cursor.html#cursor
Cursors created from the same
connection are not isolated, i.e., any
changes done to the database by a
cursor are immediately visible by the
other cursors. Cursors created from
different connections can or can not
be isolated, depending on the
connections’ isolation level. See also
rollback() and commit() methods.
Skip the cursor and just execute your query. Drop commit() as well, you can't commit when you don't have a transaction open.
| Postgres raises a "ACTIVE SQL TRANSACTION" (Errcode: 25001) | I use psycopg2 for accessing my postgres database in python. My function should create a new database, the code looks like this:
def createDB(host, username, dbname):
adminuser = settings.DB_ADMIN_USER
adminpass = settings.DB_ADMIN_PASS
try:
conn=psycopg2.connect(user=adminuser, password=adminpass, host=host)
cur = conn.cursor()
cur.execute("CREATE DATABASE %s OWNER %s" % (nospecial(dbname), nospecial(username)))
conn.commit()
except Exception, e:
raise e
finally:
cur.close()
conn.close()
def nospecial(s):
pattern = re.compile('[^a-zA-Z0-9_]+')
return pattern.sub('', s)
When I call createDB my postgres server throws an error:
CREATE DATABASE cannot run inside a transaction block
with the errorcode 25001 which stands for "ACTIVE SQL TRANSACTION".
I'm pretty sure that there is no other connection running at the same time and every connection I used before calling createDB is shut down.
| [
"It looks like your cursor() is actually a transaction:\nhttp://initd.org/psycopg/docs/cursor.html#cursor\n\nCursors created from the same\n connection are not isolated, i.e., any\n changes done to the database by a\n cursor are immediately visible by the\n other cursors. Cursors created from\n different conne... | [
3
] | [] | [] | [
"postgresql",
"psycopg2",
"python"
] | stackoverflow_0003413646_postgresql_psycopg2_python.txt |
Q:
Escaping [ in Python Regular Expressions
This reg exp search correctly checks to see if a string contains the text harry:
re.search(r'\bharry\b', '[harry] blah', re.IGNORECASE)
However, I need to ensure that the string contains [harry]. I have tried escaping with various numbers of back-slashes:
re.search(r'\b\[harry\]\b', '[harry] blah', re.IGNORECASE)
re.search(r'\b\\[harry\\]\b', '[harry] blah', re.IGNORECASE)
re.search(r'\b\\\[harry\\\]\b', '[harry] blah', re.IGNORECASE)
None of these solutions work find the match. What do I need to do?
A:
The first one is correct:
r'\b\[harry\]\b'
But this won’t match [harry] blah as [ is not a word character and so there is no word boundary. It would only match if there were a word character in front of [ like in foobar[harry] blah.
A:
You escape it the way you escape most regex metacharacter: preceding with a backslash.
Thus, r"\[harry\]" will match a literal string [harry].
The problem is with the \b in your pattern. This is the word boundary anchor.
The \b matches:
At the beginning of the string, if it starts with a word character
At the end of the string, if it ends with a word character
Between a word character \w and a non-word character \W (note the case difference)
The brackets [ and ] are NOT word characters, thus if a string starts with [, there is no \b to its left. Any where there is no \b, there is \B instead (note the case difference).
References
regular-expressions.info/Word Boundaries
http://docs.python.org/library/re.html
\b : Matches the empty string, but only at the beginning or end of a word. A word is defined as a sequence of alphanumeric or underscore characters, so the end of a word is indicated by whitespace or a non-alphanumeric, non-underscore character. Note that \b is defined as the boundary between \w and \W, so the precise set of characters deemed to be alphanumeric depends on the values of the UNICODE and LOCALE flags. Inside a character range, \b represents the backspace character, for compatibility with Python’s string literals.
A:
>>> re.search(r'\bharry\b','[harry] blah',re.IGNORECASE)
<_sre.SRE_Match object at 0x7f14d22df648>
>>> re.search(r'\b\[harry\]\b','[harry] blah',re.IGNORECASE)
>>> re.search(r'\[harry\]','[harry] blah',re.IGNORECASE)
<_sre.SRE_Match object at 0x7f14d22df6b0>
>>> re.search(r'\[harry\]','harry blah',re.IGNORECASE)
The problem is the \b, not the brackets. A single backslash is correct for escaping.
| Escaping [ in Python Regular Expressions | This reg exp search correctly checks to see if a string contains the text harry:
re.search(r'\bharry\b', '[harry] blah', re.IGNORECASE)
However, I need to ensure that the string contains [harry]. I have tried escaping with various numbers of back-slashes:
re.search(r'\b\[harry\]\b', '[harry] blah', re.IGNORECASE)
re.search(r'\b\\[harry\\]\b', '[harry] blah', re.IGNORECASE)
re.search(r'\b\\\[harry\\\]\b', '[harry] blah', re.IGNORECASE)
None of these solutions work find the match. What do I need to do?
| [
"The first one is correct:\nr'\\b\\[harry\\]\\b'\n\nBut this won’t match [harry] blah as [ is not a word character and so there is no word boundary. It would only match if there were a word character in front of [ like in foobar[harry] blah.\n",
"You escape it the way you escape most regex metacharacter: precedin... | [
7,
1,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003413838_python_regex.txt |
Q:
regular expression - incremental replacement
Is there any way to do integer incremental replacement only with regex.
Here is the problem, I have text file containing 1 000 000 lines all starting with %
I would like to have replace # by integer incrementally using regex.
input:
% line one
% line two
% line three
...
output:
1 line one
2 line two
3 line three
...
A:
n = 1
with open('sourcefile.txt') as input:
with open('destination.txt', 'w') as output:
for line in input:
if line.startswith('%'):
line = str(n) + line[1:]
n += 1
output.write(line)
A:
Here's a way to do it in Python
import re
from itertools import count
s="""
% line one
% line two
% line three"""
def f():
n=count(1)
def inner(m):
return str(next(n))
return inner
new_s = re.sub("%",f(),s)
alternatively you could use a lambda function in there like so:
new_s = re.sub("%",lambda m,n=count(1):str(next(n)),s)
But it's easy and better to skip regexp altogether
from __future__ import print_function # For Python<3
import fileinput
f=fileinput.FileInput("file.txt", inplace=1)
for i,line in enumerate(f):
print ("{0}{1}".format(i, line[1:]), end="")
Since all the lines start with "%" there is no need to even look at that first char
A:
Although this problem would best be solved by reading the file line by line and checking the first character with simple string functions, here is how you would do incremental replacement on a string in java:
Pattern p = Pattern.compile("^%");
Matcher m = p.matcher(text);
StringBuffer sb = new StringBuffer();
int i = 0;
while (m.find()) {
m.appendReplacement(sb, String.valueOf(i++));
}
m.appendTail(sb);
return sb.toString();
A:
Depending on your choice of language (you've listed a few) PHP's preg_replace_callback() might be an appropriate function to use
$text = "% First Line\n% Second Line\n% Third Line";
function cb_numbers($matches)
{
static $c = 1;
return $c++;
}
$text = preg_replace_callback(
"/(%)/",
"cb_numbers",
$text);
echo $text;
A:
in python re.sub accept function as parameter see http://docs.python.org/library/re.html#re.sub
A:
And a PHP version for good measure:
$input = @fopen('input.txt', 'r');
$output = @fopen("output.txt", "w");
if ($input && $output) {
$i = 0;
while (!feof($input)) {
$line = fgets($input);
fputs($output, ($line[0] === '%') ?
substr_replace($line, ++$i, 0, 1) :
$line
);
}
fclose($input);
fclose($output);
}
And just because you can, a perl one-liner (yes, with a regex):
perl -i.bak -pe 'BEGIN{$i=1} (s/^%/$i/) && $i++' input.txt
A:
Here's a C# (3.0+) version:
string s = "% line one\n% line two\n% line three";
int n = 1;
s = Regex.Replace(s, @"(?m)^%", m => { return n++.ToString(); });
Console.WriteLine(s);
output:
1 line one
2 line two
3 line three
Of course it requires the whole text to be loaded into memory. If I were doing this for real, I'd probably go with a line-by-line approach.
A:
import re, itertools
counter= itertools.count(1)
replacer= lambda match: "%d" % counter.next()
text= re.sub("(?m)^%", replacer, text)
counter is… a counter :). replacer is a function returning the counter values as strings. The "(?m)^%" regex is true for every % at the start of a line (note the multi-line flag).
| regular expression - incremental replacement | Is there any way to do integer incremental replacement only with regex.
Here is the problem, I have text file containing 1 000 000 lines all starting with %
I would like to have replace # by integer incrementally using regex.
input:
% line one
% line two
% line three
...
output:
1 line one
2 line two
3 line three
...
| [
"n = 1\nwith open('sourcefile.txt') as input:\n with open('destination.txt', 'w') as output:\n for line in input:\n if line.startswith('%'):\n line = str(n) + line[1:]\n n += 1\n output.write(line)\n\n",
"Here's a way to do it in Python\nimport re\nfro... | [
5,
4,
4,
0,
0,
0,
0,
0
] | [] | [] | [
"c#",
"java",
"php",
"python",
"regex"
] | stackoverflow_0003185669_c#_java_php_python_regex.txt |
Q:
Best way to generate CRC8/16 when input is odd number of BITS (not byte)? C or Python
So I'm stuck with a protocol that adds a CRC8/CRC16 over odd number of bits. (ie. it's not divisible by 8) What's the best method to generate the CRC for it in software?
There are plenty of CRC algorithm that uses table, but they are lookup per byte. Of course, there's the "fail-safe" of doing it one bit at a time. But is there a better approach? Perhaps doing it mostly by table lookup and then finish it doing a bit at a time?
I'm currently using a bitarray in python to handle this. But solution in C would also work. Thanks!
EDIT: Note that I'm interfacing with existing hardware that calc the CRC over the odd number of bits. (It's easy for the HW, since they just use a LFSR--1 bit at a time!) So while padding with known pattern would work for sake of integrity checking, it would break the hw compatibility.
A:
Padding with zeros at the front should not change the result. Computing the CRC is essentially binary long division. Unfortunately this involves splitting each byte. This is easy to with shift operators and bitwise or.
Zero padding at the end is, much easier, and depending on your reason for computing the CRC, a completely reasonable thing to do. For example, if you are using CRC for an integrity check.
Edit Taking my example from my comment. If you have 11 bits 11101110111 and want to compute the CRC, pad them to get 00000111 01110111 = 0x777, do not pad them to get 0x7770 as this will have a different CRC.
The reason that this works is that CRC is essentially binary long division
1 0 1 = 5
-------------
1 0 0 1 1 / 1 1 0 1 1 0 1
1 0 0 1 1 | |
--------- | |
1 0 0 0 0 |
0 0 0 0 0 |
--------- |
1 0 0 0 0 1
1 0 0 1 1
---------
1 1 1 0 = 14 = remainder
Has exactly the same result as
1 0 1 = 5
---------------
1 0 0 1 1 / 0 1 1 0 1 1 0 1
1 0 0 1 1 | |
--------- | |
1 0 0 0 0 |
0 0 0 0 0 |
--------- |
1 0 0 0 0 1
1 0 0 1 1
---------
1 1 1 0 = 14 = remainder
and similarly for any number of leading zeros.
Note at this point, unless you are a psychiatrist looking for field work, want to become one, or secretly desire to need to see one, it may be worth your while to skip to the Super double secret probationary edit
Further Edit Due to question change
If you have a nontrivial initial vector, you can do the following. Say we want to compute the CRC-CCITT CRC of the above string with an initializer of FFFF. We pad the string to get 0x0FFF compute the CRC-CCIT with initializer 0 to get 0x0ECE, then compute the CRC-CCIT with initializer 0xFFFF of 0x0000 to get 0x1D0F, and xor them 0x0ECE xor 0x1D0F = 0x13C1.
The CRC of an arbitrary string of 0's and a nonzero initializer can be computed quickly if the polynomial is primitive (I think they all are), but it gets complicated and I do not have nearly enough time.
The essence of the technique is that we can consider the state of the shift register as a polynomial. If we initialize it with n ones this is the same as considering the initial polynomial as p(x) = x^(n - 1) + x^(n - 2) ... + x + 1. Computing the CRC of a string of k zeros is equivalent to finding p(x) x^k mod CRC. x^k mod CRC is easily found by repeated squaring and reduction. Any library for polynomial arithmetic over GF(2) should do this.
Even further Edit It probably makes more sense in the case of nonzero initializers to pad with zeros and change the initializer to a value such that after reading |pad| number of zeros the shift register contains FFFF (or whatever the value you wanted was. These can be precomputed, and you only need to store 16 or 32 of them (or howver many bits are in your crc polynomial.
For example with CRC-CCIT with initializer 0xFFFF and a single bit 0 padding we will want to use an initializer of 0xF7EF. These can be computed by finding x^(-1) mod CRC using the extended euclidean algorithm and then computing initializer * x^(-k) mod CRC for the various padding lengths. Again any GF(2) polynomail package should make this easy. I have used NTL in the past and found it quite flexible, but it is probably overkill here. Even for 32 bit crcs exhjaustive search will probably find the initializers faster than you can write the code.
Super double secret probationary edit
Ok, Things are actually considerably simpler than I thought they were. The general idea above is correct, we want to pad the string with 0's at the front to extend the size to a multiple of 8, 16 or 32 depending on what our software implementation wants, and we want to change our initial vector to set our state to something that after reading the padding zeros will the LFSR will be set to the initial vector that we wanted. We certainly could use galois field arithmetic to do this, but there is an easier way: just run the LFSR backwards.
For example if we want to compute the CRC-CCITT (0xFFFF) of the 11 bits 11 bits 11101110111 we pad them with 5 0's to get 00000111 01110111 and then back the LFSR up five spaces to get an initial vector of 0xF060. (I've done the computation by hand, so beware).
So if you start an LSFR (or a software implementation) with IV of 0xF060 and run it on 0x0fff, you should get the same result as running an LFSR with IV 0xFFFF on the original 11 bits.
| Best way to generate CRC8/16 when input is odd number of BITS (not byte)? C or Python | So I'm stuck with a protocol that adds a CRC8/CRC16 over odd number of bits. (ie. it's not divisible by 8) What's the best method to generate the CRC for it in software?
There are plenty of CRC algorithm that uses table, but they are lookup per byte. Of course, there's the "fail-safe" of doing it one bit at a time. But is there a better approach? Perhaps doing it mostly by table lookup and then finish it doing a bit at a time?
I'm currently using a bitarray in python to handle this. But solution in C would also work. Thanks!
EDIT: Note that I'm interfacing with existing hardware that calc the CRC over the odd number of bits. (It's easy for the HW, since they just use a LFSR--1 bit at a time!) So while padding with known pattern would work for sake of integrity checking, it would break the hw compatibility.
| [
"Padding with zeros at the front should not change the result. Computing the CRC is essentially binary long division. Unfortunately this involves splitting each byte. This is easy to with shift operators and bitwise or.\nZero padding at the end is, much easier, and depending on your reason for computing the CRC, a... | [
8
] | [] | [] | [
"algorithm",
"c",
"python"
] | stackoverflow_0003411654_algorithm_c_python.txt |
Q:
sharing a string between two objects
I want two objects to share a single string object. How do I pass the string object from the first to the second such that any changes applied by one will be visible to the other? I am guessing that I would have to wrap the string in a sort of buffer object and do all sorts of complexity to get it to work.
However, I have a tendency to overthink problems, so undoubtedly there is an easier way. Or maybe sharing the string is the wrong way to go? Keep in mind that I want both objects to be able to edit the string. Any ideas?
Here is an example of a solution I could use:
class Buffer(object):
def __init__(self):
self.data = ""
def assign(self, value):
self.data = str(value)
def __getattr__(self, name):
return getattr(self.data, name)
class Descriptor(object):
def __get__(self, instance, owner):
return instance._buffer.data
def __set__(self, instance, value):
if not hasattr(instance, "_buffer"):
if isinstance(value, Buffer):
instance._buffer = value
return
instance._buffer = Buffer()
instance._buffer.assign(value)
class First(object):
data = Descriptor()
def __init__(self, data):
self.data = data
def read(self, size=-1):
if size < 0:
size = len(self.data)
data = self.data[:size]
self.data = self.data[size:]
return data
class Second(object):
data = Descriptor()
def __init__(self, data):
self.data = data
def add(self, newdata):
self.data += newdata
def reset(self):
self.data = ""
def spawn(self):
return First(self._buffer)
s = Second("stuff")
f = s.spawn()
f.data == s.data
#True
f.read(2)
#"st"
f.data
# "uff"
f.data == s.data
#True
s.data
#"uff"
s._buffer == f._buffer
#True
Again, this seems like absolute overkill for what seems like a simple problem. As well, it requires the use of the Buffer class, a descriptor, and the descriptor's impositional _buffer variable.
An alternative is to put one of the objects in charge of the string and then have it expose an interface for making changes to the string. Simpler, but not quite the same effect.
A:
I want two objects to share a single
string object.
They will, if you simply pass the string -- Python doesn't copy unless you tell it to copy.
How do I pass the string object from
the first to the second such that any
changes applied by one will be visible
to the other?
There can never be any change made to a string object (it's immutable!), so your requirement is trivially met (since a false precondition implies anything).
I am guessing that I would have to
wrap the string in a sort of buffer
object and do all sorts of complexity
to get it to work.
You could use (assuming this is Python 2 and you want a string of bytes) an array.array with a typecode of c. Arrays are mutable, so you can indeed alter them (with mutating methods -- and some operators, which are a special case of methods since they invoke special methods on the object). They don't have the myriad non-mutating methods of strings, so, if you need those, you'll indeed need a simple wrapper (delegating said methods to the str(...) of the array that the wrapper also holds).
It doesn't seem there should be any special complexity, unless of course you want to do something truly weird as you seem to given your example code (have an assignment, i.e., a *rebinding of a name, magically affect a different name -- that has absolutely nothing to do with whatever object was previously bound to the name you're rebinding, nor does it change that object in any way -- the only object it "changes" is the one holding the attribute, so it's obvious that you need descriptors or other magic on said object).
You appear to come from some language where variables (and particularly strings) are "containers of data" (like C, Fortran, or C++). In Python (like, say, in Java), names (the preferred way to call what others call "variables") always just refer to objects, they don't contain anything except exactly such a reference. Some objects can be changed, some can't, but that has absolutely nothing to do with the assignment statement (see note 1) (which doesn't change objects: it rebinds names).
(note 1): except of course that rebinding an attribute or item does alter the object that "contains" that item or attribute -- objects can and do contain, it's names that don't.
A:
Just put your value to be shared in a list, and assign the list to both objects.
class A(object):
def __init__(self, strcontainer):
self.strcontainer = strcontainer
def upcase(self):
self.strcontainer[0] = self.strcontainer[0].upper()
def __str__(self):
return self.strcontainer[0]
# create a string, inside a shareable list
shared = ['Hello, World!']
x = A(shared)
y = A(shared)
# both objects have the same list
print id(x.strcontainer)
print id(y.strcontainer)
# change value in x
x.upcase()
# show how value is changed in both x and y
print str(x)
print str(y)
Prints:
10534024
10534024
HELLO, WORLD!
HELLO, WORLD!
A:
i am not a great expert in python, but i think that if you declare a variable in a module and add a getter/setter to the module for this variable you will be able to share it this way.
| sharing a string between two objects | I want two objects to share a single string object. How do I pass the string object from the first to the second such that any changes applied by one will be visible to the other? I am guessing that I would have to wrap the string in a sort of buffer object and do all sorts of complexity to get it to work.
However, I have a tendency to overthink problems, so undoubtedly there is an easier way. Or maybe sharing the string is the wrong way to go? Keep in mind that I want both objects to be able to edit the string. Any ideas?
Here is an example of a solution I could use:
class Buffer(object):
def __init__(self):
self.data = ""
def assign(self, value):
self.data = str(value)
def __getattr__(self, name):
return getattr(self.data, name)
class Descriptor(object):
def __get__(self, instance, owner):
return instance._buffer.data
def __set__(self, instance, value):
if not hasattr(instance, "_buffer"):
if isinstance(value, Buffer):
instance._buffer = value
return
instance._buffer = Buffer()
instance._buffer.assign(value)
class First(object):
data = Descriptor()
def __init__(self, data):
self.data = data
def read(self, size=-1):
if size < 0:
size = len(self.data)
data = self.data[:size]
self.data = self.data[size:]
return data
class Second(object):
data = Descriptor()
def __init__(self, data):
self.data = data
def add(self, newdata):
self.data += newdata
def reset(self):
self.data = ""
def spawn(self):
return First(self._buffer)
s = Second("stuff")
f = s.spawn()
f.data == s.data
#True
f.read(2)
#"st"
f.data
# "uff"
f.data == s.data
#True
s.data
#"uff"
s._buffer == f._buffer
#True
Again, this seems like absolute overkill for what seems like a simple problem. As well, it requires the use of the Buffer class, a descriptor, and the descriptor's impositional _buffer variable.
An alternative is to put one of the objects in charge of the string and then have it expose an interface for making changes to the string. Simpler, but not quite the same effect.
| [
"\nI want two objects to share a single\n string object.\n\nThey will, if you simply pass the string -- Python doesn't copy unless you tell it to copy.\n\nHow do I pass the string object from\n the first to the second such that any\n changes applied by one will be visible\n to the other?\n\nThere can never be a... | [
2,
2,
1
] | [] | [] | [
"object",
"python",
"string"
] | stackoverflow_0003411614_object_python_string.txt |
Q:
Pythonic way to iterate over sequence, 4 items at a time
Possible Duplicate:
What is the most “pythonic” way to iterate over a list in chunks?
I am reading in some PNG data, which has 4 channels per pixel. I would like to iterate over the data 1 pixel at a time (meaning every 4 elements = 1 pixel, rgba).
red_channel = 0
while red_channel < len(raw_png_data):
green_channel, blue_channel, alpha_channel = red_channel +1, red_channel +2, red_channel +3
# do something with my 4 channels of pixel data ... raw_png_data[red_channel] etc
red_channel += 4
This way doesnt really seem "right". Is there a more Pythonic way to iterate over a sequence, 4 items at a time, and have those 4 items unpacked?
A:
(Python's itertools should really make all recipes as standard functions...)
You could use the grouper function:
from itertools import zip_longest
def grouper(n, iterable, fillvalue=None):
"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)
Then you can iterate the pixels by
for r,g,b,a in grouper(4, raw_png_data):
....
Alternatively, you could use
irpd = iter(raw_png_data)
for r,g,b,a in zip(irpd, irpd, irpd, irpd): # use itertools.izip in Python 2.x
....
Note that this will chop the last few bytes if the iterable's length is not a multiple of 4. OTOH, the grouper function uses izip_longest, so the extra bytes will be padded with None for that.
A:
vars = [1, 2, 3, 4, 5, 6, 7, 8]
for a, b, c, d in zip(*[iter(vars)]*4):
print a, b, c, d
A:
from itertools import izip
for r,g,b,a in izip(*[iter(data)]*4):
...
A:
for r, g, b, t in (data[i:i+4] for i in xrange(0, len(data)/4*4, 4)):
print r, g, b, t
| Pythonic way to iterate over sequence, 4 items at a time |
Possible Duplicate:
What is the most “pythonic” way to iterate over a list in chunks?
I am reading in some PNG data, which has 4 channels per pixel. I would like to iterate over the data 1 pixel at a time (meaning every 4 elements = 1 pixel, rgba).
red_channel = 0
while red_channel < len(raw_png_data):
green_channel, blue_channel, alpha_channel = red_channel +1, red_channel +2, red_channel +3
# do something with my 4 channels of pixel data ... raw_png_data[red_channel] etc
red_channel += 4
This way doesnt really seem "right". Is there a more Pythonic way to iterate over a sequence, 4 items at a time, and have those 4 items unpacked?
| [
"(Python's itertools should really make all recipes as standard functions...)\nYou could use the grouper function:\nfrom itertools import zip_longest\ndef grouper(n, iterable, fillvalue=None):\n \"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx\"\n args = [iter(iterable)] * n\n return izip_longest(fillvalue=fil... | [
38,
34,
9,
3
] | [
"Try something like this:\nfor red, green, blue, alpha in raw_png_data:\n #do something\n\nYou can pull out multiple items and never have to use an iterator. :)\nEdit: This would mean that raw_png_data needs to be a list of 4 value tuples. It would be most pythonic to put each rgba group into a tuple and then ap... | [
-4
] | [
"iteration",
"python"
] | stackoverflow_0003415072_iteration_python.txt |
Q:
testing assertion error in python
I'm doing a test suite in python based on the code provided by selenium and i get strange assertion errors when checking for the actual page like this:
sel.click("link=Overview")
sel.wait_for_page_to_load("30000")
self.assertEqual("Naaya testing - Subtitlu testare", sel.get_title())
sel.click("link=Portal properties")
sel.wait_for_page_to_load("30000")
self.assertEqual("Naaya testing - Subtitlu testare", sel.get_title())
sel.click("link=Metadata")
sel.wait_for_page_to_load("15000")
Strange in this piece of code is that i get the assertion error only at the first occurence in code, after i changed the first occurence with:
title = sel.get_title()
self.failUnless(title == "Naaya testing - Subtitlu testare","nu sunt "
"pe pagina principala")
i got rid of the error ,but i still don't get why the second assertion does not fail but the first one do ?
A:
In python when you use == operator order may make difference. Try "Your strng" == title and check result. Also assertEqual may check type, so correct code will be:
self.assertEqual("Naaya testing - Subtitlu testare", str(sel.get_title()))
or:
self.assertEqual(u"Naaya testing - Subtitlu testare", sel.get_title())
if selenium uses unicode type.
| testing assertion error in python | I'm doing a test suite in python based on the code provided by selenium and i get strange assertion errors when checking for the actual page like this:
sel.click("link=Overview")
sel.wait_for_page_to_load("30000")
self.assertEqual("Naaya testing - Subtitlu testare", sel.get_title())
sel.click("link=Portal properties")
sel.wait_for_page_to_load("30000")
self.assertEqual("Naaya testing - Subtitlu testare", sel.get_title())
sel.click("link=Metadata")
sel.wait_for_page_to_load("15000")
Strange in this piece of code is that i get the assertion error only at the first occurence in code, after i changed the first occurence with:
title = sel.get_title()
self.failUnless(title == "Naaya testing - Subtitlu testare","nu sunt "
"pe pagina principala")
i got rid of the error ,but i still don't get why the second assertion does not fail but the first one do ?
| [
"In python when you use == operator order may make difference. Try \"Your strng\" == title and check result. Also assertEqual may check type, so correct code will be:\nself.assertEqual(\"Naaya testing - Subtitlu testare\", str(sel.get_title()))\n\nor:\nself.assertEqual(u\"Naaya testing - Subtitlu testare\", sel.get... | [
2
] | [] | [] | [
"python",
"selenium",
"unit_testing"
] | stackoverflow_0003414335_python_selenium_unit_testing.txt |
Q:
Python submodule internal references -- are they just crazy?
Apologies in advange for the newbie question. I can't get my head around this, and the docs don't help!
Consider the following directory structure:
spam.py
foo / __init__.py
ham.py
eggs.py
with the following code:
# __init__.py
# blank
# ham.py
print( "got ham!" )
# eggs.py
print( "got eggs, importing ham!" )
import foo.ham
Now, if I import foo.eggs inside spam.py (!), the right thing happens and all the module references work.
BUT
If I try and execute eggs.py directly, I get an ImportError: No module named foo.ham! If I change the foo.ham imports to just ham, the right thing happens... but then I can't import foo.eggs!
So, how do I develop eggs? If I use 'undotted' references, I can develop fine, but can't try it out because I can't import the module! If I use the full foo.ham reference, I can import the package, but can't execute the submodule for development purposes!
Is this just a glitch with Python's packaging architecture? Am I doing it wrong?
A:
The parent directory for foo needs to be in the python's path:
$ ls foo
eggs.py ham.py ham.pyc __init__.py __init__.pyc
$ python foo/ham.py
got ham!
$ python foo/eggs.py
got eggs, importing ham!
Traceback (most recent call last):
File "foo/eggs.py", line 2, in <module>
import foo.ham
ImportError: No module named foo.ham
$ PYTHONPATH=. python foo/eggs.py
got eggs, importing ham!
got ham!
A:
This seems to work: Here is the directory structure:
~/test/kl% ls -R
.:
foo spam.py
./foo:
eggs.py eggs.pyc ham.py ham.pyc __init__.py __init__.pyc
Here are the file contents:
~/test/kl% cat spam.py
import foo.eggs
~/test/kl% cd foo/
~/test/kl/foo% cat eggs.py
print( "got eggs, importing ham!" )
import ham
We can import ham from spam.py, and foo/eggs.py:
~/test/kl% python spam.py
got eggs, importing ham!
got ham!
A useful rule to remember is that when you say python script.py, the directory containing script.py is added to the beginning of sys.path, the directories searched for modules. That's why python spam.py works without changing PYTHONPATH.
~/test/kl% python foo/eggs.py
got eggs, importing ham!
got ham!
Here, ~/test/kl/foo is added to the sys.path. That's okay, because eggs.py tries to import ham. Since ham.py resides in ~/test/kl/foo which is in sys.path, Python finds it just fine.
~/test/kl% cd foo
~/test/kl/foo% python eggs.py
got eggs, importing ham!
got ham!
The directory ~/test/kl was not in my PYTHONPATH.
A:
This is a Python's packaging architecture. Normally a module can import modules either from current directory with dotted reference, either from $PYTHONPATH directory.
You should understand that a module reference is just relative path to this module. So... an interpreter can't import any module that's not found on file system.
| Python submodule internal references -- are they just crazy? | Apologies in advange for the newbie question. I can't get my head around this, and the docs don't help!
Consider the following directory structure:
spam.py
foo / __init__.py
ham.py
eggs.py
with the following code:
# __init__.py
# blank
# ham.py
print( "got ham!" )
# eggs.py
print( "got eggs, importing ham!" )
import foo.ham
Now, if I import foo.eggs inside spam.py (!), the right thing happens and all the module references work.
BUT
If I try and execute eggs.py directly, I get an ImportError: No module named foo.ham! If I change the foo.ham imports to just ham, the right thing happens... but then I can't import foo.eggs!
So, how do I develop eggs? If I use 'undotted' references, I can develop fine, but can't try it out because I can't import the module! If I use the full foo.ham reference, I can import the package, but can't execute the submodule for development purposes!
Is this just a glitch with Python's packaging architecture? Am I doing it wrong?
| [
"The parent directory for foo needs to be in the python's path:\n$ ls foo\neggs.py ham.py ham.pyc __init__.py __init__.pyc\n$ python foo/ham.py\ngot ham!\n$ python foo/eggs.py\ngot eggs, importing ham!\nTraceback (most recent call last):\n File \"foo/eggs.py\", line 2, in <module>\n import foo.ham\nImportEr... | [
1,
1,
0
] | [] | [] | [
"module",
"package",
"python"
] | stackoverflow_0003414901_module_package_python.txt |
Q:
How to test if a dictionary contains certain keys
Is there a nice approach to test if a dictionary contains multiple keys?
A short version of:
d = {}
if 'a' in d and 'b' in d and 'c' in d:
pass #do something
Thanks.
Edit: I can only use python2.4 -.-
A:
You can use set.issubset(...), like so:
>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> set(['a', 'b']).issubset(d)
True
>>> set(['a', 'x']).issubset(d)
False
Python 3 has introduced a set literal syntax which has been backported to Python 2.7, so these days the above can be written:
>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> {'a', 'b'}.issubset(d)
True
>>> {'a', 'x'}.issubset(d)
False
A:
if all(test in d for test in ('a','b','c')):
# do something
A:
In Python3 you can write
set("abc")<=d.keys()
In Python2.7 you can write
d.viewkeys()>=set("abc")
of course if the keys are not single chars you can replace
set("abc") with set(('a', 'b', 'c'))
A:
Could use an itemgetter wrapped in a try / except.
>>> from operator import itemgetter
>>> d = dict(a=1,b=2,c=3,d=4)
>>> e = dict(a=1,b=2,c=3,e=4)
>>> getter=itemgetter('a','b','c','d')
>>> getter(d)
(1, 2, 3, 4)
>>> getter(e)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'd'
But actually I prefer Paul McGuire's solution
A:
In 2.4, I always use set operations for such purposes. If it's worth a warning (or other kind of msg or exception) when some expected keys are missing, in particular, I do:
missing = set(d).difference(('a', 'b', 'c'))
if missing:
logging.warn("Missing keys: %s", ', '.join(sorted(missing)))
else:
...
replacing the logging.warn call as appropriate, of course (maybe just logging.info or even logging.debug, maybe logging.error, maybe an exception).
The sorted part is mostly cosmetic (I like reliable, repeatable error messages) but also helps a bit with testing (when I mock up logging.warn -- or whatever -- in the tests, it's nice to be able to expect a specific string, and if I didn't sort the missing set the warning string might vary, of course, since sets, like dicts, don't have a concept of order).
| How to test if a dictionary contains certain keys | Is there a nice approach to test if a dictionary contains multiple keys?
A short version of:
d = {}
if 'a' in d and 'b' in d and 'c' in d:
pass #do something
Thanks.
Edit: I can only use python2.4 -.-
| [
"You can use set.issubset(...), like so:\n>>> d = {'a': 1, 'b': 2, 'c': 3}\n>>> set(['a', 'b']).issubset(d)\nTrue\n>>> set(['a', 'x']).issubset(d)\nFalse\n\n\nPython 3 has introduced a set literal syntax which has been backported to Python 2.7, so these days the above can be written:\n>>> d = {'a': 1, 'b': 2, 'c': ... | [
22,
20,
6,
1,
1
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0003415347_dictionary_python.txt |
Q:
How to use multiple Sessions in a pylons app?
I've read "Multiple database connections with Python + Pylons + SQLAlchemy" and I get how to create multiple engines using that technique, but now I'm looking for advice on how to handle the creation of Sessions for these engines. Right now, the Session in my project is defined as per Pylons convention: myapp.model.meta.Session = scoped_session(sessionmaker()) and imported as myapp.model.Session. This works fine if there's only one engine.
What's a good, maintainable approach to defining this for multiple engines? The set of engines may change at runtime, for what it's worth, so I'd need the ability to create new Sessions on the fly, without hard coding them into the model.
A:
If you want choose the database backend per one request, a good option is to call meta.Session(bind=get_engine_for_this_request()) as the first thing. That will create the session with the specified parameters. You can stick that into the BaseController if it makes sense in your case.
For multiple backends per one request the best approach depends on your specific usecase. If all the backends have the same schema, it's probably best to create multiple ScopedSessions, one for each backend. When they hold different schemas, you can create multiple MetaData objects (or Base classes in case of declarative) and bind them to the engines.
A:
Use the bind parameter to sessionmaker to bind the session to a specific connection.
See http://www.sqlalchemy.org/docs/05/reference/orm/sessions.html#sqlalchemy.orm.sessionmaker for more information.
| How to use multiple Sessions in a pylons app? | I've read "Multiple database connections with Python + Pylons + SQLAlchemy" and I get how to create multiple engines using that technique, but now I'm looking for advice on how to handle the creation of Sessions for these engines. Right now, the Session in my project is defined as per Pylons convention: myapp.model.meta.Session = scoped_session(sessionmaker()) and imported as myapp.model.Session. This works fine if there's only one engine.
What's a good, maintainable approach to defining this for multiple engines? The set of engines may change at runtime, for what it's worth, so I'd need the ability to create new Sessions on the fly, without hard coding them into the model.
| [
"If you want choose the database backend per one request, a good option is to call meta.Session(bind=get_engine_for_this_request()) as the first thing. That will create the session with the specified parameters. You can stick that into the BaseController if it makes sense in your case.\nFor multiple backends per on... | [
1,
0
] | [] | [] | [
"pylons",
"python",
"sqlalchemy"
] | stackoverflow_0003398507_pylons_python_sqlalchemy.txt |
Q:
web.py: How to selectively hide resources with 404s for any HTTP method?
I want to selectively hide some resources based on some form of authentication in web.py, but their existence is revealed by 405 responses to any HTTP method that I haven't implemented.
Here's an example:
import web
urls = (
'/secret', 'secret',
)
app = web.application(urls, globals())
class secret():
def GET(self):
if web.cookies().get('password') == 'secretpassword':
return "Dastardly secret plans..."
raise web.notfound()
if __name__ == "__main__":
app.run()
When an undefined method request is issued, the resource is revealed:
$ curl -v -X DELETE http://localhost:8080/secret
...
> DELETE /secret HTTP/1.1
...
< HTTP/1.1 405 Method Not Allowed
< Content-Type: text/html
< Allow: GET
...
I could implement the same check for the other common methods in the HTTP specification, but a creative miscreant might invent their own:
$ curl -v -X SHENANIGANS http://localhost:8080/secret
...
> SHENANIGANS /secret HTTP/1.1
...
< HTTP/1.1 405 Method Not Allowed
< Content-Type: text/html
< Allow: GET
...
Is there a way to implement a catch all method in a web.py class for any HTTP method, so I can ensure the security check will be run?
Or is there an alternative way to hide these resources?
A:
Enlightened by Daniel Kluev's answer, I ended up deriving from web.application to add support for a default method in the _delegate method:
import types
class application(web.application):
def _delegate(self, f, fvars, args=[]):
def handle_class(cls):
meth = web.ctx.method
if meth == 'HEAD' and not hasattr(cls, meth):
meth = 'GET'
if not hasattr(cls, meth):
if hasattr(cls, '_default'):
tocall = getattr(cls(), '_default')
return tocall(*args)
raise web.nomethod(cls)
tocall = getattr(cls(), meth)
return tocall(*args)
def is_class(o): return isinstance(o, (types.ClassType, type))
...
Instantiation:
app = application(urls, globals())
Page class:
class secret():
def _default(self):
raise web.notfound()
def GET(self):
...
I prefer this solution because it keeps the page classes clean and affords further customisation of the delegation process in a single place. For example, another feature I wanted was transparent overloaded POST (eg. redirecting a POST request with method=DELETE to the DELETE method of the page class) and it's simple to add that here too:
...
meth = web.ctx.method
if meth == 'POST' and 'method' in web.input():
meth = web.input()['method']
...
A:
You can implement handle-all-methods method like this:
class HelloType(type):
"""Metaclass is needed to fool hasattr(cls, method) check"""
def __getattribute__(obj, name):
try:
return object.__getattribute__(obj, name)
except AttributeError:
return object.__getattribute__(obj, '_handle_unknown')
class hello(object):
__metaclass__ = HelloType
def GET(self, *args, **kw):
if web.cookies().get('password') == 'secretpassword':
return "Dastardly secret plans..."
raise web.notfound()
def _handle_unknown(self, *args, **kw):
"""This method will be called for all requests, which have no defined method"""
raise web.notfound()
def __getattribute__(obj, name):
try:
return object.__getattribute__(obj, name)
except AttributeError:
return object.__getattribute__(obj, '_handle_unknown')
__getattribute__ is implemented twice due to the way web.py checks for method existence:
def _delegate(self, f, fvars, args=[]):
def handle_class(cls):
meth = web.ctx.method
if meth == 'HEAD' and not hasattr(cls, meth):
meth = 'GET'
if not hasattr(cls, meth): # Calls type's __getattribute__
raise web.nomethod(cls)
tocall = getattr(cls(), meth) # Calls instance's __getattribute__
A:
you can define any method in your 'secret' class, such as DELETE or SHENANIGANS, like this:
class secret():
def DELETE(self):
...
def SHENANIGANS(self):
...
| web.py: How to selectively hide resources with 404s for any HTTP method? | I want to selectively hide some resources based on some form of authentication in web.py, but their existence is revealed by 405 responses to any HTTP method that I haven't implemented.
Here's an example:
import web
urls = (
'/secret', 'secret',
)
app = web.application(urls, globals())
class secret():
def GET(self):
if web.cookies().get('password') == 'secretpassword':
return "Dastardly secret plans..."
raise web.notfound()
if __name__ == "__main__":
app.run()
When an undefined method request is issued, the resource is revealed:
$ curl -v -X DELETE http://localhost:8080/secret
...
> DELETE /secret HTTP/1.1
...
< HTTP/1.1 405 Method Not Allowed
< Content-Type: text/html
< Allow: GET
...
I could implement the same check for the other common methods in the HTTP specification, but a creative miscreant might invent their own:
$ curl -v -X SHENANIGANS http://localhost:8080/secret
...
> SHENANIGANS /secret HTTP/1.1
...
< HTTP/1.1 405 Method Not Allowed
< Content-Type: text/html
< Allow: GET
...
Is there a way to implement a catch all method in a web.py class for any HTTP method, so I can ensure the security check will be run?
Or is there an alternative way to hide these resources?
| [
"Enlightened by Daniel Kluev's answer, I ended up deriving from web.application to add support for a default method in the _delegate method:\nimport types\n\nclass application(web.application):\n def _delegate(self, f, fvars, args=[]):\n def handle_class(cls):\n meth = web.ctx.method\n ... | [
3,
1,
0
] | [] | [] | [
"http",
"python",
"web.py"
] | stackoverflow_0003382419_http_python_web.py.txt |
Q:
Asymmetric behavior for __getattr__, newstyle vs oldstyle classes
this is the first time I write here, sorry if the message is unfocuessed or too long.
I was interested in understanding more about how objects'attributes are fetched when needed. So I read the Python 2.7 documentation titled "Data Model" here, I met __getattr__ and, in order to check whether I understood or not its behavior, I wrote these simple (and incomplete) string wrappers.
class OldStr:
def __init__(self,val):
self.field=val
def __getattr__(self,name):
print "method __getattr__, attribute requested "+name
class NewStr(object):
def __init__(self,val):
self.field=val
def __getattr__(self,name):
print "method __getattr__, attribute requested "+name
As you can see they are the same except for being an oldstyle vs newstyle classes. Since the quoted text says __getattr__ is "Called when an attribute lookup has not found the attribute in the usual places", I wanted to try a + operation on two instances of those classes to see what happened, expecting an identical behavior.
But the results I got puzzled me a little bit:
>>> x=OldStr("test")
>>> x+x
method __getattr__, attribute requested __coerce__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable
Good! I did not define a method for __coerce__ (although I was expecting a request for __add__, nevermind :), so __getattr__ got involved and returned a useless thing. But then
>>> y=NewStr("test")
>>> y+y
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'NewStr' and 'NewStr'
Why this asymmetric behavior between __getattr__ in oldstyle classes and newstyle ones when using a built-in operator like +? Could someone please help me to understand what is going on, and what was my mistake in reading the documentation?
Thanks a lot, your help is strongly appreciated!
A:
See Special method lookup for new-style classes.
Special methods are directly looked up in the class object, the instance objects and consequently __getattr__() and __getattribute__() are bypassed. For precisely the same reason, instance.__add__ = foobar doesn't work.
This is done to speed up attribute access. Special methods are called very frequently, and making them subject to the standard, rather complex attribute lookup would significantly slow down the interpreter.
Attribute lookup for old-style classes is much less complex (most notably old style classes do not support descriptors), so there is no reason to treat special methods differently in old style classes.
A:
Your __getattr__ functions aren't returning anything. I don't know why the old-style class is doing the __getattr__ before looking for __add__, but it is, and this is trying to call the return value which is None.
The new-style class is doing it right: you haven't defined __add__ so it doesn't know how to add them.
A:
More info from the Python Documentation:
http://docs.python.org/reference/datamodel.html#customizing-attribute-access
| Asymmetric behavior for __getattr__, newstyle vs oldstyle classes | this is the first time I write here, sorry if the message is unfocuessed or too long.
I was interested in understanding more about how objects'attributes are fetched when needed. So I read the Python 2.7 documentation titled "Data Model" here, I met __getattr__ and, in order to check whether I understood or not its behavior, I wrote these simple (and incomplete) string wrappers.
class OldStr:
def __init__(self,val):
self.field=val
def __getattr__(self,name):
print "method __getattr__, attribute requested "+name
class NewStr(object):
def __init__(self,val):
self.field=val
def __getattr__(self,name):
print "method __getattr__, attribute requested "+name
As you can see they are the same except for being an oldstyle vs newstyle classes. Since the quoted text says __getattr__ is "Called when an attribute lookup has not found the attribute in the usual places", I wanted to try a + operation on two instances of those classes to see what happened, expecting an identical behavior.
But the results I got puzzled me a little bit:
>>> x=OldStr("test")
>>> x+x
method __getattr__, attribute requested __coerce__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable
Good! I did not define a method for __coerce__ (although I was expecting a request for __add__, nevermind :), so __getattr__ got involved and returned a useless thing. But then
>>> y=NewStr("test")
>>> y+y
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'NewStr' and 'NewStr'
Why this asymmetric behavior between __getattr__ in oldstyle classes and newstyle ones when using a built-in operator like +? Could someone please help me to understand what is going on, and what was my mistake in reading the documentation?
Thanks a lot, your help is strongly appreciated!
| [
"See Special method lookup for new-style classes. \nSpecial methods are directly looked up in the class object, the instance objects and consequently __getattr__() and __getattribute__() are bypassed. For precisely the same reason, instance.__add__ = foobar doesn't work.\nThis is done to speed up attribute access... | [
5,
1,
0
] | [] | [] | [
"coding_style",
"getattr",
"new_operator",
"python"
] | stackoverflow_0003415816_coding_style_getattr_new_operator_python.txt |
Q:
How to alternate colors in stacked bar graph in matplotlib?
I want to alternate colors in a stacked bar graph in matplotlib..so as I can get different colors for the graphs depending on their type. I have two types except that they do not alternate regularly. so I need to check their type before I choose the colors.
The problem is that it is conditional. I provide the type in an array, but there is no way to do it at the level of the plt.bar(.............)...well I think.
p1 = plt.bar(self.__ind,
self.__a,
self.__width,
color='#263F6A')
p2 = plt.bar(self.__ind,
self.__b,
self.__width,
color='#3F9AC9',
bottom = self.__arch)
p3 = plt.bar(self.__ind,
self.__c,
self.__width,
color='#76787A',
bottom = self.__a + self.__b)
self.__a and self.__b and self.__c are all data lists that I need to plot in the same figure and I have another list of types for each element of the mentioned lists above.
I only want to know how could I make it possible to change the colors of the graphs depending on the type provided by the types list and at the same time keeping all the bars in one plot.
A:
I'm confused when you say that self.__a is a list - when I try plotting a list:
In [19]: plt.bar(1,[1,2,3], 0.1, color='#ffcc00')
I get
AssertionError: incompatible sizes: argument 'height' must be length 1 or scalar
However, what you can do is plot your values in a loop:
# Setup code here...
indices = [1,2,3,4]
heights = [1.2, 2.2, 3.3, 4.4]
widths = [0.1, 0.1, 0.2, 1]
types = ['spam', 'rabbit', 'spam', 'grail']
for index, height, width, type in zip(indices, heights, widths, types):
if type == 'spam':
plt.bar(index, height, width, color='#263F6A')
elif type == 'rabbit':
plt.bar(index, height, width, color='#3F9AC9', bottom = self.__arch)
elif type == 'grail':
plt.bar(index, height, width, color='#76787a', bottom = 3)
| How to alternate colors in stacked bar graph in matplotlib? | I want to alternate colors in a stacked bar graph in matplotlib..so as I can get different colors for the graphs depending on their type. I have two types except that they do not alternate regularly. so I need to check their type before I choose the colors.
The problem is that it is conditional. I provide the type in an array, but there is no way to do it at the level of the plt.bar(.............)...well I think.
p1 = plt.bar(self.__ind,
self.__a,
self.__width,
color='#263F6A')
p2 = plt.bar(self.__ind,
self.__b,
self.__width,
color='#3F9AC9',
bottom = self.__arch)
p3 = plt.bar(self.__ind,
self.__c,
self.__width,
color='#76787A',
bottom = self.__a + self.__b)
self.__a and self.__b and self.__c are all data lists that I need to plot in the same figure and I have another list of types for each element of the mentioned lists above.
I only want to know how could I make it possible to change the colors of the graphs depending on the type provided by the types list and at the same time keeping all the bars in one plot.
| [
"I'm confused when you say that self.__a is a list - when I try plotting a list:\nIn [19]: plt.bar(1,[1,2,3], 0.1, color='#ffcc00')\n\nI get\nAssertionError: incompatible sizes: argument 'height' must be length 1 or scalar\n\nHowever, what you can do is plot your values in a loop:\n# Setup code here...\n\nindices =... | [
5
] | [] | [] | [
"bar_chart",
"matplotlib",
"python"
] | stackoverflow_0003415775_bar_chart_matplotlib_python.txt |
Q:
How can I kill off a Python web app on GAE early following a redirect?
Disclaimer: completely new to Python from a PHP background
Ok I'm using Python on Google App Engine with Google's webapp framework.
I have a function which I import as it contains things which need to be processed on each page.
def some_function(self):
if data['user'].new_user and not self.request.path == '/main/new':
self.redirect('/main/new')
This works fine when I call it, but how can I make sure the app is killed off after the redirection. I don't want anything else processing. For example I will do this:
class Dashboard(webapp.RequestHandler):
def get(self):
some_function(self)
#Continue with normal code here
self.response.out.write('Some output here')
I want to make sure that once the redirection is made in some_function() (which works fine), that no processing is done in the get() function following the redirection, nor is the "Some output here" outputted.
What should I be looking at to make this all work properly? I can't just exit the script because the webapp framework needs to run.
I realise that more than likely I'm just doing things in completely the wrong way any way for a Python app, so any guidance would be a great help. Hopefully I have explained myself properly and someone will be able to point me in the right direction.
Thanks
A:
I suggest you return a boolean from some_function() based on whether the caller should continue execution or not. Example:
def some_function(self):
if data['user'].new_user and not self.request.path == '/main/new':
self.redirect('/main/new')
return True
return False
class Dashboard(webapp.RequestHandler):
def get(self):
if some_function(self):
return
#Continue with normal code here
self.response.out.write('Some output here')
There's also a slightly more complicated alternative that might be helpful if some_function() is nested several levels deep, or if you may have many functions like this. The idea: raise an exception indicating that you want processing to stop, and use a subclass of webapp.RequestHandler which simply catches and ignores this exception. Here's a rough idea of how this might go:
class RedirectException(Exception):
"""Raise this from any method on a MyRequestHandler object to redirect immediately."""
def __init__(self, uri, permanent=False):
self.uri = uri
self.permanent = permanent
class RedirectRequestHandler(webapp.RequestHandler):
def handle_exception(self, exception, debug_mode):
if isinstance(exception, RedirectException):
self.redirect(exception.uri, exception.permanent)
else:
super(MyRequestHandler, self).handle_exception(exception, debug_mode)
This might make it a little easier to work with some_function() (and make your other request handlers a bit easier to read). For example:
def some_function(self):
if data['user'].new_user and not self.request.path == '/main/new':
raise RedirectException('/main/new')
class Dashboard(RedirectRequestHandler):
# rest of the implementation is the same ...
A:
How about this?
class Dashboard(webapp.RequestHandler):
def some_function(self):
if data['user'].new_user and not self.request.path == '/main/new':
self.redirect('/main/new')
return True
else:
return False
def get(self):
if not self.some_function():
self.response.out.write('Some output here')
For reference, if you're going to need some_function() in a lot of RequestHandlers it would be pythonic to make a class that your other RequestHandlers can subclass from:
class BaseHandler(webapp.RequestHandler):
def some_function(self):
if data['user'].new_user and not self.request.path == '/main/new':
self.redirect('/main/new')
return False
else:
return True
class Dashboard(BaseHandler):
def get(self):
if not self.some_function():
self.response.out.write('Some output here')
A:
I know this question is quite old but I was doing something today and naturally tried another solution without thinking about it, it has worked fine but I'm wondering if there would be a problem with doing it this way.
My solution now is just to return, return anything actually but I use "return False" in that there is a problem with the request as it is so I'm printing an error or redirecting elsewhere.
By returning I've already set the output etc and I'm killing off the get() or post() function early.
Is this an ok solution?
| How can I kill off a Python web app on GAE early following a redirect? | Disclaimer: completely new to Python from a PHP background
Ok I'm using Python on Google App Engine with Google's webapp framework.
I have a function which I import as it contains things which need to be processed on each page.
def some_function(self):
if data['user'].new_user and not self.request.path == '/main/new':
self.redirect('/main/new')
This works fine when I call it, but how can I make sure the app is killed off after the redirection. I don't want anything else processing. For example I will do this:
class Dashboard(webapp.RequestHandler):
def get(self):
some_function(self)
#Continue with normal code here
self.response.out.write('Some output here')
I want to make sure that once the redirection is made in some_function() (which works fine), that no processing is done in the get() function following the redirection, nor is the "Some output here" outputted.
What should I be looking at to make this all work properly? I can't just exit the script because the webapp framework needs to run.
I realise that more than likely I'm just doing things in completely the wrong way any way for a Python app, so any guidance would be a great help. Hopefully I have explained myself properly and someone will be able to point me in the right direction.
Thanks
| [
"I suggest you return a boolean from some_function() based on whether the caller should continue execution or not. Example:\ndef some_function(self):\n if data['user'].new_user and not self.request.path == '/main/new':\n self.redirect('/main/new')\n return True\n return False\n\nclass Dashboard... | [
4,
4,
0
] | [] | [] | [
"google_app_engine",
"python",
"web_applications"
] | stackoverflow_0003002233_google_app_engine_python_web_applications.txt |
Q:
python: function that will call itself
i was wondering if i can get your help with the stucture.logic of a function that will need to call itself
def populate_frequency5(d,data,total_compare):
freq=[]
prev = None
for row in d:
if prev is None or prev==row[11]:
freq.append(row[16])
doctor=row[10]
drug=row[11][:row[11].find(' ')].capitalize()
else:
make_image_url_doctor(freq,doctor,drug,data)
total_compare=True
del freq[:]
prev=row[11]
if total_compare:
(b1,bla,bla1)=medications_subset2(data,[drug.upper()])
data1=calculate_creat_conc4(b1)
populate_frequency5(data1,['a'],total_compare=True)
total_compare=False
the first time the function is called i need it to run this:
def populate_frequency5(d,data,total_compare):
freq=[]
prev = None
for row in d:
if prev is None or prev==row[11]:
freq.append(row[16])
doctor=row[10]
drug=row[11][:row[11].find(' ')].capitalize()
else:
make_image_url_doctor(freq,doctor,drug,data)
(b1,bla,bla1)=medications_subset2(data,[drug.upper()])
data1=calculate_creat_conc4(b1)
del freq[:]
prev=row[11]
then somehow the second time when i call it, i need it to run this way:
def populate_frequency5(d,data,total_compare):
freq=[]
prev = None
for row in d:
if prev is None or prev==row[11]:
freq.append(row[16])
doctor=row[10]
drug=row[11][:row[11].find(' ')].capitalize()
run_another_function()
A:
Your current logic is faulty and will lead to runaway recursion. If you ever make a recursive call, you'll pass it a total_compare of True; but then within that recursive call it will not be set to False again, so when checked it will be true and yet another recursive call (with the same defect) will inevitably result.
The setting of total_compare in the calling instance (were it ever to execute, which it won't because of the runaway recursion) is irrelevant: it's the last statement ever executed there and it's setting a local variable, so of course it can be removed without any observable effects. Maybe you don't realize that each instance of a function in recursive calls has its own set of local variables (including arguments -- they're also local variables, just ones that get initializer by the caller), which is why I'm pointing this out explicitly.
Your examples "desired code" 1 and 2 don't really help because they never show the function calling itself. Under what conditions, exactly, does the function need to call itself recursively (a) if it was called non-recursively, (b) if it was already called recursively? Remember that, to avoid runaway recursion, there must be eventually reached a "base case" where no further recursion occurs.
Given that in your first ("runaway recursion") example the recursive call appears to be the last action of the caller (net of the useless and therefore removable setting of the total_compare local variable), I should also point out that such "tail recursion" can easily be turned into iteration (and, in Python, that's usually advisable, since Python does not optimize tail recursion as other languages do).
| python: function that will call itself | i was wondering if i can get your help with the stucture.logic of a function that will need to call itself
def populate_frequency5(d,data,total_compare):
freq=[]
prev = None
for row in d:
if prev is None or prev==row[11]:
freq.append(row[16])
doctor=row[10]
drug=row[11][:row[11].find(' ')].capitalize()
else:
make_image_url_doctor(freq,doctor,drug,data)
total_compare=True
del freq[:]
prev=row[11]
if total_compare:
(b1,bla,bla1)=medications_subset2(data,[drug.upper()])
data1=calculate_creat_conc4(b1)
populate_frequency5(data1,['a'],total_compare=True)
total_compare=False
the first time the function is called i need it to run this:
def populate_frequency5(d,data,total_compare):
freq=[]
prev = None
for row in d:
if prev is None or prev==row[11]:
freq.append(row[16])
doctor=row[10]
drug=row[11][:row[11].find(' ')].capitalize()
else:
make_image_url_doctor(freq,doctor,drug,data)
(b1,bla,bla1)=medications_subset2(data,[drug.upper()])
data1=calculate_creat_conc4(b1)
del freq[:]
prev=row[11]
then somehow the second time when i call it, i need it to run this way:
def populate_frequency5(d,data,total_compare):
freq=[]
prev = None
for row in d:
if prev is None or prev==row[11]:
freq.append(row[16])
doctor=row[10]
drug=row[11][:row[11].find(' ')].capitalize()
run_another_function()
| [
"Your current logic is faulty and will lead to runaway recursion. If you ever make a recursive call, you'll pass it a total_compare of True; but then within that recursive call it will not be set to False again, so when checked it will be true and yet another recursive call (with the same defect) will inevitably r... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0003416844_python.txt |
Q:
How to include python compiler dependencies in maven web project?
I have a simple website that has some related python scripts that I use for maintenance of that website (note, the python code are util scripts that we execute manually for various tasks). I need to be able to share it with other developers who may want to edit it.
What Maven dependencies do I need to include so that the python compiler is included at runtime and can be put on the build path?
A:
I'm not sure I understood the question but Jython includes a compiler:
<dependency>
<groupId>org.python</groupId>
<artifactId>jython</artifactId>
<version>2.5.0</version>
</dependency>
| How to include python compiler dependencies in maven web project? | I have a simple website that has some related python scripts that I use for maintenance of that website (note, the python code are util scripts that we execute manually for various tasks). I need to be able to share it with other developers who may want to edit it.
What Maven dependencies do I need to include so that the python compiler is included at runtime and can be put on the build path?
| [
"I'm not sure I understood the question but Jython includes a compiler:\n<dependency>\n <groupId>org.python</groupId>\n <artifactId>jython</artifactId>\n <version>2.5.0</version>\n</dependency>\n\n"
] | [
0
] | [] | [] | [
"buildpath",
"maven_2",
"python"
] | stackoverflow_0003415928_buildpath_maven_2_python.txt |
Q:
Python - threaded pyinotify output. Better to write to file or to a string
I have a pyinotify watcher running threaded, called as a separate class, at the moment it just prints its discoveries in a terminal window, if I wanted my script to make an action based on those changes am I better to:
A) modify an array with each notification
B) write to a file in /tmp and fetch it from my main script?
c) give up programming
thanks for any input,
Stewart
A:
import Queue
changes = Queue.Queue()
and now use changes.put in the thread that discover the changes, changes.get in the thread that is supposed to act on those changes (there are several other useful methods in Queue
that you should check -- also note, per the docs, that the module's renamed to queue, all lowercase, in Python 3). Queues are intrinsically thread-safe and therefore often the best way to arrange cooperation among threads in Python.
| Python - threaded pyinotify output. Better to write to file or to a string | I have a pyinotify watcher running threaded, called as a separate class, at the moment it just prints its discoveries in a terminal window, if I wanted my script to make an action based on those changes am I better to:
A) modify an array with each notification
B) write to a file in /tmp and fetch it from my main script?
c) give up programming
thanks for any input,
Stewart
| [
"import Queue\nchanges = Queue.Queue()\n\nand now use changes.put in the thread that discover the changes, changes.get in the thread that is supposed to act on those changes (there are several other useful methods in Queue\n that you should check -- also note, per the docs, that the module's renamed to queue, all l... | [
1
] | [] | [] | [
"inotify",
"python",
"theory"
] | stackoverflow_0003416876_inotify_python_theory.txt |
Q:
Set connection settings with Pyodbc + UnixODBC + FreeTDS
I have a setup using Pyodbc, UnixODBC and FreeTDS, but somewhere in there some options are being set and I don't know where. According to SQL Server Management Studio, my program is sending some settings when it opens the connection:
set quoted_identifier off
set ansi_padding off
set ansi_nulls off
...
But I need a different set of settings:
set quoted_identifier on
set ansi_padding on
set ansi_nulls on
...
Is there any way to change this? If I can't do it with my current setup, are there any other libraries I could use in Python that would let me change it (preferably using the Python Database API)?
Changing settings in the database isn't an option because I have a bunch of other projects that use my current settings.
Solved:
Mark's answer was correct, but I couldn't get it working with FreeTDS/UnixODBC. Adding that info to my odbc.ini file worked perfectly though:
[servername]
... other options ..
AnsiNPW = YES
QuotedID = YES
A:
According to MSDN you should be able to set these in the connection string:
cnxn = pyodbc.connect("DSN=someDSN;UID=someUser;PWD=somePass;QuotedID=Yes;AnsiNPW=Yes")
| Set connection settings with Pyodbc + UnixODBC + FreeTDS | I have a setup using Pyodbc, UnixODBC and FreeTDS, but somewhere in there some options are being set and I don't know where. According to SQL Server Management Studio, my program is sending some settings when it opens the connection:
set quoted_identifier off
set ansi_padding off
set ansi_nulls off
...
But I need a different set of settings:
set quoted_identifier on
set ansi_padding on
set ansi_nulls on
...
Is there any way to change this? If I can't do it with my current setup, are there any other libraries I could use in Python that would let me change it (preferably using the Python Database API)?
Changing settings in the database isn't an option because I have a bunch of other projects that use my current settings.
Solved:
Mark's answer was correct, but I couldn't get it working with FreeTDS/UnixODBC. Adding that info to my odbc.ini file worked perfectly though:
[servername]
... other options ..
AnsiNPW = YES
QuotedID = YES
| [
"According to MSDN you should be able to set these in the connection string:\ncnxn = pyodbc.connect(\"DSN=someDSN;UID=someUser;PWD=somePass;QuotedID=Yes;AnsiNPW=Yes\")\n\n"
] | [
3
] | [] | [] | [
"odbc",
"pyodbc",
"python",
"sql_server",
"unixodbc"
] | stackoverflow_0003416814_odbc_pyodbc_python_sql_server_unixodbc.txt |
Q:
Easy way to delete a shelve .dat file left behind by my Python program?
So I have a python program that ends up leaving a .dat file from the shelve function behind after execution. I would like my program to delete or clear that file once it is done. My textbook only mentions how to create a .dat file but not how to clear it. Any good commands out there to take care of this? I don't need the .dat file again after my program runs to completion.
A:
Register an atexit handler to do the cleanup for you (as described in the documentation here).
A:
This is easy:
import sys, os
sys.atexit.register( os.remove, path_to_file )
runs os.remove( path_to_file ) when the Python interpreter exists in a normal (not killed/crashed) way. But you need to make sure the file is closed by then.
| Easy way to delete a shelve .dat file left behind by my Python program? | So I have a python program that ends up leaving a .dat file from the shelve function behind after execution. I would like my program to delete or clear that file once it is done. My textbook only mentions how to create a .dat file but not how to clear it. Any good commands out there to take care of this? I don't need the .dat file again after my program runs to completion.
| [
"Register an atexit handler to do the cleanup for you (as described in the documentation here).\n",
"This is easy:\nimport sys, os\nsys.atexit.register( os.remove, path_to_file )\n\nruns os.remove( path_to_file ) when the Python interpreter exists in a normal (not killed/crashed) way. But you need to make sure th... | [
2,
2
] | [] | [] | [
"python",
"shelve"
] | stackoverflow_0003417290_python_shelve.txt |
Q:
Plural of words using Open Office API for Python (UNO)
I would like to retrieve the plural words in different languages in Python.
I know that openoffice has an API called uno (import uno) and it should give me this ability using openoffice's language dictionaries, but I could not find any reference to it.
As a concrete example, I would something like this:
>>> print getPluralOf('table')
tables
One possibility is to download the dictionary files though this link and write a method to read the dictionary and form the plurals. But i can't believe that this is not available already using uno.
I appreciate any help
A:
You can introspect the module with dir(uno) and then try dir() on uno.XXX, with whatever looks helpful. You can also use help() on uno and its members. I've never used it and I don't have access to OO on this computer so I can't help more than that...
A:
Nodebox Linguistics includes a convenient function for pluralizing nouns, albeit only in English.
>>> import en
>>> en.noun.plural('table')
'tables'
| Plural of words using Open Office API for Python (UNO) | I would like to retrieve the plural words in different languages in Python.
I know that openoffice has an API called uno (import uno) and it should give me this ability using openoffice's language dictionaries, but I could not find any reference to it.
As a concrete example, I would something like this:
>>> print getPluralOf('table')
tables
One possibility is to download the dictionary files though this link and write a method to read the dictionary and form the plurals. But i can't believe that this is not available already using uno.
I appreciate any help
| [
"You can introspect the module with dir(uno) and then try dir() on uno.XXX, with whatever looks helpful. You can also use help() on uno and its members. I've never used it and I don't have access to OO on this computer so I can't help more than that...\n",
"Nodebox Linguistics includes a convenient function for p... | [
0,
0
] | [] | [] | [
"nlp",
"openoffice.org",
"python",
"pyuno"
] | stackoverflow_0003414702_nlp_openoffice.org_python_pyuno.txt |
Q:
python: can i set a variable to equal a function of itself?
Can I do this?
var1 = some_function(var1)
When I tried to do this I got errors, but perhaps I was doing something wrong.
A:
If the variable has been previously defined, you can do that yes.
Example:
def f(x):
return x+1
var1 = 5
var1 = f(var1)
# var1 is now 6
If the variable has not been defined previously, you can't do that, simply because there is no value that could be passed to the function.
A:
def myfun(param):
return param * 2
y = 4
y = myfun(y)
print (y)
Works fine. prints 8;
So you could describe better the problem you're experiencing, preferably with full error traceback and source code I can run to reproduce the problem.
| python: can i set a variable to equal a function of itself? | Can I do this?
var1 = some_function(var1)
When I tried to do this I got errors, but perhaps I was doing something wrong.
| [
"If the variable has been previously defined, you can do that yes.\nExample:\ndef f(x):\n return x+1\n\nvar1 = 5\nvar1 = f(var1)\n# var1 is now 6\n\nIf the variable has not been defined previously, you can't do that, simply because there is no value that could be passed to the function.\n",
"def myfun(param):\... | [
11,
2
] | [] | [] | [
"python"
] | stackoverflow_0003417488_python.txt |
Q:
python: a shorter way to append values
results_histogram_total=list(numpy.histogram(freq,bins=numpy.arange(0,6.1,.1))[0])
sum_total=sum(results_histogram_total)
big_set=[]
for i in results_histogram_total:
big_set.append(100*(i/sum_total)
is there a shorter way i can write the for loop to append the values?
A:
For appending, replace the loop with:
big_set.extend(100.0 * i / sum_total for i in results_histogram_total)
however, it's best to replace all the last three lines with just:
big_set = [100.0 * i / sum_total for i in results_histogram_total]
Also, I would advise to not call a list "something set" -- it's very confusing disinformation. But, this is just a bit of naming style advice;-).
| python: a shorter way to append values | results_histogram_total=list(numpy.histogram(freq,bins=numpy.arange(0,6.1,.1))[0])
sum_total=sum(results_histogram_total)
big_set=[]
for i in results_histogram_total:
big_set.append(100*(i/sum_total)
is there a shorter way i can write the for loop to append the values?
| [
"For appending, replace the loop with:\nbig_set.extend(100.0 * i / sum_total for i in results_histogram_total)\n\nhowever, it's best to replace all the last three lines with just:\nbig_set = [100.0 * i / sum_total for i in results_histogram_total]\n\nAlso, I would advise to not call a list \"something set\" -- it's... | [
4
] | [] | [] | [
"python"
] | stackoverflow_0003417593_python.txt |
Q:
How to find all files in current directory with filenames that match a certain pattern in python?
I am trying to find all the files in the same directory as my script that has a filename matching a certain pattern. Ideally, I would like to store it in an array once I get them. The pattern I need to match is something like: testing.JUNK.08-05.txt. All the filenames have the testing in the front and end with the date (08-05.txt). The only difference is the JUNK in the middle which can include any valid characters.
What would be the most efficient way to do this? I can be working with anywhere from 1 to thousands of files?
Additional things to note: Using python 2.6 and I need this to work on Unix-based operating systems.
A:
Use the glob module:
import glob
for name in glob.glob('testing*08-05.txt'):
print name
| How to find all files in current directory with filenames that match a certain pattern in python? | I am trying to find all the files in the same directory as my script that has a filename matching a certain pattern. Ideally, I would like to store it in an array once I get them. The pattern I need to match is something like: testing.JUNK.08-05.txt. All the filenames have the testing in the front and end with the date (08-05.txt). The only difference is the JUNK in the middle which can include any valid characters.
What would be the most efficient way to do this? I can be working with anywhere from 1 to thousands of files?
Additional things to note: Using python 2.6 and I need this to work on Unix-based operating systems.
| [
"Use the glob module:\nimport glob\nfor name in glob.glob('testing*08-05.txt'):\n print name\n\n"
] | [
14
] | [] | [] | [
"python"
] | stackoverflow_0003417745_python.txt |
Q:
py2exe access 'other_resources'
So with py2exe you can add additional data inside the library zip file, now I was wondering, how do you access this data, do you need to read it out from the zipfile or can you just access it like any other file ? or perhaps there's another way to access it.
A:
I personally never used the zipfile. Instead, I pass the data files my program used in the setup method and use the bundle_files option (as described at the bottom of this page). For instance, the program I create using this call
setup(name = "Urban Planning",
windows = [{'script': "main.py", "dest_base": "Urban_Planning"}],
options = opts, # Dictionary of options
zipfile = None, # Don't create zip file
data_files = Mydata_files) # Add list of data files to folder
also has a piece before it where a config file and some images for the user interface are added like this
Mydata_files = [] # List of data files to include
# Get the images from the [script root]/ui/images/ folder
for files in os.listdir(sys.path[0] + '/ui/images/'):
f1 = sys.path[0] + '/ui/images/' + files
if os.path.isfile(f1): # This will skip directories
f2 = 'ui/images', [f1]
Mydata_files.append(f2)
# Get the config file from the [script root]/Configs folder
Mydata_files.append(('Configs', [sys.path[0] + '/Configs/defaults.cfg']))
This way I can call my config file just like I would while running the script using idle or command prompt and my UI images display correctly.
| py2exe access 'other_resources' | So with py2exe you can add additional data inside the library zip file, now I was wondering, how do you access this data, do you need to read it out from the zipfile or can you just access it like any other file ? or perhaps there's another way to access it.
| [
"I personally never used the zipfile. Instead, I pass the data files my program used in the setup method and use the bundle_files option (as described at the bottom of this page). For instance, the program I create using this call\nsetup(name = \"Urban Planning\",\n windows = [{'script': \"main.py\", \"dest_ba... | [
1
] | [] | [] | [
"py2exe",
"python"
] | stackoverflow_0003414616_py2exe_python.txt |
Q:
Writing only part of a line to a file
I want to clean up my output and only write part of the line that I need to a new file and not the whole entire line. This is the relevent coding section:
counter = 1
for line in completedataset:
print counter
counter +=1
for t in matchedLines:
if t in line[:line.find(',')]:
smallerdataset.write(line)
break
Here is a sample of the data:
NOVE1780418","---","JAX17054099","5","156323558", etc for the line.
I only want to write up until the number before the 3rd comma. I need some help modifying write line to only write up until the third comma. This file is very large and I'm hoping that any new code won't slow the program down but rather speed it up. Thanks Bob
A:
It should be as simple as this...
for line in infile:
line = line.strip().split(',')
outfile.write(','.join(line[:3]) + '\n')
A:
for line in infile:
line = line.strip().split(',',3)
outfile.write(','.join(line[:-1]) + '\n')
If there is a possibility of ',' showing up in any of the fields, you'll need to use the csv module
| Writing only part of a line to a file | I want to clean up my output and only write part of the line that I need to a new file and not the whole entire line. This is the relevent coding section:
counter = 1
for line in completedataset:
print counter
counter +=1
for t in matchedLines:
if t in line[:line.find(',')]:
smallerdataset.write(line)
break
Here is a sample of the data:
NOVE1780418","---","JAX17054099","5","156323558", etc for the line.
I only want to write up until the number before the 3rd comma. I need some help modifying write line to only write up until the third comma. This file is very large and I'm hoping that any new code won't slow the program down but rather speed it up. Thanks Bob
| [
"It should be as simple as this...\nfor line in infile:\n line = line.strip().split(',')\n outfile.write(','.join(line[:3]) + '\\n')\n\n",
"for line in infile:\n line = line.strip().split(',',3)\n outfile.write(','.join(line[:-1]) + '\\n')\n\nIf there is a possibility of ',' showing up in any of the f... | [
4,
1
] | [] | [] | [
"line",
"python"
] | stackoverflow_0003417813_line_python.txt |
Q:
Can I skip an indeterminate amount of steps for an enclosing loop? (Python)
This is perhaps a result of bad design, but here it goes. I wasn't quite sure how to explain this problem.
So I have code that iterates over a list of words. (This list does not change.) The code then parses and combines certain words together, depending on a set of criteria, storing them in a new list. The master loop, which is taking each word one at a time, would then need to skip what the code decided was a fit. So for example:
Master loop's list of words:
ListA = [apple, banana, penguin]
Within the master loop, let's say my code decided apple and bananna belong together, so
ListB = [apple banana, penguin]
Now I would like to have Master Loop skip over bananna, it doesn't need to run the check over whether to see if banana pairs with something else. So I would use a continue statement. Here is the problem. I don't know how many words will end up paired. So I could end up needing one continue, or three continues. The only way I can think of to run continue as many times as needed would be to use a loop...but that creates a problem since continue would affect the loop it is within.
Is there a way for me to make the master loop continue as many times as needed? Perhaps I am missing something simple. Thanks for your help.
EDIT
word_list = ["apple", "banana", "penguin"] #word_list will be arbitrary in practice
phrase_length = 0 #phrase_length is the amount of times I would like to skip
for k, word in enumerate(word_list):
#I would like to have the continues run here, before any of the below code
#the code down here decides what to pair in a forward fashion
#so it starts from apple and looks ahead to see if something fits with it
#continues in this manner till it comes up with the longest possible pairing
#phrase_length is then set equal to the amount of words used make the pairing
It would waste a considerable amount of computing time, if it had to execute the code for banana as well, checking forward from there as well. Which is why I would want to skip over the banana check.
A:
you could try to use the itertools module and espacially the dropwhile function.
A:
Am I missing something?
word_list = ["apple", "banana", "penguin"]
skip_list = {}
for word in self.word_list:
if word in skip_list:
continue
# Do word-pairing logic; if word paired, skip_list[word] = 1
May not be the most programmatically efficient, but at least clear and concise.
A:
You could explicitly use the next method of the iterator.
>>> l = [1, 2, 3, 4, 5, 6]
>>> l_iter = iter(l)
>>> for n in l_iter:
if n==2:
print '{0}+{1}+{2}'.format(n, l_iter.next(), l_iter.next())
else:
print n
1
2+3+4
5
6
EDIT: yeah, that would get messy when combined with enumerate. Another option that comes to mind: write the function as a generator, something like:
def combined_words(word_list):
combined_word = ""
for k, word in enumerate(word_list):
combined_word += k
if next_word_can_be_paired:
pass
else: # next word can't be paired
yield combined_word
combined_word = ""
if combined_word:
yield combined_word # just in case anything is left over
Then call list(combined_words(word_list)) to get the new list.
| Can I skip an indeterminate amount of steps for an enclosing loop? (Python) | This is perhaps a result of bad design, but here it goes. I wasn't quite sure how to explain this problem.
So I have code that iterates over a list of words. (This list does not change.) The code then parses and combines certain words together, depending on a set of criteria, storing them in a new list. The master loop, which is taking each word one at a time, would then need to skip what the code decided was a fit. So for example:
Master loop's list of words:
ListA = [apple, banana, penguin]
Within the master loop, let's say my code decided apple and bananna belong together, so
ListB = [apple banana, penguin]
Now I would like to have Master Loop skip over bananna, it doesn't need to run the check over whether to see if banana pairs with something else. So I would use a continue statement. Here is the problem. I don't know how many words will end up paired. So I could end up needing one continue, or three continues. The only way I can think of to run continue as many times as needed would be to use a loop...but that creates a problem since continue would affect the loop it is within.
Is there a way for me to make the master loop continue as many times as needed? Perhaps I am missing something simple. Thanks for your help.
EDIT
word_list = ["apple", "banana", "penguin"] #word_list will be arbitrary in practice
phrase_length = 0 #phrase_length is the amount of times I would like to skip
for k, word in enumerate(word_list):
#I would like to have the continues run here, before any of the below code
#the code down here decides what to pair in a forward fashion
#so it starts from apple and looks ahead to see if something fits with it
#continues in this manner till it comes up with the longest possible pairing
#phrase_length is then set equal to the amount of words used make the pairing
It would waste a considerable amount of computing time, if it had to execute the code for banana as well, checking forward from there as well. Which is why I would want to skip over the banana check.
| [
"you could try to use the itertools module and espacially the dropwhile function.\n",
"Am I missing something?\nword_list = [\"apple\", \"banana\", \"penguin\"]\nskip_list = {}\n\nfor word in self.word_list:\n if word in skip_list:\n continue\n\n # Do word-pairing logic; if word paired, skip_list[wor... | [
0,
0,
0
] | [] | [] | [
"continue",
"python"
] | stackoverflow_0003417908_continue_python.txt |
Q:
python: appends only '0'
big_set=[]
for i in results_histogram_total:
big_set.append(100*(i/sum_total))
big_set returns [0,0,0,0,0,0,0,0........,0]
this wrong because i checked i and it is >0
what am i doing wrong?
A:
In Python 2.x, use from __future__ import division to get sane division behavior.
A:
try this list comprehension instead
big_set = [100*i/sum_total for i in results_histogram_total]
note that / truncates in Python2, so you may wish to use
big_set = [100.0*i/sum_total for i in results_histogram_total]
A:
If sum_total is an integer (what is sum_total.__class__ equal to ?),
python seems to use integer division.
Try i / float(sum_total) instead.
A:
Probably has to do with float division.
i is probably less than sum_total which in integer division returns 0.
100 * 0 is 0.
Try casting it to a float.
| python: appends only '0' | big_set=[]
for i in results_histogram_total:
big_set.append(100*(i/sum_total))
big_set returns [0,0,0,0,0,0,0,0........,0]
this wrong because i checked i and it is >0
what am i doing wrong?
| [
"In Python 2.x, use from __future__ import division to get sane division behavior.\n",
"try this list comprehension instead\nbig_set = [100*i/sum_total for i in results_histogram_total]\n\nnote that / truncates in Python2, so you may wish to use\nbig_set = [100.0*i/sum_total for i in results_histogram_total]\n\n"... | [
5,
3,
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0003418060_python.txt |
Q:
py. 'decimal' mod.: why flags on context rather than numbers
Here is an example to explain what I'm on about:
c = Decimal(10) / Decimal(3)
c = Decimal(10) / Decimal(2)
If I do this, then print c, the inexact and rounded flags are raised. Even though the result is accurate. Shouldn't flags therefore be attributes of numbers rather than the context? This problem is especially apparent when I program lengthy calculation using a stack.
To pose a more meaningful question: How do I properly deal with this?
It seems I have to keep track of everything manually. If I clear flags before calculations, I would lose some informations about numbers calculated before. Which may now appear accurate. This is especially annoying when working with numbers like 1.0000000154342.
For a critical application, it would be really nice to be sure about what is accurate and what isn't. It would also be nice to not have the wrong flags raised, just because it looks bad.
It still assume there is a good rationale behind this, which I haven't understood. I'd be thankful for an explanation.
A:
Read this: http://docs.python.org/library/decimal.html#context-objects
You have context objects that you can save and restore so that you don't lose flag values.
| py. 'decimal' mod.: why flags on context rather than numbers | Here is an example to explain what I'm on about:
c = Decimal(10) / Decimal(3)
c = Decimal(10) / Decimal(2)
If I do this, then print c, the inexact and rounded flags are raised. Even though the result is accurate. Shouldn't flags therefore be attributes of numbers rather than the context? This problem is especially apparent when I program lengthy calculation using a stack.
To pose a more meaningful question: How do I properly deal with this?
It seems I have to keep track of everything manually. If I clear flags before calculations, I would lose some informations about numbers calculated before. Which may now appear accurate. This is especially annoying when working with numbers like 1.0000000154342.
For a critical application, it would be really nice to be sure about what is accurate and what isn't. It would also be nice to not have the wrong flags raised, just because it looks bad.
It still assume there is a good rationale behind this, which I haven't understood. I'd be thankful for an explanation.
| [
"Read this: http://docs.python.org/library/decimal.html#context-objects\nYou have context objects that you can save and restore so that you don't lose flag values.\n"
] | [
0
] | [] | [] | [
"decimal",
"python"
] | stackoverflow_0003418483_decimal_python.txt |
Q:
python: open unfocused tab with webbrowser
I would like to open a new tab in my web browser using python's webbrowser. However, now my browser is brought to the top and I am directly moved to the opened tab. I haven't found any information about this in documentation, but maybe there is some hidden api. Can I open this tab in the possible most unobtrusive way, which means:
not bringing browser to the top if it's minimzed,
not moving me the opened tab (especially if I am at the moment working in other tab - my process is working in the background and it would be very annoying to have suddenly my work interrupted by a new tab)?
A:
On WinXP, at least, it appears that this is not possible (from my tests with IE).
From what I can see, webbrowser is a fairly simple convenience module that creates (probably ) a subprocess-style call to the browser executable.
If you want that sort of granularity you'll have to see if your browser accepts command line arguments to that effect, or exposes that control in some other way.
| python: open unfocused tab with webbrowser | I would like to open a new tab in my web browser using python's webbrowser. However, now my browser is brought to the top and I am directly moved to the opened tab. I haven't found any information about this in documentation, but maybe there is some hidden api. Can I open this tab in the possible most unobtrusive way, which means:
not bringing browser to the top if it's minimzed,
not moving me the opened tab (especially if I am at the moment working in other tab - my process is working in the background and it would be very annoying to have suddenly my work interrupted by a new tab)?
| [
"On WinXP, at least, it appears that this is not possible (from my tests with IE).\nFrom what I can see, webbrowser is a fairly simple convenience module that creates (probably ) a subprocess-style call to the browser executable. \nIf you want that sort of granularity you'll have to see if your browser accepts comm... | [
0
] | [] | [] | [
"python",
"python_webbrowser",
"tabs"
] | stackoverflow_0003417756_python_python_webbrowser_tabs.txt |
Q:
device behind firewall connect via ssh
There have been a few questions like this around the place but none have really answered my question specifically.(for example Connecting to device behind firewall )
What I want is a central server, that receives a heartbeat from multiple ( say 100's) embedded devices behind personal firewalls. These devices need to be able to do two things.
Grab new config from the server. I
suspect I can just do this via a
http get from the device to the
server and pull down some XML, then
reload its own config.
Open an ssh connection to the server
to allow an admin to login to the
command line of the device and do
maintenance and troubleshooting
remotely.ie device => server <= admin and admin can get to bash command line or equivalent.
the device is a low powered embedded device that will be running linux. A solution in python would be preferable (im thinking something with paramiko for the ssh) but im open to other solutions. The main thing is there is there will be no technical users in the private network, so it should be able to plug into a consumer grade ADSL modem, get a DHCP address and all this should work. I can preload the device with anything before hand, for example ssh certificates for passwordless ssh etc.
anybody got any idea's?
Cheers
Mark
A:
You can setup ssh tunnel (from python script or from console):
ssh -NR10022:localhost:22 foo@mainserver.com
Then you can simply login to main server and then ssh bar@localhost -p 10022
You should have ssh keys, so you don't have to put password (google about "ssh without password").
A:
A more elaborate method might be some type of firewall hole punching.
On second though, maybe this is not necessary, since there is only one firewall involved. The trick is to get your embedded device to initiate an outbound connection first.
| device behind firewall connect via ssh | There have been a few questions like this around the place but none have really answered my question specifically.(for example Connecting to device behind firewall )
What I want is a central server, that receives a heartbeat from multiple ( say 100's) embedded devices behind personal firewalls. These devices need to be able to do two things.
Grab new config from the server. I
suspect I can just do this via a
http get from the device to the
server and pull down some XML, then
reload its own config.
Open an ssh connection to the server
to allow an admin to login to the
command line of the device and do
maintenance and troubleshooting
remotely.ie device => server <= admin and admin can get to bash command line or equivalent.
the device is a low powered embedded device that will be running linux. A solution in python would be preferable (im thinking something with paramiko for the ssh) but im open to other solutions. The main thing is there is there will be no technical users in the private network, so it should be able to plug into a consumer grade ADSL modem, get a DHCP address and all this should work. I can preload the device with anything before hand, for example ssh certificates for passwordless ssh etc.
anybody got any idea's?
Cheers
Mark
| [
"You can setup ssh tunnel (from python script or from console):\nssh -NR10022:localhost:22 foo@mainserver.com\n\nThen you can simply login to main server and then ssh bar@localhost -p 10022\nYou should have ssh keys, so you don't have to put password (google about \"ssh without password\").\n",
"A more elaborate ... | [
2,
0
] | [] | [] | [
"device",
"embedded",
"linux",
"python",
"ssh"
] | stackoverflow_0003412203_device_embedded_linux_python_ssh.txt |
Q:
Django Template Headings
Is there a way in Django templates to show a heading for a field (name of the field) only if the field has a value.
For instance if one of the fields was called Year Established it might look something like this.
Year Established: 1985
But if the field was empty then it wouldn't show Year Established like this.
Year Estabished:
I know you could do an if statement around each field but with over 50 fields this seems a little tedious, messy and redundant.
A:
@register.filter
def labeled(value, label):
if value:
return label + value
else:
return ""
then you can:
{{ year_est|labeled:"Year Established: " }}
| Django Template Headings | Is there a way in Django templates to show a heading for a field (name of the field) only if the field has a value.
For instance if one of the fields was called Year Established it might look something like this.
Year Established: 1985
But if the field was empty then it wouldn't show Year Established like this.
Year Estabished:
I know you could do an if statement around each field but with over 50 fields this seems a little tedious, messy and redundant.
| [
"@register.filter\ndef labeled(value, label):\n if value:\n return label + value\n else:\n return \"\"\n\nthen you can:\n{{ year_est|labeled:\"Year Established: \" }}\n\n"
] | [
3
] | [] | [] | [
"django",
"python",
"templates"
] | stackoverflow_0003418339_django_python_templates.txt |
Q:
FreeTDS translating MS SQL money type to python float, not Decimal
I am connecting to an MS SQL Server db from Python in Linux. I am connecting via pyodbc using the FreeTDS driver. When I return a money field from MSSQL it comes through as a float, rather than a Python Decimal.
The problem is with FreeTDS. If I run the exact same Python code from Windows (where I do not need to use FreeTDS), pyodbc returns a Python Decimal.
How can I get back a Python Decimal when I'm running the code in Linux?
A:
You could always just convert it to Decimal when it comes back...
A:
It was a bug in FreeTDS. The bug has been fixed in the CVS head of FreeTDS as of August 4, 2010 (thanks Freddy Ziglio). See my post on the web2py message board for more info.
| FreeTDS translating MS SQL money type to python float, not Decimal | I am connecting to an MS SQL Server db from Python in Linux. I am connecting via pyodbc using the FreeTDS driver. When I return a money field from MSSQL it comes through as a float, rather than a Python Decimal.
The problem is with FreeTDS. If I run the exact same Python code from Windows (where I do not need to use FreeTDS), pyodbc returns a Python Decimal.
How can I get back a Python Decimal when I'm running the code in Linux?
| [
"You could always just convert it to Decimal when it comes back...\n",
"It was a bug in FreeTDS. The bug has been fixed in the CVS head of FreeTDS as of August 4, 2010 (thanks Freddy Ziglio). See my post on the web2py message board for more info.\n"
] | [
1,
0
] | [] | [] | [
"freetds",
"pyodbc",
"python",
"sql_server"
] | stackoverflow_0003371795_freetds_pyodbc_python_sql_server.txt |
Q:
Writing a Shell in Python?
Why is this such a bad idea? (According to many people)
A:
I don't think it's a bad idea. Lots of people use IPython which is a shell written in Python :)
In fact you may want to base your effort around IPython. scipy does this, for example
A:
I've always thought it was quite a cool idea. Last time I got the urge to give it a go I was thinking about a maple-style worksheet interface for Python. Sadly I can't find the very cool Python+GTK+Cairo code for an interactive shell that is out there somewhere, but searching now I did come across a couple of things that might interest you.
Reinteract is very close to what I had in mind.
PyShell is closer to a traditional shell, the source is available and it says on the website that he's seeking help.
Edit: This older question on unix shell written in a reasonable language was a related link and has lots more examples.
A:
Another shell written in Python is hotwire - it has some interesting ideas and a mix of commandline and gui interface. It is written in Python but can let you freely intermix code in sh, python, perl and ruby, plus its own language 'HotWirePipe'.
Unfortunately the main site for it seems to have died, but it is archived in the wayback machine.
| Writing a Shell in Python? | Why is this such a bad idea? (According to many people)
| [
"I don't think it's a bad idea. Lots of people use IPython which is a shell written in Python :)\nIn fact you may want to base your effort around IPython. scipy does this, for example\n",
"I've always thought it was quite a cool idea. Last time I got the urge to give it a go I was thinking about a maple-style wor... | [
3,
0,
0
] | [] | [] | [
"python",
"shell"
] | stackoverflow_0003410296_python_shell.txt |
Q:
Vector algebra in functional
How to implement vector sum, using functional programming in python.
This code work for n <100, but not for n > 1000.
from itertools import *
#n=10000 # do not try!!!
n=100
twin=((i,i**2,i**3) for i in xrange(1,n+1))
def sum(x=0,y=0):
return x+y
def dubsum(x,y):
return (reduce(sum,i) for i in izip(x,y) )
print [ i for i in reduce(dubsum,twin) ]
A:
Like this:
print [sum(e) for e in izip(*twin)]
Or even more functionally:
print map(sum, izip(*twin))
Note that zipping is very much like transposing a two-dimensional array.
>>> zip([1, 2, 3, 4],
... [5, 6, 7, 8]) == [(1, 5),
... (2, 6),
... (3, 7),
... (4, 8)]
True
A:
Python has built in sum, why bother:
from itertools import *
n=10000
twin=((i,i**2,i**3) for i in xrange(1,n+1))
x,y,z= izip(*twin)
print sum(x),sum(y),sum(z)
| Vector algebra in functional | How to implement vector sum, using functional programming in python.
This code work for n <100, but not for n > 1000.
from itertools import *
#n=10000 # do not try!!!
n=100
twin=((i,i**2,i**3) for i in xrange(1,n+1))
def sum(x=0,y=0):
return x+y
def dubsum(x,y):
return (reduce(sum,i) for i in izip(x,y) )
print [ i for i in reduce(dubsum,twin) ]
| [
"Like this:\nprint [sum(e) for e in izip(*twin)]\n\nOr even more functionally:\nprint map(sum, izip(*twin))\n\nNote that zipping is very much like transposing a two-dimensional array.\n>>> zip([1, 2, 3, 4],\n... [5, 6, 7, 8]) == [(1, 5),\n... (2, 6),\n... (3, 7)... | [
2,
0
] | [] | [] | [
"function",
"python",
"vector"
] | stackoverflow_0003419202_function_python_vector.txt |
Q:
Python method overload based on argument count?
If I call QApplication's init without arguments i get
TypeError: arguments did not match any overloaded call:
QApplication(list-of-str): not enough arguments
QApplication(list-of-str, bool): not enough arguments
QApplication(list-of-str, QApplication.Type): not enough arguments
QApplication(Display, int visual=0, int colormap=0): not enough arguments
QApplication(Display, list-of-str, int visual=0, int cmap=0): not enough arguments
very interesting! How can I write a class like that?? I mean, every trick for this kind of function overloading I saw did not involve explicit signatures.
A:
TypeError is just another Exception. You can take *args **kwargs, check those, and raise a TypeError yourself, specify the text displayed - e.g. listing the expected call.
That being said, PyQt is a bunch of .pyd == native python extension, written in C or C++ (using Boost::Python). At least the latter supports "real" overloads afaik.
Either way, you shouldn't do this unless you have a really good reason. Python is duck-typed, embrace it.
A:
It's quite possible that its init is simply using __init__(self, *args, **kwargs) and then doing its own signature testing against the args list and kwargs dict.
| Python method overload based on argument count? | If I call QApplication's init without arguments i get
TypeError: arguments did not match any overloaded call:
QApplication(list-of-str): not enough arguments
QApplication(list-of-str, bool): not enough arguments
QApplication(list-of-str, QApplication.Type): not enough arguments
QApplication(Display, int visual=0, int colormap=0): not enough arguments
QApplication(Display, list-of-str, int visual=0, int cmap=0): not enough arguments
very interesting! How can I write a class like that?? I mean, every trick for this kind of function overloading I saw did not involve explicit signatures.
| [
"TypeError is just another Exception. You can take *args **kwargs, check those, and raise a TypeError yourself, specify the text displayed - e.g. listing the expected call.\nThat being said, PyQt is a bunch of .pyd == native python extension, written in C or C++ (using Boost::Python). At least the latter supports \... | [
3,
0
] | [] | [] | [
"overloading",
"python"
] | stackoverflow_0003419282_overloading_python.txt |
Q:
Visualize high dimensional field arrows?
I have a big list of tuples (a, b), where both a and b are 9-dimensional vectors from the same space. This essentially encodes states of a system and some transitions. I would like to visualize the field described by these tuples, as arrows pointing from a->b, either in 2D or 3D. One of my problems however is that this is not a well-behaved vector field (not continuous) but I have reasons to believe that it can probably be laid out nicely, even in 2D.
Does anyone know of a toolbox (for matlab/python) or program that can do this? This would presumably first involve some kind of dimensionality reduction on a and b and then plot little arrows from one point to another.
Thank you for your help!
A:
I'm not 100% sure if this answers your question or not, but you may want to look at Recurrence Plots. If this is what you're after, then you wont need any additional Matlab toolboxes.
A:
Okay, turns out MATLAB can do this but it's not very pretty.
It basically boils down to doing PCA, and then using the quiver function to do the plotting:
My matrix X here contains starting points of my high dimensional nodes in odd rows, and ending points in even rows. Then:
[COEFF, SCORE]= princomp(zscore(X));
x=SCORE(1:2:end,1);
y=SCORE(1:2:end,2);
z=SCORE(1:2:end,3);
u=SCORE(2:2:end,1);
v=SCORE(2:2:end,2);
w=SCORE(2:2:end,3);
quiver3(x,y,z,u-x,v-y,w-z,0);
The downside is that I can't find a good way to color the edges, so I get a huge mess if I just do it trivially. Ah well, good enough for now!
A:
Here's a Matlab toolbox of dimension reduction algorithms. I haven't worked with it, but I have worked with dimension reduction, and it seems like a manifold charting/local coordinates algorithm would be able to extract a low-dimensional representation.
TU Delft Dim. Red. Toolbox
| Visualize high dimensional field arrows? | I have a big list of tuples (a, b), where both a and b are 9-dimensional vectors from the same space. This essentially encodes states of a system and some transitions. I would like to visualize the field described by these tuples, as arrows pointing from a->b, either in 2D or 3D. One of my problems however is that this is not a well-behaved vector field (not continuous) but I have reasons to believe that it can probably be laid out nicely, even in 2D.
Does anyone know of a toolbox (for matlab/python) or program that can do this? This would presumably first involve some kind of dimensionality reduction on a and b and then plot little arrows from one point to another.
Thank you for your help!
| [
"I'm not 100% sure if this answers your question or not, but you may want to look at Recurrence Plots. If this is what you're after, then you wont need any additional Matlab toolboxes.\n",
"Okay, turns out MATLAB can do this but it's not very pretty.\nIt basically boils down to doing PCA, and then using the quive... | [
1,
1,
1
] | [] | [] | [
"matlab",
"multidimensional_array",
"python",
"vector",
"visualization"
] | stackoverflow_0003191834_matlab_multidimensional_array_python_vector_visualization.txt |
Q:
Generator in if-statement in python
Or How to if-statement in a modified list.
I've been reading StackOverflow for a while (thanks to everyone). I love it. I also seen that you can post a question and answer it yourself. Sorry if I duplicate, but I didn't found this particular answer on StackOverflow.
How do you verify if a element is in a list but modify it in the same time?
My problem:
myList = ["Foo", "Bar"]
if "foo" in myList:
print "found!"
As I don't know the case of the element in the list I want to compare with lower case list. The obvious but ugly answer would be:
myList = ["Foo", "Bar"]
lowerList = []
for item in myList:
lowerList.append(item.lower())
if "foo" in lowerList:
print "found!"
Can I do it better ?
A:
if any(s.lower() == "foo" for s in list): print "found"
A:
List comprehensions:
mylist = ["Foo", "Bar"]
lowerList = [item.lower() for item in mylist]
Then you can do something like if "foo" in lowerlist or bypass the temporary variable entirely with if "foo" in [item.lower() for item in mylist]
A:
How about:
theList = ["Foo", "Bar"]
lowerCaseSet = set(x.lower for x in theList)
if "foo" in lowerCaseSet:
print "found"
BTW. you shouldn't call your variable list as this word is already used by list type.
A:
This combines the memory advantages of a generator expression with the speed gains from removing duplicates:
if "foo" in (s.lower() for s in set(list)): print "found"
A:
Please do not use list as variable name, here is version which puts generator to variable and demonstrates, that generation stopped after finding the answer and did not exhaust the generator:
list_to_search = ["Foo", "Bar"]
lowergen = (item.lower() for item in list_to_search)
if "foo" in lowergen:
print "found!"
print next(lowergen), 'is next after it'
| Generator in if-statement in python | Or How to if-statement in a modified list.
I've been reading StackOverflow for a while (thanks to everyone). I love it. I also seen that you can post a question and answer it yourself. Sorry if I duplicate, but I didn't found this particular answer on StackOverflow.
How do you verify if a element is in a list but modify it in the same time?
My problem:
myList = ["Foo", "Bar"]
if "foo" in myList:
print "found!"
As I don't know the case of the element in the list I want to compare with lower case list. The obvious but ugly answer would be:
myList = ["Foo", "Bar"]
lowerList = []
for item in myList:
lowerList.append(item.lower())
if "foo" in lowerList:
print "found!"
Can I do it better ?
| [
"if any(s.lower() == \"foo\" for s in list): print \"found\"\n\n",
"List comprehensions:\nmylist = [\"Foo\", \"Bar\"]\nlowerList = [item.lower() for item in mylist]\n\nThen you can do something like if \"foo\" in lowerlist or bypass the temporary variable entirely with if \"foo\" in [item.lower() for item in myli... | [
8,
1,
0,
0,
0
] | [] | [] | [
"generator",
"if_statement",
"list",
"list_comprehension",
"python"
] | stackoverflow_0003419528_generator_if_statement_list_list_comprehension_python.txt |
Q:
How do you delete a file (located in the same directory that your script is running in) in Python?
I'm trying to delete a certain file within the directory that I'm running my Python program in.
def erase_custom_file():
directory=os.listdir(os.getcwd())
for somefile in directory:
if somefile=="file.csv":
os.remove(???)
I'm not sure what my next step should be. I know that os.remove takes in a path for a parameter but I'm not sure how to direct it to the file I want. Help me please?
A:
Use unlink() and path.join()
>>> try:
... os.unlink(os.path.join(os.getcwd(),'file.csv'))
... except OSError, e:
... print e #file does not exist or you don't have permission
A:
This should work:
os.remove( os.path.join( directory, somefile ) )
A:
If you are trying to delete a scratch file you made earlier you can try using temporary files. these will automatically be deleted during garbage collection.
reference: http://docs.python.org/library/tempfile.html
| How do you delete a file (located in the same directory that your script is running in) in Python? | I'm trying to delete a certain file within the directory that I'm running my Python program in.
def erase_custom_file():
directory=os.listdir(os.getcwd())
for somefile in directory:
if somefile=="file.csv":
os.remove(???)
I'm not sure what my next step should be. I know that os.remove takes in a path for a parameter but I'm not sure how to direct it to the file I want. Help me please?
| [
"Use unlink() and path.join()\n>>> try:\n... os.unlink(os.path.join(os.getcwd(),'file.csv'))\n... except OSError, e:\n... print e #file does not exist or you don't have permission\n\n",
"This should work:\nos.remove( os.path.join( directory, somefile ) )\n\n",
"If you are trying to delete a scratch file you m... | [
6,
2,
0
] | [] | [] | [
"delete_file",
"python"
] | stackoverflow_0003419457_delete_file_python.txt |
Q:
How to write a simple server-push implementation in Python using django?
I would like to write a simple server-push implementation either using long pooling or comet that integrates into the server.
I don't want to use a networking framework like twisted because I want to learn how everything is done internally.
What exactly should I learn?
What specifications should I look at?
I prefer something that fits to apache so long pooling is better right?
Is there a way to implement such a thing without any external framework like Stackless Python?
A:
Using Django it is not possible, because django works behind standard http server. To push you need to write a server supporting large number of paralell connections. To start with, I recommend reading Orbited source code. Read both server (python) and client (javascript) code.
| How to write a simple server-push implementation in Python using django? | I would like to write a simple server-push implementation either using long pooling or comet that integrates into the server.
I don't want to use a networking framework like twisted because I want to learn how everything is done internally.
What exactly should I learn?
What specifications should I look at?
I prefer something that fits to apache so long pooling is better right?
Is there a way to implement such a thing without any external framework like Stackless Python?
| [
"Using Django it is not possible, because django works behind standard http server. To push you need to write a server supporting large number of paralell connections. To start with, I recommend reading Orbited source code. Read both server (python) and client (javascript) code. \n"
] | [
0
] | [] | [] | [
"comet",
"django",
"long_polling",
"python",
"server_push"
] | stackoverflow_0003417836_comet_django_long_polling_python_server_push.txt |
Q:
python or database?
i am reading a csv file into a list of a list in python. it is around 100mb right now. in a couple of years that file will go to 2-5gigs. i am doing lots of log calculations on the data. the 100mb file is taking the script around 1 minute to do. after the script does a lot of fiddling with the data, it creates URL's that point to google charts and then downloads the charts locally.
can i continue to use python on a 2gig file or should i move the data into a database?
A:
I'd only put it into a relational database if:
The data is actually relational and expressing it that way helps shrink the size of the data set by normalizing it.
You can take advantage of triggers and stored procedures to offload some of the calculations that your Python code is performing now.
You can take advantage of queries to only perform calculations on data that's changed, cutting down on the amount of work done by Python.
If neither of those things is true, I don't see much difference between a database and a file. Both ultimately have to be stored on the file system.
If Python has to process all of it, and getting it into memory means loading an entire data set, then there's no difference between a database and a flat file.
2GB of data in memory could mean page swapping and thrashing by your application. I would be careful and get some data before I blamed the problem on the file. Just because you access the data from a database won't solve a paging problem.
If your data's flat, I see less advantage in a database, unless "flat" == "highly denormalized".
I'd recommend some profiling to see what's consuming CPU and memory before I made a change. You're guessing about the root cause right now. Better to get some data so you know where the time is being spent.
A:
If you need to go through all lines each time you perform the "fiddling" it wouldn't really make much difference, assuming the actual "fiddling" is whats eating your cycles.
Perhaps you could store the results of your calculations somehow, then a database would probably be nice. Also, databases have methods for ensuring data integrity and stuff like that, so a database is often a great place for storing large sets of data (duh! ;)).
A:
I don't know exactly what you are doing. But a database will just change how the data is stored. and in fact it might take longer since most reasonable databases may have constraints put on columns and additional processing for the checks. In many cases having the whole file local, going through and doing calculations is going to be more efficient than querying and writing it back to the database (subject to disk speeds, network and database contention, etc...). But in some cases the database may speed things up, especially because if you do indexing it is easy to get subsets of the data.
Anyway you mentioned logs, so before you go database crazy I have the following ideas for you to check out. Anyway I'm not sure if you have to keep going through every log since the beginning of time to download charts and you expect it to grow to 2 GB or if eventually you are expecting 2 GB of traffic per day/week.
ARCHIVING -- you can archive old logs, say every few months. Copy the production logs to an archive location and clear the live logs out. This will keep the file size reasonable. If you are wasting time accessing the file to find the small piece you need then this will solve your issue.
You might want to consider converting to Java or C. Especially on loops and calculations you might see a factor of 30 or more speedup. This will probably reduce the time immediately. But over time as data creeps up, some day this will slow down as well. if you have no bound on the amount of data, eventually even hand optimized Assembly by the world's greatest programmer will be too slow. But it might give you 10x the time...
You also may want to think about figuring out the bottleneck (is it disk access, is it cpu time) and based on that figuring out a scheme to do this task in parallel. If it is processing, look into multi-threading (and eventually multiple computers), if it is disk access consider splitting the file among multiple machines...It really depends on your situation. But I suspect archiving might eliminate the need here.
As was suggested, if you are doing the same calculations over and over again, then just store them. Whether you use a database or a file this will give you a huge speedup.
If you are downloading stuff and that is a bottleneck, look into conditional gets using the if modified request. Then only download changed items. If you are just processing new charts then ignore this suggestion.
Oh and if you are sequentially reading a giant log file, looking for a specific place in the log line by line, just make another file storing the last file location you worked with and then do a seek each run.
Before an entire database, you may want to think of SQLite.
Finally a "couple of years" seems like a long time in programmer time. Even if it is just 2, a lot can change. Maybe your department/division will be laid off. Maybe you will have moved on and your boss. Maybe the system will be replaced by something else. Maybe there will no longer be a need for what you are doing. If it was 6 months I'd say fix it. but for a couple of years, in most cases, I'd say just use the solution you have now and once it gets too slow then look to do something else. You could make a comment in the code with your thoughts on the issue and even an e-mail to your boss so he knows it as well. But as long as it works and will continue doing so for a reasonable amount of time, I would consider it "done" for now. No matter what solution you pick, if data grows unbounded you will need to reconsider it. Adding more machines, more disk space, new algorithms/systems/developments. Solving it for a "couple of years" is probably pretty good.
A:
I always reach for a database for larger datasets.
A database gives me some stuff for "free"; that is, I don't have to code it.
searching
sorting
indexing
language-independent connections
Something like SQLite might be the answer for you.
Also, you should investigate the "nosql" databases; it sounds like your problem might fit well into one of them.
A:
At 2 gigs, you may start running up against speed issues. I work with model simulations for which it calls hundreds of csv files and it takes about an hour to go through 3 iterations, or about 20 minutes per loop.
This is a matter of personal preference, but I would go with something like PostGreSql because it integrates the speed of python with the capacity of a sql-driven relational database. I encountered the same issue a couple of years ago when my Access db was corrupting itself and crashing on a daily basis. It was either MySQL or PostGres and I chose Postgres because of its python friendliness. Not to say MySQL would not work with Python, because it does, which is why I say its personal preference.
Hope that helps with your decision-making!
| python or database? | i am reading a csv file into a list of a list in python. it is around 100mb right now. in a couple of years that file will go to 2-5gigs. i am doing lots of log calculations on the data. the 100mb file is taking the script around 1 minute to do. after the script does a lot of fiddling with the data, it creates URL's that point to google charts and then downloads the charts locally.
can i continue to use python on a 2gig file or should i move the data into a database?
| [
"I'd only put it into a relational database if:\n\nThe data is actually relational and expressing it that way helps shrink the size of the data set by normalizing it.\nYou can take advantage of triggers and stored procedures to offload some of the calculations that your Python code is performing now.\nYou can take ... | [
4,
4,
4,
2,
1
] | [] | [] | [
"python",
"sql"
] | stackoverflow_0003419624_python_sql.txt |
Q:
In class definition inherited from dict why is there a difference in defining attributes?
In a class inherited from dict, why don't the two ways of defining an attribute produce the same result? Why do I see attr1 but not attr2?
class my_dict(dict):
def __init__(self):
dict.__init__(self)
self['attr1'] = 'seen'
setattr(self, 'attr2', 'unseen')
In [1]: x = my_dict()
In [2]: x
Out[2]: {'attr1': 'seen'}
A:
For the same reason that:
x = {}
x.foo = 34
doesn't work. dicts don't work by defining attributes.
A:
x.attr2
# => 'unseen'
| In class definition inherited from dict why is there a difference in defining attributes? | In a class inherited from dict, why don't the two ways of defining an attribute produce the same result? Why do I see attr1 but not attr2?
class my_dict(dict):
def __init__(self):
dict.__init__(self)
self['attr1'] = 'seen'
setattr(self, 'attr2', 'unseen')
In [1]: x = my_dict()
In [2]: x
Out[2]: {'attr1': 'seen'}
| [
"For the same reason that:\nx = {}\nx.foo = 34\n\ndoesn't work. dicts don't work by defining attributes.\n",
"x.attr2\n# => 'unseen'\n\n"
] | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0003419921_python.txt |
Q:
traceback.print_exc() python question
I am using the following line of code in IDLE to print out my traceback in an eception:
traceback.print_exc()
For some reason I get the red text error message, but then it is followed by a blue text of "None".
Not sure what that None is about, any ideas?
A:
print_exc() prints formatted exception to stderr. If you need string value, call format_exc()
A:
print_exc() doesn't return anything, which in Python is actually returning None. Looks like IDLE is showing you the None it returned.
| traceback.print_exc() python question | I am using the following line of code in IDLE to print out my traceback in an eception:
traceback.print_exc()
For some reason I get the red text error message, but then it is followed by a blue text of "None".
Not sure what that None is about, any ideas?
| [
"print_exc() prints formatted exception to stderr. If you need string value, call format_exc()\n",
"print_exc() doesn't return anything, which in Python is actually returning None. Looks like IDLE is showing you the None it returned.\n"
] | [
7,
5
] | [] | [] | [
"exception_handling",
"python"
] | stackoverflow_0003418834_exception_handling_python.txt |
Q:
In-place dictionary inversion in Python
I need to invert a dictionary of lists, I don't know how to explain it in English exactly, so here is some code that does what I want. It just takes too much memory.
def invert(oldDict):
invertedDict = {}
for key,valuelist in oldDict.iteritems():
for value in valuelist:
try:
entry = invertedDict[value]
if key not in entry:
entry.append(key)
except KeyError:
invertedDict[value] = [key]
return invertedDict
The original is a dict of lists, and the result is a dict of lists. This "inverts" it.
test = {}
test[1] = [1999,2000,2001]
test[2] = [440,441]
test[3] = [440,2000]
print invert(test)
This gives:
{2000: [1, 3], 2001: [1], 440: [2, 3], 441: [2], 1999: [1]}
I need to know if this can be done in-place, because my current strategy is exceeding the amount of physical memory on my machine with the dictionary I am working with. Can you think of a way to do it with generators?
A:
This doesn't do it in place, but consumes oldDict by using popitem()
from collections import defaultdict
def invert(oldDict):
invertedDict = defaultdict(list)
while oldDict:
key, valuelist = oldDict.popitem()
for value in valuelist:
invertedDict[value].append(key)
return invertedDict
I have a feeling that dict's are never resized unless the size increases, so you may need to add+remove a dummy item periodically. See Shrinkage rate
from collections import defaultdict
def invert(oldDict):
invertedDict = defaultdict(list)
i=0
while oldDict:
key, valuelist = oldDict.popitem()
for value in valuelist:
invertedDict[value].append(key)
i+=1
if i%1000==0: # allow the dict to release memory from time to time
oldDict[None]=None
del oldDict[None]
return invertedDict
A:
It probably takes many millions of entries to run out of RAM on modern machine if the algorithm is correct. Assuming this, you have to use some persistent storage for the data to process only chunk at a time. Why not use simple database table with 2 columns to store the dict?
key value
1 1999
1 2000
1 2001
2 440
2 441
...
Then you can use either column as a key by selecting with order by on needed column and grouping values from other column with simple python code.
A:
I actually don't see any way the memory usage of your current algorithm could be significantly improved on. You do use iterators rather than creating new lists/dicts outright, so the only significant memory usage comes from the original dictionary and the new inverted dictionary.
If you don't have enough RAM to run this algorithm with the dictionary you're actually using, all I can think of is to somehow avoid keeping both the original dict and the inverted dict in memory at the same time. One way to do that would be to remove items from the original dict as you add them to the inverted dict, which could be done like this:
def invert(old_dict):
inverted = collections.defaultdict(list)
while old_dict:
k,v = old_dict.popitem()
for vi in v:
inverted[vi].append(k)
return inverted
(notice that I also used defaultdict to simplify the code, but if you really need a pure dict, not a subclass, you could do something like what you had originally with the try/except)
If you want to keep both the original and inverted dictionaries available after the algorithm completes, all I can think of is to store them in disk files, and find some way to only load a piece at a time. I don't know of any standard Python module that is able to store a dict to disk and load only a piece of it at a time, so you might have to write your own code for that.
A:
I don't have a direct answer. Here is some of my thought.
I think what you want to do can be called Inverted index
I don't believe it can be done in-place, nor do I think it is the right strategy. You should look at disk based solution. Perhaps sort or organized your original data structure, write it out to one or more files, then read it back and merge them into your final data structure.
| In-place dictionary inversion in Python | I need to invert a dictionary of lists, I don't know how to explain it in English exactly, so here is some code that does what I want. It just takes too much memory.
def invert(oldDict):
invertedDict = {}
for key,valuelist in oldDict.iteritems():
for value in valuelist:
try:
entry = invertedDict[value]
if key not in entry:
entry.append(key)
except KeyError:
invertedDict[value] = [key]
return invertedDict
The original is a dict of lists, and the result is a dict of lists. This "inverts" it.
test = {}
test[1] = [1999,2000,2001]
test[2] = [440,441]
test[3] = [440,2000]
print invert(test)
This gives:
{2000: [1, 3], 2001: [1], 440: [2, 3], 441: [2], 1999: [1]}
I need to know if this can be done in-place, because my current strategy is exceeding the amount of physical memory on my machine with the dictionary I am working with. Can you think of a way to do it with generators?
| [
"This doesn't do it in place, but consumes oldDict by using popitem()\nfrom collections import defaultdict\ndef invert(oldDict):\n invertedDict = defaultdict(list)\n while oldDict:\n key, valuelist = oldDict.popitem()\n for value in valuelist:\n invertedDict[value].append(key)\n re... | [
5,
2,
1,
0
] | [] | [] | [
"generator",
"hashtable",
"list",
"python"
] | stackoverflow_0003418189_generator_hashtable_list_python.txt |
Q:
wxPython: How to make a TextCtrl fill a Panel
How do I set the size of a multi-line TextCtrl to always fill its parent panel?
A:
Use a boxSizer.
When you add your textCtrl to the sizer set the proportion to 1 and pass the wx.EXPAND flag, that way your textCtrl should fill the panel even when the panel is resized
bsizer = wx.BoxSizer()
bsizer.Add(yourTxtCtrl, 1, wx.EXPAND)
Put the following at the end of your panels initialization to set the layout
self.SetSizerAndFit(bsizer)
| wxPython: How to make a TextCtrl fill a Panel | How do I set the size of a multi-line TextCtrl to always fill its parent panel?
| [
"Use a boxSizer.\nWhen you add your textCtrl to the sizer set the proportion to 1 and pass the wx.EXPAND flag, that way your textCtrl should fill the panel even when the panel is resized \nbsizer = wx.BoxSizer()\nbsizer.Add(yourTxtCtrl, 1, wx.EXPAND)\n\nPut the following at the end of your panels initialization to ... | [
11
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0003420021_python_wxpython.txt |
Q:
Confusion about string find?
I have a list of data that I want to search through. This new list of data is structured like so.
name, address dob family members age height etc..
I want to search through the lines of data so that I stop the search at the ',' that appears after the name to optimize the search. I believe I want to use this command:
str.find(sub[, start[, end]])
I'm having trouble writing the code in this structure though. Any tips on how to make string find work for me?
Here is some sample data:
Bennet, John, 17054099","5","156323558","-","0", 714 //
Menendez, Juan,7730126","5","158662525" 11844 //
Brown, Jamal,"9","22966592","+","0",,"4432 //
The idea is I want my program to search only to the first ',' and not search through the rest of the large lines.
EDIT. So here is my code.
I want the to search the lines in completedataset only until the first comma. I'm still confused as to how I should implement these suggestions into my existing code.
counter = 1
for line in completedataset:
print counter
counter +=1
for t in matchedLines:
if t in line:
smallerdataset.write(line)
A:
You can do it quite directly:
s = 'Bennet, John, 17054099","5","156323558","-","0", 714 //'
print s.find('John', 0, s.index(',')) # find the index of ',' and stop there
A:
If I understand your specs correctly,
for thestring in listdata:
firstcomma = thestring.find(',')
havename = thestring.find(name, 0, firstcomma)
if havename >= 0:
print "found name:", thestring[:firstcomma]
Edit: given the OP's edit of the Q, this would become something like:
counter = 1
for line in completedataset:
print counter
counter += 1
firstcomma = thestring.find(',')
havename = thestring.find(t, 0, firstcomma)
if havename >= 0:
smallerdataset.write(line)
Of course, the use of counter is unPythonically low-level, and a better eqv would be
for counter, line in enumerate(completedataset):
print counter + 1
firstcomma = thestring.find(',')
havename = thestring.find(t, 0, firstcomma)
if havename >= 0:
smallerdataset.write(line)
but that doesn't affect the question as asked.
A:
You will probably search in each line, so you can just split them by ', ' and then do a search on a first element:
for line in file:
name=line.split(', ')[0]
if name.find('smth'):
break
A:
Any reason why you have to use find?
Why not just do something like:
if str.split(",", 1)[0] == search_string:
...
Edit:
Just thought I'd point out - I was just testing this and the split approach seems just as fast (if not faster than find). Test the performance of both approaches using the timeit module and see what you get.
Try:
python -m timeit -n 10000 -s "a='''Bennet, John, 17054099','5','156323558','-','0', 714'''" "a.split(',',1)[0] == 'Bennet'"
then compare with:
python -m timeit -n 10000 -s "a='''Bennet, John, 17054099','5','156323558','-','0', 714'''" "a.find('Bennet', 0, a.find(','))"
Make the name longer (e.g "BennetBennetBennetBennetBennetBennet") and you realize that find suffers more than split
Note: am using split with the maxsplit option
A:
If you're checking a lot of names against each line, it seems like the biggest optimization might be only processing each line for commas once!
for line in completedataset:
i = line.index(',')
first_field = line[:i]
for name in matchedNames:
if name in first_field:
smalldataset.append(name)
| Confusion about string find? | I have a list of data that I want to search through. This new list of data is structured like so.
name, address dob family members age height etc..
I want to search through the lines of data so that I stop the search at the ',' that appears after the name to optimize the search. I believe I want to use this command:
str.find(sub[, start[, end]])
I'm having trouble writing the code in this structure though. Any tips on how to make string find work for me?
Here is some sample data:
Bennet, John, 17054099","5","156323558","-","0", 714 //
Menendez, Juan,7730126","5","158662525" 11844 //
Brown, Jamal,"9","22966592","+","0",,"4432 //
The idea is I want my program to search only to the first ',' and not search through the rest of the large lines.
EDIT. So here is my code.
I want the to search the lines in completedataset only until the first comma. I'm still confused as to how I should implement these suggestions into my existing code.
counter = 1
for line in completedataset:
print counter
counter +=1
for t in matchedLines:
if t in line:
smallerdataset.write(line)
| [
"You can do it quite directly:\ns = 'Bennet, John, 17054099\",\"5\",\"156323558\",\"-\",\"0\", 714 //'\nprint s.find('John', 0, s.index(',')) # find the index of ',' and stop there\n\n",
"If I understand your specs correctly,\nfor thestring in listdata:\n firstcomma = thestring.find(',')\n havename = thestr... | [
5,
3,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003406892_python.txt |
Q:
networking program crashes
i got this code from http://www.evolt.org/node/60276 and modified it to listen for a single "1" coming from the other side
but whenever i run this program it stops and python IDLE goes to non-responding on "data1,addr = UDPSock.recvfrom(1024)"
def get1():
# Server program, receives 1 if ball found
# ff1 is file w/ received data
import socket
import time
# Set the socket parameters
host = "mysystem"
port = 21567
#buf = 1024
addr = (host,port)
# Create socket (UDP) and bind to address
UDPSock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
UDPSock.bind(addr)
# Receive messages
while 1:
print "waiting..............."
data1,addr = UDPSock.recvfrom(1024)
print "got 1"
if not data1:
print "Client has exited!"
break
else:
print "\nReceived message '", data1,"'"
UDPSock.close() # Close socket
print "socket closed\n"
#call some other function that uses 1
and client side
def send1():
# Client program, sends 1 if ball found
# mf1 is file with data to be sent
import socket
# Set the socket parameters
host = "mysystem"
port = 21567
buf = 1024
addr = (host,port)
# Create socket (UDP)
UDPSock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
mf1=1
print mf1
# Send messages
if(UDPSock.sendto(str(mf1),addr)):
print "Sending message '",str(mf1),"'....."
# Close socket
UDPSock.close()
does anyone know what might be the cause of this? (sorry for long post)
A:
As a second guess (I replaced my first guess with this) I suspect that you are running the receiver in IDLE and then IDLE is hanging so you can't run the client. I don't know exactly how IDLE works as I never use it, but the line containing recvfrom will stop the Python thread its running in until data is sent. So you need to start the client in a separate instance of IDLE or from the command line or something.
At any rate, I have tested the program in question on my Python with 127.0.0.1 as the host, and it worked fine, for some values of fine. The recvfrom does hang, but only until some data is sent, then it comes back with the data and prints it out and everything. You do have a bug that happens after that though. :-)
| networking program crashes | i got this code from http://www.evolt.org/node/60276 and modified it to listen for a single "1" coming from the other side
but whenever i run this program it stops and python IDLE goes to non-responding on "data1,addr = UDPSock.recvfrom(1024)"
def get1():
# Server program, receives 1 if ball found
# ff1 is file w/ received data
import socket
import time
# Set the socket parameters
host = "mysystem"
port = 21567
#buf = 1024
addr = (host,port)
# Create socket (UDP) and bind to address
UDPSock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
UDPSock.bind(addr)
# Receive messages
while 1:
print "waiting..............."
data1,addr = UDPSock.recvfrom(1024)
print "got 1"
if not data1:
print "Client has exited!"
break
else:
print "\nReceived message '", data1,"'"
UDPSock.close() # Close socket
print "socket closed\n"
#call some other function that uses 1
and client side
def send1():
# Client program, sends 1 if ball found
# mf1 is file with data to be sent
import socket
# Set the socket parameters
host = "mysystem"
port = 21567
buf = 1024
addr = (host,port)
# Create socket (UDP)
UDPSock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
mf1=1
print mf1
# Send messages
if(UDPSock.sendto(str(mf1),addr)):
print "Sending message '",str(mf1),"'....."
# Close socket
UDPSock.close()
does anyone know what might be the cause of this? (sorry for long post)
| [
"As a second guess (I replaced my first guess with this) I suspect that you are running the receiver in IDLE and then IDLE is hanging so you can't run the client. I don't know exactly how IDLE works as I never use it, but the line containing recvfrom will stop the Python thread its running in until data is sent. ... | [
0
] | [] | [] | [
"networking",
"python"
] | stackoverflow_0003420062_networking_python.txt |
Q:
Minimize to gnome panel
I have an application written in python, I would like it to be able to "minimize" to the gnome panel, much like how gnome's rhytmbox minimizes to the panel. Is it easily possible to do this?
I've run the examples from here but failed to get any of them working and those don't seem to be exactly what I'm looking for. Any good places to start?
A:
The examples linked show how to write panel applets, which have been somewhat discouraged for a while now. Instead, you probably want to create a gtk.StatusIcon. Status icons require the user to have a system tray, but given their widespread use that covers just about everyone.
Once you've got your status icon, minimizing to the panel is a simple matter of:
showing/hiding your application window when the icon is clicked, probably in the StatusIcon's activate signal handler; and
listen to window-state-event on your window, intercepting iconify changes so that you can hide your window instead of it being shown in the taskbar
Of course, using a status icon like this isn't really recommended from a UI point of view, but it is the most pragmatic solution currently.
| Minimize to gnome panel | I have an application written in python, I would like it to be able to "minimize" to the gnome panel, much like how gnome's rhytmbox minimizes to the panel. Is it easily possible to do this?
I've run the examples from here but failed to get any of them working and those don't seem to be exactly what I'm looking for. Any good places to start?
| [
"The examples linked show how to write panel applets, which have been somewhat discouraged for a while now. Instead, you probably want to create a gtk.StatusIcon. Status icons require the user to have a system tray, but given their widespread use that covers just about everyone.\nOnce you've got your status icon, m... | [
3
] | [] | [] | [
"applet",
"gnome",
"python"
] | stackoverflow_0003419512_applet_gnome_python.txt |
Q:
What is a good django library for logging in users with Twitter, Facebook or an OpenID provider?
I want to create an application that allows a user to register and login to a django application with an external provider. In addition, I then want the user to be able to associate additional accounts with that initial account. Finally, I would like the user to be able to login to the application with one of the other associated accounts.
So if a user initially signs in with Facebook Connect, I want them to be able to link their Google account. Then, if they log out, they can log in with their Google account (via openid) and it logs the user in as though they logged in via Facebook Connect.
Does anything like this exist already? Or do I need to write it myself?
A:
The perfect solution for you seems to be Django-SocialAuth. See here. From the page:
Here is an app to allow logging in via twitter, facebook, openid, yahoo, google, which should work transparently with Django authentication system. (@login_required, User and other infrastructure work as expected.) Demo and Code
Edit: I'm pretty sure that SO uses django-SocialAuth for it's login system, looking at the project's demo page.
| What is a good django library for logging in users with Twitter, Facebook or an OpenID provider? | I want to create an application that allows a user to register and login to a django application with an external provider. In addition, I then want the user to be able to associate additional accounts with that initial account. Finally, I would like the user to be able to login to the application with one of the other associated accounts.
So if a user initially signs in with Facebook Connect, I want them to be able to link their Google account. Then, if they log out, they can log in with their Google account (via openid) and it logs the user in as though they logged in via Facebook Connect.
Does anything like this exist already? Or do I need to write it myself?
| [
"The perfect solution for you seems to be Django-SocialAuth. See here. From the page:\nHere is an app to allow logging in via twitter, facebook, openid, yahoo, google, which should work transparently with Django authentication system. (@login_required, User and other infrastructure work as expected.) Demo and Code\... | [
1
] | [] | [] | [
"facebook",
"oauth",
"openid",
"python"
] | stackoverflow_0003420540_facebook_oauth_openid_python.txt |
Q:
Django MySql setup
I set up Mysql5, mysql5-server and py26-mysql using Macports. I then started the mysql server and was able to start the prompt with mysql5
In my settings.py i changed database_engine to "mysql" and put "dev.db" in database_name.
I left the username and password blank as the database doesnt exist yet.
When I ran python manage.py syncdb, django raised an error
'django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: dynamic module does not define init function (init_mysql)`
How do I fix this? Do I have to create the database first? is it something else?
A:
syncdb will not create a database for you -- it only creates tables that don't already exist in your schema. You need to:
Create a user to 'own' the database (root is a bad choice).
Create the database with that user.
Update the Django database settings with the correct database name, user, and password.
A:
You need to install MySQLdb: http://sourceforge.net/projects/mysql-python/
This can be a painful process depending on your setup. See other discussions on SO regarding MySQLdb install on mac os x:
How to install MySQLdb (Python data access library to MySQL) on Mac OS X?
EDIT: Sorry, skimmed past the fact that you already installed MySQLdb via py26-mysql, but this error seems to point to something that went wrong with that install. I've had lots of problems with MySQLdb on Mac OS X, always something different I have to do to make it work.
| Django MySql setup | I set up Mysql5, mysql5-server and py26-mysql using Macports. I then started the mysql server and was able to start the prompt with mysql5
In my settings.py i changed database_engine to "mysql" and put "dev.db" in database_name.
I left the username and password blank as the database doesnt exist yet.
When I ran python manage.py syncdb, django raised an error
'django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: dynamic module does not define init function (init_mysql)`
How do I fix this? Do I have to create the database first? is it something else?
| [
"syncdb will not create a database for you -- it only creates tables that don't already exist in your schema. You need to:\n\nCreate a user to 'own' the database (root is a bad choice).\nCreate the database with that user.\nUpdate the Django database settings with the correct database name, user, and password.\n\n... | [
1,
1
] | [] | [] | [
"django",
"mysql",
"python"
] | stackoverflow_0003376673_django_mysql_python.txt |
Q:
How can I assign names to some numbers to feed them into a random number generator as variables
I need some assistance here.
import urllib2
pen = urllib2.Request("http://silasanio.appspot.com/mean_stdev")
response = urllib2.urlopen(pen)
f = response.read()
print f
-0.0011935729005
0.0313498454115
...............
..............
the numbers above were returned together with some other texts.
My problem is I want those numbers as variables to feed a random number generator. That is I want the first number assigned mean and the second assigned standard_deviation.
I need assistance on how to do that, please.
Thanks
A:
If you can avoid making f, you can just use:
lines = response.readlines()
mean = float(lines[0])
stddev = float(lines[1])
If you need f for other purposes, replace the first of these statements with
lines = f.splitlines()
| How can I assign names to some numbers to feed them into a random number generator as variables | I need some assistance here.
import urllib2
pen = urllib2.Request("http://silasanio.appspot.com/mean_stdev")
response = urllib2.urlopen(pen)
f = response.read()
print f
-0.0011935729005
0.0313498454115
...............
..............
the numbers above were returned together with some other texts.
My problem is I want those numbers as variables to feed a random number generator. That is I want the first number assigned mean and the second assigned standard_deviation.
I need assistance on how to do that, please.
Thanks
| [
"If you can avoid making f, you can just use:\nlines = response.readlines()\nmean = float(lines[0])\nstddev = float(lines[1])\n\nIf you need f for other purposes, replace the first of these statements with\nlines = f.splitlines()\n\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0003420786_python.txt |
Q:
Issues with time.sleep and Multithreading in Python
I am having an issue with the time.sleep() function in python. I am running a script that needs to wait for another program to generate txt files. Although, this is a terribly old machine, so when I sleep the python script, I run into issues with the other program not generating files. Is there any alternatives to using time.sleep()? I thought locking the thread might work but essentially it would just be a loop of locking the thread for a couple of seconds. I'll give some pseudo code here of what I'm doing.
While running:
if filesFound != []:
moveFiles
else:
time.sleep(1)
A:
One way to do a non-blocking wait is to use threading.Event:
import threading
dummy_event = threading.Event()
dummy_event.wait(timeout=1)
This can be set() from another thread to indicate that something has completed. But if you are doing stuff in another thread, you could avoid the timeout and event altogether and just join the other thread:
import threading
def create_the_file(completion_event):
# Do stuff to create the file
def Main():
worker = threading.Thread(target=create_the_file)
worker.start()
# We will stop here until the "create_the_file" function finishes
worker.join()
# Do stuff with the file
If you want an example of using events for more fine-grained control, I can show you that...
The threading approach won't work if your platform doesn't provide the threading module. For example, if you try to substitute the dummy_threading module, dummy_event.wait() returns immediately. Not sure about the join() approach.
If you are waiting for other processes to finish, you would be better off managing them from your own script using the subprocess module (and then, for example, using the wait method to be sure the process is done before you do further work).
If you can't manage the subprocess from your script, but you know the PID, you can use the os.waitpid() function. Beware of the OSError if the process has already finished by the time you use this function...
If you want a cross-platform way to watch a directory to be notified of new files, I'd suggest using a GIO FileMonitor from PyGTK/PyGObject. You can get a monitor on a directory using the monitor_directory method of a GIO.File.
Quick sample code for a directory watch:
import gio
def directory_changed(monitor, file1, file2, evt_type):
print "Changed:", file1, file2, evt_type
gfile = gio.File(".")
monitor = gfile.monitor_directory(gio.FILE_MONITOR_NONE, None)
monitor.connect("changed", directory_changed)
import glib
ml = glib.MainLoop()
ml.run()
| Issues with time.sleep and Multithreading in Python | I am having an issue with the time.sleep() function in python. I am running a script that needs to wait for another program to generate txt files. Although, this is a terribly old machine, so when I sleep the python script, I run into issues with the other program not generating files. Is there any alternatives to using time.sleep()? I thought locking the thread might work but essentially it would just be a loop of locking the thread for a couple of seconds. I'll give some pseudo code here of what I'm doing.
While running:
if filesFound != []:
moveFiles
else:
time.sleep(1)
| [
"One way to do a non-blocking wait is to use threading.Event:\nimport threading\ndummy_event = threading.Event()\ndummy_event.wait(timeout=1)\n\nThis can be set() from another thread to indicate that something has completed. But if you are doing stuff in another thread, you could avoid the timeout and event altoget... | [
7
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0003416160_multithreading_python.txt |
Q:
Anyone know a better way do write this login function in django
Hay I was wondering if anyone knew a better way to do this.
def login_user(request):
username = request.POST.get('username')
password = request.POST.get('password')
user = User.objects.filter(username=username)
if user:
user = user[0]
if user.password == generate_password(password):
return HttpResponse("password fine")
else:
return HttpResponse("password incorrect")
else:
return HttpResponse("no user found by that username")
and the generate_password function is just
generate_password(string):
return hashlib.sha224(str(string)).hexdigest()
Any ideas would be great.
Thanks
A:
Why don't use Django auth default views ?
A:
the only amelioration i see is use get instead of filter (it will save you one line)
user = User.objects.get(username=username)
A:
Looking at the level of control you want to have, you'll want to make use of the authenticate and maybe login functions in django.contrib.auth. These are the main functions for accessing authentication. I should stress that you really, really should use these instead of finding the user and checking the password hash manually. There are a number of reasons why:
they will make use of whatever authentication backend you or someone else in the future have installed
your version will be far less tested than Django's and is more likely to open security holes
it's quicker, shorter, more flexible and more readable
Django's auth app will probably change in the near future, sticking to authenticate will help you migrate to the new auth app when it gets written/committed/released
If you do want to rewrite the way a user is found and authenticated, write your own Authenticate backend, which will be used when you call authentication (even in someone else's app, like the admin). This is the only place you should rewrite authentication in Django.
The following examples are from the Django auth docs.
1. Checking a user's password:
from django.contrib.auth import authenticate
user = authenticate(username='john', password='secret')
if user is not None:
if user.is_active:
print "You provided a correct username and password!"
else:
print "Your account has been disabled!"
else:
print "Your username and password were incorrect."
2. Custom authentication backend:
Here is a backend that uses the same authenticate method as Django's, which you can find at django.contrib.auth.backends.ModelBackend:
from django.contrib.auth.models import User
class MyBackend:
def authenticate(self, username=None, password=None):
try:
user = User.objects.get(username=username)
if user.check_password(password):
return user
except User.DoesNotExist:
return None
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
A:
You should download django-registration and go through the code. It manages everything for you, including cleaning the code. Your original code will not handle empty submissions.
http://bitbucket.org/ubernostrum/django-registration/
| Anyone know a better way do write this login function in django | Hay I was wondering if anyone knew a better way to do this.
def login_user(request):
username = request.POST.get('username')
password = request.POST.get('password')
user = User.objects.filter(username=username)
if user:
user = user[0]
if user.password == generate_password(password):
return HttpResponse("password fine")
else:
return HttpResponse("password incorrect")
else:
return HttpResponse("no user found by that username")
and the generate_password function is just
generate_password(string):
return hashlib.sha224(str(string)).hexdigest()
Any ideas would be great.
Thanks
| [
"Why don't use Django auth default views ?\n",
"the only amelioration i see is use get instead of filter (it will save you one line)\nuser = User.objects.get(username=username)\n\n",
"Looking at the level of control you want to have, you'll want to make use of the authenticate and maybe login functions in djang... | [
5,
1,
1,
0
] | [] | [] | [
"authentication",
"django",
"python"
] | stackoverflow_0003416182_authentication_django_python.txt |
Q:
Porting Quartz 2d python demo to pure Core Graphics C
let me first off noting that I have absolutely no idea what I'm doing with objective-c and mac development (though I'm fine with c). I made a wonderfully simple graphics utility on leopard with the Quartz-2d binding for python:
http://developer.apple.com/graphicsimaging/pythonandquartz.html
that basically inputs a text file and writes a nice png file (it's a command line utility). I was happy as a pig in mud until I moved the utility to our snow leopard servers and discovered that there were all sorts of issues with CoreGraphics and 32 bit python on snow leopard. Some of these issues are soluble, and some not. So, I'm attempting to port this simple utility script to objective-c (really C I suppose) and running into a few issues. Does anyone else know if there's a nice example almost exactly like the one given in python and quartz, but all in native code?
My major issue is writing the graphics context to a file
myBitmapContext = MyCreateBitmapContext (400, 300);
CGContextSetRGBFillColor (myBitmapContext, 1, 0, 0, 1);
CGContextFillRect (myBitmapContext, CGRectMake (0, 0, 200, 100 ));
CGContextSetRGBFillColor (myBitmapContext, 0, 0, 1, .5);
CGContextFillRect (myBitmapContext, CGRectMake (0, 0, 100, 200 ));
CGImageRef myImage = CGBitmapContextCreateImage (myBitmapContext);// 5
CGContextDrawImage(myBitmapContext, myBoundingBox, myImage);// 6
char *bitmapData = CGBitmapContextGetData(myBitmapContext); // 7
// I'd like to write to a file here!
CGContextRelease (myBitmapContext);// 8
if (bitmapData) free(bitmapData); // 9
CGImageRelease(myImage);
MyCreateBitmapContext is a simple function from apple's guide on quartz 2d.
TL;DR Does anyone have a C port of the python demo given in the above link?
A:
CGImageRef myImage = CGBitmapContextCreateImage (myBitmapContext);// 5
CGContextDrawImage(myBitmapContext, myBoundingBox, myImage);// 6
What? Why would you capture the contents of the context as an image, and then draw that image back into the context you got it from?
// I'd like to write to a file here!
Do step 5, then feed that image to a CGImageDestination.
You may find the Core Graphics Reference Collection handy. There's a document like that for each of most of the frameworks.
| Porting Quartz 2d python demo to pure Core Graphics C | let me first off noting that I have absolutely no idea what I'm doing with objective-c and mac development (though I'm fine with c). I made a wonderfully simple graphics utility on leopard with the Quartz-2d binding for python:
http://developer.apple.com/graphicsimaging/pythonandquartz.html
that basically inputs a text file and writes a nice png file (it's a command line utility). I was happy as a pig in mud until I moved the utility to our snow leopard servers and discovered that there were all sorts of issues with CoreGraphics and 32 bit python on snow leopard. Some of these issues are soluble, and some not. So, I'm attempting to port this simple utility script to objective-c (really C I suppose) and running into a few issues. Does anyone else know if there's a nice example almost exactly like the one given in python and quartz, but all in native code?
My major issue is writing the graphics context to a file
myBitmapContext = MyCreateBitmapContext (400, 300);
CGContextSetRGBFillColor (myBitmapContext, 1, 0, 0, 1);
CGContextFillRect (myBitmapContext, CGRectMake (0, 0, 200, 100 ));
CGContextSetRGBFillColor (myBitmapContext, 0, 0, 1, .5);
CGContextFillRect (myBitmapContext, CGRectMake (0, 0, 100, 200 ));
CGImageRef myImage = CGBitmapContextCreateImage (myBitmapContext);// 5
CGContextDrawImage(myBitmapContext, myBoundingBox, myImage);// 6
char *bitmapData = CGBitmapContextGetData(myBitmapContext); // 7
// I'd like to write to a file here!
CGContextRelease (myBitmapContext);// 8
if (bitmapData) free(bitmapData); // 9
CGImageRelease(myImage);
MyCreateBitmapContext is a simple function from apple's guide on quartz 2d.
TL;DR Does anyone have a C port of the python demo given in the above link?
| [
"\nCGImageRef myImage = CGBitmapContextCreateImage (myBitmapContext);// 5\n\nCGContextDrawImage(myBitmapContext, myBoundingBox, myImage);// 6\n\n\nWhat? Why would you capture the contents of the context as an image, and then draw that image back into the context you got it from?\n\n// I'd like to write to a file he... | [
1
] | [] | [] | [
"c",
"core_graphics",
"objective_c",
"python",
"quartz_2d"
] | stackoverflow_0003420471_c_core_graphics_objective_c_python_quartz_2d.txt |
Q:
How to handle undecodable filenames in Python?
I'd really like to have my Python application deal exclusively with Unicode strings internally. This has been going well for me lately, but I've run into an issue with handling paths. The POSIX API for filesystems isn't Unicode, so it's possible (and actually somewhat common) for files to have "undecodable" names: filenames that aren't encoded in the filesystem's stated encoding.
In Python, this manifests as a mixture of unicode and str objects being returned from os.listdir().
>>> os.listdir(u'/path/to/foo')
[u'bar', 'b\xe1z']
In that example, the character '\xe1' is encoded in Latin-1 or somesuch, even when the (hypothetical) filesystem reports sys.getfilesystemencoding() == 'UTF-8' (in UTF-8, that character would be the two bytes '\xc3\xa1'). For this reason, you'll get UnicodeErrors all over the place if you try to use, for example, os.path.join() with Unicode paths, because the filename can't be decoded.
The Python Unicode HOWTO offers this advice about unicode pathnames:
Note that in most occasions, the Unicode APIs should be used. The bytes APIs should only be used on systems where undecodable file names can be present, i.e. Unix systems.
Because I mainly care about Unix systems, does this mean I should restructure my program to deal only with bytestrings for paths? (If so, how can I maintain Windows compatibility?) Or are there other, better ways of dealing with undecodable filenames? Are they rare enough "in the wild" that I should just ask users to rename their damn files?
(If it is best to just deal with bytestrings internally, I have a followup question: How do I store bytestrings in SQLite for one column while keeping the rest of the data as friendly Unicode strings?)
A:
Python does have a solution to the problem, if you're willing to switch to Python 3.1 or later:
PEP 383 - Non-decodable Bytes in System Character Interfaces.
A:
If you need to store bytestrings in a DB that is geared for UNICODE then it is probably easier to record the bytestrings encoded in hex. That way, the hex-encoded string is safe to store as a unicode string in the db.
As for the UNIX pathname issue, my understanding is that there is no particular encoding enforced for filenames so it is entirely possible to have Latin-1, KOI-8-R, CP1252 and others on various files. This means that each component in a pathname could have a separate encoding.
I would be tempted to try and guess the encoding of filenames using something like the chardet module. Of course, there are no guarantees so you still have to handle exceptions, but you would have fewer undecodeable names. Some software replaces undecodeable characters by ? which is non-reversible. I would rather see them replaced with \xdd or \xdddd because it can be manually reversed if necessary. In some applications it may be possible to present the string to a user so that they can key in unicode characters to replace the unencodeable ones.
If you do go down this route, you may end up extending chardet to handle this job. It would be nice to supplement it with a utility that scans a filesystem finding undecodeable names and produces a list that could be edited, then fed back, to fix all the names with unicode equivalents.
| How to handle undecodable filenames in Python? | I'd really like to have my Python application deal exclusively with Unicode strings internally. This has been going well for me lately, but I've run into an issue with handling paths. The POSIX API for filesystems isn't Unicode, so it's possible (and actually somewhat common) for files to have "undecodable" names: filenames that aren't encoded in the filesystem's stated encoding.
In Python, this manifests as a mixture of unicode and str objects being returned from os.listdir().
>>> os.listdir(u'/path/to/foo')
[u'bar', 'b\xe1z']
In that example, the character '\xe1' is encoded in Latin-1 or somesuch, even when the (hypothetical) filesystem reports sys.getfilesystemencoding() == 'UTF-8' (in UTF-8, that character would be the two bytes '\xc3\xa1'). For this reason, you'll get UnicodeErrors all over the place if you try to use, for example, os.path.join() with Unicode paths, because the filename can't be decoded.
The Python Unicode HOWTO offers this advice about unicode pathnames:
Note that in most occasions, the Unicode APIs should be used. The bytes APIs should only be used on systems where undecodable file names can be present, i.e. Unix systems.
Because I mainly care about Unix systems, does this mean I should restructure my program to deal only with bytestrings for paths? (If so, how can I maintain Windows compatibility?) Or are there other, better ways of dealing with undecodable filenames? Are they rare enough "in the wild" that I should just ask users to rename their damn files?
(If it is best to just deal with bytestrings internally, I have a followup question: How do I store bytestrings in SQLite for one column while keeping the rest of the data as friendly Unicode strings?)
| [
"Python does have a solution to the problem, if you're willing to switch to Python 3.1 or later:\nPEP 383 - Non-decodable Bytes in System Character Interfaces.\n",
"If you need to store bytestrings in a DB that is geared for UNICODE then it is probably easier to record the bytestrings encoded in hex. That way, th... | [
5,
2
] | [] | [] | [
"character_encoding",
"filenames",
"path",
"python",
"unicode"
] | stackoverflow_0003409381_character_encoding_filenames_path_python_unicode.txt |
Q:
What exactly does a non-shallow filecmp.cmp do?
I'm using Python 2.6.2. The docs for the filecmp module say:
The filecmp module defines functions to compare files and directories, with various optional time/correctness trade-offs.
and, of the filecmp.cmp function:
filecmp.cmp(f1, f2[, shallow])
Compare the files named f1 and f2, returning True if they seem equal, False otherwise.
Unless shallow is given and is false, files with identical os.stat() signatures are taken to be equal.
What they don't do is specify just what is the correctness level one obtains with shallow=False. So, what does shallow=False do? How correct is it?
A:
Consulting the source filecmp.py reveals that if shallow=False, filecmp.cmp first checks a few select properties of os.stat(), regardless of whether shallow is True or False. If the stat properties that are examined are the same, it returns True. Else, it checks its internal cache to see if the files have already been compared earlier. If it has, it returns True. Else, it reads BUFSIZE = 8*1024 chunks of data from both files and does an exact contents comparison until it reaches the end of the file. It returns True if the two files have exactly the same contents.
| What exactly does a non-shallow filecmp.cmp do? | I'm using Python 2.6.2. The docs for the filecmp module say:
The filecmp module defines functions to compare files and directories, with various optional time/correctness trade-offs.
and, of the filecmp.cmp function:
filecmp.cmp(f1, f2[, shallow])
Compare the files named f1 and f2, returning True if they seem equal, False otherwise.
Unless shallow is given and is false, files with identical os.stat() signatures are taken to be equal.
What they don't do is specify just what is the correctness level one obtains with shallow=False. So, what does shallow=False do? How correct is it?
| [
"Consulting the source filecmp.py reveals that if shallow=False, filecmp.cmp first checks a few select properties of os.stat(), regardless of whether shallow is True or False. If the stat properties that are examined are the same, it returns True. Else, it checks its internal cache to see if the files have already ... | [
13
] | [] | [] | [
"filecompare",
"python"
] | stackoverflow_0003421523_filecompare_python.txt |
Q:
How to remove duplicates in Links genrated using mechnize in Python?
Here is my code in python which Genrates a list of link objects. I want to remove duplicates form them.
cb = list()
for link in br.links(url_regex="inquiry-results.jsp"):
cb.append(link)
print set(cb)
But It returns the error unhashable instance. link is something like this -
Link(
base_url='http://casesearch.courts.state.md.us/inquiry/inquirySearch.jis',
url='/inquiry/inquiry-results.jsp?action=..........',
text='12',
tag='a',
attrs=[('href', '/inquiry/inquiry-results.jsp?action=.......'),
('title', 'Go to page 12')]
),
[Added newlines and dots just for convenience]
How can I remove duplicates?
A:
You can construct a dictionary using URLs as keys and the get its values:
cb = {}
for link in br.links(url_regex="inquiry-results.jsp"):
cb[link.url] = link
print cb.values()
| How to remove duplicates in Links genrated using mechnize in Python? | Here is my code in python which Genrates a list of link objects. I want to remove duplicates form them.
cb = list()
for link in br.links(url_regex="inquiry-results.jsp"):
cb.append(link)
print set(cb)
But It returns the error unhashable instance. link is something like this -
Link(
base_url='http://casesearch.courts.state.md.us/inquiry/inquirySearch.jis',
url='/inquiry/inquiry-results.jsp?action=..........',
text='12',
tag='a',
attrs=[('href', '/inquiry/inquiry-results.jsp?action=.......'),
('title', 'Go to page 12')]
),
[Added newlines and dots just for convenience]
How can I remove duplicates?
| [
"You can construct a dictionary using URLs as keys and the get its values:\ncb = {}\nfor link in br.links(url_regex=\"inquiry-results.jsp\"):\n cb[link.url] = link\nprint cb.values()\n\n"
] | [
3
] | [] | [] | [
"duplicate_removal",
"mechanize",
"python",
"set"
] | stackoverflow_0003421737_duplicate_removal_mechanize_python_set.txt |
Q:
AttributeError - type object 'Services' has no attribute 'service_price'
I'm trying to create something like an invoice program, to create invoices and calculate prices.
I am still on the models part and I am trying to calculate all the services includes in a single invoice and update them in Invoices.subtotal.
My problem is that I cannot pass the summary value of Services.service_price to Invoices.subtotal.
When I click [Save and Continue editing] I see this:
AttributeError at /admin/invoices/invoices/1/
type object 'Services' has no attribute 'service_price'
Request Method: POST
Request URL: http://192.168.1.3/invmaster/admin/invoices/invoices/1/
Django Version: 1.2.1
Exception Type: AttributeError
Exception Value:
type object 'Services' has no attribute 'service_price'
Exception Location: /opt/invmaster/invoices/models.py in save, line 24
Python Executable: /usr/bin/python
Python Version: 2.6.5
Here is some code:
invoices/models.py
1 from django.db import models
2
3 from invmaster.general.models import Client
4 from invmaster.general.models import job_name
5 from invmaster.general.models import my_data
6
7 from decimal import *
8 import math
9
10 ### Invoices table
11 class Invoices (models.Model):
12 invoice_id = models.AutoField(primary_key=True)
13 client_name = models.ForeignKey(Client)
14 date_created = models.DateField()
15 subtotal = models.DecimalField('Precio sin IVA:(euros)',max_digits=6, decimal_places=2)
16 total = models.DecimalField('Precio Final:(euros)',max_digits=6, decimal_places=2, blank=True, null=True)
17 paid = models.BooleanField()
18 class Meta:
19 db_table = u'invInvoices'
20
21 def save(self, *args, **kwargs):
22 #self.subtotal = int(Services.service_price)
23 f = my_data()
24 self.subtotal = Services.service_price
25 self.total = self.subtotal * ((Decimal(f.IVA)/100)+1)
26 super(Invoices, self).save(*args, **kwargs)
27
28
29
30 ### Services table
31 class Services (models.Model):
32 JOB_CUANTITY = ( (u'H',u'Horas'),
33 (u'U',u'Unidades'),
34 )
35 invoice_id = models.ForeignKey(Invoices)
36 service_type = models.CharField('Tipo',max_length=1, choices=JOB_CUANTITY)
37 service_cuantity = models.IntegerField('Cantidad/Horas', max_length=2)
38 service_name = models.ForeignKey(job_name)
39 service_unit_price = models.DecimalField('Precio por unidad (euros):',max_digits=6, decimal_places=2,blank=True, null=True)
40 service_price = models.DecimalField('Precio (euros):',max_digits=6, decimal_places=2, blank=True, null=True)
41
42 class Meta:
43 db_table = u'invServices'
44 def __unicode__(self):
45 return u'%s' % (self.service_name)
46 def save(self, *args, **kwargs):
47 self.service_price = self.service_cuantity * self.service_unit_price
48 super(Services, self).save(*args, **kwargs)
other files:
general/models.py
### General table
8 class my_data (models.Model):
...
16 IVA = models.IntegerField(max_length=2, default='18') ### IVA = VAT # 18 = 18%
...
26 ### Clients table
27 class Client (models.Model):
28 client_id = models.AutoField(primary_key=True)
29 client_name = models.CharField(max_length=45, unique=True)
...
### Jobs
58 class job_name (models.Model):
59 job_type_id = models.AutoField(primary_key=True)
60 job_name = models.CharField('Servicio/Producto',max_length=60, unique=True)
61 job_price = models.DecimalField('Precio sin IVA (euros:)', max_digits=6, decimal_places=2)
62
63 class Meta:
64 db_table = u'genJobNames'
65
66 def __unicode__(self):
67 return u'%s (%s)' % (self.job_name, self.job_price)
Sorry for my English and for the question if it is stupid (I'm not a programmer, I'm a sysadmin, and I'm new in python/django :-) )
Thanks in advance
Cheers
UPDATE:
files:
linadmin.homeunix.net/models.txt
linadmin.homeunix.net/admin.txt
A:
You haven't got a summary value anywhere. Services.service_price makes no sense in this context - it's a reference to the model field itself, at the class level, rather than to the value of any particular instance of it.
You need some code to calculate the actual value. Bear in mind that you have a ForeignKey from Services to Invoices, which means that each invoice can have many services. So presumably what you want is the total value of all services related to this invoice. You can work this out using an aggregation:
from django.db.models import Sum
service_sum = self.services_set.aggregate(Sum('service_price'))
self.subtotal = service_sum['service_price__sum']
which does a SUM query against the database for all related services.
| AttributeError - type object 'Services' has no attribute 'service_price' | I'm trying to create something like an invoice program, to create invoices and calculate prices.
I am still on the models part and I am trying to calculate all the services includes in a single invoice and update them in Invoices.subtotal.
My problem is that I cannot pass the summary value of Services.service_price to Invoices.subtotal.
When I click [Save and Continue editing] I see this:
AttributeError at /admin/invoices/invoices/1/
type object 'Services' has no attribute 'service_price'
Request Method: POST
Request URL: http://192.168.1.3/invmaster/admin/invoices/invoices/1/
Django Version: 1.2.1
Exception Type: AttributeError
Exception Value:
type object 'Services' has no attribute 'service_price'
Exception Location: /opt/invmaster/invoices/models.py in save, line 24
Python Executable: /usr/bin/python
Python Version: 2.6.5
Here is some code:
invoices/models.py
1 from django.db import models
2
3 from invmaster.general.models import Client
4 from invmaster.general.models import job_name
5 from invmaster.general.models import my_data
6
7 from decimal import *
8 import math
9
10 ### Invoices table
11 class Invoices (models.Model):
12 invoice_id = models.AutoField(primary_key=True)
13 client_name = models.ForeignKey(Client)
14 date_created = models.DateField()
15 subtotal = models.DecimalField('Precio sin IVA:(euros)',max_digits=6, decimal_places=2)
16 total = models.DecimalField('Precio Final:(euros)',max_digits=6, decimal_places=2, blank=True, null=True)
17 paid = models.BooleanField()
18 class Meta:
19 db_table = u'invInvoices'
20
21 def save(self, *args, **kwargs):
22 #self.subtotal = int(Services.service_price)
23 f = my_data()
24 self.subtotal = Services.service_price
25 self.total = self.subtotal * ((Decimal(f.IVA)/100)+1)
26 super(Invoices, self).save(*args, **kwargs)
27
28
29
30 ### Services table
31 class Services (models.Model):
32 JOB_CUANTITY = ( (u'H',u'Horas'),
33 (u'U',u'Unidades'),
34 )
35 invoice_id = models.ForeignKey(Invoices)
36 service_type = models.CharField('Tipo',max_length=1, choices=JOB_CUANTITY)
37 service_cuantity = models.IntegerField('Cantidad/Horas', max_length=2)
38 service_name = models.ForeignKey(job_name)
39 service_unit_price = models.DecimalField('Precio por unidad (euros):',max_digits=6, decimal_places=2,blank=True, null=True)
40 service_price = models.DecimalField('Precio (euros):',max_digits=6, decimal_places=2, blank=True, null=True)
41
42 class Meta:
43 db_table = u'invServices'
44 def __unicode__(self):
45 return u'%s' % (self.service_name)
46 def save(self, *args, **kwargs):
47 self.service_price = self.service_cuantity * self.service_unit_price
48 super(Services, self).save(*args, **kwargs)
other files:
general/models.py
### General table
8 class my_data (models.Model):
...
16 IVA = models.IntegerField(max_length=2, default='18') ### IVA = VAT # 18 = 18%
...
26 ### Clients table
27 class Client (models.Model):
28 client_id = models.AutoField(primary_key=True)
29 client_name = models.CharField(max_length=45, unique=True)
...
### Jobs
58 class job_name (models.Model):
59 job_type_id = models.AutoField(primary_key=True)
60 job_name = models.CharField('Servicio/Producto',max_length=60, unique=True)
61 job_price = models.DecimalField('Precio sin IVA (euros:)', max_digits=6, decimal_places=2)
62
63 class Meta:
64 db_table = u'genJobNames'
65
66 def __unicode__(self):
67 return u'%s (%s)' % (self.job_name, self.job_price)
Sorry for my English and for the question if it is stupid (I'm not a programmer, I'm a sysadmin, and I'm new in python/django :-) )
Thanks in advance
Cheers
UPDATE:
files:
linadmin.homeunix.net/models.txt
linadmin.homeunix.net/admin.txt
| [
"You haven't got a summary value anywhere. Services.service_price makes no sense in this context - it's a reference to the model field itself, at the class level, rather than to the value of any particular instance of it.\nYou need some code to calculate the actual value. Bear in mind that you have a ForeignKey fro... | [
4
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0003422342_django_django_admin_python.txt |
Q:
Perform an action over 2 and 2 elements in a list
I have a list of numbers, say
data = [45,34,33,20,16,13,12,3]
I'd like to compute the difference between 2 and 2 items, (that is, for the above data
I want to compute 45-34,33-20,16-13 and 12-3, what's the python way of doing that ?
Also, more generally, how should I apply a function to 2 and 2 of these elements, that is, I want to call myfunc(data[0],data[1]),myfunc(data[2],data[3]) and so on over the list.
A:
Try slicing the list:
from itertools import izip
[myfunc(a, b) for a, b in izip(data[::2], data[1::2])]
or you can use the fact that izip guarantees the order in which it consumes its arguments:
idata = iter(data)
[myfunc(a, b) for a, b in izip(idata, idata)]
A:
You could create your own iterator to iterate over the elements two-by-two:
class myiter(object):
def __iter__(self):
return self
def next(self):
a = self.l.next()
b = self.l.next()
return (a, b)
def __init__(self, l):
self.l = iter(l)
The iterator returns tuples of two elements at a time:
>>> for x, y in i(data):
... print x, y
45 34
33 20
16 13
12 3
Then you can use it to map your function:
>>> [myfunc(x, y) for x, y in myiter(data)]
A:
def pairs(iterable):
while iterable:
yield next(iterable),next(iterable)
data = [45,34,33,20,16,13,12,3]
print "With pairs generator"
print ','.join(str(a-b) for a,b in pairs(iter(data)))
Consuming version (data will be removed from the list, so take copy if still needed), "without comprehension".
print 'By simple list pop way'
data_c = data[:]
result=[]
while data_c: result.append(data_c.pop(0)-data_c.pop(0))
print result
I would use generally list comprehensions and slicing, but these solutions are maybe sometimes more understandable.
A:
from itertools import tee,izip
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return izip(a, b)
for a,b in pairwise(data):
print a-b
Requires Python 2.6 or later. I took pairwise() from here.
A:
diffs = [data[i] - data[i+1] for i in range(0, len(data), 2)]
or the general case
pairs = [(data[i], data[i+1]) for i in range(0, len(data), 2)]
results = [myfunc(*p) for p in pairs]
Not as elegant as some of the other solutions maybe. Still this ought to be mentioned.
| Perform an action over 2 and 2 elements in a list | I have a list of numbers, say
data = [45,34,33,20,16,13,12,3]
I'd like to compute the difference between 2 and 2 items, (that is, for the above data
I want to compute 45-34,33-20,16-13 and 12-3, what's the python way of doing that ?
Also, more generally, how should I apply a function to 2 and 2 of these elements, that is, I want to call myfunc(data[0],data[1]),myfunc(data[2],data[3]) and so on over the list.
| [
"Try slicing the list:\nfrom itertools import izip\n[myfunc(a, b) for a, b in izip(data[::2], data[1::2])]\n\nor you can use the fact that izip guarantees the order in which it consumes its arguments:\nidata = iter(data)\n[myfunc(a, b) for a, b in izip(idata, idata)]\n\n",
"You could create your own iterator to i... | [
6,
2,
2,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0003422322_python.txt |
Q:
git server side hooks
I am running into a problem when running the follow python script on the server looking for commit information for the push making sure it follows a particular syntax, I am unable to get input from the user which is why the username and password are hard coded. I am now also unable to get the list of commit message that occurred before this particular push.
#!/usr/bin/python
import SOAPpy
import getpass
import datetime
import sys
import re
import logging
import os
def login(x,y):
try:
auth = soap.login(x, y)
return auth
except:
sys.exit( "Invalid username or password")
def getIssue(auth,issue):
try:
issue = soap.getIssue(auth, issue)
except:
sys.exit("No issue of that type found : Make sure all PRs are vaild jira PRs")
def git_get_commit_msg(commit_id):
return get_shell_cmd_output("git rev-list --pretty --max-count=1 " + commit_id)
def git_get_last_commit_id():
return get_shell_cmd_output("git log --pretty=format:%H -1")
def getCommitText():
commit_msg_filename = sys.argv[1]
try:
commit_msg_text = open(commit_msg_filename).read()
return commit_msg_text
except:
sys.exit("Could not read commit message")
def git_get_array_of_commit_ids(start_id, end_id):
output = get_shell_cmd_output("git rev-list " + start_id + ".." + end_id)
if output == "":
return None
commit_id_array = string.split(output, '\n')
return commit_id_array
def get_shell_cmd_output(cmd):
try:
proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
return proc.stdout.read().rstrip('\n')
except KeyboardInterrupt:
logging.info("... interrupted")
except Exception, e:
logging.error("Failed trying to execute '%s'", cmd)
def findpattern(commit_msg):
pattern = re.compile("\w\w*-\d\d*")
group = pattern.findall(commit_msg)
print group
found = len(group)
found =0
issues = 0
for match in group:
auth = soap.login(jirauser,passwd)
getIssue(auth,match)
issues = issues + 1
found+=1
if found ==0:
sys.exit("No issue patterns found.")
print "Retrieved issues: " + str(issues)
def update():
print sys.argv[2]
print sys.argv[3]
old_commit_id = sys.argv[2]
new_commit_id = sys.argv[3]
commit_id_array = git_get_array_of_commit_ids(old_commit_id, new_commit_id)
for commit_id in commit_id_array:
commit_text = git_get_commit_msg(commit_id)
findpattern(commit_text)
soap = SOAPpy.WSDL.Proxy('some url')
# this line if for repointing the input from dev/null
#sys.stdin = open('/dev/tty', 'r') # this fails horribly.
#ask user for input
#jirauser = raw_inp
#("Username for jira: ")
jirauser = "username"
passwd = "987654321"
#passwd = getpass.getpass("Password for %s: " % jirauser)
login(jirauser,passwd)
#commit_msg = getCommitText()
#findpattern(commit_msg)
update()
The intended goal of this code is to check the commits made locally, and to parse through them for the intended pattern, as well as checking the in jira if that PR exists. it is a server side hook that get activated on a push to the repository.
Any tips on writing python hooks would be appreciated. Please and thank you.
A:
I suggest that you have a look at gitorious (http://gitorious.org/gitorious).
They use ssh to handle authentication and rights management (getting the username given by ssh).
They also have some hooks on git repositories. I guess it could help to see how they are processing git hooks using ruby.
A:
By the time your update hook fires, the server has the new commits: the question is whether your hook will allow the ref in question to move. What information from the local (sending) repository do you want?
For the credentials issue, funnel everyone through a single user. For example, GitHub does it with the git user, which is why their SSH URLs begin with git@github.com:.... Then in ~git/.ssh/authorized_keys, associate a username with each key. Note that the following should be on a single line but is wrapped for presentation purposes.
no-agent-forwarding,no-port-forwarding,no-pty,no-X11-forwarding,
command="env myuser=gbgcoll /usr/bin/git-shell -c \"${SSH_ORIGINAL_COMMAND:-}\""
ssh-rsa AAAAB...
Now to see who's trying to do the update, your hook examines the $myuser environment variable.
This doesn't give you each user's Jira credentials. To solve that issue, create a dummy Jira account that has read-only access to everything, and hardcode that Jira account's credentials in your hook. This allows you to verify that a given PR exists.
| git server side hooks | I am running into a problem when running the follow python script on the server looking for commit information for the push making sure it follows a particular syntax, I am unable to get input from the user which is why the username and password are hard coded. I am now also unable to get the list of commit message that occurred before this particular push.
#!/usr/bin/python
import SOAPpy
import getpass
import datetime
import sys
import re
import logging
import os
def login(x,y):
try:
auth = soap.login(x, y)
return auth
except:
sys.exit( "Invalid username or password")
def getIssue(auth,issue):
try:
issue = soap.getIssue(auth, issue)
except:
sys.exit("No issue of that type found : Make sure all PRs are vaild jira PRs")
def git_get_commit_msg(commit_id):
return get_shell_cmd_output("git rev-list --pretty --max-count=1 " + commit_id)
def git_get_last_commit_id():
return get_shell_cmd_output("git log --pretty=format:%H -1")
def getCommitText():
commit_msg_filename = sys.argv[1]
try:
commit_msg_text = open(commit_msg_filename).read()
return commit_msg_text
except:
sys.exit("Could not read commit message")
def git_get_array_of_commit_ids(start_id, end_id):
output = get_shell_cmd_output("git rev-list " + start_id + ".." + end_id)
if output == "":
return None
commit_id_array = string.split(output, '\n')
return commit_id_array
def get_shell_cmd_output(cmd):
try:
proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
return proc.stdout.read().rstrip('\n')
except KeyboardInterrupt:
logging.info("... interrupted")
except Exception, e:
logging.error("Failed trying to execute '%s'", cmd)
def findpattern(commit_msg):
pattern = re.compile("\w\w*-\d\d*")
group = pattern.findall(commit_msg)
print group
found = len(group)
found =0
issues = 0
for match in group:
auth = soap.login(jirauser,passwd)
getIssue(auth,match)
issues = issues + 1
found+=1
if found ==0:
sys.exit("No issue patterns found.")
print "Retrieved issues: " + str(issues)
def update():
print sys.argv[2]
print sys.argv[3]
old_commit_id = sys.argv[2]
new_commit_id = sys.argv[3]
commit_id_array = git_get_array_of_commit_ids(old_commit_id, new_commit_id)
for commit_id in commit_id_array:
commit_text = git_get_commit_msg(commit_id)
findpattern(commit_text)
soap = SOAPpy.WSDL.Proxy('some url')
# this line if for repointing the input from dev/null
#sys.stdin = open('/dev/tty', 'r') # this fails horribly.
#ask user for input
#jirauser = raw_inp
#("Username for jira: ")
jirauser = "username"
passwd = "987654321"
#passwd = getpass.getpass("Password for %s: " % jirauser)
login(jirauser,passwd)
#commit_msg = getCommitText()
#findpattern(commit_msg)
update()
The intended goal of this code is to check the commits made locally, and to parse through them for the intended pattern, as well as checking the in jira if that PR exists. it is a server side hook that get activated on a push to the repository.
Any tips on writing python hooks would be appreciated. Please and thank you.
| [
"I suggest that you have a look at gitorious (http://gitorious.org/gitorious).\nThey use ssh to handle authentication and rights management (getting the username given by ssh).\nThey also have some hooks on git repositories. I guess it could help to see how they are processing git hooks using ruby.\n",
"By the ti... | [
2,
1
] | [] | [] | [
"git",
"githooks",
"jira",
"python",
"ssh"
] | stackoverflow_0003375283_git_githooks_jira_python_ssh.txt |
Q:
Extracting a tag value in BeautifulSoup when unable to match by position or attributes
I'm using BS to scrape a web page and i'm a little stuck with a small problem. Here's a snippet of HTML from the page.
<span style="font-family: arial;"><span style="font-weight: bold;">Artist:</span> M.I.A.<br>
</span>
Once I've got the soup, how can I find this tag and get the artist name i.e. M.I.A.
I cannot match the tag with the style attribute as it is used in a dozen places in the page. I don't even know the exact location of the span tag as it changes position from page to page. Therefore, I can't match by position. The artist name changes but the title span structure is always the same.
I would only like the extract the artist name (the M.I.A. bit).
A:
BeautifulSoup is kind of dead, since SGMLParser is deprecated. I suggest you use the better lxml library -- It even has xpath support!!
from lxml import html
text = '''
<span style="font-family: arial;">
<span style="font-weight: bold;">Artist:</span>M.I.A.<br>
</span>
'''
doc = html.fromstring(text)
print ''.join(doc.xpath("//span/span[text()='Artist:']/../text()"))
This xpath expression means "find the span tag which is inside another span tag and contains the text 'Artist:', and grab all the text of the parent containing tag". It correctly prints M.I.A. as one would expect.
| Extracting a tag value in BeautifulSoup when unable to match by position or attributes | I'm using BS to scrape a web page and i'm a little stuck with a small problem. Here's a snippet of HTML from the page.
<span style="font-family: arial;"><span style="font-weight: bold;">Artist:</span> M.I.A.<br>
</span>
Once I've got the soup, how can I find this tag and get the artist name i.e. M.I.A.
I cannot match the tag with the style attribute as it is used in a dozen places in the page. I don't even know the exact location of the span tag as it changes position from page to page. Therefore, I can't match by position. The artist name changes but the title span structure is always the same.
I would only like the extract the artist name (the M.I.A. bit).
| [
"BeautifulSoup is kind of dead, since SGMLParser is deprecated. I suggest you use the better lxml library -- It even has xpath support!!\nfrom lxml import html\n\ntext = '''\n<span style=\"font-family: arial;\">\n <span style=\"font-weight: bold;\">Artist:</span>M.I.A.<br>\n</span>\n'''\n\ndoc = html.fromstring(... | [
1
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0003422770_beautifulsoup_python.txt |
Q:
Comparing local file with remote file
I have the following problem: I have a local .zip file and a .zip file located on a server. I need to check if the .zip file on the server is different from the local one; if they are not I need to pull the new one from the server. My question is how do I compare them without downloading the file from the server and comparing them locally?
I could create an MD5 hash for the zip file on the server when creating the .zip file and then compare it with the MD5 of my local .zip file, but is there a simpler way?
A:
Short answer: You can't.
Long answer: To compare with the zip file on the server, someone has to read that file. Either you can do that locally, which would involve pulling it, or you can ask the server to do it for you. Can you run code on the server?
Edit
If you can run Python on the server, why not hash the file and compare hashes?
import hashlib
with open( <path-to-file>, "rb" ) as theFile:
m = hashlib.md5( )
for line in theFile:
m.update( line )
with open( <path-to-hashfile>, "wb" ) as theFile:
theFile.write( m.digest( ) )
and then compare the contents of hashfile with a locally-generated hash?
Another edit
You asked for a simpler way. Think about this in an abstract way for a moment:
You don't want to download the entire zip file.
Hence, you can't process the entire file locally (because that would involve reading all of it from the server, which is equivalent to downloading it!).
Hence, you need to do some processing on the server. Specifically, you want to come up with some small amount of data that 'encodes' the file, so that you can fetch this small amount of data without fetching the whole file.
But this is a hash!
Therefore, you need to do some sort of hashing. Given that, I think the above is pretty simple.
A:
I would like to know how you intend to compare them locally, if it were the case. You can apply the same logic to compare them remotely.
A:
You can log in using ssh and make a md5 hash for the file remotely and a md5 hash for the current local file. If the md5s are matching the files are identicaly, else they are different.
| Comparing local file with remote file | I have the following problem: I have a local .zip file and a .zip file located on a server. I need to check if the .zip file on the server is different from the local one; if they are not I need to pull the new one from the server. My question is how do I compare them without downloading the file from the server and comparing them locally?
I could create an MD5 hash for the zip file on the server when creating the .zip file and then compare it with the MD5 of my local .zip file, but is there a simpler way?
| [
"Short answer: You can't.\nLong answer: To compare with the zip file on the server, someone has to read that file. Either you can do that locally, which would involve pulling it, or you can ask the server to do it for you. Can you run code on the server?\nEdit\nIf you can run Python on the server, why not hash the ... | [
2,
0,
0
] | [] | [] | [
"comparison",
"md5",
"python"
] | stackoverflow_0003423510_comparison_md5_python.txt |
Q:
Adding same text to two different lists
How can I add the same text(s) to two or more different lists?
For example, this is what I am doing:
>>> msg = 'Do it'
>>> first = list()
>>> second = list()
>>> first.append(msg)
>>> second.append(msg)
Not only this is causing redundancy, I think it makes for poor code. Is there any way I can add the same text to two or more different lists in one go?
A:
first, second = [], []
for lst in (first, second):
lst.append(msg)
But it would be better if you'd tell us what problem are you solving.
A:
This is inefficient. Why not make one list and then copy() it when you need to differentiate the two?
msg = 'Do it'
theList = [ ]
theList.append( msg )
# Later...
first = theList
second = theList.copy( )
EDIT
I saw your edit. Why not do:
header = [ ]
# Generate header here.
# Later...
for theFile in theFiles:
theFile.write( header )
A:
Why do you need keeping 2 identical lists, instead of one? Describe your task in more details.
A:
Without the write trick
If you have to set the first element after the construction of the list because you don't know it before the simplest is to reserve the place
first, second = [], []
for lst in (first, second):
lst.append(None)
... work on your lists
msg = 'Do it'
for lst in (first, second):
lst[0] = msg
| Adding same text to two different lists | How can I add the same text(s) to two or more different lists?
For example, this is what I am doing:
>>> msg = 'Do it'
>>> first = list()
>>> second = list()
>>> first.append(msg)
>>> second.append(msg)
Not only this is causing redundancy, I think it makes for poor code. Is there any way I can add the same text to two or more different lists in one go?
| [
"first, second = [], []\nfor lst in (first, second):\n lst.append(msg)\n\nBut it would be better if you'd tell us what problem are you solving.\n",
"This is inefficient. Why not make one list and then copy() it when you need to differentiate the two?\nmsg = 'Do it'\ntheList = [ ]\ntheList.append( msg )\n# Late... | [
4,
3,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003422962_python.txt |
Q:
python 2.7 / exec / what is wrong?
I have this code which runs fine in Python 2.5 but not in 2.7:
import sys
import traceback
try:
from io import StringIO
except:
from StringIO import StringIO
def CaptureExec(stmt):
oldio = (sys.stdin, sys.stdout, sys.stderr)
sio = StringIO()
sys.stdout = sys.stderr = sio
try:
exec(stmt, globals(), globals())
out = sio.getvalue()
except Exception, e:
out = str(e) + "\n" + traceback.format_exc()
sys.stdin, sys.stdout, sys.stderr = oldio
return out
print "%s" % CaptureExec("""
import random
print "hello world"
""")
And I get:
string argument expected, got 'str'
Traceback (most recent call last):
File "D:\3.py", line 13, in CaptureExec
exec(stmt, globals(), globals())
File "", line 3, in
TypeError: string argument expected, got 'str'
A:
io.StringIO is confusing in Python 2.7 because it's backported from the 3.x bytes/string world. This code gets the same error as yours:
from io import StringIO
sio = StringIO()
sio.write("Hello\n")
causes:
Traceback (most recent call last):
File "so2.py", line 3, in <module>
sio.write("Hello\n")
TypeError: string argument expected, got 'str'
If you are only using Python 2.x, then skip the io module altogether, and stick with StringIO. If you really want to use io, change your import to:
from io import BytesIO as StringIO
A:
It's bad news
io.StringIO wants to work with unicode. You might think you can fix it by putting a u in front of the string you want to print like this
print "%s" % CaptureExec("""
import random
print u"hello world"
""")
however print is really broken for this as it causes 2 writes to the StringIO. The first one is u"hello world" which is fine, but then it follows with "\n"
so instead you need to write something like this
print "%s" % CaptureExec("""
import random
sys.stdout.write(u"hello world\n")
""")
| python 2.7 / exec / what is wrong? | I have this code which runs fine in Python 2.5 but not in 2.7:
import sys
import traceback
try:
from io import StringIO
except:
from StringIO import StringIO
def CaptureExec(stmt):
oldio = (sys.stdin, sys.stdout, sys.stderr)
sio = StringIO()
sys.stdout = sys.stderr = sio
try:
exec(stmt, globals(), globals())
out = sio.getvalue()
except Exception, e:
out = str(e) + "\n" + traceback.format_exc()
sys.stdin, sys.stdout, sys.stderr = oldio
return out
print "%s" % CaptureExec("""
import random
print "hello world"
""")
And I get:
string argument expected, got 'str'
Traceback (most recent call last):
File "D:\3.py", line 13, in CaptureExec
exec(stmt, globals(), globals())
File "", line 3, in
TypeError: string argument expected, got 'str'
| [
"io.StringIO is confusing in Python 2.7 because it's backported from the 3.x bytes/string world. This code gets the same error as yours:\nfrom io import StringIO\nsio = StringIO()\nsio.write(\"Hello\\n\")\n\ncauses:\nTraceback (most recent call last):\n File \"so2.py\", line 3, in <module>\n sio.write(\"Hello\... | [
15,
2
] | [] | [] | [
"exec",
"python",
"redirect",
"stdio",
"stringio"
] | stackoverflow_0003423601_exec_python_redirect_stdio_stringio.txt |
Q:
Dynamic class field creation before metaclass machinery
I'm trying to get rid of exec in a code similar to this:
class A(object):
for field in ['one', 'two', 'three']:
exec '%s = "%s value"' % (field, field)
...so that:
>>> A.one
'one value'
>>> A.two
'two value'
>>> A.three
'three value'
EDIT: and also the requirement mentioned in the subject is met i.e. A.one is 'one value', before A is instantiated (not to be mistaken for A() instantiated).
Is there a way?
A:
Use the setattr function.
class A(object):
pass
for field in ['one', 'two', 'three']:
setattr(A, field, field + ' value')
A:
I'd just inherit from the metaclass and do it there
class MyMetaClass(MetaClass):
def __new__(meta, classname, baseclasses, classdict):
fields = classdict['__myfields__']
for field in fields:
classdict[field] = field + ' value'
del classDict['__myfields__']
MetaClass.__new__(meta, classname, baseclasses, classdict)
Then you can just do:
class A(object):
__metaclass__ = MyMetaClass
__myfields__ = ['one', 'two', 'three']
A:
>>> values = 'one', 'two', 'three'
>>> A = type('A', (object,), {i: i + ' value' for i in values})
>>> A.one
'one value'
>>> A.three
'three value'
A:
You say you want to generate something dynamically that the metaclass can process. There's a very simple way to achieve that without resorting to hackery like exec. All you have to do is think of this in a different way: modify the metaclass so that the names are generated there.
class AutoFieldMeta(type):
def __new__(mcs, name, bases, d):
for field in d.get('AUTOFIELDS', ()):
d[field] = field + ' value'
return type.__new__(mcs, name, bases, d)
class A(object, metaclass=AutoFieldMeta):
AUTOFIELDS = ('one', 'two', 'three')
>>> A.one
'one value'
>>>
and if you don't want to modify the existing metaclass you can subclass it.
A:
This works too and I think it's a happy end...
class A(object):
for a in ['one', 'two', 'three']:
locals().update({a: a + ' value'})
And for anyone searching for assignment expression in Python, this is in the same mood as aaronasterling answer :):
http://code.activestate.com/recipes/202234-assignment-in-expression/
A:
Let me preface this by saying that this is incredibly hackish but eliminates the exec. We just stick the attributes on the current stack frame as the code in the class statement is being executed. It is only guaranteed to work on CPython and there are warnings against doing it in the manual. I would highly recommend that you go with duncans metaclass solution.
import sys
class A(object):
for field in ['one', 'two', 'three']:
sys._getframe().f_locals[field] = field + ' value'
| Dynamic class field creation before metaclass machinery | I'm trying to get rid of exec in a code similar to this:
class A(object):
for field in ['one', 'two', 'three']:
exec '%s = "%s value"' % (field, field)
...so that:
>>> A.one
'one value'
>>> A.two
'two value'
>>> A.three
'three value'
EDIT: and also the requirement mentioned in the subject is met i.e. A.one is 'one value', before A is instantiated (not to be mistaken for A() instantiated).
Is there a way?
| [
"Use the setattr function.\nclass A(object):\n pass\n\nfor field in ['one', 'two', 'three']:\n setattr(A, field, field + ' value')\n\n",
"I'd just inherit from the metaclass and do it there\nclass MyMetaClass(MetaClass):\n def __new__(meta, classname, baseclasses, classdict):\n fields = classdict['__m... | [
2,
2,
2,
1,
1,
0
] | [] | [] | [
"dynamic",
"python"
] | stackoverflow_0003423361_dynamic_python.txt |
Q:
Python: how to change (last) element of tuple?
The question is a bit misleading, because a tuple is immutable. What I want is:
Having a tuple a = (1, 2, 3, 4) get a tuple b that is exactly like a except for the last argument which is, say, twice the last element of a.
=> b == (1, 2, 3, 8)
A:
b = a[:-1] + (a[-1]*2,)
What I'm doing here is concatenation of two tuples, the first containing everything but the last element, and a new tuple containing the mutation of the final element. The result is a new tuple containing what you want.
Note that for + to return a tuple, both operands must be a tuple.
A:
I would do something like:
b=list(a)
b[-1]*=2
b=tuple(b)
A:
Here's one way of doing it:
>>> a = (1, 2, 3, 4)
>>> b = a[:-1] + (a[-1]*2, )
>>> a
(1, 2, 3, 4)
>>> b
(1, 2, 3, 8)
So what happens on the second line? a[:-1] means all of a except the last element. a[-1] is the last element, and we multiply it by two. The (a[-1]*2, ) turns the result into a tuple, and the sliced tuple is concatenated with it using the + operator. The result is put in b.
You can probably fit this to your specific case.
| Python: how to change (last) element of tuple? | The question is a bit misleading, because a tuple is immutable. What I want is:
Having a tuple a = (1, 2, 3, 4) get a tuple b that is exactly like a except for the last argument which is, say, twice the last element of a.
=> b == (1, 2, 3, 8)
| [
"b = a[:-1] + (a[-1]*2,)\n\nWhat I'm doing here is concatenation of two tuples, the first containing everything but the last element, and a new tuple containing the mutation of the final element. The result is a new tuple containing what you want.\nNote that for + to return a tuple, both operands must be a tuple.\... | [
22,
8,
5
] | [] | [] | [
"python"
] | stackoverflow_0003424507_python.txt |
Q:
python url regexp
I have a regexp and i want to add output of regexp to my url
for exmaple
url = 'blabla.com'
r = re.findall(r'<p>(.*?</a>))
r output - /any_string/on/any/server/
but a dont know how to make get-request with regexp output
blabla.com/any_string/on/any/server/
A:
Don't use regex to parse html. Use a real parser.
I suggest using the lxml.html parser. lxml supports xpath, which is a very powerful way of querying structured documents. There's a ready-to-use make_links_absolute() method that does what you ask. It's also very fast.
As an example, in this question's page HTML source code (the one you're reading now) there's this part:
<li><a id="nav-tags" href="/tags">Tags</a></li>
The xpath expression //a[@id='nav-tags']/@href means: "Get me the href attribute of all <a> tags with id attribute equal to nav-tags". Let's use it:
from lxml import html
url = 'http://stackoverflow.com/questions/3423822/python-url-regexp'
doc = html.parse(url).getroot()
doc.make_links_absolute()
links = doc.xpath("//a[@id='nav-tags']/@href")
print links
The result:
['http://stackoverflow.com/tags']
A:
Just get beautiful soup:
http://www.crummy.com/software/BeautifulSoup/documentation.html#Parsing+a+Document
import urllib2
from BeautifulSoup import BeautifulSoup
page = urllib2.urlopen(url)
soup = BeautifulSoup(page)
soup.findAll('p')
| python url regexp | I have a regexp and i want to add output of regexp to my url
for exmaple
url = 'blabla.com'
r = re.findall(r'<p>(.*?</a>))
r output - /any_string/on/any/server/
but a dont know how to make get-request with regexp output
blabla.com/any_string/on/any/server/
| [
"Don't use regex to parse html. Use a real parser.\nI suggest using the lxml.html parser. lxml supports xpath, which is a very powerful way of querying structured documents. There's a ready-to-use make_links_absolute() method that does what you ask. It's also very fast.\nAs an example, in this question's page HTML ... | [
2,
0
] | [] | [] | [
"python",
"regex",
"urllib2"
] | stackoverflow_0003423822_python_regex_urllib2.txt |
Q:
Getting ready to convert from Python 2.x to 3.x
As we all know by now (I hope), Python 3 is slowly beginning to replace Python 2.x. Of course it will be many MANY years before most of the existing code is finally ported, but there are things we can do right now in our version 2.x code to make the switch easier.
Obviously taking a look at what's new in 3.x will be helpful, but what are some things we can do right now to make the upcoming conversion more painless (as well as make it easier to output updates to concurrent versions if needed)? I'm specifically thinking about lines we can start our scripts off with that will make earlier versions of Python more similar to 3.x, though other habits are also welcome.
The most obvious code to add to the top of the script that I can think of is:
from __future__ import division
from __future__ import print_function
try:
range = xrange
except NameError:
pass
The most obvious habit thing I can think of is
"{0} {1}!".format("Hello", "World") for string formatting.
Any other lines and good habits to get into?
A:
The biggest problem that cannot be adequately addressed by micro-level changes and 2to3 is the change of the default string type from bytes to Unicode.
If your code needs to do anything with encodings and byte I/O, it's going to need a bunch of manual effort to convert correctly, so that things that have to be bytes remain bytes, and are decoded appropriately at the right stage. You'll find that some string methods (in particular format()) and library calls require Unicode strings, so you may need extra decode/encode cycles just to use the strings as Unicode even if they're really just bytes.
This is not helped by the fact that some of the Python standard library modules have been crudely converted using 2to3 without proper attention to bytes/unicode/encoding issues, and so themselves make mistakes about what string type is appropriate. Some of this is being thrashed out, but at least from Python 3.0 to 3.2 you will face confusing and potentially buggy behaviour from packages like urllib, email and wsgiref that need to know about byte encodings.
You can ameliorate the problem by being careful every time you write a string literal. Use u'' strings for anything that's inherently character-based, b'' strings for anything that's really bytes, and '' for the ‘default string’ type where it doesn't matter or you need to match a library call's string use requirements.
Unfortunately the b'' syntax was only introduced in Python 2.6, so doing this cuts off users of earlier versions.
eta:
what's the difference?
Oh my. Well...
A byte contains a value in the range 0–255, and may represent a load of binary data (eg. the contents of an image) or some text, in which case there has to be a standard chosen for how to map a set of characters into those bytes. Most of these ‘encoding’ standards map the normal ‘ASCII’ character set into the bytes 0–127 in the same way, so it's generally safe to use byte strings for ASCII-only text processing in Python 2.
If you want to use any of the characters outside the ASCII set in a byte string, you're in trouble, because each encoding maps a different set of characters into the remaining byte values 128–255, and most encodings can't map every possible character to bytes. This is the source of all those problems where you load a file from one locale into a Windows app in another locale and all the accented or non-Latin letters change to the wrong ones, making an unreadable mess. (aka ‘mojibake’.)
There are also ‘multibyte’ encodings, which try to fit more characters into the available space by using more than one byte to store each character. These were introduced for East Asian locales, as there are so very many Chinese characters. But there's also UTF-8, a better-designed modern multibyte encoding which can accommodate every character.
If you are working on byte strings in a multibyte encoding—and today you probably will be, because UTF-8 is very widely used; really, no other encoding should be used in a modern application—then you've got even more problems than just keeping track of what encoding you're playing with. len() is going to be telling you the length in bytes, not the length in characters, and if you start indexing and altering the bytes you're very likely to break a multibyte sequence in two, generating an invalid sequence and generally confusing everything.
For this reason, Python 1.6 and later have native Unicode strings (spelled u'something'), where each unit in the string is a character, not a byte. You can len() them, slice them, replace them, regex them, and they'll always behave appropriately. For text processing tasks they are indubitably better, which is why Python 3 makes them the default string type (without having to put a u before the '').
The catch is that a lot of existing interfaces, such as filenames on OSes other than Windows, or HTTP, or SMTP, are primarily byte-based, with a separate way of specifying the encoding. So when you are dealing with components that need bytes you have to take care to encode your unicode strings to bytes correctly, and in Python 3 you will have to do it explicitly in some places where before you didn't need to.
It is an internal implementation detail that Unicode strings take ‘two bytes’ of storage per unit internally. You never get to see that storage; you shouldn't think of it in terms of bytes. The units you are working on are conceptually characters, regardless of how Python chooses to represent them in memory.
...aside:
This isn't quite true. On ‘narrow builds’ of Python like the Windows build, each unit of a Unicode string is not technically a character, but a UTF-16 ‘code unit’. For the characters in the Basic Multilingual Plane, from 0x0000–0xFFFF you won't notice any difference, but if you're using characters from outside this 16-bit range, those in the ‘astral planes’, you'll find they take two units instead of one, and, again, you risk splitting a character when you slice them.
This is pretty bad, and has happened because Windows (and others, such as Java) settled on UTF-16 as an in-memory storage mechanism before Unicode grew beyond the 65,000-character limit. However, use of these extended characters is still pretty rare, and anyone on Windows will be used to them breaking in many applications, so it's likely not critical for you.
On ‘wide builds’, Unicode strings are made of real character ‘code point’ units, so even the extended characters outside of the BMP can be handled consistently and easily. The price to pay for this is efficiency: each string unit takes up four bytes of storage in memory.
A:
I'm trying to get in the habit of using things like var1//var2 whenever I actually want integer division (and not a float). Not a big step towards Python 3, but at least I won't have to go back and check all of my division :)
| Getting ready to convert from Python 2.x to 3.x | As we all know by now (I hope), Python 3 is slowly beginning to replace Python 2.x. Of course it will be many MANY years before most of the existing code is finally ported, but there are things we can do right now in our version 2.x code to make the switch easier.
Obviously taking a look at what's new in 3.x will be helpful, but what are some things we can do right now to make the upcoming conversion more painless (as well as make it easier to output updates to concurrent versions if needed)? I'm specifically thinking about lines we can start our scripts off with that will make earlier versions of Python more similar to 3.x, though other habits are also welcome.
The most obvious code to add to the top of the script that I can think of is:
from __future__ import division
from __future__ import print_function
try:
range = xrange
except NameError:
pass
The most obvious habit thing I can think of is
"{0} {1}!".format("Hello", "World") for string formatting.
Any other lines and good habits to get into?
| [
"The biggest problem that cannot be adequately addressed by micro-level changes and 2to3 is the change of the default string type from bytes to Unicode.\nIf your code needs to do anything with encodings and byte I/O, it's going to need a bunch of manual effort to convert correctly, so that things that have to be by... | [
12,
5
] | [] | [] | [
"python",
"python_2.x",
"python_3.x",
"upgrade"
] | stackoverflow_0003424292_python_python_2.x_python_3.x_upgrade.txt |
Q:
Is twisted.internet.reactor global?
For example, if one application does from twisted.internet import reactor, and another application does the same, are those reactors the same?
I am asking because Deluge, an application that uses twisted, looks like it uses the reactor to connect their UI (gtk) to the rest of the application being driven by twisted (I am trying to understand the source). For example, when the UI is closed it simply calls reactor.stop().
Is that all there is to it? It just seems kind of magic to me. What if I wanted to run another application that uses twisted?
A:
Yes, every module in Python is always global, or, to put it better, a singleton: when you do from twisted.internet import reactor, Python's import mechanism first checks sys.modules['twisted.internet.reactor'], and, if that exists, returns said value; only if it doesn't exist (i.e., the first time a module is imported) is the module actually loaded for the first time (and stashed into an entry in sys.modules for possible future imports).
There is nothing especially magical in the Singleton design pattern, though it can sometimes prove limiting when you desperately need more than one of those thingies for which the architecture has decreed "there can be only one". Twisted's docs acknowledge that:
New application code should prefer to
pass and accept the reactor as a
parameter where it is needed, rather
than relying on being able to import
this module to get a reference. This
simplifies unit testing and may make
it easier to one day support multiple
reactors (as a performance
enhancement), though this is not
currently possible.
The best way to make it possible, if it's crucial to your app, is to contribute to the Twisted project, either labor (coding the subtle mechanisms needed to support multiple reactors, that is, multiple event loops, within a single app) or funding (money will enable sustaining somebody with a stipend in order to perform this work).
Otherwise, use separate processes (e.g. with the multiprocessing module of the standard library) with no more than one reactor each.
A:
The reactor is indeed global. It takes care of the event loop, and you register handlers to consume events. If you want to use several applications with the same reactor, you can use the twistd daemon. http://twistedmatrix.com/documents/current/core/howto/application.html
| Is twisted.internet.reactor global? | For example, if one application does from twisted.internet import reactor, and another application does the same, are those reactors the same?
I am asking because Deluge, an application that uses twisted, looks like it uses the reactor to connect their UI (gtk) to the rest of the application being driven by twisted (I am trying to understand the source). For example, when the UI is closed it simply calls reactor.stop().
Is that all there is to it? It just seems kind of magic to me. What if I wanted to run another application that uses twisted?
| [
"Yes, every module in Python is always global, or, to put it better, a singleton: when you do from twisted.internet import reactor, Python's import mechanism first checks sys.modules['twisted.internet.reactor'], and, if that exists, returns said value; only if it doesn't exist (i.e., the first time a module is impo... | [
14,
2
] | [] | [] | [
"networking",
"python",
"reactor",
"twisted"
] | stackoverflow_0003424825_networking_python_reactor_twisted.txt |
Q:
Cherokee + uWSGI + Pylons
I have successfully deployed a Django app with uWSGI + Cherokee.
However, I want to experiment with Pylons before I go decide on Django.
So far I have followed the instructions/recommendations here:
Deploying Pylons with uWSGI
Paster serve works without a hitch. But when I try to serve via uWSGI, I get nowhere:
/usr/bin/uwsgi -s :5000 --paste config:/var/www/env/helloworld/development.ini -H /var/www/env -M
My uWSGI master and worker processes are spawned. SO, I visit http://localhost:5000
This is what I get:
Error 324 (net::ERR_EMPTY_RESPONSE): Unknown error.
And my terminal reads back (and repeats when I refresh browser):
invalid request block size: 21573...skip
What am I doing wrong?
I cannot find any guide or step-by-step specific for uWSGI + Cherokee
A:
You should not visit http://localhost:5000. 5000 it's the port use for the communication between Cherokee and uWSGI. So you're trying to access uWSGI directly. You need to configure Cherokee and then go to the address:port you have configured in Cherokee to see your website.
Docs:
Cherokee-uWSGI
uWSGI
| Cherokee + uWSGI + Pylons | I have successfully deployed a Django app with uWSGI + Cherokee.
However, I want to experiment with Pylons before I go decide on Django.
So far I have followed the instructions/recommendations here:
Deploying Pylons with uWSGI
Paster serve works without a hitch. But when I try to serve via uWSGI, I get nowhere:
/usr/bin/uwsgi -s :5000 --paste config:/var/www/env/helloworld/development.ini -H /var/www/env -M
My uWSGI master and worker processes are spawned. SO, I visit http://localhost:5000
This is what I get:
Error 324 (net::ERR_EMPTY_RESPONSE): Unknown error.
And my terminal reads back (and repeats when I refresh browser):
invalid request block size: 21573...skip
What am I doing wrong?
I cannot find any guide or step-by-step specific for uWSGI + Cherokee
| [
"You should not visit http://localhost:5000. 5000 it's the port use for the communication between Cherokee and uWSGI. So you're trying to access uWSGI directly. You need to configure Cherokee and then go to the address:port you have configured in Cherokee to see your website.\nDocs:\n\nCherokee-uWSGI\nuWSGI\n\n"
] | [
5
] | [] | [] | [
"cherokee",
"pylons",
"python",
"uwsgi"
] | stackoverflow_0003423860_cherokee_pylons_python_uwsgi.txt |
Q:
Problem using MySQLdb on OSX: symbol not found _mysql_affected_rows
This is related to a previous question.
However, the main posted solution there is not working for me. I'm on Snow Leopard, using the 32-bit 5.1.49 MySQL dmg install. I'm using the built in python (apparently, as noted in the comments, my Python version is different), which appears to be 2.6.5 32-bit:
Python 2.6.5 (r265:79359, Mar 24 2010, 01:32:55)
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.maxint
2147483647
I've downloaded MySQL-python 1.2.3 from the usual location and changed site.cfg so that mysql_config points to the right place and the registry_key directive is commented out. The packages seems to build and install just fine:
caywork:MySQL-python-1.2.3 carl$ python setup.py clean
running clean
caywork:MySQL-python-1.2.3 carl$ python setup.py build
running build
running build_py
copying MySQLdb/release.py -> build/lib.macosx-10.3-fat-2.6/MySQLdb
running build_ext
caywork:MySQL-python-1.2.3 carl$ sudo python setup.py install
running install
running bdist_egg
running egg_info
writing MySQL_python.egg-info/PKG-INFO
writing top-level names to MySQL_python.egg-info/top_level.txt
writing dependency_links to MySQL_python.egg-info/dependency_links.txt
reading manifest file 'MySQL_python.egg-info/SOURCES.txt'
reading manifest template 'MANIFEST.in'
warning: no files found matching 'MANIFEST'
warning: no files found matching 'ChangeLog'
warning: no files found matching 'GPL'
writing manifest file 'MySQL_python.egg-info/SOURCES.txt'
installing library code to build/bdist.macosx-10.3-fat/egg
running install_lib
running build_py
copying MySQLdb/release.py -> build/lib.macosx-10.3-fat-2.6/MySQLdb
running build_ext
creating build/bdist.macosx-10.3-fat/egg
copying build/lib.macosx-10.3-fat-2.6/_mysql.so -> build/bdist.macosx-10.3-fat/egg
copying build/lib.macosx-10.3-fat-2.6/_mysql_exceptions.py -> build/bdist.macosx-10.3-fat/egg
creating build/bdist.macosx-10.3-fat/egg/MySQLdb
copying build/lib.macosx-10.3-fat-2.6/MySQLdb/__init__.py -> build/bdist.macosx-10.3-fat/egg/MySQLdb
copying build/lib.macosx-10.3-fat-2.6/MySQLdb/connections.py -> build/bdist.macosx-10.3-fat/egg/MySQLdb
creating build/bdist.macosx-10.3-fat/egg/MySQLdb/constants
copying build/lib.macosx-10.3-fat-2.6/MySQLdb/constants/__init__.py -> build/bdist.macosx-10.3-fat/egg/MySQLdb/constants
copying build/lib.macosx-10.3-fat-2.6/MySQLdb/constants/CLIENT.py -> build/bdist.macosx-10.3-fat/egg/MySQLdb/constants
copying build/lib.macosx-10.3-fat-2.6/MySQLdb/constants/CR.py -> build/bdist.macosx-10.3-fat/egg/MySQLdb/constants
copying build/lib.macosx-10.3-fat-2.6/MySQLdb/constants/ER.py -> build/bdist.macosx-10.3-fat/egg/MySQLdb/constants
copying build/lib.macosx-10.3-fat-2.6/MySQLdb/constants/FIELD_TYPE.py -> build/bdist.macosx-10.3-fat/egg/MySQLdb/constants
copying build/lib.macosx-10.3-fat-2.6/MySQLdb/constants/FLAG.py -> build/bdist.macosx-10.3-fat/egg/MySQLdb/constants
copying build/lib.macosx-10.3-fat-2.6/MySQLdb/constants/REFRESH.py -> build/bdist.macosx-10.3-fat/egg/MySQLdb/constants
copying build/lib.macosx-10.3-fat-2.6/MySQLdb/converters.py -> build/bdist.macosx-10.3-fat/egg/MySQLdb
copying build/lib.macosx-10.3-fat-2.6/MySQLdb/cursors.py -> build/bdist.macosx-10.3-fat/egg/MySQLdb
copying build/lib.macosx-10.3-fat-2.6/MySQLdb/release.py -> build/bdist.macosx-10.3-fat/egg/MySQLdb
copying build/lib.macosx-10.3-fat-2.6/MySQLdb/times.py -> build/bdist.macosx-10.3-fat/egg/MySQLdb
byte-compiling build/bdist.macosx-10.3-fat/egg/_mysql_exceptions.py to _mysql_exceptions.pyc
byte-compiling build/bdist.macosx-10.3-fat/egg/MySQLdb/__init__.py to __init__.pyc
byte-compiling build/bdist.macosx-10.3-fat/egg/MySQLdb/connections.py to connections.pyc
byte-compiling build/bdist.macosx-10.3-fat/egg/MySQLdb/constants/__init__.py to __init__.pyc
byte-compiling build/bdist.macosx-10.3-fat/egg/MySQLdb/constants/CLIENT.py to CLIENT.pyc
byte-compiling build/bdist.macosx-10.3-fat/egg/MySQLdb/constants/CR.py to CR.pyc
byte-compiling build/bdist.macosx-10.3-fat/egg/MySQLdb/constants/ER.py to ER.pyc
byte-compiling build/bdist.macosx-10.3-fat/egg/MySQLdb/constants/FIELD_TYPE.py to FIELD_TYPE.pyc
byte-compiling build/bdist.macosx-10.3-fat/egg/MySQLdb/constants/FLAG.py to FLAG.pyc
byte-compiling build/bdist.macosx-10.3-fat/egg/MySQLdb/constants/REFRESH.py to REFRESH.pyc
byte-compiling build/bdist.macosx-10.3-fat/egg/MySQLdb/converters.py to converters.pyc
byte-compiling build/bdist.macosx-10.3-fat/egg/MySQLdb/cursors.py to cursors.pyc
byte-compiling build/bdist.macosx-10.3-fat/egg/MySQLdb/release.py to release.pyc
byte-compiling build/bdist.macosx-10.3-fat/egg/MySQLdb/times.py to times.pyc
creating stub loader for _mysql.so
byte-compiling build/bdist.macosx-10.3-fat/egg/_mysql.py to _mysql.pyc
creating build/bdist.macosx-10.3-fat/egg/EGG-INFO
copying MySQL_python.egg-info/PKG-INFO -> build/bdist.macosx-10.3-fat/egg/EGG-INFO
copying MySQL_python.egg-info/SOURCES.txt -> build/bdist.macosx-10.3-fat/egg/EGG-INFO
copying MySQL_python.egg-info/dependency_links.txt -> build/bdist.macosx-10.3-fat/egg/EGG-INFO
copying MySQL_python.egg-info/top_level.txt -> build/bdist.macosx-10.3-fat/egg/EGG-INFO
writing build/bdist.macosx-10.3-fat/egg/EGG-INFO/native_libs.txt
zip_safe flag not set; analyzing archive contents...
creating 'dist/MySQL_python-1.2.3-py2.6-macosx-10.3-fat.egg' and adding 'build/bdist.macosx-10.3-fat/egg' to it
removing 'build/bdist.macosx-10.3-fat/egg' (and everything under it)
Processing MySQL_python-1.2.3-py2.6-macosx-10.3-fat.egg
Removing /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/MySQL_python-1.2.3-py2.6-macosx-10.3-fat.egg
Copying MySQL_python-1.2.3-py2.6-macosx-10.3-fat.egg to /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages
MySQL-python 1.2.3 is already the active version in easy-install.pth
Installed /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/MySQL_python-1.2.3-py2.6-macosx-10.3-fat.egg
Processing dependencies for MySQL-python==1.2.3
Finished processing dependencies for MySQL-python==1.2.3
But when I try to use it, I get this:
caywork:MySQL-python-1.2.3 carl$ python -c "import MySQLdb"
/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/MySQL_python-1.2.3-py2.6-macosx-10.3-fat.egg/_mysql.py:3: UserWarning: Module _mysql was already imported from /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/MySQL_python-1.2.3-py2.6-macosx-10.3-fat.egg/_mysql.pyc, but /Users/carl/Source/MySQL-python-1.2.3 is being added to sys.path
Traceback (most recent call last):
File "", line 1, in
File "MySQLdb/__init__.py", line 19, in
import _mysql
File "build/bdist.macosx-10.3-fat/egg/_mysql.py", line 7, in
File "build/bdist.macosx-10.3-fat/egg/_mysql.py", line 6, in __bootstrap__
ImportError: dlopen(/Users/carl/.python-eggs/MySQL_python-1.2.3-py2.6-macosx-10.3-fat.egg-tmp/_mysql.so, 2): Symbol not found: _mysql_affected_rows
Referenced from: /Users/carl/.python-eggs/MySQL_python-1.2.3-py2.6-macosx-10.3-fat.egg-tmp/_mysql.so
Expected in: dynamic lookup
All I can find on the web are older examples of this problem, along with numerous rants about how hard it is to get MySQL-python working on OSX. If anyone can help with this, I would greatly appreciate it!!
A:
The only (admittedly kludgy) solution that I ended up getting to work was to use MySQL-python-1.2.2 after applying this patch, cobbled together from advice found here (http://www.mangoorange.com/2008/08/01/installing-python-mysqldb-122-on-mac-os-x/) and here (http://flo.nigsch.com/?p=62). Sorry for the lack of links but I don't have enough rep points to post more than one link.
| Problem using MySQLdb on OSX: symbol not found _mysql_affected_rows | This is related to a previous question.
However, the main posted solution there is not working for me. I'm on Snow Leopard, using the 32-bit 5.1.49 MySQL dmg install. I'm using the built in python (apparently, as noted in the comments, my Python version is different), which appears to be 2.6.5 32-bit:
Python 2.6.5 (r265:79359, Mar 24 2010, 01:32:55)
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.maxint
2147483647
I've downloaded MySQL-python 1.2.3 from the usual location and changed site.cfg so that mysql_config points to the right place and the registry_key directive is commented out. The packages seems to build and install just fine:
caywork:MySQL-python-1.2.3 carl$ python setup.py clean
running clean
caywork:MySQL-python-1.2.3 carl$ python setup.py build
running build
running build_py
copying MySQLdb/release.py -> build/lib.macosx-10.3-fat-2.6/MySQLdb
running build_ext
caywork:MySQL-python-1.2.3 carl$ sudo python setup.py install
running install
running bdist_egg
running egg_info
writing MySQL_python.egg-info/PKG-INFO
writing top-level names to MySQL_python.egg-info/top_level.txt
writing dependency_links to MySQL_python.egg-info/dependency_links.txt
reading manifest file 'MySQL_python.egg-info/SOURCES.txt'
reading manifest template 'MANIFEST.in'
warning: no files found matching 'MANIFEST'
warning: no files found matching 'ChangeLog'
warning: no files found matching 'GPL'
writing manifest file 'MySQL_python.egg-info/SOURCES.txt'
installing library code to build/bdist.macosx-10.3-fat/egg
running install_lib
running build_py
copying MySQLdb/release.py -> build/lib.macosx-10.3-fat-2.6/MySQLdb
running build_ext
creating build/bdist.macosx-10.3-fat/egg
copying build/lib.macosx-10.3-fat-2.6/_mysql.so -> build/bdist.macosx-10.3-fat/egg
copying build/lib.macosx-10.3-fat-2.6/_mysql_exceptions.py -> build/bdist.macosx-10.3-fat/egg
creating build/bdist.macosx-10.3-fat/egg/MySQLdb
copying build/lib.macosx-10.3-fat-2.6/MySQLdb/__init__.py -> build/bdist.macosx-10.3-fat/egg/MySQLdb
copying build/lib.macosx-10.3-fat-2.6/MySQLdb/connections.py -> build/bdist.macosx-10.3-fat/egg/MySQLdb
creating build/bdist.macosx-10.3-fat/egg/MySQLdb/constants
copying build/lib.macosx-10.3-fat-2.6/MySQLdb/constants/__init__.py -> build/bdist.macosx-10.3-fat/egg/MySQLdb/constants
copying build/lib.macosx-10.3-fat-2.6/MySQLdb/constants/CLIENT.py -> build/bdist.macosx-10.3-fat/egg/MySQLdb/constants
copying build/lib.macosx-10.3-fat-2.6/MySQLdb/constants/CR.py -> build/bdist.macosx-10.3-fat/egg/MySQLdb/constants
copying build/lib.macosx-10.3-fat-2.6/MySQLdb/constants/ER.py -> build/bdist.macosx-10.3-fat/egg/MySQLdb/constants
copying build/lib.macosx-10.3-fat-2.6/MySQLdb/constants/FIELD_TYPE.py -> build/bdist.macosx-10.3-fat/egg/MySQLdb/constants
copying build/lib.macosx-10.3-fat-2.6/MySQLdb/constants/FLAG.py -> build/bdist.macosx-10.3-fat/egg/MySQLdb/constants
copying build/lib.macosx-10.3-fat-2.6/MySQLdb/constants/REFRESH.py -> build/bdist.macosx-10.3-fat/egg/MySQLdb/constants
copying build/lib.macosx-10.3-fat-2.6/MySQLdb/converters.py -> build/bdist.macosx-10.3-fat/egg/MySQLdb
copying build/lib.macosx-10.3-fat-2.6/MySQLdb/cursors.py -> build/bdist.macosx-10.3-fat/egg/MySQLdb
copying build/lib.macosx-10.3-fat-2.6/MySQLdb/release.py -> build/bdist.macosx-10.3-fat/egg/MySQLdb
copying build/lib.macosx-10.3-fat-2.6/MySQLdb/times.py -> build/bdist.macosx-10.3-fat/egg/MySQLdb
byte-compiling build/bdist.macosx-10.3-fat/egg/_mysql_exceptions.py to _mysql_exceptions.pyc
byte-compiling build/bdist.macosx-10.3-fat/egg/MySQLdb/__init__.py to __init__.pyc
byte-compiling build/bdist.macosx-10.3-fat/egg/MySQLdb/connections.py to connections.pyc
byte-compiling build/bdist.macosx-10.3-fat/egg/MySQLdb/constants/__init__.py to __init__.pyc
byte-compiling build/bdist.macosx-10.3-fat/egg/MySQLdb/constants/CLIENT.py to CLIENT.pyc
byte-compiling build/bdist.macosx-10.3-fat/egg/MySQLdb/constants/CR.py to CR.pyc
byte-compiling build/bdist.macosx-10.3-fat/egg/MySQLdb/constants/ER.py to ER.pyc
byte-compiling build/bdist.macosx-10.3-fat/egg/MySQLdb/constants/FIELD_TYPE.py to FIELD_TYPE.pyc
byte-compiling build/bdist.macosx-10.3-fat/egg/MySQLdb/constants/FLAG.py to FLAG.pyc
byte-compiling build/bdist.macosx-10.3-fat/egg/MySQLdb/constants/REFRESH.py to REFRESH.pyc
byte-compiling build/bdist.macosx-10.3-fat/egg/MySQLdb/converters.py to converters.pyc
byte-compiling build/bdist.macosx-10.3-fat/egg/MySQLdb/cursors.py to cursors.pyc
byte-compiling build/bdist.macosx-10.3-fat/egg/MySQLdb/release.py to release.pyc
byte-compiling build/bdist.macosx-10.3-fat/egg/MySQLdb/times.py to times.pyc
creating stub loader for _mysql.so
byte-compiling build/bdist.macosx-10.3-fat/egg/_mysql.py to _mysql.pyc
creating build/bdist.macosx-10.3-fat/egg/EGG-INFO
copying MySQL_python.egg-info/PKG-INFO -> build/bdist.macosx-10.3-fat/egg/EGG-INFO
copying MySQL_python.egg-info/SOURCES.txt -> build/bdist.macosx-10.3-fat/egg/EGG-INFO
copying MySQL_python.egg-info/dependency_links.txt -> build/bdist.macosx-10.3-fat/egg/EGG-INFO
copying MySQL_python.egg-info/top_level.txt -> build/bdist.macosx-10.3-fat/egg/EGG-INFO
writing build/bdist.macosx-10.3-fat/egg/EGG-INFO/native_libs.txt
zip_safe flag not set; analyzing archive contents...
creating 'dist/MySQL_python-1.2.3-py2.6-macosx-10.3-fat.egg' and adding 'build/bdist.macosx-10.3-fat/egg' to it
removing 'build/bdist.macosx-10.3-fat/egg' (and everything under it)
Processing MySQL_python-1.2.3-py2.6-macosx-10.3-fat.egg
Removing /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/MySQL_python-1.2.3-py2.6-macosx-10.3-fat.egg
Copying MySQL_python-1.2.3-py2.6-macosx-10.3-fat.egg to /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages
MySQL-python 1.2.3 is already the active version in easy-install.pth
Installed /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/MySQL_python-1.2.3-py2.6-macosx-10.3-fat.egg
Processing dependencies for MySQL-python==1.2.3
Finished processing dependencies for MySQL-python==1.2.3
But when I try to use it, I get this:
caywork:MySQL-python-1.2.3 carl$ python -c "import MySQLdb"
/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/MySQL_python-1.2.3-py2.6-macosx-10.3-fat.egg/_mysql.py:3: UserWarning: Module _mysql was already imported from /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/MySQL_python-1.2.3-py2.6-macosx-10.3-fat.egg/_mysql.pyc, but /Users/carl/Source/MySQL-python-1.2.3 is being added to sys.path
Traceback (most recent call last):
File "", line 1, in
File "MySQLdb/__init__.py", line 19, in
import _mysql
File "build/bdist.macosx-10.3-fat/egg/_mysql.py", line 7, in
File "build/bdist.macosx-10.3-fat/egg/_mysql.py", line 6, in __bootstrap__
ImportError: dlopen(/Users/carl/.python-eggs/MySQL_python-1.2.3-py2.6-macosx-10.3-fat.egg-tmp/_mysql.so, 2): Symbol not found: _mysql_affected_rows
Referenced from: /Users/carl/.python-eggs/MySQL_python-1.2.3-py2.6-macosx-10.3-fat.egg-tmp/_mysql.so
Expected in: dynamic lookup
All I can find on the web are older examples of this problem, along with numerous rants about how hard it is to get MySQL-python working on OSX. If anyone can help with this, I would greatly appreciate it!!
| [
"The only (admittedly kludgy) solution that I ended up getting to work was to use MySQL-python-1.2.2 after applying this patch, cobbled together from advice found here (http://www.mangoorange.com/2008/08/01/installing-python-mysqldb-122-on-mac-os-x/) and here (http://flo.nigsch.com/?p=62). Sorry for the lack of lin... | [
0
] | [] | [] | [
"macos",
"mysql",
"python"
] | stackoverflow_0003423289_macos_mysql_python.txt |
Q:
using Python to import a CSV (lookup table) and add GPS coordinates to another output CSV
So I have already imported one XML-ish file with 3000 elements and parsed them into a CSV for output. But I also need to import a second CSV file with 'keyword','latitude','longitude' as columns and use it to add the GPS coordinates to additional columns on the first file.
Reading the python tutorial, it seems like {dictionary} is what I need, although I've read on here that tuples might be better. I don't know.
But either way - I start with:
floc = open('c:\python\kenya_location_lookup.csv','r')
l = csv.DictReader(floc)
for row in l: print row.keys()
The output look like:
{'LATITUDE': '-1.311467078', 'LONGITUDE': '36.77352011', 'KEYWORD': 'Kianda'}
{'LATITUDE': '-1.315288401', 'LONGITUDE': '36.77614331', 'KEYWORD': 'Soweto'}
{'LATITUDE': '-1.315446430425027', 'LONGITUDE': '36.78170621395111', 'KEYWORD': 'Gatwekera'}
{'LATITUDE': '-1.3136151425171327', 'LONGITUDE': '36.785863637924194', 'KEYWORD': 'Kisumu Ndogo'}
I'm a newbie (and not a programmer). Question is how do I use the keys to pluck out the corresponding row data and match it against words in the body of the element in the other set?
A:
Reading the python tutorial, it seems
like {dictionary} is what I need,
although I've read on here that tuples
might be better. I don't know.
They're both fine choices for this task.
print row.keys() The output look
like:
{'LATITUDE': '-1.311467078',
No it doesn't! This is the output from print row, most definitely NOT print row.keys(). Please don't supply disinformation in your questions, it makes them really hard to answer effectively (being a newbie makes no difference: surely you can check that the output you provide actually comes from the code you also provide!).
I'm a newbie (and not a programmer).
Question is how do I use the keys to
pluck out the corresponding row data
and match it against words in the body
of the element in the other set?
Since you give us absolutely zero information on the structure of "the other set", you make it of course impossible to answer this question. Guessing wildly, if for example the entries in "the other set" are also dicts each with a key of KEYWORD, you want to build an auxiliary dict first, then merge (some of) its entries in the "other set":
l = csv.DictReader(floc)
dloc = dict((d['KEYWORD'], d) for d in l)
for d in otherset:
d.update(dloc.get(d['KEYWORD'], ()))
This will leave the location missing from the other set when not present in a corresponding keyword entry in the CSV -- if that's a problem you may want to use a "fake location" dictionary as the default for missing entries instead of that () in the last statement I've shown. But, this is all wild speculation anyway, due to the dearth of info in your Q.
A:
If you dump the DictReader into a list (data = [row for row in csv.DictReader(file)]), and you have unique keywords for each row, convert that list of dictionaries into a dictionary of dictionaries, using that keyword as the key.
>>> data = [row for row in csv.DictReader(open('C:\\my.csv'),
... ('num','time','time2'))]
>>> len(data) # lots of old data :P
1410
>>> data[1].keys()
['time2', 'num', 'time']
>>> keyeddata = {}
>>> for row in data[2:]: # I have some junk rows
... keyeddata[row['num']] = row
...
>>> keyeddata['32']
{'num': '32', 'time2': '8', 'time': '13269'}
Once you have the keyword pulled out, you can iterate through your other list, grab the keyword from it, and use it as the index for the lat/long list. Pull out the lat/long from that index and add it to the other list.
A:
Thanks -
Alex: My code for the other set is working, and the only relevant part is that I have a string that may or may not contain the 'keyword' that is in this dictionary.
Structurally, this is how I organized it:
def main():
f = open('c:\python\ggce.sms', 'r')
sensetree = etree.parse(f)
senses = sensetree.getiterator('SenseMakingItem')
bodies = sensetree.getiterator('Body')
stories = []
for body in bodies:
fix_body(body)
storybyte = unicode(body.text)
storybit = storybyte.encode('ascii','ignore')
stories.append(storybit)
rows = [ids,titles,locations,stories]
out = map(None, *rows)
print out[120:121]
write_data(out,'c:\python\output_test.csv')
(I omitted the code for getting its, titles, locations because they work and will not be used to get the real locations from the data within stories)
Hope this helps.
| using Python to import a CSV (lookup table) and add GPS coordinates to another output CSV | So I have already imported one XML-ish file with 3000 elements and parsed them into a CSV for output. But I also need to import a second CSV file with 'keyword','latitude','longitude' as columns and use it to add the GPS coordinates to additional columns on the first file.
Reading the python tutorial, it seems like {dictionary} is what I need, although I've read on here that tuples might be better. I don't know.
But either way - I start with:
floc = open('c:\python\kenya_location_lookup.csv','r')
l = csv.DictReader(floc)
for row in l: print row.keys()
The output look like:
{'LATITUDE': '-1.311467078', 'LONGITUDE': '36.77352011', 'KEYWORD': 'Kianda'}
{'LATITUDE': '-1.315288401', 'LONGITUDE': '36.77614331', 'KEYWORD': 'Soweto'}
{'LATITUDE': '-1.315446430425027', 'LONGITUDE': '36.78170621395111', 'KEYWORD': 'Gatwekera'}
{'LATITUDE': '-1.3136151425171327', 'LONGITUDE': '36.785863637924194', 'KEYWORD': 'Kisumu Ndogo'}
I'm a newbie (and not a programmer). Question is how do I use the keys to pluck out the corresponding row data and match it against words in the body of the element in the other set?
| [
"\nReading the python tutorial, it seems\n like {dictionary} is what I need,\n although I've read on here that tuples\n might be better. I don't know.\n\nThey're both fine choices for this task.\n\nprint row.keys() The output look\n like:\n{'LATITUDE': '-1.311467078',\n\nNo it doesn't! This is the output from ... | [
1,
0,
0
] | [] | [] | [
"csv",
"dictionary",
"geocoding",
"gps",
"python"
] | stackoverflow_0003424741_csv_dictionary_geocoding_gps_python.txt |
Q:
Finding the last group in a regular expression
Three underscore separated elements make my strings :
- first (letters and digits)
- middle (letters, digits and underscore)
- last (letters and digits)
The last element is optional.
Note : I need to access my groups by their names, not their indices.
Examples :
String : abc_def
first : abc
middle : def
last : None
String : abc_def_xyz
first : abc
middle: def
last: xyz
String : abc_def_ghi_jkl_xyz
first : abc
middle : def_ghi_jkl
last : xyz
I can't find the right regex...
I have two ideas so far :
Optional group
(?P<first>[a-z]+)_(?P<middle>\w+)(_(?P<last>[a-z]+))?
But the middle group matches until the end of the string :
String : abc_def_ghi_jkl_xyz
first : abc
middle : def_ghi_jkl_xyz
last : vide
Using the '|'
(?P<first>[a-z]+)_(?P<middle>\w+)_(?P<last>[a-z]+)|(?P<first>[a-z]+)_(?P<middle>\w+)
This expression is invalid : first and middle groups are declared two times. I though I could write an expression reusing the matched group from the first part of the expression :
(?P<first>[a-z]+)_(?P<middle>\w+)_(?P<last>[a-z]+)|(?P=first)_(?P=middle)
The expression is valid, however strings with just a first and a middle like abc_def are not matched.
Note
These strings are actually parts of a path I need to match. It could be paths like :
/my/path/to/abc_def
/my/path/to/abc_def/
/my/path/to/abc_def/some/other/stuf
/my/path/to/abc_def/some/other/stuf/
/my/path/to/abc_def_ghi_jkl_xyz
/my/path/to/abc_def_ghi_jkl_xyz/
/my/path/to/abc_def_ghi_jkl_xyz/some/other/stuf
/my/path/to/abc_def_ghi_jkl_xyz/some/other/stuf/
...
Any idea to solve my problem solely with regular expressions ? Post-processing the matched groups is not an option.
Thank you very much !
A:
Change the middle group to be non-greedy, and add beginning and end-of-string anchors:
^(?P<first>[a-z]+)_(?P<middle>\w+?)(_(?P<last>[a-z]+))?$
By default, the \w+will match as much as possible, which eats the rest of the string. Adding the ? tells it to match as little as possible.
Thanks to Tim Pietzcker for pointing out the anchor requirements.
A:
Use
^(?P<first>[a-z]+)_(?P<middle>\w+?)(_(?P<last>[a-z]+))?$
^ and $ anchor the regex at start and end of the string.
Making the \w+? lazy allows it to match as little as possible (but at least one character).
EDIT:
For your changed requirements that now include paths before and after this string, this works:
^(.*?/)(?P<first>[a-z]+)_(?P<middle>\w+?)(_(?P<last>[a-z]+))?(/.*)?$
Code sample (Python 3.1):
import re
paths = ["/my/path/to/abc_def",
"/my/path/to/abc_def/",
"/my/path/to/abc_def/some/other/stuf",
"/my/path/to/abc_def/some/other/stuf/",
"/my/path/to/abc_def_ghi_jkl_xyz",
"/my/path/to/abc_def_ghi_jkl_xyz/",
"/my/path/to/abc_def_ghi_jkl_xyz/some/other/stuf",
"/my/path/to/abc_def_ghi_jkl_xyz/some/other/stuf/"]
regex = re.compile(r"^(.*?/)(?P<first>[a-z]+)_(?P<middle>\w+?)(_(?P<last>[a-z]+))?(/.*)?$")
for path in paths:
match = regex.match(path)
print ("{}:\nBefore: {}\nFirst: {}\nMiddle: {}\nLast: {}\nAfter: {}\n".format(
path, match.group(1), match.group("first"), match.group("middle"),
match.group("last"), match.group(6)))
Output:
/my/path/to/abc_def:
Before: /my/path/to/
First: abc
Middle: def
Last: None
After: None
/my/path/to/abc_def/:
Before: /my/path/to/
First: abc
Middle: def
Last: None
After: /
/my/path/to/abc_def/some/other/stuf:
Before: /my/path/to/
First: abc
Middle: def
Last: None
After: /some/other/stuf
/my/path/to/abc_def/some/other/stuf/:
Before: /my/path/to/
First: abc
Middle: def
Last: None
After: /some/other/stuf/
/my/path/to/abc_def_ghi_jkl_xyz:
Before: /my/path/to/
First: abc
Middle: def_ghi_jkl
Last: xyz
After: None
/my/path/to/abc_def_ghi_jkl_xyz/:
Before: /my/path/to/
First: abc
Middle: def_ghi_jkl
Last: xyz
After: /
/my/path/to/abc_def_ghi_jkl_xyz/some/other/stuf:
Before: /my/path/to/
First: abc
Middle: def_ghi_jkl
Last: xyz
After: /some/other/stuf
/my/path/to/abc_def_ghi_jkl_xyz/some/other/stuf/:
Before: /my/path/to/
First: abc
Middle: def_ghi_jkl
Last: xyz
After: /some/other/stuf/
A:
Try this regular expression:
^(?P<first>[a-z]+)_(?P<middle>[a-z]+(?:_[a-z]+)*?)(?:_(?P<last>[a-z]+))?$
Here’s a test case:
import re
strings = ['abc_def', 'abc_def_xyz', 'abc_def_ghi_jkl_xyz']
pattern = '^(?P<first>[a-z]+)_(?P<middle>[a-z]+(?:_[a-z]+)*?)(?:_(?P<last>[a-z]+))?$'
for string in strings:
m = re.match(pattern, string)
print m.groupdict()
The output is:
{'middle': 'def', 'last': None, 'first': 'abc'}
{'middle': 'def', 'last': 'xyz', 'first': 'abc'}
{'middle': 'def_ghi_jkl', 'last': 'xyz', 'first': 'abc'}
A:
No need to be that complicated.
>>> s="abc_def_ghi_jkl_xyz"
>>> s.rsplit("_",1)
>>> splitted=s.split("_")
>>> first=splitted[0]
>>> last=splitted[-1]
>>> middle=splitted[1:-1]
>>> middle='_'.join(splitted[1:-1])
>>> print middle
def_ghi_jkl
A:
Thanks for your help everyone ! The two keys of my problem where :
- adding an anchor at the end of my pattern
- making the middle group non greedy.
So :
/start/of/the/path/(?P<a>[a-z]+)_(?P<b>\w+?)(_(?P<c>[a-z]+))?(/|$)
That way all the following strings are matched :
/jobs/ads/abc_J123/previs/m_name
/jobs/ads/abc_J123/previs/m_name/
/jobs/ads/abc_J123/previs/m_name/some_stuff
/jobs/ads/abc_J123/previs/m_name/some_stuff/
/jobs/ads/abc_J123/previs/m_name/some_stuff/other_stuff
/jobs/ads/abc_J123/previs/m_name/some_stuff/other_stuff/
/jobs/ads/abc_J123/previs/m_name_stage
/jobs/ads/abc_J123/previs/m_name_stage/
/jobs/ads/abc_J123/previs/m_name_stage/some_stuff
/jobs/ads/abc_J123/previs/m_name_stage/some_stuff/
/jobs/ads/abc_J123/previs/m_name_stage/some_stuff/other_stuff
/jobs/ads/abc_J123/previs/m_name_stage/some_stuff/other_stuff/
/jobs/ads/abc_J123/previs/m_long_name_stage
/jobs/ads/abc_J123/previs/m_long_name_stage/
/jobs/ads/abc_J123/previs/m_long_name_stage/some_stuff
/jobs/ads/abc_J123/previs/m_long_name_stage/some_stuff/
/jobs/ads/abc_J123/previs/m_long_name_stage/some_stuff/other_stuff
/jobs/ads/abc_J123/previs/m_long_name_stage/some_stuff/other_stuff/
Thank you very much for your help !
| Finding the last group in a regular expression | Three underscore separated elements make my strings :
- first (letters and digits)
- middle (letters, digits and underscore)
- last (letters and digits)
The last element is optional.
Note : I need to access my groups by their names, not their indices.
Examples :
String : abc_def
first : abc
middle : def
last : None
String : abc_def_xyz
first : abc
middle: def
last: xyz
String : abc_def_ghi_jkl_xyz
first : abc
middle : def_ghi_jkl
last : xyz
I can't find the right regex...
I have two ideas so far :
Optional group
(?P<first>[a-z]+)_(?P<middle>\w+)(_(?P<last>[a-z]+))?
But the middle group matches until the end of the string :
String : abc_def_ghi_jkl_xyz
first : abc
middle : def_ghi_jkl_xyz
last : vide
Using the '|'
(?P<first>[a-z]+)_(?P<middle>\w+)_(?P<last>[a-z]+)|(?P<first>[a-z]+)_(?P<middle>\w+)
This expression is invalid : first and middle groups are declared two times. I though I could write an expression reusing the matched group from the first part of the expression :
(?P<first>[a-z]+)_(?P<middle>\w+)_(?P<last>[a-z]+)|(?P=first)_(?P=middle)
The expression is valid, however strings with just a first and a middle like abc_def are not matched.
Note
These strings are actually parts of a path I need to match. It could be paths like :
/my/path/to/abc_def
/my/path/to/abc_def/
/my/path/to/abc_def/some/other/stuf
/my/path/to/abc_def/some/other/stuf/
/my/path/to/abc_def_ghi_jkl_xyz
/my/path/to/abc_def_ghi_jkl_xyz/
/my/path/to/abc_def_ghi_jkl_xyz/some/other/stuf
/my/path/to/abc_def_ghi_jkl_xyz/some/other/stuf/
...
Any idea to solve my problem solely with regular expressions ? Post-processing the matched groups is not an option.
Thank you very much !
| [
"Change the middle group to be non-greedy, and add beginning and end-of-string anchors:\n^(?P<first>[a-z]+)_(?P<middle>\\w+?)(_(?P<last>[a-z]+))?$\n\nBy default, the \\w+will match as much as possible, which eats the rest of the string. Adding the ? tells it to match as little as possible.\nThanks to Tim Pietzcker ... | [
4,
1,
0,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003425330_python_regex.txt |
Q:
Python script to convert po file to localized json
I need python script to convert po file to localized json.
A:
you might start here http://docs.python.org/library/gettext.html and here http://docs.python.org/library/json.html
A:
http://jsgettext.berlios.de/ contains a .po to json converter (p.erl) - for python you can use polib to access .po file contents and transform as desired
| Python script to convert po file to localized json | I need python script to convert po file to localized json.
| [
"you might start here http://docs.python.org/library/gettext.html and here http://docs.python.org/library/json.html\n",
"http://jsgettext.berlios.de/ contains a .po to json converter (p.erl) - for python you can use polib to access .po file contents and transform as desired\n"
] | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0002696119_python.txt |
Q:
A simpler i18n for Python/Django
My question is regarding i18n in Python. From what I understand, it involves:
Create a messages file per language (ONLY ONE?!).
in this file, each message will be of the format
English message here
Message en Francais ici (yea crappy french..)
then have this file compiled into another faster binary format
repeat for all other langs needed
in app code (Django) use the translate method with english (or default) language which will be translated correctly based on locale... tr('English message Here')
Probably I'm a bit off on the steps, but this seems to be the general sense right?
What I'm wondering is, is there a simpler way? I mean in the java webapp world, you set up message bundle files in the bundleName_locale.properties format. In each one you usually have a key to message relation like greeting = Hello World. You can have lots of different properties files for different sub sections of your site/app. All the locale files are hierarchical, and missing keys in a sub locale fall through to the parent etc. This is all done automatically by Java, no setup required.
Is there anything like this in the Django/Python world? Is this just insane to follow this route? Could I fake this using a module as a stand in for a java .properties file? Sorry for the long-winded question, and thanks for any input.
A:
While you could do this fairly simply, I would question why.
As is:
Django's i18n is based around gettext, which has never given me any performance problems.
You don't have to create the message file, Django will do it for you.
The messages files Django creates can be sent as a text file to just about anyone for translation.
I spent about 5 minutes explaining to someone how to use them, and a day later got back a fantastic translation of my entire site.
Marking the strings in your code is very simple.
_("My String") is normal for .py files by using from django.utils.translation import ugettext as _.
{% trans "My String" %} in your templates. Again, quite simple.
Writing out bundle.getString("My String") seems like it would get old, quick.
You can easily incorporate Django's i18n into your JavaScript, if needed.
There are web-based editors for the message files.
You don't have to define a string more than once, it conglomerates all instances into one token across your entire app.
How many times do you have to define "Save" in your Java properties files?
Still in a nice, version-tracking friendly, text file.
If you hack together a .properties-like way to define your strings, you'd still want to compile them so that you don't have to parse the text file at execution time.
Example of empty .po file:
#: templates/inquiries/settings/new_field.html:12
#: templates/inquiries/settings/new_form.html:4
msgid "Save"
msgstr ""
Personally, I don't see a reason to bother hacking together a replacement for a solution which already exists and works well.
| A simpler i18n for Python/Django | My question is regarding i18n in Python. From what I understand, it involves:
Create a messages file per language (ONLY ONE?!).
in this file, each message will be of the format
English message here
Message en Francais ici (yea crappy french..)
then have this file compiled into another faster binary format
repeat for all other langs needed
in app code (Django) use the translate method with english (or default) language which will be translated correctly based on locale... tr('English message Here')
Probably I'm a bit off on the steps, but this seems to be the general sense right?
What I'm wondering is, is there a simpler way? I mean in the java webapp world, you set up message bundle files in the bundleName_locale.properties format. In each one you usually have a key to message relation like greeting = Hello World. You can have lots of different properties files for different sub sections of your site/app. All the locale files are hierarchical, and missing keys in a sub locale fall through to the parent etc. This is all done automatically by Java, no setup required.
Is there anything like this in the Django/Python world? Is this just insane to follow this route? Could I fake this using a module as a stand in for a java .properties file? Sorry for the long-winded question, and thanks for any input.
| [
"While you could do this fairly simply, I would question why. \nAs is:\n\nDjango's i18n is based around gettext, which has never given me any performance problems.\nYou don't have to create the message file, Django will do it for you.\nThe messages files Django creates can be sent as a text file to just about anyo... | [
13
] | [] | [] | [
"django",
"internationalization",
"python"
] | stackoverflow_0003424939_django_internationalization_python.txt |
Q:
Simple protocols (like twisted.pb) vs messaging (AMQP/JMS) vs web services (REST/SOAP)
I'm currently using twisted's perspective broker on python and I have considered in the past switching to something like RabbitMQ but I'm not sure it could just replace pb - I feel like I might be comparing apples to oranges here.
I've been reading a lot about REST lately and the inevitable debate with SOAP, which led me to read about "enterprisey" web service stuff like SOA.
I have a project coming up in which I'll need to implement some erp-like functionality over web and desktop so I'm considering which approach/technology to use to communicate between servers and clients. But I'm also trying to learn as much as I can about all of this, so I don't want just to solve this particular problem.
What do you use for communication between your servers and clients?
I understand a python-specific protocol like perspective broker can limit my interoperability, but am I right to assume some AMQP protocol could replace it?
If I'm not mistaken, both twisted.pb and amqp use an always-on connection and a very low overhead protocol. But in one hand, keeping a large number of clients connected all the time could be a problem, and on the other hand, even with http keep-alive and whatever tricks they use the serialization part would still be a problem with web services.
If I'm wrong in any of my assumptions I would appreciate if someone could point me in the right direction to learn more.
A:
As always, "it depends". First, let's clear up the terminology.
Twisted's Perspective Broker basically is a system you can use when you have control over both ends of a distributed action (both client and server ends). It provides a way to copy objects from one end to the other and to call methods on remote objects. Copying involves serialising the object to a format suitable for network transfer, and then transferring it using Twisted's own transfer protocol. This is useful when both ends can use Twisted, and you don't need to interface with non-Twisted systems.
Generally speaking, Web Services are client-server applications that rely on HTTP for communication. The client uses HTTP to make a request to the server, which returns a result. Parameters can be encoded in eg. GET or POST requests or use a data section in a POST request to send, for example, an XML-formatted document that describes the action to be taken.
REST is the architectural idea that all resources and operations on resources that a system exposes should be directly addressable. To put it somewhat simply, it means that the URI used to access or manipulate the resource includes the resource name and the operation to carry out on it. REST can be and commonly is implemented as a Web Service using HTTP.
SOAP is a protocol for message exchange. It consists of two parts: a choice of several transport methods, and a single XML-based message format. The transport method can be, for example, HTTP, which makes SOAP a candidate for implementing Wed Services. The message format specifies all details about the requested action and the result of the action.
JMS is an API standard for Java-based messaging systems. It defines some semantics for messages (such as one-to-one or one-to-many) and includes methods for addressing, creating messages, populating them with parameters and data, sending them, and receiving and decoding them. The API makes sure that you can, in theory, change the underlying messaging system implementation without having to rewrite all of your code. However, the message system implementation doesn't need to be protocol-compatible with another JMS-enabled messaging system. So having one JMS system doesn't automatically mean that you can exchange messages with another JMS system. You probably need to build some kind of bridge service for that to work, which is going to be a major challenge especially when it comes to addressing.
AMQP attempts to improve the situation by defining a wire protocol that messaging systems must obey. This means that messaging systems from different vendors can exchange messages.
Finally, SOA is an architecture concept where applications are broken down into reusable services. These services are then combined ("orchestrated") to implement the application. Each time a new application is made, there is a chance of reusing the existing services. SOA is also something that requires non-technical support activities so that the reuse really happens and services are designed to be general enough. Also, SOA is one way of starting to package functionality in legacy systems into a meaningful whole that can then be extended and developed further using more modern techniques. SOA can be implemented using a variety of technologies, such as Web Services, messaging systems, or an Enterprise Service Bus.
You pondered the tradeoff between one connection per request and keeping the connection open for multiple requests. This depends on available resources, the messaging pattern, and the size of your data. If the incoming message stream is constantly the same, then it could be fine to let connections stay open since their amount won't change very much. On the other hand, if there are bursts of messages from several systems, then it could be useful to release resources and not let connections linger for too long. Also, if lots of data is transferred per connection, then the overhead of opening and closing the connection is small compared to the total transaction length. On the other hand, if you transfer lots of very small messages, then keeping the connection open could prove beneficial. Benchmarking with your particular parameters is the only way to be sure.
AMQP could indeed replace the Twisted-specific protocol. This would allow interacting with a non-Twisted system.
I hope this proves useful to you. If you're still wondering about something (and I think you are, since this is such a large area) then I would suggest splitting things into smaller questions and posting them individually. The answers can then be more precise.
| Simple protocols (like twisted.pb) vs messaging (AMQP/JMS) vs web services (REST/SOAP) | I'm currently using twisted's perspective broker on python and I have considered in the past switching to something like RabbitMQ but I'm not sure it could just replace pb - I feel like I might be comparing apples to oranges here.
I've been reading a lot about REST lately and the inevitable debate with SOAP, which led me to read about "enterprisey" web service stuff like SOA.
I have a project coming up in which I'll need to implement some erp-like functionality over web and desktop so I'm considering which approach/technology to use to communicate between servers and clients. But I'm also trying to learn as much as I can about all of this, so I don't want just to solve this particular problem.
What do you use for communication between your servers and clients?
I understand a python-specific protocol like perspective broker can limit my interoperability, but am I right to assume some AMQP protocol could replace it?
If I'm not mistaken, both twisted.pb and amqp use an always-on connection and a very low overhead protocol. But in one hand, keeping a large number of clients connected all the time could be a problem, and on the other hand, even with http keep-alive and whatever tricks they use the serialization part would still be a problem with web services.
If I'm wrong in any of my assumptions I would appreciate if someone could point me in the right direction to learn more.
| [
"As always, \"it depends\". First, let's clear up the terminology.\nTwisted's Perspective Broker basically is a system you can use when you have control over both ends of a distributed action (both client and server ends). It provides a way to copy objects from one end to the other and to call methods on remote obj... | [
12
] | [] | [] | [
"amqp",
"network_protocols",
"python",
"twisted",
"web_services"
] | stackoverflow_0003421200_amqp_network_protocols_python_twisted_web_services.txt |
Q:
PYTHONPATH storage location
Where is my pythonpath stored?
When I write
import sys
sys.path
Where does Python get that data?
A:
Python gets that data from the path attribute of the sys module. This path is a list, and if you want to add a new directory to the path, just use the append method.
For instance, to add the directory /home/me/mypy to the path, just do:
import sys
sys.path.append("/home/me/mypy")
| PYTHONPATH storage location | Where is my pythonpath stored?
When I write
import sys
sys.path
Where does Python get that data?
| [
"Python gets that data from the path attribute of the sys module. This path is a list, and if you want to add a new directory to the path, just use the append method.\nFor instance, to add the directory /home/me/mypy to the path, just do:\nimport sys\nsys.path.append(\"/home/me/mypy\")\n\n"
] | [
2
] | [] | [] | [
"python",
"pythonpath"
] | stackoverflow_0003414287_python_pythonpath.txt |
Q:
Deleting lines in python after I write them
Ok here is my existing code:
////////////// = []
for line in datafile:
splitline = line.split()
for item in splitline:
if not item.endswith("JAX"):
if item.startswith("STF") or item.startswith("BRACKER"):
//////////.append( item )
for line in //////////
print /////////////
/////////// +=1
for t in//////
if t in line[:line.find(',')]:
line = line.strip().split(',')
///////////////write(','.join(line[:3]) + '\n')
break
/////////////.close()
/////////////close()
///////////.close()
I want to make a further optimization. The file is really large. I would like to delete the lines from it that have been matched after they have been matched and written to the small file to reduce the amount of time it takes to search through the big file. Any suggestions on how I should go about this?
A:
You cannot delete lines in a text file - it would require moving all the data after the deleted line up to fill the gap, and would be massively inefficient.
One way to do it is to write a temp file with all the lines you want to keep in bigfile.txt, and when you have finished processing delete bigfile.txt and rename the temp file to replace it.
Alternatively if bigfile.txt is small enough to fit in memory you could read the entire file into a list and delete the lines from the list, then write the list back to disk.
I would also guess from your code that bigfile.txt is some sort of CSV file. If so then it may be better to convert it to a database file and use SQL to query it. Python comes with the SQLite module built in and there are 3rd party libraries for most other databases.
A:
As I said in a comment, it doesn't look to me like the size of "bigfile" should be slowing down the speed at which the count increments. When you iterate over a file like that, Python just reads one line at a time in order.
The optimizations you can do at this point depend on how big matchedLines is, and what relationship the matchedLines strings have to the text you're looking in.
If matchedLines is big, you could save time by only doing the 'find' once:
for line in completedataset:
text = line[:line.find(',')]
for t in matchedLines:
if t in text:
line = line.strip().split(',')
smallerdataset.write(','.join(line[:3]) + '\n')
break
In my tests, the 'find' took about 300 nanoseconds, so if matchedLines is a few million items long, there's your extra second right there.
If you're looking for exact matches, not substring matches, you can speed things WAY up by using a set:
matchedLines = set(matchedLines)
for line in completedataset:
target = line[:line.find(',')]
## One lookup and you're done!
if target in matchedLines:
line = line.strip().split(',')
smallerdataset.write(','.join(line[:3]) + '\n')
If the target texts that don't match tend to look completely different from ones that do (for example, most of the targets are random strings, and matchedLines is a bunch of names) AND the matchedLines are all above a certain length, you could try to get really clever by checking substrings. Suppose all matchedLines are at least 5 characters long...
def subkeys(s):
## e.g. if len(s) is 7, return s[0:5], s[1:6], s[2:7].
return [s[i:i+5] for i in range(len(s) + 1 - 5)]
existing_subkeys = set()
for line in matchedLines:
existing_subkeys.update(subkeys(line))
for line in completedataset:
target = line[:line.find(',')]
might_match = False
for subkey in subkeys(target):
if subkey in existing_subkeys:
might_match = True
break
if might_match:
# Then we have to do the old slow way.
for matchedLine in matchedLines:
if matchedLine in target:
# Do the split and write and so on.
But it's really easy to outsmart yourself trying to do things like that, and it depends what your data looks like.
| Deleting lines in python after I write them | Ok here is my existing code:
////////////// = []
for line in datafile:
splitline = line.split()
for item in splitline:
if not item.endswith("JAX"):
if item.startswith("STF") or item.startswith("BRACKER"):
//////////.append( item )
for line in //////////
print /////////////
/////////// +=1
for t in//////
if t in line[:line.find(',')]:
line = line.strip().split(',')
///////////////write(','.join(line[:3]) + '\n')
break
/////////////.close()
/////////////close()
///////////.close()
I want to make a further optimization. The file is really large. I would like to delete the lines from it that have been matched after they have been matched and written to the small file to reduce the amount of time it takes to search through the big file. Any suggestions on how I should go about this?
| [
"You cannot delete lines in a text file - it would require moving all the data after the deleted line up to fill the gap, and would be massively inefficient.\nOne way to do it is to write a temp file with all the lines you want to keep in bigfile.txt, and when you have finished processing delete bigfile.txt and ren... | [
1,
0
] | [] | [] | [
"lines",
"python"
] | stackoverflow_0003418310_lines_python.txt |
Q:
Trying to call readline() on a file object in python but it's pausing
I'm using the readline() function to read data from a file object obtained through the subprocess module: proc = subprocess.Popen(cmd, bufsize=0, stdout=subprocess.PIPE). This allows me to use proc.stdout as a file-like object with proc.stdout.readline(). My issue is that this pauses waiting for input and I'd like it to time out and move on if there isn't input there when I make the readline call. I'm running Python 2.4, how can I get the readline method to stop pausing? Thanks.
A:
On a posix-y platform (basically any popular platform except Windows), the select module offers the right tools for this purpose. Unfortunately, on Windows, select only works on sockets (not on pipes, which is what subprocess.Popen will be using), so the situation is not quite as clear there. Do you need to run on Windows...?
If not, just use the p.stdout.fileno() of your subprocess object p in a select.select call with a short timeout -- it's really easy!
Edit: here's a simple example (assuming the needed imports of course):
>>> def f():
... p = subprocess.Popen("sleep 10; echo ciao", shell=True, stdout=subprocess.PIPE)
... while True:
... r, w, x = select.select([p.stdout.fileno()],[],[],1.0)
... if r: return p.stdout.read()
... print 'not ready yet'
...
>>> f()
not ready yet
not ready yet
not ready yet
not ready yet
not ready yet
not ready yet
not ready yet
not ready yet
not ready yet
not ready yet
'ciao\n'
>>>
Note there is no way to "wait for a complete line": this waits for "any output at all" (then blocks until all the output is ready). To read just what's available, use fcntl to set os.O_NODELAY on the file descriptor (what fileno() returns) before you start looping.
| Trying to call readline() on a file object in python but it's pausing | I'm using the readline() function to read data from a file object obtained through the subprocess module: proc = subprocess.Popen(cmd, bufsize=0, stdout=subprocess.PIPE). This allows me to use proc.stdout as a file-like object with proc.stdout.readline(). My issue is that this pauses waiting for input and I'd like it to time out and move on if there isn't input there when I make the readline call. I'm running Python 2.4, how can I get the readline method to stop pausing? Thanks.
| [
"On a posix-y platform (basically any popular platform except Windows), the select module offers the right tools for this purpose. Unfortunately, on Windows, select only works on sockets (not on pipes, which is what subprocess.Popen will be using), so the situation is not quite as clear there. Do you need to run ... | [
3
] | [] | [] | [
"file",
"python",
"subprocess",
"wait"
] | stackoverflow_0003426250_file_python_subprocess_wait.txt |
Q:
py-appscript is starting a new Finder instance
i have a py2app application, which runs an appscript using py-appscript. the Applescript code is this one line:
app('Finder').update(<file alias of a certain file>)
What this normally does is update a file's preview in Finder. It works most of the time, except for Leopard. In Leopard, everytime that script is executed, instead of updating the file, it starts a new instance of Finder. What am I doing wrong? The app was built on the same machine (the Leopard).
A:
Seeing as how py-appscript is a layer between python and the application you are scripting via Applescript, I would suggest porting the statement to pure Applescript and see if it works there. There are a lot of things that can go wrong with Applescript (and your statement alone) to begin with and it's not obvious what is the expected before with py-appscript when an error occurs.
| py-appscript is starting a new Finder instance | i have a py2app application, which runs an appscript using py-appscript. the Applescript code is this one line:
app('Finder').update(<file alias of a certain file>)
What this normally does is update a file's preview in Finder. It works most of the time, except for Leopard. In Leopard, everytime that script is executed, instead of updating the file, it starts a new instance of Finder. What am I doing wrong? The app was built on the same machine (the Leopard).
| [
"Seeing as how py-appscript is a layer between python and the application you are scripting via Applescript, I would suggest porting the statement to pure Applescript and see if it works there. There are a lot of things that can go wrong with Applescript (and your statement alone) to begin with and it's not obvious... | [
1
] | [] | [] | [
"applescript",
"python"
] | stackoverflow_0003425643_applescript_python.txt |
Q:
Deploying python executables- PyInstaller, cx-freeze, etc
I'm looking to find a way to bundle a python app into stand-alone executables so my windows and mac using friends can use it without installing ugly dependencies. Looking online I've found a few utilities to help do this, including py2exe for windows and py2app for mac, as well as PyInstaller, cx-freeze, and bbfreeze. What have ya'll used and what would you recommend?
A:
I've been building a python app with PyQt and PyQwt for the past few weeks and have had the same problem. I found py2app completely impossible to use, I kept running into so many problems constantly that I gave up. A few days later found PyInstaller which is fantastic. It understands both PyQt and PyQwt out of the box - and does a very nice job in wrapping everything into an app bundle. Haven't tried building a Windows executable with it yet though.
I found a good article at arstechnica on how to use py2exe and py2app although it's a bit old (you can probably skip the python 2.5 stuff) http://arstechnica.com/open-source/guides/2009/03/how-to-deploying-pyqt-applications-on-windows-and-mac-os-x.ars/
I would highly recommend using PyInstaller. There are a couple of tricks though you need to do for OS X since the support is currently only preminary http://diotavelli.net/PyQtWiki/PyInstallerOnMacOSX
A:
I use py2exe to create a windows executable. The documentation is somewhat messy, but once I pulled together a working setup.py to use as a template I haven't had any problems altering it to generate any given exe. I've usually been able to find helpful information though Google searches, like when I needed to bundle in pngs for the UI to use.
| Deploying python executables- PyInstaller, cx-freeze, etc | I'm looking to find a way to bundle a python app into stand-alone executables so my windows and mac using friends can use it without installing ugly dependencies. Looking online I've found a few utilities to help do this, including py2exe for windows and py2app for mac, as well as PyInstaller, cx-freeze, and bbfreeze. What have ya'll used and what would you recommend?
| [
"I've been building a python app with PyQt and PyQwt for the past few weeks and have had the same problem. I found py2app completely impossible to use, I kept running into so many problems constantly that I gave up. A few days later found PyInstaller which is fantastic. It understands both PyQt and PyQwt out of the... | [
1,
0
] | [] | [] | [
"deployment",
"python"
] | stackoverflow_0003426381_deployment_python.txt |
Q:
Python/feedparser script won't display on CGI/ character coding
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
import cgi
import string
import feedparser
count = 0
print "Content-Type: text/html\n\n"
print """<PRE><B>WORK MAINTENANCE/B></PRE>"""
d = feedparser.parse("http://www.hep.hr/ods/rss/radovi.aspx?dp=zagreb")
for opis in d:
try:
print """<B>Place/Time:</B> %s<br>""" % d.entries[count].title
print """<B>Streets:</B> %s<br>""" % d.entries[count].description
print """<B>Published:</B> %s<br>""" % d.entries[count].date
print "<br>"
count+= 1
except:
pass
I have a problem with CGI and paython script. Under the terminal script runs just fine except "IndexError: list index out of range", and I put pass for that. But when I run script through CGI I only get WORK MAINTENANCE line and first line from d.entries[count].title repeated 9 times? So confusing...
Also how can I setup support in feedparser for Croation(balkan) letters; č,ć,š,ž,đ ?
# -- coding: utf-8 -- is not working and I m running Ubuntu server.
Thank you in advance for help.
Regards.
A:
for opis in d:
try:
print """<B>Place/Time:</B> %s<br>""" % d.entries[count].title
You're not using 'opis' in your output.
Try something like this:
for entry in d.entries:
try:
print """<B>Place/Time:</B> %s<br>""" % entry.title
....
A:
Oke had another problem, text that I manualy entered would show on CGI but RSS web pages wouldnt. So you need to encode before you write:
# -*- coding: utf-8 -*-
import sys, os, string
import cgi
import feedparser
import codecs
d = blablablabla
print "Content-Type: text/html; charset=utf-8\n\n"
print
for entry in d.entries:
print """%s""" % entry.title.encode('utf-8')
| Python/feedparser script won't display on CGI/ character coding | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
import cgi
import string
import feedparser
count = 0
print "Content-Type: text/html\n\n"
print """<PRE><B>WORK MAINTENANCE/B></PRE>"""
d = feedparser.parse("http://www.hep.hr/ods/rss/radovi.aspx?dp=zagreb")
for opis in d:
try:
print """<B>Place/Time:</B> %s<br>""" % d.entries[count].title
print """<B>Streets:</B> %s<br>""" % d.entries[count].description
print """<B>Published:</B> %s<br>""" % d.entries[count].date
print "<br>"
count+= 1
except:
pass
I have a problem with CGI and paython script. Under the terminal script runs just fine except "IndexError: list index out of range", and I put pass for that. But when I run script through CGI I only get WORK MAINTENANCE line and first line from d.entries[count].title repeated 9 times? So confusing...
Also how can I setup support in feedparser for Croation(balkan) letters; č,ć,š,ž,đ ?
# -- coding: utf-8 -- is not working and I m running Ubuntu server.
Thank you in advance for help.
Regards.
| [
"\nfor opis in d:\n try:\n print \"\"\"<B>Place/Time:</B> %s<br>\"\"\" % d.entries[count].title\n\n\nYou're not using 'opis' in your output.\nTry something like this:\nfor entry in d.entries:\n try:\n print \"\"\"<B>Place/Time:</B> %s<br>\"\"\" % entry.title\n ....\n\n",
"Oke had anot... | [
0,
0
] | [] | [] | [
"cgi",
"character_encoding",
"feedparser",
"python",
"ubuntu"
] | stackoverflow_0003393414_cgi_character_encoding_feedparser_python_ubuntu.txt |
Q:
Simple problem with dicT in Python
I have this dicT in my code that contain some positions.
position = ['712,352',
'712,390',
'622,522']
when I'm trying to run this part
def MouseMove(x,y):
ctypes.windll.user32.SetCursorPos(x,y)
with MouseMove(position[0]), the compiler says to me that I need 2 arguments on this command...
how can I solve this?
A:
It's not a dictionary but a list. Perhaps you mean to do something like this:
position = [(712,352),
(712,390),
(622,522)]
MouseMove(*position[0])
| Simple problem with dicT in Python | I have this dicT in my code that contain some positions.
position = ['712,352',
'712,390',
'622,522']
when I'm trying to run this part
def MouseMove(x,y):
ctypes.windll.user32.SetCursorPos(x,y)
with MouseMove(position[0]), the compiler says to me that I need 2 arguments on this command...
how can I solve this?
| [
"It's not a dictionary but a list. Perhaps you mean to do something like this:\nposition = [(712,352), \n (712,390), \n (622,522)]\n\nMouseMove(*position[0])\n\n"
] | [
5
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0003426677_dictionary_python.txt |
Q:
python regexp help
Good day. Little question about reg exp.
I have a string look like
http://servercom/smth/Age=&Filter=2&
How can i cut & with regexp from url?
After regexp url-string must be http://server.com/smth/Age=1&Filter=2&
A:
You don't need regex for that:
changed = str.replace('&', '&');
http://docs.python.org/library/string.html#string.replace
A:
You are translating XML escaped special characters. Use the standard lib:
>>> u = "http://servercom/smth/Age=&Filter=2&
>>> import xml.sax.saxutils
>>> xml.sax.saxutils.unescape(u)
'http://servercom/smth/Age=&Filter=2&'
| python regexp help | Good day. Little question about reg exp.
I have a string look like
http://servercom/smth/Age=&Filter=2&
How can i cut & with regexp from url?
After regexp url-string must be http://server.com/smth/Age=1&Filter=2&
| [
"You don't need regex for that:\nchanged = str.replace('&', '&');\n\nhttp://docs.python.org/library/string.html#string.replace\n",
"You are translating XML escaped special characters. Use the standard lib:\n>>> u = \"http://servercom/smth/Age=&Filter=2&\n>>> import xml.sax.saxutils\n>>> xml.sax.saxuti... | [
5,
2
] | [] | [] | [
"python",
"regex",
"url"
] | stackoverflow_0003426675_python_regex_url.txt |
Q:
What is the Python 'buffer' type for?
There is a buffer type in Python, but how can I use it?
In the Python documentation about buffer(), the description is:
buffer(object[, offset[, size]])
The object argument must be an object that supports the buffer call interface (such as strings, arrays, and buffers). A new buffer object will be created which references the object argument. The buffer object will be a slice from the beginning of object (or from the specified offset). The slice will extend to the end of object (or will have a length given by the size argument).
A:
An example usage:
>>> s = 'Hello world'
>>> t = buffer(s, 6, 5)
>>> t
<read-only buffer for 0x10064a4b0, size 5, offset 6 at 0x100634ab0>
>>> print t
world
The buffer in this case is a sub-string, starting at position 6 with length 5, and it doesn't take extra storage space - it references a slice of the string.
This isn't very useful for short strings like this, but it can be necessary when using large amounts of data. This example uses a mutable bytearray:
>>> s = bytearray(1000000) # a million zeroed bytes
>>> t = buffer(s, 1) # slice cuts off the first byte
>>> s[1] = 5 # set the second element in s
>>> t[0] # which is now also the first element in t!
'\x05'
This can be very helpful if you want to have more than one view on the data and don't want to (or can't) hold multiple copies in memory.
Note that buffer has been replaced by the better named memoryview in Python 3, though you can use either in Python 2.7.
Note also that you can't implement a buffer interface for your own objects without delving into the C API, i.e. you can't do it in pure Python.
A:
I think buffers are e.g. useful when interfacing Python to native libraries (Guido van Rossum explains buffer in this mailing list post).
For example, NumPy seems to use buffer for efficient data storage:
import numpy
a = numpy.ndarray(1000000)
The a.data is a:
<read-write buffer for 0x1d7b410, size 8000000, offset 0 at 0x1e353b0>
| What is the Python 'buffer' type for? | There is a buffer type in Python, but how can I use it?
In the Python documentation about buffer(), the description is:
buffer(object[, offset[, size]])
The object argument must be an object that supports the buffer call interface (such as strings, arrays, and buffers). A new buffer object will be created which references the object argument. The buffer object will be a slice from the beginning of object (or from the specified offset). The slice will extend to the end of object (or will have a length given by the size argument).
| [
"An example usage:\n>>> s = 'Hello world'\n>>> t = buffer(s, 6, 5)\n>>> t\n<read-only buffer for 0x10064a4b0, size 5, offset 6 at 0x100634ab0>\n>>> print t\nworld\n\nThe buffer in this case is a sub-string, starting at position 6 with length 5, and it doesn't take extra storage space - it references a slice of the ... | [
159,
30
] | [] | [] | [
"python",
"python_2.7"
] | stackoverflow_0003422685_python_python_2.7.txt |
Q:
All possible combinations of a list of a list
I am in desperate need for some algorithm help when combining lists inside lists. Assuming that I have the following data structure:
fields = [ ['a1', 'a2', 'a3'],
['b1', 'b2', 'b3'],
['c1', 'c2', 'c3'],
['d1', 'd2', 'd3'] ]
I am trying to write a generator (Python) that will yield each possible combination of the items so that the following code:
for x in thegenerator(fields):
print(x)
would give the following output:
['a1', 'b1', 'c1', 'd1']
['a1', 'b1', 'c1', 'd2']
['a1', 'b1', 'c1', 'd3']
['a1', 'b1', 'c2', 'd1']
['a1', 'b1', 'c2', 'd2']
['a1', 'b1', 'c2', 'd3']
...
['a3', 'b3', 'c3', 'd3']
However, my mindset is completely off today so I can not think how I best can iterate the structure to get all the combinations the most clean way using Python. I am sure this has been done before by someone, but after a few searches on google and stack I have given up finding the correct combination of keywords in order to find a suitable algorithm for this problem.
Any ideas what the most clean algorithm to fix this would be?
A:
Just use itertools.product, it does exactly what you're trying to do. If you're interested in the algorithm, you can always look at the source code.
A:
itertools.product(*fields)
| All possible combinations of a list of a list | I am in desperate need for some algorithm help when combining lists inside lists. Assuming that I have the following data structure:
fields = [ ['a1', 'a2', 'a3'],
['b1', 'b2', 'b3'],
['c1', 'c2', 'c3'],
['d1', 'd2', 'd3'] ]
I am trying to write a generator (Python) that will yield each possible combination of the items so that the following code:
for x in thegenerator(fields):
print(x)
would give the following output:
['a1', 'b1', 'c1', 'd1']
['a1', 'b1', 'c1', 'd2']
['a1', 'b1', 'c1', 'd3']
['a1', 'b1', 'c2', 'd1']
['a1', 'b1', 'c2', 'd2']
['a1', 'b1', 'c2', 'd3']
...
['a3', 'b3', 'c3', 'd3']
However, my mindset is completely off today so I can not think how I best can iterate the structure to get all the combinations the most clean way using Python. I am sure this has been done before by someone, but after a few searches on google and stack I have given up finding the correct combination of keywords in order to find a suitable algorithm for this problem.
Any ideas what the most clean algorithm to fix this would be?
| [
"Just use itertools.product, it does exactly what you're trying to do. If you're interested in the algorithm, you can always look at the source code.\n",
"itertools.product(*fields)\n\n"
] | [
10,
3
] | [] | [] | [
"algorithm",
"data_structures",
"permutation",
"python"
] | stackoverflow_0003427232_algorithm_data_structures_permutation_python.txt |
Q:
How to remove 'None' from an Appended Multidimensional Array using numpy
I need to take a csv file and import this data into a multi-dimensional array in python, but I am not sure how to strip the 'None' values out of the array after I have appended my data to the empty array.
I first created a structure like this:
storecoeffs = numpy.empty((5,11), dtype='object')
This returns an 5 row by 11 column array populated by 'None'.
Next, I opened my csv file and converted it to an array:
coeffsarray = list(csv.reader(open("file.csv")))
coeffsarray = numpy.array(coeffsarray, dtype='object')
Then, I appended the two arrays:
newmatrix = numpy.append(storecoeffs, coeffsarray, axis=1)
The result is an array populated by 'None' values followed by the data that I want (first two rows shown to give you an idea as to the nature of my data):
array([[None, None, None, None, None, None, None, None, None, None, None,
workers, constant, hhsize, inc1, inc2, inc3, inc4, age1, age2,
age3, age4],[None, None, None, None, None, None, None, None, None, None, None,
w0, 7.334, -1.406, 2.823, 2.025, 0.5145, 0, -4.936, -5.054, -2.8, 0],,...]], dtype=object)
How do I remove those 'None' objects from each row so what I am left with is the 5 x11 multidimensional array with my data?
A:
Why are you allocating an entire array of Nones and appending to that? Is coeffsarray not the array you want?
Edit
Oh. Use numpy.reshape.
import numpy
coeffsarray = numpy.reshape( coeffsarray, ( 5, 11 ) )
A:
Start with an empty array?
storecoeffs = numpy.empty((5,0), dtype='object')
A:
why not simply using numpy.loadtxt():
newmatrix = numpy.loadtxt("file.csv", dtype='object')
should do the job, if i understood well you question.
A:
@Gnibbler's answer is technically correct, but there's no reason to create the initial storecoeffs array in the first place. Just load in your values and then create an array from them. As @Mermoz noted, though, your use case looks simple enough for numpy.loadtxt().
Beyond that, why are you using an object array?? It's probably not what you want... Right now, you're storing the numerical values as strings, not floats!
You have essentially two ways to handle your data in numpy. If you want easy access to named columns, use a structured array (or a record array). If you want to have a "normal" multidimensional array, just use an array of floats, ints, etc. Object arrays have a specific purpose, but it's probably not what you're doing.
For example:
To just load in the data as a normal 2D numpy array (assuming all your data can be represented easily as a float):
import numpy as np
# Note that this ignores your column names, and attempts to
# convert all values to a float...
data = np.loadtxt('input_filename.txt', delimiter=',', skiprows=1)
# Access the first column
workers = data[:,0]
To load your data in as a structured array, you might do something like this:
import numpy as np
infile = file('input_filename.txt')
# Read in the names of the columns from the first row...
names = infile.next().strip().split()
# Make a dtype from these names...
dtype = {'names':names, 'formats':len(names)*[np.float]}
# Read the data in...
data = np.loadtxt(infile, dtype=dtype, delimiter=',')
# Note that data is now effectively 1-dimensional. To access a column,
# index it by name
workers = data['workers']
# Note that this is now one-dimensional... You can't treat it like a 2D array
data[1:10, 3:5] # <-- Raises an error!
data[1:10][['inc1', 'inc2']] # <-- Effectively the same thing, but works..
If you have non-numerical values in your data and want to handle them as strings, you'll need to use a structured array, specify which fields you want to be strings, and set a max length for the strings in the field.
From your sample data, it looks like the first column, "workers" is a non-numerical value that you might want to store as a string and all the rest look like floats. In that case, you'd do something like this:
import numpy as np
infile = file('input_filename.txt')
names = infile.next().strip().split()
# Create the dtype... The 'S10' indicates a string field with a length of 10
dtype = {'names':names, 'formats':['S10'] + (len(names) - 1)*[np.float]}
data = np.loadtxt(infile, dtype=dtype, delimiter=',')
# The "workers" field is now a string array
print data['workers']
# Compare this to the other fields
print data['constant']
If there are cases where you really need the flexibility of the csv module (e.g. text fields with commas), you can use it to read the data, and then convert it to a structured array with the appropriate dtype.
Hope that makes things a bit clearer...
| How to remove 'None' from an Appended Multidimensional Array using numpy | I need to take a csv file and import this data into a multi-dimensional array in python, but I am not sure how to strip the 'None' values out of the array after I have appended my data to the empty array.
I first created a structure like this:
storecoeffs = numpy.empty((5,11), dtype='object')
This returns an 5 row by 11 column array populated by 'None'.
Next, I opened my csv file and converted it to an array:
coeffsarray = list(csv.reader(open("file.csv")))
coeffsarray = numpy.array(coeffsarray, dtype='object')
Then, I appended the two arrays:
newmatrix = numpy.append(storecoeffs, coeffsarray, axis=1)
The result is an array populated by 'None' values followed by the data that I want (first two rows shown to give you an idea as to the nature of my data):
array([[None, None, None, None, None, None, None, None, None, None, None,
workers, constant, hhsize, inc1, inc2, inc3, inc4, age1, age2,
age3, age4],[None, None, None, None, None, None, None, None, None, None, None,
w0, 7.334, -1.406, 2.823, 2.025, 0.5145, 0, -4.936, -5.054, -2.8, 0],,...]], dtype=object)
How do I remove those 'None' objects from each row so what I am left with is the 5 x11 multidimensional array with my data?
| [
"Why are you allocating an entire array of Nones and appending to that? Is coeffsarray not the array you want?\nEdit\nOh. Use numpy.reshape.\nimport numpy\ncoeffsarray = numpy.reshape( coeffsarray, ( 5, 11 ) )\n\n",
"Start with an empty array?\nstorecoeffs = numpy.empty((5,0), dtype='object')\n\n",
"why not sim... | [
1,
1,
1,
1
] | [] | [] | [
"extract",
"multidimensional_array",
"numpy",
"python",
"slice"
] | stackoverflow_0003427036_extract_multidimensional_array_numpy_python_slice.txt |
Q:
How does Pythonic garbage collection with numpy array appends and deletes?
I am trying to adapt the underlying structure of plotting code (matplotlib) that is updated on a timer to go from using Python lists for the plot data to using numpy arrays. I want to be able to lower the time step for the plot as much as possible, and since the data may get up into the thousands of points, I start to lose valuable time fast if I can't. I know that numpy arrays are preferred for this sort of thing, but I am having trouble figuring out when I need to think like a Python programmer and when I need to think like a C++ programmer maximize my efficiency of memory access.
It says in the scipy.org docs for the append() function that it returns a copy of the arrays appended together. Do all these copies get garbage-collected properly? For example:
import numpy as np
a = np.arange(10)
a = np.append(a,10)
print a
This is my reading of what is going on on the C++-level, but if I knew what I was talking about, I wouldn't be asking the question, so please correct me if I'm wrong! =P
First a block of 10 integers gets allocated, and the symbol a points to the beginning of that block. Then a new block of 11 integers is allocated, for a total of 21 ints (84 bytes) being used. Then the a pointer is moved to the start of the 11-int block. My guess is that this would result in the garbage-collection algorithm decrementing the reference count of the 10-int block to zero and de-allocating it. Is this right? If not, how do I ensure I don't create overhead when appending?
I also am not sure how to properly delete a numpy array when I am done using it. I have a reset button on my plots that just flushes out all the data and starts over. When I had lists, this was done using del data[:]. Is there an equivalent function for numpy arrays? Or should I just say data = np.array([]) and count on the garbage collector to do the work for me?
A:
The point of automatic memory management is that you don't think about it. In the code that you wrote, the copies will be garbage-collected fine (it's nigh on impossible to confuse Python's memory management). However, because np.append is not in-place, the code will create a new array in memory (containing the concatenation of a and 10) and then the variable a will be updated to point to this new array. Since a now no longer points to the original array, which had a refcount of 1, its refcount is decremented to 0 and it will be cleaned up automatically. You can use gc.collect to force a full cleanup.
Python's strength does not lie in fine-tuning memory access, although it is possible to optimise. You are probably best sorted pre-allocating a (using e.g. a = np.zeros( <size> )); if you need finer tuning than that it starts to get a bit hairy. You could have a look at the Cython + Numpy tutorial for a very neat and easy way to integrate C with Python for efficiency.
Variables in Python just point to the location where their contents are stored; you can del any variable and it will decrease the reference count of its target by one. The target will be cleaned automatically after its reference count hits zero. The moral of this is, don't worry about cleaning up your memory. It will happen automatically.
| How does Pythonic garbage collection with numpy array appends and deletes? | I am trying to adapt the underlying structure of plotting code (matplotlib) that is updated on a timer to go from using Python lists for the plot data to using numpy arrays. I want to be able to lower the time step for the plot as much as possible, and since the data may get up into the thousands of points, I start to lose valuable time fast if I can't. I know that numpy arrays are preferred for this sort of thing, but I am having trouble figuring out when I need to think like a Python programmer and when I need to think like a C++ programmer maximize my efficiency of memory access.
It says in the scipy.org docs for the append() function that it returns a copy of the arrays appended together. Do all these copies get garbage-collected properly? For example:
import numpy as np
a = np.arange(10)
a = np.append(a,10)
print a
This is my reading of what is going on on the C++-level, but if I knew what I was talking about, I wouldn't be asking the question, so please correct me if I'm wrong! =P
First a block of 10 integers gets allocated, and the symbol a points to the beginning of that block. Then a new block of 11 integers is allocated, for a total of 21 ints (84 bytes) being used. Then the a pointer is moved to the start of the 11-int block. My guess is that this would result in the garbage-collection algorithm decrementing the reference count of the 10-int block to zero and de-allocating it. Is this right? If not, how do I ensure I don't create overhead when appending?
I also am not sure how to properly delete a numpy array when I am done using it. I have a reset button on my plots that just flushes out all the data and starts over. When I had lists, this was done using del data[:]. Is there an equivalent function for numpy arrays? Or should I just say data = np.array([]) and count on the garbage collector to do the work for me?
| [
"The point of automatic memory management is that you don't think about it. In the code that you wrote, the copies will be garbage-collected fine (it's nigh on impossible to confuse Python's memory management). However, because np.append is not in-place, the code will create a new array in memory (containing the co... | [
10
] | [] | [] | [
"arrays",
"garbage_collection",
"memory_management",
"numpy",
"python"
] | stackoverflow_0003427632_arrays_garbage_collection_memory_management_numpy_python.txt |
Q:
is there a better way to hold this data then a dictionary of dictionaries of dictionaries? python
I am creating a data structure dynamically that holds car information. The dictionary looks something like this:
cars = {'toyota': {'prius': {'transmission':'automatic', 'mpg':30, 'misc':[]}}}
The outermost dictionary contains car brand (toyota, bmw, etc.), the second dictionary contains model (prius, m5, etc.) and the inner dictionary contains details of the car. Is this the best way to hold this information?
I am both building the data structure and accessing it. I can't really think of another way to do it but the code looks kind of messy with a bunch of:
cars['toyota'].setdefault('prius', {}).setdefault('misc', []).append('hello')
A:
As Justin suggested, classes would be ideal.
You could easily do something like this:
class Car(object):
def __init__(self, make, model=None, trans=None, mpg=None, misc=None):
if make == 'Toyta' and model is None:
model = 'Prius'
self.make = make
self.model = model
self.transmission = trans
self.mpg = mpg
if misc is None:
self.misc = []
#other class stuff here
def __str__(self):
return "Make: {make} Model: {model} Mpg: {mpg}".format(make=self.make,
model=self.model,
mpg=self.mpg)
def __repr__(self):
return str(self)
cars = [Car('Toyota', 'Prius', 'Automatic', '30'),
Car('Mitsubishi', 'Echo LRX', 'Automatic', '20')]
for car in cars:
print car
HTH!
A:
Python has classes. I don't know if it makes sense with your data structure, but you could organize everything into a collection of Car classes.
A:
Why not create JSON structure? Semantically you might be able to gain a little more expressiveness rather than accessing your data as dictionary elements.
A:
One idea - flatten the nested dictionary keyed by a multi-segment name separated by period. E.g.
cars.setvalue('toyota.prius.transmission', 'automatic')
cars.setvalue('toyota.prius.mpg', '30')
cars.setvalue('toyota.prius.misc', [])
cars.getvalue('toyota.prius.misc').append('hello')
class Car:
def setvalue(self, key, value):
# parse the key and do your mess here, like
# cars['toyota'].setdefault('prius', {}).setdefault('misc', [])
| is there a better way to hold this data then a dictionary of dictionaries of dictionaries? python | I am creating a data structure dynamically that holds car information. The dictionary looks something like this:
cars = {'toyota': {'prius': {'transmission':'automatic', 'mpg':30, 'misc':[]}}}
The outermost dictionary contains car brand (toyota, bmw, etc.), the second dictionary contains model (prius, m5, etc.) and the inner dictionary contains details of the car. Is this the best way to hold this information?
I am both building the data structure and accessing it. I can't really think of another way to do it but the code looks kind of messy with a bunch of:
cars['toyota'].setdefault('prius', {}).setdefault('misc', []).append('hello')
| [
"As Justin suggested, classes would be ideal.\nYou could easily do something like this:\nclass Car(object):\n def __init__(self, make, model=None, trans=None, mpg=None, misc=None):\n if make == 'Toyta' and model is None:\n model = 'Prius'\n self.make = make\n self.model = model\n ... | [
12,
5,
0,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0003427198_dictionary_python.txt |
Q:
Where to manually install python files
I'm having trouble with setuptools in a larger project where a python package has to be "constructed" from several debian packages (each containing a subpackage of the "main" package). Thus we decided to install the files manully instead of using "setup.py install", but we are unsure of the location to use. We first used a directory in /usr/share that we already use for other stuff we install. This works fine except for the fact that we have to mess around with PYTHONPATH before starting any application.
Is there any place that is in the default sys.path where we could install packages instead? I was thinking about /usr/lib/python2.6/dist-packages (which is where the files should end up when you use setuptools as well, shouldnt they?), but I'm kind of reluctant of writing to a place like this with custom install scripts... Also, what if Ubuntu switches to 2.7, do we have to move as well then? Any "best practice" how to do something like this? This whole site-packages/dist-packages concept is so under-documented :(
A:
It is kind of hard to say where you need to install your Python packages taking into account that, in fact, you can install it anywhere you want. The best place in my opinion is to put them into /usr/local/share/YOURPACKAGENAME in case it was not installed by apt-get (aptitude etc...). In either case, you have to create a small wrapper around you python script(s) which inserts a path(s) to where your package(s) are located into "sys.path" variable. For example, "yum" for Ubuntu puts its files to "/usr/share/yum-cli" by default and "/usr/bin/yum" script contains the following lines:
#!/usr/bin/python
...
sys.path.insert(0, '/usr/share/yum-cli')
try:
import yummain
yummain.user_main(sys.argv[1:], exit_code=True)
except KeyboardInterrupt, e:
...
Alternatively, you have to set PYTHONPATH environment variable. There is nothing wrong with that.
| Where to manually install python files | I'm having trouble with setuptools in a larger project where a python package has to be "constructed" from several debian packages (each containing a subpackage of the "main" package). Thus we decided to install the files manully instead of using "setup.py install", but we are unsure of the location to use. We first used a directory in /usr/share that we already use for other stuff we install. This works fine except for the fact that we have to mess around with PYTHONPATH before starting any application.
Is there any place that is in the default sys.path where we could install packages instead? I was thinking about /usr/lib/python2.6/dist-packages (which is where the files should end up when you use setuptools as well, shouldnt they?), but I'm kind of reluctant of writing to a place like this with custom install scripts... Also, what if Ubuntu switches to 2.7, do we have to move as well then? Any "best practice" how to do something like this? This whole site-packages/dist-packages concept is so under-documented :(
| [
"It is kind of hard to say where you need to install your Python packages taking into account that, in fact, you can install it anywhere you want. The best place in my opinion is to put them into /usr/local/share/YOURPACKAGENAME in case it was not installed by apt-get (aptitude etc...). In either case, you have to ... | [
2
] | [] | [] | [
"debian",
"packaging",
"python",
"setuptools",
"ubuntu"
] | stackoverflow_0003424323_debian_packaging_python_setuptools_ubuntu.txt |
Q:
What does the unary operator ~ do in numpy?
I came across a line of code using Python's numpy that looked like this:
~array([0,1,2,3,4,5,4,3,2,1,0,-1,-2])
And it gave the output:
array([-1, -2, -3, -4, -5, -6, -5, -4, -3, -2, -1, 0, 1])
Does the unary operator (~) take an array and apply A -> -(A+1)
If so, whats the point?
A:
Chris Lutz' comment is correct.
~ is the bitwise negation operator
It looks like it turns A to -(A+1) because on many modern computers, negative numbers are represented as the Two's Complement of the corresponding positive integer, where the number is subtracted from 2^(bit length) (that's "two to the power of bit length", not "two exclusive or bit length"...).
In such a system, -1 would be represented as all ones.
Of course, so would the sum of a number and its bitwise negative, so we have the situation where
a + ~a = -1 =>
~a = -1 - a =>
~a = -(a + 1)
as you noticed.
A:
http://en.wikipedia.org/wiki/Bitwise_operation#NOT
The reason why you end up with negative numbers is how they are represented in binary form:
http://en.wikipedia.org/wiki/Two%27s_complement
A:
The ~ is the ones' complement operator and if you're using with ints it can be used in any python program (it's not exclusively of numpy)
A:
The point is to be able to take the complement of the vales in an array. In the case of numpy it appears to be shorthand for the following:
>>> map(lambda e: ~e, [0,1,2,3,4,5,4,3,2,1,0,-1,-2])
[-1, -2, -3, -4, -5, -6, -5, -4, -3, -2, -1, 0, 1]
| What does the unary operator ~ do in numpy? | I came across a line of code using Python's numpy that looked like this:
~array([0,1,2,3,4,5,4,3,2,1,0,-1,-2])
And it gave the output:
array([-1, -2, -3, -4, -5, -6, -5, -4, -3, -2, -1, 0, 1])
Does the unary operator (~) take an array and apply A -> -(A+1)
If so, whats the point?
| [
"Chris Lutz' comment is correct.\n~ is the bitwise negation operator\nIt looks like it turns A to -(A+1) because on many modern computers, negative numbers are represented as the Two's Complement of the corresponding positive integer, where the number is subtracted from 2^(bit length) (that's \"two to the power of ... | [
14,
4,
2,
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0003428014_numpy_python.txt |
Q:
django shell triggering Postgres idle transaction problems
It's not the fault of the django (iPython) shell, actually. The problem is developers who open the django shell ./manage.py shell run through some queries (it often only generates selects), and then either leave the shell running or somehow kill their (ssh) session (actually, I'm not sure if the latter case leaves the transaction open - I haven't tested it)
In any case, nagios regularly alerts over these idle transactions. We could, of course call developer.stop_doing_that_dammit() but it's unreliable.
I'm looking for thoughts on resolving this in a way that allows developers to use the django shell, but closes transactions should they forget to close their session out.
A:
You may always run a cron job, that will call pg_cancel_backend() within the database, for the backends that are idle for longer than e.g. 1 day (of course that depends on the nagios settings).
| django shell triggering Postgres idle transaction problems | It's not the fault of the django (iPython) shell, actually. The problem is developers who open the django shell ./manage.py shell run through some queries (it often only generates selects), and then either leave the shell running or somehow kill their (ssh) session (actually, I'm not sure if the latter case leaves the transaction open - I haven't tested it)
In any case, nagios regularly alerts over these idle transactions. We could, of course call developer.stop_doing_that_dammit() but it's unreliable.
I'm looking for thoughts on resolving this in a way that allows developers to use the django shell, but closes transactions should they forget to close their session out.
| [
"You may always run a cron job, that will call pg_cancel_backend() within the database, for the backends that are idle for longer than e.g. 1 day (of course that depends on the nagios settings).\n"
] | [
1
] | [] | [] | [
"django",
"ipython",
"postgresql",
"python"
] | stackoverflow_0003427505_django_ipython_postgresql_python.txt |
Q:
Pygments in wxPython?
Is it at all possible to use Pygments inside of wxPython to provide syntax highlighting?
A:
Positive. While pygments is originally aimed at CSS output, you can define a pygments formatter to define styles for a wx.StyledTextCtrl for example. I happen to have done that just recently:
http://relet.net/frog/archives/170
| Pygments in wxPython? | Is it at all possible to use Pygments inside of wxPython to provide syntax highlighting?
| [
"Positive. While pygments is originally aimed at CSS output, you can define a pygments formatter to define styles for a wx.StyledTextCtrl for example. I happen to have done that just recently:\nhttp://relet.net/frog/archives/170\n"
] | [
4
] | [] | [] | [
"highlighting",
"pygments",
"python",
"syntax",
"wxpython"
] | stackoverflow_0003428193_highlighting_pygments_python_syntax_wxpython.txt |
Q:
Python os.system() - does it leave history (bash_history,etc.)?
I'm using os.system() to invoke some openssl command from my ubuntu box. I specify password in line so it looks like:
//python code
os.system("openssl enc -aes-256-cbc ... -k password")
I need to know if is possible to track this command in some shell / bash history file (as it is possible if I type this command into terminal directly, so basically I'm asking if password handling is secure that way)
A:
No, bash only logs commands that are entered interactively.
Commands executed through os.system are not logged anywhere.
A:
No, it does not, however on a multiuser box, passing passwords via command-line parameters is considered bad for security, as other users can (in principle) see them via "ps" etc.
Passing the password via a file descriptor (e.g. stdin) or environment variable is immune to this attack; most programs have support for one of these methods instead. If it bothers you, consider using one of those.
A:
While the arguments are not logged (only interactive commands are logged, and that's in a file that is stored with correct permissions in your home directory) there is still a real danger with passing passwords. Both the command line arguments and the environment variables are visible to all users of the machine who use ps with the correct options. The exact options to do this vary between OSes, so check your local documentation (on OSX, it's ps -wwaxE that spills the beans).
The safe way to pass the password in is either via a pipe and the -pass stdin option to openssl (-k is insecure and obsolete) or via a file with carefully-set permissions and the -pass file:pathname option (replacing pathname with the name of the file, of course). You could also use -pass fd:number but I don't know how easy that is to fit with os.system. All the above are secure (possibly with care) because you can't peek inside pipes and you can properly secure the filesystem.
Of course, once you've taken these steps to secure your invocation of openssl, whether or not it is logged won't matter; it will be secure anyway.
| Python os.system() - does it leave history (bash_history,etc.)? | I'm using os.system() to invoke some openssl command from my ubuntu box. I specify password in line so it looks like:
//python code
os.system("openssl enc -aes-256-cbc ... -k password")
I need to know if is possible to track this command in some shell / bash history file (as it is possible if I type this command into terminal directly, so basically I'm asking if password handling is secure that way)
| [
"No, bash only logs commands that are entered interactively.\nCommands executed through os.system are not logged anywhere.\n",
"No, it does not, however on a multiuser box, passing passwords via command-line parameters is considered bad for security, as other users can (in principle) see them via \"ps\" etc.\nPas... | [
1,
1,
1
] | [] | [] | [
"linux",
"python"
] | stackoverflow_0003423542_linux_python.txt |
Q:
Extracting a set of words with the Python/NLTK, then comparing it to a standard English dictionary
I have:
from __future__ import division
import nltk, re, pprint
f = open('/home/a/Desktop/Projects/FinnegansWake/JamesJoyce-FinnegansWake.txt')
raw = f.read()
tokens = nltk.wordpunct_tokenize(raw)
text = nltk.Text(tokens)
words = [w.lower() for w in text]
f2 = open('/home/a/Desktop/Projects/FinnegansWake/catted-several-long-Russian-novels-and-the-NYT.txt')
englishraw = f2.read()
englishtokens = nltk.wordpunct_tokenize(englishraw)
englishtext = nltk.Text(englishtokens)
englishwords = [w.lower() for w in englishwords]
which is straight from the NLTK manual. What I want to do next is to compare vocab to an exhaustive set of English words, like the OED, and extract the difference -- the set of Finnegans Wake words that have not, and probably never will, be in the OED. I'm much more of a verbal person than a math-oriented person, so I haven't figured out how to do that yet, and the manual goes into way too much detail about stuff I don't actually want to do. I'm assuming it's just one or two more lines of code, though.
A:
If your English dictionary is indeed a set (hopefully of lowercased words),
set(vocab) - english_dictionary
gives you the set of words which are in the vocab set but not in the english_dictionary one. (It's a pity that you turned vocab into a list by that sorted, since you need to turn it back into a set to perform operations such as this set difference!).
If your English dictionary is in some different format, not really a set or not comprised only of lowercased words, you'll have to tell us what that format is for us to be able to help!-)
Edit: given the OP's edit shows that both words (what was previously called vocab) and englishwords (what I previously called english_dictionary) are in fact lists of lowercased words, then
newwords = set(words) - set(englishwords)
or
newwords = set(words).difference(englishwords)
are two ways to express "the set of words that are not englishwords". The former is slightly more concise, the latter perhaps a bit more readable (since it uses the word "difference" explicitly, instead of a minus sign) and perhaps a bit more efficient (since it doesn't explicitly transform the list englishwords into a set -- though, if speed is crucial this needs to be checked by measurement, since "internally" difference still needs to do some kind of "transformation-to-set"-like operation).
If you're keen to have a list as the result instead of a set, sorted(newwords) will give you an alphabetically sorted list (list(newwords) would give you a list a bit faster, but in totally arbitrary order, and I suspect you'd rather wait a tiny extra amount of time and get, in return, a nicely alphabetized result;-).
| Extracting a set of words with the Python/NLTK, then comparing it to a standard English dictionary | I have:
from __future__ import division
import nltk, re, pprint
f = open('/home/a/Desktop/Projects/FinnegansWake/JamesJoyce-FinnegansWake.txt')
raw = f.read()
tokens = nltk.wordpunct_tokenize(raw)
text = nltk.Text(tokens)
words = [w.lower() for w in text]
f2 = open('/home/a/Desktop/Projects/FinnegansWake/catted-several-long-Russian-novels-and-the-NYT.txt')
englishraw = f2.read()
englishtokens = nltk.wordpunct_tokenize(englishraw)
englishtext = nltk.Text(englishtokens)
englishwords = [w.lower() for w in englishwords]
which is straight from the NLTK manual. What I want to do next is to compare vocab to an exhaustive set of English words, like the OED, and extract the difference -- the set of Finnegans Wake words that have not, and probably never will, be in the OED. I'm much more of a verbal person than a math-oriented person, so I haven't figured out how to do that yet, and the manual goes into way too much detail about stuff I don't actually want to do. I'm assuming it's just one or two more lines of code, though.
| [
"If your English dictionary is indeed a set (hopefully of lowercased words),\nset(vocab) - english_dictionary\n\ngives you the set of words which are in the vocab set but not in the english_dictionary one. (It's a pity that you turned vocab into a list by that sorted, since you need to turn it back into a set to p... | [
4
] | [] | [] | [
"nlp",
"nltk",
"python",
"set",
"text"
] | stackoverflow_0003428131_nlp_nltk_python_set_text.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.