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: change file descriptor for socket in python I'm trying to manually create the file descriptor associated with a socket in python and then loaded directly into memory with mmap. Create a file into memory with mmap is simple, but I can not find a way to associate the file with a socket. Thanks for your responses. The problem I have is I can not make more of a number of sockets for python (or operating system) I get the error: "[errno 24] Too many open files." I think the error is because I can not create more file descriptors on disk, so I want to create them in memory. To avoid this limitation. Any suggestions? A: Why do you want to load this into memory using mmap? If you are on a unix variant, you can create a unix socket which is a file descriptor which can be used just like any other socket. A socket and a memory-mapped file are two distinct entities - it is probably not a good idea to try and mix them. Perhaps it would be helpful to take a step back and discuss what you are trying to do at a higher level. A: There is a good chance that I am royally misinterpreting your question. Are you saying that there is an existing socket file for which you would like to create a Python socket object? If so, socket.fromfd() will duplicate the fd and create a socket object. http://docs.python.org/library/socket.html#socket.fromfd edit to address Dani's post I think that you misunderstand how file descriptors work. There is a limit set by the OS. This has nothing to do with what the FDs point to, so mmap will not help you here (sockets aren't on disk either btw). You probably just need to do better file management - close files when you are done with them. In case if you just have really demanding requirements, you may need to increase the limit on open FDs. This blog post has an excellent example of using the resource module (*NIX-only) to get and set the open file limit. The getrlimit man page has more information on its use.
change file descriptor for socket in python
I'm trying to manually create the file descriptor associated with a socket in python and then loaded directly into memory with mmap. Create a file into memory with mmap is simple, but I can not find a way to associate the file with a socket. Thanks for your responses. The problem I have is I can not make more of a number of sockets for python (or operating system) I get the error: "[errno 24] Too many open files." I think the error is because I can not create more file descriptors on disk, so I want to create them in memory. To avoid this limitation. Any suggestions?
[ "Why do you want to load this into memory using mmap? If you are on a unix variant, you can create a unix socket which is a file descriptor which can be used just like any other socket. A socket and a memory-mapped file are two distinct entities - it is probably not a good idea to try and mix them.\nPerhaps it would be helpful to take a step back and discuss what you are trying to do at a higher level.\n", "There is a good chance that I am royally misinterpreting your question. Are you saying that there is an existing socket file for which you would like to create a Python socket object? If so, socket.fromfd() will duplicate the fd and create a socket object.\nhttp://docs.python.org/library/socket.html#socket.fromfd\nedit to address Dani's post\nI think that you misunderstand how file descriptors work. There is a limit set by the OS. This has nothing to do with what the FDs point to, so mmap will not help you here (sockets aren't on disk either btw). You probably just need to do better file management - close files when you are done with them.\nIn case if you just have really demanding requirements, you may need to increase the limit on open FDs. This blog post has an excellent example of using the resource module (*NIX-only) to get and set the open file limit. The getrlimit man page has more information on its use.\n" ]
[ 1, 0 ]
[]
[]
[ "file_descriptor", "python", "sockets" ]
stackoverflow_0002922548_file_descriptor_python_sockets.txt
Q: What are simple instructions for creating a Python package structure and egg? I just completed my first (minor) Python project, and my boss wants me to package it nicely so that it can be distributed and called from other programs easily. He suggested I look into eggs. I've been googling and reading, but I'm just getting confused. Most of the sites I'm looking at explain how to use Python eggs that were already created, or how to create an egg from a setup.py file (which I don't yet have). All I have now is an Eclipse pydev project with about 4 modules and a settings/configuration file. In easy steps, how do I go about structuring it into folders/packages and compiling it into an egg? And once it's an egg, what do I have to know about deploying/building/using it? I'm really starting from scratch here, so don't assume I know anything; simple step-by-step instructions would be really helpful... These are some of the sites that I've been looking at so far: http://peak.telecommunity.com/DevCenter/PythonEggs http://www.packtpub.com/article/writing-a-package-in-python http://www.ibm.com/developerworks/library/l-cppeak3.html#N10232 I've also browsed a few SO questions but haven't really found what I need. Thanks! A: All you need is read this: The Hitchhiker's Guide to Packaging or install PasteScript using pip or easy_install, then paster create your_package_name and you'll get a template for your python package A: You should hold to the standard packaging of distutils. Quoting James Bennett: Please, for the love of Guido, stop using setuptools and easy_install, and use distutils and pip instead. Starting from there, a quite standard distribution looks like: module/ README setup.py # follow http://docs.python.org/distutils/setupscript.html tests/ A: You should be able to find what you need in one of the following, depending on what version of Python you're using: http://docs.python.org/distutils/ http://docs.python.org/py3k/distutils/index.html
What are simple instructions for creating a Python package structure and egg?
I just completed my first (minor) Python project, and my boss wants me to package it nicely so that it can be distributed and called from other programs easily. He suggested I look into eggs. I've been googling and reading, but I'm just getting confused. Most of the sites I'm looking at explain how to use Python eggs that were already created, or how to create an egg from a setup.py file (which I don't yet have). All I have now is an Eclipse pydev project with about 4 modules and a settings/configuration file. In easy steps, how do I go about structuring it into folders/packages and compiling it into an egg? And once it's an egg, what do I have to know about deploying/building/using it? I'm really starting from scratch here, so don't assume I know anything; simple step-by-step instructions would be really helpful... These are some of the sites that I've been looking at so far: http://peak.telecommunity.com/DevCenter/PythonEggs http://www.packtpub.com/article/writing-a-package-in-python http://www.ibm.com/developerworks/library/l-cppeak3.html#N10232 I've also browsed a few SO questions but haven't really found what I need. Thanks!
[ "All you need is read this: The Hitchhiker's Guide to Packaging \nor install PasteScript using pip or easy_install, then\npaster create your_package_name\n\nand you'll get a template for your python package\n", "You should hold to the standard packaging of distutils. Quoting James Bennett:\n\nPlease, for the love of Guido, stop using setuptools and easy_install, and use distutils and pip instead.\n\nStarting from there, a quite standard distribution looks like:\nmodule/\nREADME\nsetup.py # follow http://docs.python.org/distutils/setupscript.html\ntests/\n\n", "You should be able to find what you need in one of the following, depending on what version of Python you're using:\nhttp://docs.python.org/distutils/ \nhttp://docs.python.org/py3k/distutils/index.html\n" ]
[ 30, 3, 2 ]
[]
[]
[ "egg", "package", "python" ]
stackoverflow_0002922498_egg_package_python.txt
Q: Python MySQLdb LOAD LOCAL INFILE problems The problem is a simple one. When I execute the following I get different results depending on whether I run it from the MySQL console and from inside a Python Script using MySQLdb: LOAD DATA LOCAL INFILE '/tmp/source.csv' INTO TABLE test FIELDS TERMINATED BY '|' IGNORE 1 LINES; Console gives the following results: Records: 35002 Deleted: 0 Skipped: 0 Warnings: 0 Python (via .info()) returns the following: Records: 34977 Deleted: 0 Skipped: 0 Warnings: 8 So in summary, same source file, same SQL request, different results. From the console I can 'SHOW WARNINGS' an get a better handle on which records are causing the problems and why but from Python I can't idenitify how to do this or more importantly what the cause of the problem could be. Any suggestions? MySQL Server '5.1.41-3ubuntu12.1' Python '2.6.5' Tables are MyISAM A: After loading the data, execute SELECT @@warning_count; check if greater than 0. If it is than execute SHOW WARNINGS; and dump the result (returns 3 columns: Level, Code, Message) or throw an exception. You can execute both statements exactly like every other select * from ... query.
Python MySQLdb LOAD LOCAL INFILE problems
The problem is a simple one. When I execute the following I get different results depending on whether I run it from the MySQL console and from inside a Python Script using MySQLdb: LOAD DATA LOCAL INFILE '/tmp/source.csv' INTO TABLE test FIELDS TERMINATED BY '|' IGNORE 1 LINES; Console gives the following results: Records: 35002 Deleted: 0 Skipped: 0 Warnings: 0 Python (via .info()) returns the following: Records: 34977 Deleted: 0 Skipped: 0 Warnings: 8 So in summary, same source file, same SQL request, different results. From the console I can 'SHOW WARNINGS' an get a better handle on which records are causing the problems and why but from Python I can't idenitify how to do this or more importantly what the cause of the problem could be. Any suggestions? MySQL Server '5.1.41-3ubuntu12.1' Python '2.6.5' Tables are MyISAM
[ "After loading the data, execute\nSELECT @@warning_count;\n\ncheck if greater than 0.\nIf it is than execute\nSHOW WARNINGS;\n\nand dump the result (returns 3 columns: Level, Code, Message) or throw an exception.\nYou can execute both statements exactly like every other select * from ... query.\n" ]
[ 1 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0002922535_mysql_python.txt
Q: Python time objects with more than 24 hours I have a time out of Linux that is in hh:mm:sec, but the hh can be greater than 24 hours. So if the time is 1 day 12 hours, it would be 36:00:00. Is there a way to take this format and easily make a time object? What I would really like to do is take the the required time i.e. 36:00:00, and the time that it has been running 4:46:23, and subtract the two to get the time remaining. I figured time delta might be the most convenient way to do this in Python, but I'd also be open to other suggestions. Thanks. A: timedelta is indeed what you want. Here is a more complete example that does what you asked. >>> import datetime >>> a = datetime.timedelta(hours=36) >>> b = datetime.timedelta(hours=4, minutes=46, seconds=23) >>> c = a - b >>> print c 1 day, 7:13:37 A: What you need is the timedelta object: http://docs.python.org/library/datetime.html#timedelta-objects 36 hours: d = timedelta(hours=36)
Python time objects with more than 24 hours
I have a time out of Linux that is in hh:mm:sec, but the hh can be greater than 24 hours. So if the time is 1 day 12 hours, it would be 36:00:00. Is there a way to take this format and easily make a time object? What I would really like to do is take the the required time i.e. 36:00:00, and the time that it has been running 4:46:23, and subtract the two to get the time remaining. I figured time delta might be the most convenient way to do this in Python, but I'd also be open to other suggestions. Thanks.
[ "timedelta is indeed what you want. Here is a more complete example that does what you asked.\n>>> import datetime\n>>> a = datetime.timedelta(hours=36)\n>>> b = datetime.timedelta(hours=4, minutes=46, seconds=23)\n>>> c = a - b\n>>> print c\n1 day, 7:13:37\n\n", "What you need is the timedelta object: http://docs.python.org/library/datetime.html#timedelta-objects\n36 hours:\nd = timedelta(hours=36)\n\n" ]
[ 16, 10 ]
[]
[]
[ "python", "time", "timedelta" ]
stackoverflow_0002922735_python_time_timedelta.txt
Q: How do I do this in Python (File Manipulation)? I have a bunch of HTML files in HTML folder. Those HTML files have unicode characters which I solved by using filter(lambda x: x in string.printable, line). Now how do I write the changes back to the original file? What is the best way of doing it? Each HTML file is of 30 kb in size. 1 import os, string 2 3 for file in os.listdir("HTML/"): 4 print file 5 myfile = open('HTML/' + file) 6 fileList = myfile.readlines() 9 for line in fileList: 10 #print line 11 line = filter(lambda x: x in string.printable, line) 12 myfile.close() A: Use the fileinput module. It allows you to read and write to the same file in place: import fileinput,sys,os files=[os.path.join('HTML',filename) for filename in os.listdir("HTML/")] for line in fileinput.input(files, inplace=True): line = filter(lambda x: x in string.printable, line) sys.stdout.write(line) A: At first I didn't understand what @~unutbu was getting at, but after reading the documentation for fileinput module I found this, which I hadn't seen before (emphasis mine): Optional in-place filtering: if the keyword argument inplace=1 is passed to fileinput.input() or to the FileInput constructor, the file is moved to a backup file and standard output is directed to the input file (if a file of the same name as the backup file already exists, it will be replaced silently). This makes it possible to write a filter that rewrites its input file in place. If the backup parameter is given (typically as backup='.'), it specifies the extension for the backup file, and the backup file remains around; by default, the extension is '.bak' and it is deleted when the output file is closed. In-place filtering is disabled when standard input is read. So I think his answer is best, and this explains why. A: This should work on Linux; support on other operative systems is iffy (see below). import os, string for file in os.listdir("HTML/"): print file myfile = open('HTML/' + file) fileList = myfile.readlines() for pos, line in enumerate(fileList): line = filter(lambda x: x in string.printable, line) # see note 1 fileList[pos] = line myfile.close() myfile = open('HTML/' + file, "wz") # see note 2 myfile.write("\n".join(fileList)) Note 1. Simply assigning to line does not change fileList. Variables really are labels (references) onto objects: assigning to a label changes the object the label is attached to. That line creates a list which is then assigned Note 2. The "wz" file mode empties the file on opening (it should be the equivalent of the O_TRUNC flag when passed to open() ). It might not be available on platforms other than Linux.
How do I do this in Python (File Manipulation)?
I have a bunch of HTML files in HTML folder. Those HTML files have unicode characters which I solved by using filter(lambda x: x in string.printable, line). Now how do I write the changes back to the original file? What is the best way of doing it? Each HTML file is of 30 kb in size. 1 import os, string 2 3 for file in os.listdir("HTML/"): 4 print file 5 myfile = open('HTML/' + file) 6 fileList = myfile.readlines() 9 for line in fileList: 10 #print line 11 line = filter(lambda x: x in string.printable, line) 12 myfile.close()
[ "Use the fileinput module. It allows you to read and write to the same file in place:\nimport fileinput,sys,os\nfiles=[os.path.join('HTML',filename) for filename in os.listdir(\"HTML/\")]\nfor line in fileinput.input(files, inplace=True): \n line = filter(lambda x: x in string.printable, line)\n sys.stdout.write(line)\n\n", "At first I didn't understand what @~unutbu was getting at, but after reading the documentation for fileinput module I found this, which I hadn't seen before (emphasis mine):\n\nOptional in-place filtering: if the\n keyword argument inplace=1 is passed\n to fileinput.input() or to the\n FileInput constructor, the file is\n moved to a backup file and standard\n output is directed to the input file\n (if a file of the same name as the\n backup file already exists, it will be\n replaced silently). This makes it\n possible to write a filter that\n rewrites its input file in place. If\n the backup parameter is given\n (typically as backup='.'), it specifies the\n extension for the backup file, and the\n backup file remains around; by\n default, the extension is '.bak' and\n it is deleted when the output file is\n closed. In-place filtering is disabled\n when standard input is read.\n\nSo I think his answer is best, and this explains why.\n", "This should work on Linux; support on other operative systems is iffy (see below).\nimport os, string\n\nfor file in os.listdir(\"HTML/\"):\n print file\n myfile = open('HTML/' + file)\n fileList = myfile.readlines()\n for pos, line in enumerate(fileList):\n line = filter(lambda x: x in string.printable, line) # see note 1\n fileList[pos] = line \n myfile.close()\n myfile = open('HTML/' + file, \"wz\") # see note 2\n myfile.write(\"\\n\".join(fileList))\n\nNote 1. Simply assigning to line does not change fileList. Variables really are labels (references) onto objects: assigning to a label changes the object the label is attached to. That line creates a list which is then assigned\nNote 2. The \"wz\" file mode empties the file on opening (it should be the equivalent of the O_TRUNC flag when passed to open() ). It might not be available on platforms other than Linux.\n" ]
[ 3, 2, 0 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0002923310_file_io_python.txt
Q: Parse large XML file w/ script or use BioPython API? Hey guys this is my first question on here. I'm trying to make a local copy of the UniprotKB in SQL. The UniprotKB is 2.1GB, and it comes in XML and a special text format used by SwissProt Here are my options: 1) Use a SAX parser (XML) - I chose Ruby, and Nokogiri. I started writing the parser, but my initial reaction: how would I map the XML schema to the SAX parser? 2) BioPython - I already have BioSQL/Biopython installed, which literally created my SQL schema for me, and I was able to successfully insert one SwissProt/Uniprot txt file into the database. I'm running it right now (crosses fingers) on the entire 2.1gb. Here is the code I'm running: from Bio import SeqIO from BioSQL import BioSeqDatabase from Bio import SwissProt server = BioSeqDatabase.open_database(driver = "MySQLdb", user = "root", passwd = "", host="localhost", db = "bioseqdb") db = server["uniprot"] iterator = SeqIO.parse(open("/path/to/uniprot_sprot.dat", "r"), "swiss") db.load(iterator) server.commit() Edit: it's now crashing because the transactions are getting locked (since the tables are Innodb) Error Number: 1205 Lock wait timeout exceeded; try restarting transaction. I'm using MySQL version: 5.1.43 Should I switch my database to Postgrelsql ? A: Switched to PostgrelSQL for convenience purposes. Some of the issues were resolved by downloading the NCBI taxonomy information (which I did not know was necessary, should have been more clear in the documentation), so I ended up using the Swiss parser from BioPython because it fits so nicely with BioSQL.
Parse large XML file w/ script or use BioPython API?
Hey guys this is my first question on here. I'm trying to make a local copy of the UniprotKB in SQL. The UniprotKB is 2.1GB, and it comes in XML and a special text format used by SwissProt Here are my options: 1) Use a SAX parser (XML) - I chose Ruby, and Nokogiri. I started writing the parser, but my initial reaction: how would I map the XML schema to the SAX parser? 2) BioPython - I already have BioSQL/Biopython installed, which literally created my SQL schema for me, and I was able to successfully insert one SwissProt/Uniprot txt file into the database. I'm running it right now (crosses fingers) on the entire 2.1gb. Here is the code I'm running: from Bio import SeqIO from BioSQL import BioSeqDatabase from Bio import SwissProt server = BioSeqDatabase.open_database(driver = "MySQLdb", user = "root", passwd = "", host="localhost", db = "bioseqdb") db = server["uniprot"] iterator = SeqIO.parse(open("/path/to/uniprot_sprot.dat", "r"), "swiss") db.load(iterator) server.commit() Edit: it's now crashing because the transactions are getting locked (since the tables are Innodb) Error Number: 1205 Lock wait timeout exceeded; try restarting transaction. I'm using MySQL version: 5.1.43 Should I switch my database to Postgrelsql ?
[ "Switched to PostgrelSQL for convenience purposes. Some of the issues were resolved by downloading the NCBI taxonomy information (which I did not know was necessary, should have been more clear in the documentation), so I ended up using the Swiss parser from BioPython because it fits so nicely with BioSQL. \n" ]
[ 0 ]
[]
[]
[ "bioinformatics", "python", "xml" ]
stackoverflow_0002915442_bioinformatics_python_xml.txt
Q: How can I connect to a mail server using SMTP over SSL using Python? So I have been having a hard time sending email from my school's email address. It is SSL and I could only find this code online by Matt Butcher that works with SSL: import smtplib, socket __version__ = "1.00" __all__ = ['SMTPSSLException', 'SMTP_SSL'] SSMTP_PORT = 465 class SMTPSSLException(smtplib.SMTPException): """Base class for exceptions resulting from SSL negotiation.""" class SMTP_SSL (smtplib.SMTP): """This class provides SSL access to an SMTP server. SMTP over SSL typical listens on port 465. Unlike StartTLS, SMTP over SSL makes an SSL connection before doing a helo/ehlo. All transactions, then, are done over an encrypted channel. This class is a simple subclass of the smtplib.SMTP class that comes with Python. It overrides the connect() method to use an SSL socket, and it overrides the starttles() function to throw an error (you can't do starttls within an SSL session). """ certfile = None keyfile = None def __init__(self, host='', port=0, local_hostname=None, keyfile=None, certfile=None): """Initialize a new SSL SMTP object. If specified, `host' is the name of the remote host to which this object will connect. If specified, `port' specifies the port (on `host') to which this object will connect. `local_hostname' is the name of the localhost. By default, the value of socket.getfqdn() is used. An SMTPConnectError is raised if the SMTP host does not respond correctly. An SMTPSSLError is raised if SSL negotiation fails. Warning: This object uses socket.ssl(), which does not do client-side verification of the server's cert. """ self.certfile = certfile self.keyfile = keyfile smtplib.SMTP.__init__(self, host, port, local_hostname) def connect(self, host='localhost', port=0): """Connect to an SMTP server using SSL. `host' is localhost by default. Port will be set to 465 (the default SSL SMTP port) if no port is specified. If the host name ends with a colon (`:') followed by a number, that suffix will be stripped off and the number interpreted as the port number to use. This will override the `port' parameter. Note: This method is automatically invoked by __init__, if a host is specified during instantiation. """ # MB: Most of this (Except for the socket connection code) is from # the SMTP.connect() method. I changed only the bare minimum for the # sake of compatibility. if not port and (host.find(':') == host.rfind(':')): i = host.rfind(':') if i >= 0: host, port = host[:i], host[i+1:] try: port = int(port) except ValueError: raise socket.error, "nonnumeric port" if not port: port = SSMTP_PORT if self.debuglevel > 0: print>>stderr, 'connect:', (host, port) msg = "getaddrinfo returns an empty list" self.sock = None for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res try: self.sock = socket.socket(af, socktype, proto) if self.debuglevel > 0: print>>stderr, 'connect:', (host, port) self.sock.connect(sa) # MB: Make the SSL connection. sslobj = socket.ssl(self.sock, self.keyfile, self.certfile) except socket.error, msg: if self.debuglevel > 0: print>>stderr, 'connect fail:', (host, port) if self.sock: self.sock.close() self.sock = None continue break if not self.sock: raise socket.error, msg # MB: Now set up fake socket and fake file classes. # Thanks to the design of smtplib, this is all we need to do # to get SSL working with all other methods. self.sock = smtplib.SSLFakeSocket(self.sock, sslobj) self.file = smtplib.SSLFakeFile(sslobj); (code, msg) = self.getreply() if self.debuglevel > 0: print>>stderr, "connect:", msg return (code, msg) def setkeyfile(self, keyfile): """Set the absolute path to a file containing a private key. This method will only be effective if it is called before connect(). This key will be used to make the SSL connection.""" self.keyfile = keyfile def setcertfile(self, certfile): """Set the absolute path to a file containing a x.509 certificate. This method will only be effective if it is called before connect(). This certificate will be used to make the SSL connection.""" self.certfile = certfile def starttls(): """Raises an exception. You cannot do StartTLS inside of an ssl session. Calling starttls() will return an SMTPSSLException""" raise SMTPSSLException, "Cannot perform StartTLS within SSL session." And then my code: import ssmtplib conn = ssmtplib.SMTP_SSL('HOST') conn.login('USERNAME','PW') conn.ehlo() conn.sendmail('FROM_EMAIL', 'TO_EMAIL', "MESSAGE") conn.close() And got this error: /Users/Jake/Desktop/Beth's Program/ssmtplib.py:116: DeprecationWarning: socket.ssl() is deprecated. Use ssl.wrap_socket() instead. sslobj = socket.ssl(self.sock, self.keyfile, self.certfile) Traceback (most recent call last): File "emailer.py", line 5, in conn = ssmtplib.SMTP_SSL('HOST') File "/Users/Jake/Desktop/Beth's Program/ssmtplib.py", line 79, in init smtplib.SMTP.init(self, host, port, local_hostname) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/smtplib.py", line 239, in init (code, msg) = self.connect(host, port) File "/Users/Jake/Desktop/Beth's Program/ssmtplib.py", line 131, in connect self.sock = smtplib.SSLFakeSocket(self.sock, sslobj) AttributeError: 'module' object has no attribute 'SSLFakeSocket' Thank you! A: That code you've found seems to be for an older version, considering the deprecation warning. Maybe you can get by with the stdlib: There is a SMTP_SSL class as of Python 2.6, and as of at least 2.4 there is a starttls method on the plaintext SMTP class.
How can I connect to a mail server using SMTP over SSL using Python?
So I have been having a hard time sending email from my school's email address. It is SSL and I could only find this code online by Matt Butcher that works with SSL: import smtplib, socket __version__ = "1.00" __all__ = ['SMTPSSLException', 'SMTP_SSL'] SSMTP_PORT = 465 class SMTPSSLException(smtplib.SMTPException): """Base class for exceptions resulting from SSL negotiation.""" class SMTP_SSL (smtplib.SMTP): """This class provides SSL access to an SMTP server. SMTP over SSL typical listens on port 465. Unlike StartTLS, SMTP over SSL makes an SSL connection before doing a helo/ehlo. All transactions, then, are done over an encrypted channel. This class is a simple subclass of the smtplib.SMTP class that comes with Python. It overrides the connect() method to use an SSL socket, and it overrides the starttles() function to throw an error (you can't do starttls within an SSL session). """ certfile = None keyfile = None def __init__(self, host='', port=0, local_hostname=None, keyfile=None, certfile=None): """Initialize a new SSL SMTP object. If specified, `host' is the name of the remote host to which this object will connect. If specified, `port' specifies the port (on `host') to which this object will connect. `local_hostname' is the name of the localhost. By default, the value of socket.getfqdn() is used. An SMTPConnectError is raised if the SMTP host does not respond correctly. An SMTPSSLError is raised if SSL negotiation fails. Warning: This object uses socket.ssl(), which does not do client-side verification of the server's cert. """ self.certfile = certfile self.keyfile = keyfile smtplib.SMTP.__init__(self, host, port, local_hostname) def connect(self, host='localhost', port=0): """Connect to an SMTP server using SSL. `host' is localhost by default. Port will be set to 465 (the default SSL SMTP port) if no port is specified. If the host name ends with a colon (`:') followed by a number, that suffix will be stripped off and the number interpreted as the port number to use. This will override the `port' parameter. Note: This method is automatically invoked by __init__, if a host is specified during instantiation. """ # MB: Most of this (Except for the socket connection code) is from # the SMTP.connect() method. I changed only the bare minimum for the # sake of compatibility. if not port and (host.find(':') == host.rfind(':')): i = host.rfind(':') if i >= 0: host, port = host[:i], host[i+1:] try: port = int(port) except ValueError: raise socket.error, "nonnumeric port" if not port: port = SSMTP_PORT if self.debuglevel > 0: print>>stderr, 'connect:', (host, port) msg = "getaddrinfo returns an empty list" self.sock = None for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res try: self.sock = socket.socket(af, socktype, proto) if self.debuglevel > 0: print>>stderr, 'connect:', (host, port) self.sock.connect(sa) # MB: Make the SSL connection. sslobj = socket.ssl(self.sock, self.keyfile, self.certfile) except socket.error, msg: if self.debuglevel > 0: print>>stderr, 'connect fail:', (host, port) if self.sock: self.sock.close() self.sock = None continue break if not self.sock: raise socket.error, msg # MB: Now set up fake socket and fake file classes. # Thanks to the design of smtplib, this is all we need to do # to get SSL working with all other methods. self.sock = smtplib.SSLFakeSocket(self.sock, sslobj) self.file = smtplib.SSLFakeFile(sslobj); (code, msg) = self.getreply() if self.debuglevel > 0: print>>stderr, "connect:", msg return (code, msg) def setkeyfile(self, keyfile): """Set the absolute path to a file containing a private key. This method will only be effective if it is called before connect(). This key will be used to make the SSL connection.""" self.keyfile = keyfile def setcertfile(self, certfile): """Set the absolute path to a file containing a x.509 certificate. This method will only be effective if it is called before connect(). This certificate will be used to make the SSL connection.""" self.certfile = certfile def starttls(): """Raises an exception. You cannot do StartTLS inside of an ssl session. Calling starttls() will return an SMTPSSLException""" raise SMTPSSLException, "Cannot perform StartTLS within SSL session." And then my code: import ssmtplib conn = ssmtplib.SMTP_SSL('HOST') conn.login('USERNAME','PW') conn.ehlo() conn.sendmail('FROM_EMAIL', 'TO_EMAIL', "MESSAGE") conn.close() And got this error: /Users/Jake/Desktop/Beth's Program/ssmtplib.py:116: DeprecationWarning: socket.ssl() is deprecated. Use ssl.wrap_socket() instead. sslobj = socket.ssl(self.sock, self.keyfile, self.certfile) Traceback (most recent call last): File "emailer.py", line 5, in conn = ssmtplib.SMTP_SSL('HOST') File "/Users/Jake/Desktop/Beth's Program/ssmtplib.py", line 79, in init smtplib.SMTP.init(self, host, port, local_hostname) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/smtplib.py", line 239, in init (code, msg) = self.connect(host, port) File "/Users/Jake/Desktop/Beth's Program/ssmtplib.py", line 131, in connect self.sock = smtplib.SSLFakeSocket(self.sock, sslobj) AttributeError: 'module' object has no attribute 'SSLFakeSocket' Thank you!
[ "That code you've found seems to be for an older version, considering the deprecation warning. Maybe you can get by with the stdlib: There is a SMTP_SSL class as of Python 2.6, and as of at least 2.4 there is a starttls method on the plaintext SMTP class.\n" ]
[ 1 ]
[]
[]
[ "email", "python", "smtp", "ssl" ]
stackoverflow_0002923561_email_python_smtp_ssl.txt
Q: How to store wiki sites (vcs) as a personal project I am trying to write a wiki with the help of django. I'm a beginner when it comes to web development. I am at the (early) point where I need to decide how to store the wiki sites. I have three approaches in mind and would like to know your suggestion. Flat files I considered a flat file approach with a version control system like git or mercurial. Firstly, I would have some example wikis to look at like http://hatta.sheep.art.pl/. Secondly, the vcs would probably deal with editing conflicts and keeping the edit history, so I would not have to reinvent the wheel. And thirdly, I could probably easily clone the wiki repository, so I (or for that matter others) can have an offline copy of the wiki. On the other hand, as far as I know, I can not use django models with flat files. Then, if I wanted to add fields to a wiki site, like a category, I would need to somehow keep a reference to that flat file in order to associate the fields in the database with the flat file. Besides, I don't know if it is a good idea to have all the wiki sites in one repository. I imagine it is more natural to have kind of like a repository per wiki site resp. file. Last but not least, I'm not sure, but I think using flat files would limit my deploying capabilities because web hosts maybe don't allow creating files (I'm thinking, for example, of Google App Engine) Storing in a database By storing the wiki sites in the database I can utilize django models and associate arbitrary fields with the wiki site. I probably would also have an easier life deploying the wiki. But I would not get vcs features like history and conflict resolving per se. I searched for django-extensions to help me and I found django-reversion. However, I do not fully understand if it fit my needs. Does it track model changes like for example if I change the django model file, or does it track the content of the models (which would fit my need). Plus, I do not see if django reversion would help me with edit conflicts. Storing a vcs repository in a database field This would be my ideal solution. It would combine the advantages of both previous approaches without the disadvantages. That is; I would have vcs features but I would save the wiki sites in a database. The problem is: I have no idea how feasible that is. I just imagine saving a wiki site/source together with a git/mercurial repository in a database field. Yet, I somehow doubt database fields work like that. So, I'm open for any other approaches but this is what I came up with. Also, if you're interested, you can find the crappy early test I'm working on here http://github.com/eugenkiss/instantwiki-test A: In none of your choices have you considered whether you wish to be able to search your wiki. If this is a consideration, having the 'live' copy of each page in a database with full text search would be hugely beneficial. For this reason, I would personally go with storing the pages in a database every time - otherwise you'll have to create your own index somewhere. As far as version logging goes, you only need store the live copy in an indexable format. You could automatically create a history item within your 'page' model when an changed page is written back to the database. You can cut down on the storage overhead of earlier page revisions by compressing the data, should this become necessary. If you're expecting a massive amount of change logging, you might want to read this answer here: How does one store history of edits effectively? A: Creating a wiki is fun and rewarding, but there are a lot of prebuilt wiki software packages already. I suggest Wikipedia's List of wiki software. In particular, MoinMoin and Trac are good. Finally, John Sutherland has made a wiki using Django.
How to store wiki sites (vcs)
as a personal project I am trying to write a wiki with the help of django. I'm a beginner when it comes to web development. I am at the (early) point where I need to decide how to store the wiki sites. I have three approaches in mind and would like to know your suggestion. Flat files I considered a flat file approach with a version control system like git or mercurial. Firstly, I would have some example wikis to look at like http://hatta.sheep.art.pl/. Secondly, the vcs would probably deal with editing conflicts and keeping the edit history, so I would not have to reinvent the wheel. And thirdly, I could probably easily clone the wiki repository, so I (or for that matter others) can have an offline copy of the wiki. On the other hand, as far as I know, I can not use django models with flat files. Then, if I wanted to add fields to a wiki site, like a category, I would need to somehow keep a reference to that flat file in order to associate the fields in the database with the flat file. Besides, I don't know if it is a good idea to have all the wiki sites in one repository. I imagine it is more natural to have kind of like a repository per wiki site resp. file. Last but not least, I'm not sure, but I think using flat files would limit my deploying capabilities because web hosts maybe don't allow creating files (I'm thinking, for example, of Google App Engine) Storing in a database By storing the wiki sites in the database I can utilize django models and associate arbitrary fields with the wiki site. I probably would also have an easier life deploying the wiki. But I would not get vcs features like history and conflict resolving per se. I searched for django-extensions to help me and I found django-reversion. However, I do not fully understand if it fit my needs. Does it track model changes like for example if I change the django model file, or does it track the content of the models (which would fit my need). Plus, I do not see if django reversion would help me with edit conflicts. Storing a vcs repository in a database field This would be my ideal solution. It would combine the advantages of both previous approaches without the disadvantages. That is; I would have vcs features but I would save the wiki sites in a database. The problem is: I have no idea how feasible that is. I just imagine saving a wiki site/source together with a git/mercurial repository in a database field. Yet, I somehow doubt database fields work like that. So, I'm open for any other approaches but this is what I came up with. Also, if you're interested, you can find the crappy early test I'm working on here http://github.com/eugenkiss/instantwiki-test
[ "In none of your choices have you considered whether you wish to be able to search your wiki. If this is a consideration, having the 'live' copy of each page in a database with full text search would be hugely beneficial. For this reason, I would personally go with storing the pages in a database every time - otherwise you'll have to create your own index somewhere.\nAs far as version logging goes, you only need store the live copy in an indexable format. You could automatically create a history item within your 'page' model when an changed page is written back to the database. You can cut down on the storage overhead of earlier page revisions by compressing the data, should this become necessary.\nIf you're expecting a massive amount of change logging, you might want to read this answer here:\nHow does one store history of edits effectively?\n", "Creating a wiki is fun and rewarding, but there are a lot of prebuilt wiki software packages already. I suggest Wikipedia's List of wiki software. In particular, MoinMoin and Trac are good. Finally, John Sutherland has made a wiki using Django.\n" ]
[ 2, 0 ]
[]
[]
[ "database", "django", "python", "version_control", "wiki" ]
stackoverflow_0002893303_database_django_python_version_control_wiki.txt
Q: Howto install distribute for Python 3 I am trying to install distribute using ActivePython 3.1.2 on Windows. Running python distribute_setup.py as described on the cheese shop give me: No setuptools distribution found running install Traceback (most recent call last): File "setup.py", line 177, in scripts = scripts, File "C:\Dev\Python_x86\3.1\lib\distutils\core.py", line 149, in setup dist.run_commands() File "C:\Dev\Python_x86\3.1\lib\distutils\dist.py", line 919, in run_commands self.run_command(cmd) File "C:\Dev\Python_x86\3.1\lib\distutils\dist.py", line 938, in run_command cmd_obj.run() File "build\src\setuptools\command\install.py", line 73, in run self.do_egg_install() File "build\src\setuptools\command\install.py", line 82, in do_egg_install easy_install = self.distribution.get_command_class('easy_install') File "build\src\setuptools\dist.py", line 361, in get_command_class self.cmdclass[command] = cmdclass = ep.load() File "build\src\pkg_resources.py", line 1953, in load entry = import(self.module_name, globals(),globals(), ['name']) File "build\src\setuptools\command\easy_install.py", line 16, in from setuptools.sandbox import run_setup File "build\src\setuptools\sandbox.py", line 164, in fromlist=['name']).file) AttributeError: 'module' object has no attribute 'file' Something went wrong during the installation. See the error message above. Is there possibly an unknown dependency that I'm missing? Downloading the source tarball and executing python setup.py install produces the exact same output. Edit: Added the full stack trace for running the installer. A: So apparently the python.org version of Python3 is different from the ActiveState version of Python3. (You should file a bug to someone (I'm not sure to whom)) The fix I have (I'm not sure of all the repercussions) Download: http://pypi.python.org/packages/source/d/distribute/distribute-0.6.12.tar.gz#md5=5a52e961f8d8799d243fe8220f9d760e and then extracting it and modify: distribute-0.6.12\setuptools\sandbox.py:165 from: except ImportError: to except (ImportError, AttributeError): that will silence the error and allow you to run: python setup.py install It took me awhile to find a package from http://pypi.python.org/pypi?:action=browse&c=533&show=all that would actually install on either version of Python3. "files" was the first package, and since it installed I am pretty sure that easy_install is working for both copies of Python3. ...hope it works! (That's all I can help you with) A: this is a bug with Distribute http://bitbucket.org/tarek/distribute/issue/151 ... it should be fixed by next release (0.6.13). It is only reproducible with PyWin32 installed; and ActivePython comes bundled with PyWin32.
Howto install distribute for Python 3
I am trying to install distribute using ActivePython 3.1.2 on Windows. Running python distribute_setup.py as described on the cheese shop give me: No setuptools distribution found running install Traceback (most recent call last): File "setup.py", line 177, in scripts = scripts, File "C:\Dev\Python_x86\3.1\lib\distutils\core.py", line 149, in setup dist.run_commands() File "C:\Dev\Python_x86\3.1\lib\distutils\dist.py", line 919, in run_commands self.run_command(cmd) File "C:\Dev\Python_x86\3.1\lib\distutils\dist.py", line 938, in run_command cmd_obj.run() File "build\src\setuptools\command\install.py", line 73, in run self.do_egg_install() File "build\src\setuptools\command\install.py", line 82, in do_egg_install easy_install = self.distribution.get_command_class('easy_install') File "build\src\setuptools\dist.py", line 361, in get_command_class self.cmdclass[command] = cmdclass = ep.load() File "build\src\pkg_resources.py", line 1953, in load entry = import(self.module_name, globals(),globals(), ['name']) File "build\src\setuptools\command\easy_install.py", line 16, in from setuptools.sandbox import run_setup File "build\src\setuptools\sandbox.py", line 164, in fromlist=['name']).file) AttributeError: 'module' object has no attribute 'file' Something went wrong during the installation. See the error message above. Is there possibly an unknown dependency that I'm missing? Downloading the source tarball and executing python setup.py install produces the exact same output. Edit: Added the full stack trace for running the installer.
[ "So apparently the python.org version of Python3 is different from the ActiveState version of Python3. (You should file a bug to someone (I'm not sure to whom))\nThe fix I have (I'm not sure of all the repercussions)\nDownload:\nhttp://pypi.python.org/packages/source/d/distribute/distribute-0.6.12.tar.gz#md5=5a52e961f8d8799d243fe8220f9d760e\nand then extracting it and modify:\ndistribute-0.6.12\\setuptools\\sandbox.py:165\nfrom:\nexcept ImportError:\n\nto\nexcept (ImportError, AttributeError):\n\nthat will silence the error and allow you to run:\npython setup.py install\nIt took me awhile to find a package from http://pypi.python.org/pypi?:action=browse&c=533&show=all that would actually install on either version of Python3. \"files\" was the first package, and since it installed I am pretty sure that easy_install is working for both copies of Python3.\n...hope it works! (That's all I can help you with)\n", "this is a bug with Distribute http://bitbucket.org/tarek/distribute/issue/151 ... it should be fixed by next release (0.6.13). It is only reproducible with PyWin32 installed; and ActivePython comes bundled with PyWin32.\n" ]
[ 3, 3 ]
[]
[]
[ "distribute", "python", "python_3.x", "pywin32", "setuptools" ]
stackoverflow_0002831231_distribute_python_python_3.x_pywin32_setuptools.txt
Q: What does the star and doublestar operator mean in a function call? What does the * operator mean in Python, such as in code like zip(*x) or f(**k)? How is it handled internally in the interpreter? Does it affect performance at all? Is it fast or slow? When is it useful and when is it not? Should it be used in a function declaration or in a call? A: The single star * unpacks the sequence/collection into positional arguments, so you can do this: def sum(a, b): return a + b values = (1, 2) s = sum(*values) This will unpack the tuple so that it actually executes as: s = sum(1, 2) The double star ** does the same, only using a dictionary and thus named arguments: values = { 'a': 1, 'b': 2 } s = sum(**values) You can also combine: def sum(a, b, c, d): return a + b + c + d values1 = (1, 2) values2 = { 'c': 10, 'd': 15 } s = sum(*values1, **values2) will execute as: s = sum(1, 2, c=10, d=15) Also see section 4.7.4 - Unpacking Argument Lists of the Python documentation. Additionally you can define functions to take *x and **y arguments, this allows a function to accept any number of positional and/or named arguments that aren't specifically named in the declaration. Example: def sum(*values): s = 0 for v in values: s = s + v return s s = sum(1, 2, 3, 4, 5) or with **: def get_a(**values): return values['a'] s = get_a(a=1, b=2) # returns 1 this can allow you to specify a large number of optional parameters without having to declare them. And again, you can combine: def sum(*values, **options): s = 0 for i in values: s = s + i if "neg" in options: if options["neg"]: s = -s return s s = sum(1, 2, 3, 4, 5) # returns 15 s = sum(1, 2, 3, 4, 5, neg=True) # returns -15 s = sum(1, 2, 3, 4, 5, neg=False) # returns 15 A: In a function call the single star turns a list into seperate arguments (e.g. zip(*x) is the same as zip(x1,x2,x3) if x=[x1,x2,x3]) and the double star turns a dictionary into seperate keyword arguments (e.g. f(**k) is the same as f(x=my_x, y=my_y) if k = {'x':my_x, 'y':my_y}. In a function definition it's the other way around: the single star turns an arbitrary number of arguments into a list, and the double start turns an arbitrary number of keyword arguments into a dictionary. E.g. def foo(*x) means "foo takes an arbitrary number of arguments and they will be accessible through the list x (i.e. if the user calls foo(1,2,3), x will be [1,2,3])" and def bar(**k) means "bar takes an arbitrary number of keyword arguments and they will be accessible through the dictionary k (i.e. if the user calls bar(x=42, y=23), k will be {'x': 42, 'y': 23})". A: I find this particularly useful for when you want to 'store' a function call. For example, suppose I have some unit tests for a function 'add': def add(a, b): return a + b tests = { (1,4):5, (0, 0):0, (-1, 3):3 } for test, result in tests.items(): print 'test: adding', test, '==', result, '---', add(*test) == result There is no other way to call add, other than manually doing something like add(test[0], test[1]), which is ugly. Also, if there are a variable number of variables, the code could get pretty ugly with all the if-statements you would need. Another place this is useful is for defining Factory objects (objects that create objects for you). Suppose you have some class Factory, that makes Car objects and returns them. You could make it so that myFactory.make_car('red', 'bmw', '335ix') creates Car('red', 'bmw', '335ix'), then returns it. def make_car(*args): return Car(*args) This is also useful when you want to call a superclass' constructor. A: It is called the extended call syntax. From the documentation: If the syntax *expression appears in the function call, expression must evaluate to a sequence. Elements from this sequence are treated as if they were additional positional arguments; if there are positional arguments x1,..., xN, and expression evaluates to a sequence y1, ..., yM, this is equivalent to a call with M+N positional arguments x1, ..., xN, y1, ..., yM. and: If the syntax **expression appears in the function call, expression must evaluate to a mapping, the contents of which are treated as additional keyword arguments. In the case of a keyword appearing in both expression and as an explicit keyword argument, a TypeError exception is raised.
What does the star and doublestar operator mean in a function call?
What does the * operator mean in Python, such as in code like zip(*x) or f(**k)? How is it handled internally in the interpreter? Does it affect performance at all? Is it fast or slow? When is it useful and when is it not? Should it be used in a function declaration or in a call?
[ "The single star * unpacks the sequence/collection into positional arguments, so you can do this:\ndef sum(a, b):\n return a + b\n\nvalues = (1, 2)\n\ns = sum(*values)\n\nThis will unpack the tuple so that it actually executes as:\ns = sum(1, 2)\n\nThe double star ** does the same, only using a dictionary and thus named arguments:\nvalues = { 'a': 1, 'b': 2 }\ns = sum(**values)\n\nYou can also combine:\ndef sum(a, b, c, d):\n return a + b + c + d\n\nvalues1 = (1, 2)\nvalues2 = { 'c': 10, 'd': 15 }\ns = sum(*values1, **values2)\n\nwill execute as: \ns = sum(1, 2, c=10, d=15)\n\nAlso see section 4.7.4 - Unpacking Argument Lists of the Python documentation.\n\nAdditionally you can define functions to take *x and **y arguments, this allows a function to accept any number of positional and/or named arguments that aren't specifically named in the declaration.\nExample:\ndef sum(*values):\n s = 0\n for v in values:\n s = s + v\n return s\n\ns = sum(1, 2, 3, 4, 5)\n\nor with **:\ndef get_a(**values):\n return values['a']\n\ns = get_a(a=1, b=2) # returns 1\n\nthis can allow you to specify a large number of optional parameters without having to declare them.\nAnd again, you can combine:\ndef sum(*values, **options):\n s = 0\n for i in values:\n s = s + i\n if \"neg\" in options:\n if options[\"neg\"]:\n s = -s\n return s\n\ns = sum(1, 2, 3, 4, 5) # returns 15\ns = sum(1, 2, 3, 4, 5, neg=True) # returns -15\ns = sum(1, 2, 3, 4, 5, neg=False) # returns 15\n\n", "In a function call the single star turns a list into seperate arguments (e.g. zip(*x) is the same as zip(x1,x2,x3) if x=[x1,x2,x3]) and the double star turns a dictionary into seperate keyword arguments (e.g. f(**k) is the same as f(x=my_x, y=my_y) if k = {'x':my_x, 'y':my_y}.\nIn a function definition it's the other way around: the single star turns an arbitrary number of arguments into a list, and the double start turns an arbitrary number of keyword arguments into a dictionary. E.g. def foo(*x) means \"foo takes an arbitrary number of arguments and they will be accessible through the list x (i.e. if the user calls foo(1,2,3), x will be [1,2,3])\" and def bar(**k) means \"bar takes an arbitrary number of keyword arguments and they will be accessible through the dictionary k (i.e. if the user calls bar(x=42, y=23), k will be {'x': 42, 'y': 23})\".\n", "I find this particularly useful for when you want to 'store' a function call.\nFor example, suppose I have some unit tests for a function 'add':\ndef add(a, b): return a + b\ntests = { (1,4):5, (0, 0):0, (-1, 3):3 }\nfor test, result in tests.items():\n print 'test: adding', test, '==', result, '---', add(*test) == result\n\nThere is no other way to call add, other than manually doing something like add(test[0], test[1]), which is ugly. Also, if there are a variable number of variables, the code could get pretty ugly with all the if-statements you would need.\nAnother place this is useful is for defining Factory objects (objects that create objects for you).\nSuppose you have some class Factory, that makes Car objects and returns them.\nYou could make it so that myFactory.make_car('red', 'bmw', '335ix') creates Car('red', 'bmw', '335ix'), then returns it.\ndef make_car(*args):\n return Car(*args)\n\nThis is also useful when you want to call a superclass' constructor.\n", "It is called the extended call syntax. From the documentation:\n\nIf the syntax *expression appears in the function call, expression must evaluate to a sequence. Elements from this sequence are treated as if they were additional positional arguments; if there are positional arguments x1,..., xN, and expression evaluates to a sequence y1, ..., yM, this is equivalent to a call with M+N positional arguments x1, ..., xN, y1, ..., yM.\n\nand:\n\nIf the syntax **expression appears in the function call, expression must evaluate to a mapping, the contents of which are treated as additional keyword arguments. In the case of a keyword appearing in both expression and as an explicit keyword argument, a TypeError exception is raised.\n\n" ]
[ 1135, 25, 22, 19 ]
[]
[]
[ "argument_unpacking", "iterable_unpacking", "parameter_passing", "python", "syntax" ]
stackoverflow_0002921847_argument_unpacking_iterable_unpacking_parameter_passing_python_syntax.txt
Q: how to create plots (non-flash) with mouse-over info boxes on the fly for the web? I'm thinking about creating a tool to visualize scientific data on a website. For this, the user enters some query string and out comes a simple (x,y)-plot (similar to this) I know that using Matplotlib, one can generate graphics on the fly for python. However, this doesn't solve the need for some custom java-script code to display the info boxes. I also came across google chart tools, which are very close to what I need. The problem here is, that the code needs to be fetched from google, which my employer won't like. What would be the best OSS library for python, Java, PHP (or Java-script) out there to meet my requirements? Thanks, Chris A: If you need dynamic elements without flash or Java applet then JavaScript is the best choice. To create plots you could use HTML5 canvas element. Capturing mouse events is JS is trivial...
how to create plots (non-flash) with mouse-over info boxes on the fly for the web?
I'm thinking about creating a tool to visualize scientific data on a website. For this, the user enters some query string and out comes a simple (x,y)-plot (similar to this) I know that using Matplotlib, one can generate graphics on the fly for python. However, this doesn't solve the need for some custom java-script code to display the info boxes. I also came across google chart tools, which are very close to what I need. The problem here is, that the code needs to be fetched from google, which my employer won't like. What would be the best OSS library for python, Java, PHP (or Java-script) out there to meet my requirements? Thanks, Chris
[ "If you need dynamic elements without flash or Java applet then JavaScript is the best choice. To create plots you could use HTML5 canvas element.\nCapturing mouse events is JS is trivial... \n" ]
[ 0 ]
[]
[]
[ "html", "javascript", "plot", "python" ]
stackoverflow_0002924051_html_javascript_plot_python.txt
Q: Building a survey to put in a WordPress website using Python/Django So I've been given a task to build a survey to get data regarding time slot preferences of prospective students for a particular course. I know there are really quick solutions to this like Google Forms, SurveyMonkey, but since it's not unusually hard, I want to implement the survey myself in a totally new language as an opportunity to get started with it and also be able to customize and provide dynamic info to the users who are voting. Although I have done some stuff in PHP, C++, javascript, etc, I'm pretty new to Python+Django framework but it's something I've been meaning to get into since a long time ago. Initially, what I want is to make a grid with the days of the week as columns and time-durations as rows. In each cell I want to provide users a way to choose how strong (high/medium/low) their preference for this particular day+time is. I also want to show how many "votes" have already been cast for this particular preference because this will influence a lot in their decisions and as a result make this process easier when we are going to define the classes. I'll probably store the data in MySQL. Could anyone point me to some really good Python+Django tutorials for my particular purpose? Does anyone think I'm wasting my time with this trivial task by choosing new tools and that I should just use something I already know (like PHP) or a free service or plugin for Wordpress? Thanks! A: The Django book is a good starting point, together with the documentation on the Django site itself. Integrating it into Wordpress could be more complicated, if you need tight integration I would not use a different language. And in general I would never say that learing a new and different language is a waste of time, and Django is a pretty nice Framework. A: IF YOU WANT TO LEARN DJANGO itself: Some of the machinery you need It's part ot the basic tutorial you can find inside the official Django documentation: the Poll app. There is also a Django Survey project on google code IF YOU WANT A CLOUD (free or cheap) SERVICE: In this case I'd like to point you to Wufoo that is a very nice web form builder which have also a FREE plan with report and notifications (by mail, SMS or web hooks). It's very easy to integrate and the only hassle you will get is to retrieve the poll results from them. They provide a lot of way to export them and offer also a very simple API.
Building a survey to put in a WordPress website using Python/Django
So I've been given a task to build a survey to get data regarding time slot preferences of prospective students for a particular course. I know there are really quick solutions to this like Google Forms, SurveyMonkey, but since it's not unusually hard, I want to implement the survey myself in a totally new language as an opportunity to get started with it and also be able to customize and provide dynamic info to the users who are voting. Although I have done some stuff in PHP, C++, javascript, etc, I'm pretty new to Python+Django framework but it's something I've been meaning to get into since a long time ago. Initially, what I want is to make a grid with the days of the week as columns and time-durations as rows. In each cell I want to provide users a way to choose how strong (high/medium/low) their preference for this particular day+time is. I also want to show how many "votes" have already been cast for this particular preference because this will influence a lot in their decisions and as a result make this process easier when we are going to define the classes. I'll probably store the data in MySQL. Could anyone point me to some really good Python+Django tutorials for my particular purpose? Does anyone think I'm wasting my time with this trivial task by choosing new tools and that I should just use something I already know (like PHP) or a free service or plugin for Wordpress? Thanks!
[ "The Django book is a good starting point, together with the documentation on the Django site itself.\nIntegrating it into Wordpress could be more complicated, if you need tight integration I would not use a different language.\nAnd in general I would never say that learing a new and different language is a waste of time, and Django is a pretty nice Framework.\n", "IF YOU WANT TO LEARN DJANGO itself:\nSome of the machinery you need It's part ot the basic tutorial you can find inside the official Django documentation: the Poll app.\nThere is also a Django Survey project on google code\nIF YOU WANT A CLOUD (free or cheap) SERVICE:\nIn this case I'd like to point you to Wufoo that is a very nice web form builder which have also a FREE plan with report and notifications (by mail, SMS or web hooks). It's very easy to integrate and the only hassle you will get is to retrieve the poll results from them. They provide a lot of way to export them and offer also a very simple API.\n" ]
[ 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002924413_django_python.txt
Q: don't show on panel I am trying to write a simple aplication (a continuously changing label on a window on the upper left side of the screen) and I don't want it to be seen on panel but only on system tray.Because it will run for a long time. How can I do that? Thanks. PS: I am using python and pyqt on Linux. I tried SplashScreen but when I clicked on the window it disapears. I have a contexmenu on the window, so I must click on it.! http://www.qtcentre.org/attachment.php?attachmentid=4686&d=1274802065 A: I found the solution. I set the window flag as "Qt.Popup". Now there in no window on the panel.
don't show on panel
I am trying to write a simple aplication (a continuously changing label on a window on the upper left side of the screen) and I don't want it to be seen on panel but only on system tray.Because it will run for a long time. How can I do that? Thanks. PS: I am using python and pyqt on Linux. I tried SplashScreen but when I clicked on the window it disapears. I have a contexmenu on the window, so I must click on it.! http://www.qtcentre.org/attachment.php?attachmentid=4686&d=1274802065
[ "I found the solution. I set the window flag as \"Qt.Popup\". Now there in no window on the panel. \n" ]
[ 1 ]
[]
[]
[ "pyqt", "python", "qt" ]
stackoverflow_0002916245_pyqt_python_qt.txt
Q: IP address of domain on shared host I have domain on a shared hosting provider. How do I find the direct IP address of my domain using Python? Is it possible to post to a script on my domain using the IP address and not the website itself? Thanks. A: I guess the IP should be static so do you really need to look it up more than once? You need to specify the domain name so that the webserver knows which host configuration to use if you don't have a dedicated IP or your host is the default for that webserver A: import socket socket.gethostbyname("www.stackoverflow.com") '69.59.196.211' will get you the ip address (as a string) of your domain. However, if it's shared hosting I would think it highly unlikely that you'll be able to access your hosting via the ip - most likely you'll have something like Apache's VirtualHost Directive in place which limits you to only 'seeing' requests to your domain. Requests to the IP address will be served by some default configuration. Would very much depend on the nature of your hosting. A: A curious request ... To look up a domain name, do something like this: import socket ipaddress = socket.gethostbyname('www.bbc.co.uk') Regarding posting to the IP address: I don't think it would work in the normal way (like from a browser), because there will probably be many sites held under that address. But, I guess you could do it in a very manual way, using a programming language (e.g. Python), if you connected a client socket to the site's IP address, but still sent the website's name in the HTTP Host request header. I don't know if that poses more questions than it answers, and I don't know why you'd want to do either of the above, but there it is. Good luck!
IP address of domain on shared host
I have domain on a shared hosting provider. How do I find the direct IP address of my domain using Python? Is it possible to post to a script on my domain using the IP address and not the website itself? Thanks.
[ "\nI guess the IP should be static so do you really need to look it up more than once?\nYou need to specify the domain name so that the webserver knows which host configuration to use if you don't have a dedicated IP or your host is the default for that webserver\n\n", "import socket\nsocket.gethostbyname(\"www.stackoverflow.com\")\n'69.59.196.211'\n\nwill get you the ip address (as a string) of your domain.\nHowever, if it's shared hosting I would think it highly unlikely that you'll be able to access your hosting via the ip - most likely you'll have something like Apache's VirtualHost Directive in place which limits you to only 'seeing' requests to your domain. Requests to the IP address will be served by some default configuration.\nWould very much depend on the nature of your hosting.\n", "A curious request ...\nTo look up a domain name, do something like this:\nimport socket\nipaddress = socket.gethostbyname('www.bbc.co.uk')\n\nRegarding posting to the IP address: \nI don't think it would work in the normal way (like from a browser), because there will probably be many sites held under that address.\nBut, I guess you could do it in a very manual way, using a programming language (e.g. Python), if you connected a client socket to the site's IP address, but still sent the website's name in the HTTP Host request header.\nI don't know if that poses more questions than it answers, and I don't know why you'd want to do either of the above, but there it is.\nGood luck!\n" ]
[ 0, 0, 0 ]
[]
[]
[ "cgi", "python" ]
stackoverflow_0002924736_cgi_python.txt
Q: Python unicode problem I'm receiving some data from a ZODB (Zope Object Database). I receive a mybrains object. Then I do: o = mybrains.getObject() and I receive a "Person" object in my project. Then, I can do b = o.name and doing print b on my class I get: José Carlos and print b.name.__class__ <type 'unicode'> I have a lot of "Person" objects. They are added to a list. names = [o.nome, o1.nome, o2.nome] Then, I trying to create a text file with this data. delimiter = ';' all = delimiter.join(names) + '\n' No problem. Now, when I do a print all I have: José Carlos;Jonas;Natália Juan;John But when I try to create a file of it: f = open("/tmp/test.txt", "w") f.write(all) I get an error like this (the positions aren't exaclty the same, since I change the names) UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 84: ordinal not in range(128) If I can print already with the "correct" form to display it, why I can't write a file with it? Which encode/decode method should I use to write a file with this data? I'm using Python 2.4.5 (can't upgrade it) A: UnicodeEncodeError: 'ascii' codec write is trying to encode the string using the ascii codec (which doesn't have a way of encoding accented characters like é or à. Instead use import codecs with codecs.open("/tmp/test.txt",'w',encoding='utf-8') as f: f.write(all.decode('utf-8')) or choose some other codec (like cp1252) which can encode the characters in your string. PS. all.decode('utf-8') was used above because f.write expects a unicode string. Better than using all.decode('utf-8') would be to convert all your strings to unicode early, work in unicode, and encode to a specific encoding like 'utf-8' late -- only when you have to. PPS. It looks like names might already be a list of unicode strings. In that case, define delimiter to be a unicode string too: delimiter = u';', so all will be a unicode string. Then with codecs.open("/tmp/test.txt",'w',encoding='utf-8') as f: f.write(all) should work (unless there is some issue with Python 2.4 that I'm not aware of.) If 'utf-8' does not work, remember to try other encodings that contain the characters you need, and that your computer knows about. On Windows, that might mean 'cp1252'. A: You told Python to print all, but since all has no fixed computer representation, Python first had to convert all to some printable form. Since you didn't tell Python how to do the conversion, it assumed you wanted ASCII. Unfortunately, ASCII can only handle values from 0 to 127, and all contains values out of that range, hence you see an error. To fix this use: all = "José Carlos;Jonas;Natália Juan;John" import codecs f = codecs.open("/tmp/test.txt", "w", "utf-8") f.write(all.decode("utf-8")) f.close()
Python unicode problem
I'm receiving some data from a ZODB (Zope Object Database). I receive a mybrains object. Then I do: o = mybrains.getObject() and I receive a "Person" object in my project. Then, I can do b = o.name and doing print b on my class I get: José Carlos and print b.name.__class__ <type 'unicode'> I have a lot of "Person" objects. They are added to a list. names = [o.nome, o1.nome, o2.nome] Then, I trying to create a text file with this data. delimiter = ';' all = delimiter.join(names) + '\n' No problem. Now, when I do a print all I have: José Carlos;Jonas;Natália Juan;John But when I try to create a file of it: f = open("/tmp/test.txt", "w") f.write(all) I get an error like this (the positions aren't exaclty the same, since I change the names) UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 84: ordinal not in range(128) If I can print already with the "correct" form to display it, why I can't write a file with it? Which encode/decode method should I use to write a file with this data? I'm using Python 2.4.5 (can't upgrade it)
[ "\nUnicodeEncodeError: 'ascii' codec\n\nwrite is trying to encode the string using the ascii codec (which doesn't have a way of encoding accented characters like é or à.\nInstead use\nimport codecs\nwith codecs.open(\"/tmp/test.txt\",'w',encoding='utf-8') as f: \n f.write(all.decode('utf-8'))\n\nor choose some other codec (like cp1252) which can encode the characters in your string.\nPS. all.decode('utf-8') was used above because f.write expects a unicode string. Better than using all.decode('utf-8') would be to convert all your strings to unicode early, work in unicode, and encode to a specific encoding like 'utf-8' late -- only when you have to.\nPPS. It looks like names might already be a list of unicode strings. In that case, define delimiter to be a unicode string too: delimiter = u';', so all will be a unicode string. Then \nwith codecs.open(\"/tmp/test.txt\",'w',encoding='utf-8') as f: \n f.write(all)\n\nshould work (unless there is some issue with Python 2.4 that I'm not aware of.)\nIf 'utf-8' does not work, remember to try other encodings that contain the characters you need, and that your computer knows about. On Windows, that might mean 'cp1252'.\n", "You told Python to print all, but since all has no fixed computer representation, Python first had to convert all to some printable form. Since you didn't tell Python how to do the conversion, it assumed you wanted ASCII. Unfortunately, ASCII can only handle values from 0 to 127, and all contains values out of that range, hence you see an error.\nTo fix this use:\nall = \"José Carlos;Jonas;Natália Juan;John\"\nimport codecs\nf = codecs.open(\"/tmp/test.txt\", \"w\", \"utf-8\")\nf.write(all.decode(\"utf-8\"))\nf.close()\n\n" ]
[ 3, 0 ]
[]
[]
[ "file_io", "python", "unicode" ]
stackoverflow_0002924792_file_io_python_unicode.txt
Q: Python Four steps setup with progressBars I'm having a problem with the code below. When I run it the progress bar will pulse for around 10 secs as meant to and then move on to downloading and will show the progress but when finished it will not move on to the next step it just locks up. import sys import time import pygtk import gtk import gobject import threading import urllib import urlparse class WorkerThread(threading.Thread): def __init__ (self, function, parent, arg = None): threading.Thread.__init__(self) self.function = function self.parent = parent self.arg = arg self.parent.still_working = True def run(self): # when does "run" get executed? self.parent.still_working = True if self.arg == None: self.function() else: self.function(self.arg) self.parent.still_working = False def stop(self): self = None class MainWindow: def __init__(self): gtk.gdk.threads_init() self.wTree = gtk.Builder() self.wTree.add_from_file("gui.glade") self.mainWindows() def mainWindows(self): self.mainWindow = self.wTree.get_object("frmMain") dic = { "on_btnNext_clicked" : self.mainWindowNext, } self.wTree.connect_signals(dic) self.mainWindow.show() self.installerStep = 0 # 0 = none, 1 = preinstall, 2 = download, 3 = install info, 4 = install #gtk.main() self.mainWindowNext() def pulse(self): self.wTree.get_object("progress").pulse() if self.still_working == False: self.mainWindowNext() return self.still_working def preinstallStep(self): self.wTree.get_object("progress").set_fraction(0) self.wTree.get_object("btnNext").set_sensitive(0) self.wTree.get_object("notebook1").set_current_page(0) self.installerStep = 1 WT = WorkerThread(self.heavyWork, self) #Would do a heavy function here like setup some thing WT.start() gobject.timeout_add(75, self.pulse) def downloadStep(self): self.wTree.get_object("progress").set_fraction(0) self.wTree.get_object("btnNext").set_sensitive(0) self.wTree.get_object("notebook1").set_current_page(0) self.installerStep = 2 urllib.urlretrieve('http://mozilla.mirrors.evolva.ro//firefox/releases/3.6.3/win32/en-US/Firefox%20Setup%203.6.3.exe', '/tmp/firefox.exe', self.updateHook) self.mainWindowNext() def updateHook(self, blocks, blockSize, totalSize): percentage = float ( blocks * blockSize ) / totalSize if percentage > 1: percentage = 1 self.wTree.get_object("progress").set_fraction(percentage) while gtk.events_pending(): gtk.main_iteration() def installInfoStep(self): self.wTree.get_object("btnNext").set_sensitive(1) self.wTree.get_object("notebook1").set_current_page(1) self.installerStep = 3 def installStep(self): self.wTree.get_object("progress").set_fraction(0) self.wTree.get_object("btnNext").set_sensitive(0) self.wTree.get_object("notebook1").set_current_page(0) self.installerStep = 4 WT = WorkerThread(self.heavyWork, self) #Would do a heavy function here like setup some thing WT.start() gobject.timeout_add(75, self.pulse) def mainWindowNext(self, widget = None): if self.installerStep == 0: self.preinstallStep() elif self.installerStep == 1: self.downloadStep() elif self.installerStep == 2: self.installInfoStep() elif self.installerStep == 3: self.installStep() elif self.installerStep == 4: sys.exit(0) def heavyWork(self): time.sleep(10) if __name__ == '__main__': MainWindow() gtk.main() I have a feeling that its something to do with: while gtk.events_pending(): gtk.main_iteration() Is there a better way of doing this? A: Don't ever do this: while gtk.events_pending(): gtk.main_iteration() Unless you really know what you are doing. And if you really do, do it like this: def refresh_gui(delay=0.0001, wait=0.0001): """Use up all the events waiting to be run :param delay: Time to wait before using events :param wait: Time to wait between iterations of events This function will block until all pending events are emitted. This is useful in testing to ensure signals and other asynchronous functionality is required to take place. (c) PyGTKHelpers Authors 2005-2010 """ time.sleep(delay) while gtk.events_pending(): gtk.main_iteration_do(block=False) time.sleep(wait) using block=False and some delays. If you want to use threads, I personally wouldn't recommend subclassing Thread like that (there is no point), instead, I would advise an approach like this which has an example of updating a progress bar.
Python Four steps setup with progressBars
I'm having a problem with the code below. When I run it the progress bar will pulse for around 10 secs as meant to and then move on to downloading and will show the progress but when finished it will not move on to the next step it just locks up. import sys import time import pygtk import gtk import gobject import threading import urllib import urlparse class WorkerThread(threading.Thread): def __init__ (self, function, parent, arg = None): threading.Thread.__init__(self) self.function = function self.parent = parent self.arg = arg self.parent.still_working = True def run(self): # when does "run" get executed? self.parent.still_working = True if self.arg == None: self.function() else: self.function(self.arg) self.parent.still_working = False def stop(self): self = None class MainWindow: def __init__(self): gtk.gdk.threads_init() self.wTree = gtk.Builder() self.wTree.add_from_file("gui.glade") self.mainWindows() def mainWindows(self): self.mainWindow = self.wTree.get_object("frmMain") dic = { "on_btnNext_clicked" : self.mainWindowNext, } self.wTree.connect_signals(dic) self.mainWindow.show() self.installerStep = 0 # 0 = none, 1 = preinstall, 2 = download, 3 = install info, 4 = install #gtk.main() self.mainWindowNext() def pulse(self): self.wTree.get_object("progress").pulse() if self.still_working == False: self.mainWindowNext() return self.still_working def preinstallStep(self): self.wTree.get_object("progress").set_fraction(0) self.wTree.get_object("btnNext").set_sensitive(0) self.wTree.get_object("notebook1").set_current_page(0) self.installerStep = 1 WT = WorkerThread(self.heavyWork, self) #Would do a heavy function here like setup some thing WT.start() gobject.timeout_add(75, self.pulse) def downloadStep(self): self.wTree.get_object("progress").set_fraction(0) self.wTree.get_object("btnNext").set_sensitive(0) self.wTree.get_object("notebook1").set_current_page(0) self.installerStep = 2 urllib.urlretrieve('http://mozilla.mirrors.evolva.ro//firefox/releases/3.6.3/win32/en-US/Firefox%20Setup%203.6.3.exe', '/tmp/firefox.exe', self.updateHook) self.mainWindowNext() def updateHook(self, blocks, blockSize, totalSize): percentage = float ( blocks * blockSize ) / totalSize if percentage > 1: percentage = 1 self.wTree.get_object("progress").set_fraction(percentage) while gtk.events_pending(): gtk.main_iteration() def installInfoStep(self): self.wTree.get_object("btnNext").set_sensitive(1) self.wTree.get_object("notebook1").set_current_page(1) self.installerStep = 3 def installStep(self): self.wTree.get_object("progress").set_fraction(0) self.wTree.get_object("btnNext").set_sensitive(0) self.wTree.get_object("notebook1").set_current_page(0) self.installerStep = 4 WT = WorkerThread(self.heavyWork, self) #Would do a heavy function here like setup some thing WT.start() gobject.timeout_add(75, self.pulse) def mainWindowNext(self, widget = None): if self.installerStep == 0: self.preinstallStep() elif self.installerStep == 1: self.downloadStep() elif self.installerStep == 2: self.installInfoStep() elif self.installerStep == 3: self.installStep() elif self.installerStep == 4: sys.exit(0) def heavyWork(self): time.sleep(10) if __name__ == '__main__': MainWindow() gtk.main() I have a feeling that its something to do with: while gtk.events_pending(): gtk.main_iteration() Is there a better way of doing this?
[ "Don't ever do this:\nwhile gtk.events_pending():\n gtk.main_iteration()\n\nUnless you really know what you are doing. And if you really do, do it like this:\ndef refresh_gui(delay=0.0001, wait=0.0001):\n \"\"\"Use up all the events waiting to be run\n\n :param delay: Time to wait before using events\n :param wait: Time to wait between iterations of events\n\n This function will block until all pending events are emitted. This is\n useful in testing to ensure signals and other asynchronous functionality\n is required to take place.\n\n (c) PyGTKHelpers Authors 2005-2010\n \"\"\"\n time.sleep(delay)\n while gtk.events_pending():\n gtk.main_iteration_do(block=False)\n time.sleep(wait)\n\nusing block=False and some delays.\nIf you want to use threads, I personally wouldn't recommend subclassing Thread like that (there is no point), instead, I would advise an approach like this which has an example of updating a progress bar.\n" ]
[ 1 ]
[]
[]
[ "multithreading", "progress_bar", "pygtk", "python" ]
stackoverflow_0002844902_multithreading_progress_bar_pygtk_python.txt
Q: Python matching some characters into a string I'm trying to extract/match data from a string using regular expression but I don't seem to get it. I wan't to extract from the following string the i386 (The text between the last - and .iso): /xubuntu/daily/current/lucid-alternate-i386.iso This should also work in case of: /xubuntu/daily/current/lucid-alternate-amd64.iso And the result should be either i386 or amd64 given the case. Thanks a lot for your help. A: You could also use split in this case (instead of regex): >>> str = "/xubuntu/daily/current/lucid-alternate-i386.iso" >>> str.split(".iso")[0].split("-")[-1] 'i386' split gives you a list of elements on which your string got 'split'. Then using Python's slicing syntax you can get to the appropriate parts. A: r"/([^-]*)\.iso/" The bit you want will be in the first capture group. A: First off, let's make our life simpler and only get the file name. >>> os.path.split("/xubuntu/daily/current/lucid-alternate-i386.iso") ('/xubuntu/daily/current', 'lucid-alternate-i386.iso') Now it's just a matter of catching all the letters between the last dash and the '.iso'. A: If you will be matching several of these lines using re.compile() and saving the resulting regular expression object for reuse is more efficient. s1 = "/xubuntu/daily/current/lucid-alternate-i386.iso" s2 = "/xubuntu/daily/current/lucid-alternate-amd64.iso" pattern = re.compile(r'^.+-(.+)\..+$') m = pattern.match(s1) m.group(1) 'i386' m = pattern.match(s2) m.group(1) 'amd64' A: The expression should be without the leading trailing slashes. import re line = '/xubuntu/daily/current/lucid-alternate-i386.iso' rex = re.compile(r"([^-]*)\.iso") m = rex.search(line) print m.group(1) Yields 'i386' A: reobj = re.compile(r"(\w+)\.iso$") match = reobj.search(subject) if match: result = match.group(1) else: result = "" Subject contains the filename and path. A: >>> import os >>> path = "/xubuntu/daily/current/lucid-alternate-i386.iso" >>> file, ext = os.path.splitext(os.path.split(path)[1]) >>> processor = file[file.rfind("-") + 1:] >>> processor 'i386'
Python matching some characters into a string
I'm trying to extract/match data from a string using regular expression but I don't seem to get it. I wan't to extract from the following string the i386 (The text between the last - and .iso): /xubuntu/daily/current/lucid-alternate-i386.iso This should also work in case of: /xubuntu/daily/current/lucid-alternate-amd64.iso And the result should be either i386 or amd64 given the case. Thanks a lot for your help.
[ "You could also use split in this case (instead of regex):\n>>> str = \"/xubuntu/daily/current/lucid-alternate-i386.iso\"\n>>> str.split(\".iso\")[0].split(\"-\")[-1]\n'i386'\n\nsplit gives you a list of elements on which your string got 'split'. Then using Python's slicing syntax you can get to the appropriate parts.\n", "r\"/([^-]*)\\.iso/\"\n\nThe bit you want will be in the first capture group.\n", "First off, let's make our life simpler and only get the file name.\n>>> os.path.split(\"/xubuntu/daily/current/lucid-alternate-i386.iso\")\n('/xubuntu/daily/current', 'lucid-alternate-i386.iso')\n\nNow it's just a matter of catching all the letters between the last dash and the '.iso'.\n", "If you will be matching several of these lines using re.compile() and saving the resulting regular expression object for reuse is more efficient.\ns1 = \"/xubuntu/daily/current/lucid-alternate-i386.iso\"\ns2 = \"/xubuntu/daily/current/lucid-alternate-amd64.iso\"\n\npattern = re.compile(r'^.+-(.+)\\..+$')\n\nm = pattern.match(s1)\nm.group(1)\n'i386'\n\nm = pattern.match(s2)\nm.group(1)\n'amd64'\n\n", "The expression should be without the leading trailing slashes.\nimport re\n\nline = '/xubuntu/daily/current/lucid-alternate-i386.iso'\nrex = re.compile(r\"([^-]*)\\.iso\")\nm = rex.search(line)\nprint m.group(1)\n\nYields 'i386'\n", "reobj = re.compile(r\"(\\w+)\\.iso$\")\nmatch = reobj.search(subject)\nif match:\n result = match.group(1)\nelse:\n result = \"\"\n\nSubject contains the filename and path.\n", ">>> import os\n>>> path = \"/xubuntu/daily/current/lucid-alternate-i386.iso\"\n>>> file, ext = os.path.splitext(os.path.split(path)[1])\n>>> processor = file[file.rfind(\"-\") + 1:]\n>>> processor\n'i386'\n\n" ]
[ 3, 1, 1, 1, 0, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002925306_python_regex.txt
Q: Is Python appropriate for algorithms focused on scientific computing? My interests in programming lie mainly in algorithms, and lately I have seen many reputable researchers write a lot of their code in python. How easy and convenient is python for scientific computing? Does it have a library of algorithms that compares to matlab's? Is Python a scripting language or does it compile? Is it a great language for prototyping an algorithm? How long would it take me to learn enough of it to be productive provided I know C well and OO programming somewhat? Is it OO based? Sorry for the condensed format of questions, but I'm very curious and was hoping a more experienced programmer could help me out. A: How easy and convenient is python for scientific computing? Scipy/NumPy. Does it have a library of algorithms that compares to matlab's? Yes. Is Python a scripting language or does it compile? Interpreted. Is it a great language for prototyping an algorithm? Yes. How long would it take me to learn enough of it to be productive provided I know C well and OO programming somewhat? Depends. Is it OO based? Yes. A: How easy and convenient is python for scientific computing? Very! You should try attending the SciPy conferences (every year there's one in the US and one in Europe) to get a real feeling for that, but even just the rest of the scipy.org site should give you some impression. Does it have a library of algorithms that compares to matlab's? I don't know matlab, but the amount of stuff available in/for Python is staggering. Is Python a scripting language or does it compile? Python is a language, and it offers many implementations (all open-source). The most popular one, CPython, compiles sources to its own bytecode which its virtual machine then executes (the compilation is very fast and happens transparently when needed, but compiled files are typically stored on disk and recompiled only when needed). That's very similar to Java/JVM or C#/.Net, except the compilation step can be subsumed with the execution step (but of course you can have a build system which compiles ahead-of-time, if you want). Jython compiles to JVM bytecode, which a JVM then executes; Microsoft's IronPython (their first fully open source project, I believe) compiles to CRL (".Net bytecode") which .Net and Mono can then execute. They both support both just-in-time and ahead-of-time compilation to their respective bytecodes. PyPy can compile Python sources to many things, including (for a subset of Python) directly (ahead-of-time) to native machine language or (for all of Python) to an intermediate code which is then compiled to machine language in just-in-time fashion. PyPy is incredibly flexible in terms of the kind of build systems you can set up. (Its name comes from the fact that it's coded in Python itself, and that's surely still a plus in many terms, but the speed of the code it makes, and its flexibility, are its biggest strengths today). These four implementations are all production quality at this time (historically, they became so in the order I've listed -- PyPy most recently, and actually pretty recently indeed, but I like what I see there very much these days). Is it a great language for prototyping an algorithm? I can't think of a better one; see chapter 18 of the Python Cookbook, especially the introduction by Tim Peters, for more. That intro is entirely readable in the Google Books link I just gave, and I really can't do it justice in what's already going to be a long SO answer; please click on the link and read that intro! How long would it take me to learn enough of it to be productive provided I know C well and OO programming somewhat? When I first met Python, after browsing through the tutorial, I decided to give it a try when I had a free weekend with my family away: I'd devote one weekend (Friday 6pm to Sunday midnight, or, well, wee hours on Monday perhaps) to learning the language by doing in it a CGI web app to compute and show various kinds of bridge probabilities (as a bridge enthusiast, but known in the field mostly through my probability and computer work about it, it's a problem I've long loved: I learned Fortran back in my freshman year, though at that time as an EE major I wasn't supposed to do programming until junior year, by punching cards to solve that kind of problem;-). Of course I didn't expect to finish the task from scratch in 54 hours or so (minus sleep time;-) while teaching myself the language and its library (CGI and the needed algorithms I already knew well), but I wanted to see how far I would get (evaluating Python vs the other languages I was a guru in at the time, mostly perl and C++). Less than 24 hours later (admittedly having slept little that night, I was just too excited), I stepped back and had to admit that I was finished -- not only did my little CGI web app have all the functionality I had had in mind, but I had also made it able to give output in different natural languages by building from scratch a little templating system (I knew there were plenty -- that's why I named mine yaptu, "Yet Another Python Templating Utility" -- but I just didn't have time to learn anything outside of the language and standard library... rolling my own was faster;-). That's when I irretrievably fell in love with Python. Not long after, I ended up leaving my existing high-flying career for a spell writing books and freelancing with Python, and a few years later I moved across an ocean and two continents to join one of the largest companies extensively using Python (my current employer, Google) -- in the meantime having re-married (to my current wife, Anna -- she was also co-author in one of my books and the first woman Member of the Python Software Foundation). Our "vanity" license plate reads P♥THON...;-). So, OK, I'm biased. But it all started with those <24 hours in which I accomplished more than I had hoped to do in >54 hours (despite being, like all SW developers, an incurable optimist whenever it comes to "how long will it take me to do X" for any SW-centered X;-). Is it OO based? Yes, but multi-paradigm (like C++... but even more than C++) -- you don't have to use classes when you don't need them, and it has reasonable support for functional programming too (definitely not as deep as "true" FP languages like Haskell, but still very useful for many tasks). A: It bytecompiles, and then sends the bytecode through an interpreter. Official Tutorial NumPy You are now set. A: Answer your question one by one: How easy and convenient is python for scientific computing? One great point of python is that it provides very intuitive way of writing code. The powerful embedded data structure such as dictionary and list would help you a lot in scientific computing. Besides, as a dynamic language, you do not need to deal with many low level detail which you have to do in C. Does it have a library of algorithms that compares to matlab's? Indeed, python has a great number of library of algorithms. For example, you can use NumPy and SciPy to support large, multi-dimensional arrays and matrices compuation. And you can find more detail in those links: official site of numpy: http://numpy.scipy.org/ wikipedia of numpy: http://en.wikipedia.org/wiki/NumPy Besides, python also has library to support network analysis. For example, networkx library is a great tool for graph analysis. Is Python a scripting language or does it compile? Generally, python is designed as a scripting language. But there is also tools for compile, for example, py2exe. I recommend you to use python as a scripting language. I think you may have performance concern about python. And a usually applied solution is to write those performance critic module in c/c++, and glue them by SWIG. Is it a great language for prototyping an algorithm? Sure it is. With the rich support of embedded data structure, you can quick implement some complicated algorithm with shorter code compared to C/C++. Typical example is as following: //C++ loop a one dimensional array and print value const int N = 100; int A[N]; for (int i = 0; i < N; ++i) cout << i; #python loop a one dimensional array and print value for i in range(100): print i And as a scripting language, you do not need compile, run, recompile, run, it would save you a lot of time. How long would it take me to learn enough of it to be productive provided I know C well and OO programming somewhat? Is it OO based? Python is different from C. You may find it is not very convinent to write c-style code in python. But python is easy to start, most syntaxes are just plain English. Moreover, there are some great tutorials for python. For example, dive into python is very nice for beginners. Python provides mechanism for OO based programming. A: I've used Python for 6 years for scientific computing. Having come from matlab/IDL, it was very easy to do the switch since it's also interpreted. There are 3rd party tools such as SciPy and Matplotlib to help specifically with data analysis /visualization. Also, if you look in Amazon there are books targeting this audience. Python is also very often used to teach programming because of it's simple yet powerful syntax. A: If you know C and some object oriented programming you'll learn python very quickly - most of the key things in just a few hours of reading / tinkering with it. Here are the main differentiators: - Designed to be easy to learn quickly and to encourage writing readable code. - Has the fewest warts of any object oriented programming language. - Doesn't force you to write object oriented code however. - Makes it easy to write scripts that can be executed stand alone or imported into others. Object Oriented features: - True polymorphism. Unlike C++ and derivatives such as Java you don't have to stand on your head to make your code polymorphic, generic and reusable - even in ways you didn't think about beforehand. This is because although it's strongly typed it's not statically typed. So as long as your objects have the expected methods or attributes that some piece of code wants, it'll work. This is known as duck typing. - Introspection - so you can easily check if a method or attribute is present before accessing it. Also is great for debugging. - You can add attributes and even methods to objects at run time. Very malleable code. - Supports multiple inheritance. Problems: - Typically faster than Ruby but sometimes slower than Java. - You have to get used to seeing the word self all over the place. - Hard for C style developers to let go of having to type curly braces and semi-colons. Seeing uncluttered code like that can make you feel like there's just something missing. There's a programming style guide that all python developers are meant to follow: http://www.python.org/dev/peps/pep-0008/ There's a variant of it that's faster than the main version and supports an easy to use concurrency mechanism. It's known as Stackless Python because it does away with using the C stack. EVE Online is written in this language. Here's an example of something I suppose could be considered scientific programming - adjusting sound waves - it's simply cool - scroll down to the bottom for source and see how relatively simple it is. http://musicmachinery.com/2010/05/21/the-swinger/ A: Is Python appropriate for algorithms focused on scientific computing? Yes A: You asked about compiled/interpreted. If your concern here was execution speed, there is an aspect of python that doesn't seem to have been covered explicitly---you can use tools like SWIG and boost.python to make your lightning fast C/C++ packages appear in your python as modules. Once you get to the module, it will run at the speed/efficiency of the underlying C/C++ implementation. Many modules are available that take advantage of this. So, you get to do all the organizational stuff in clear, flexible, easy to learn Python, and then when you get to your heavy number crunching, you get to hand off the problem to a fast, efficient routine. You get the best of both worlds.
Is Python appropriate for algorithms focused on scientific computing?
My interests in programming lie mainly in algorithms, and lately I have seen many reputable researchers write a lot of their code in python. How easy and convenient is python for scientific computing? Does it have a library of algorithms that compares to matlab's? Is Python a scripting language or does it compile? Is it a great language for prototyping an algorithm? How long would it take me to learn enough of it to be productive provided I know C well and OO programming somewhat? Is it OO based? Sorry for the condensed format of questions, but I'm very curious and was hoping a more experienced programmer could help me out.
[ "\nHow easy and convenient is python for scientific computing?\n\nScipy/NumPy.\n\nDoes it have a library of algorithms that compares to matlab's?\n\nYes.\n\nIs Python a scripting language or does it compile?\n\nInterpreted.\n\nIs it a great language for prototyping an algorithm?\n\nYes.\n\nHow long would it take me to learn enough of it to be productive provided I know C well and OO programming somewhat?\n\nDepends.\n\nIs it OO based?\n\nYes.\n", "\nHow easy and convenient is python for\n scientific computing?\n\nVery! You should try attending the SciPy conferences (every year there's one in the US and one in Europe) to get a real feeling for that, but even just the rest of the scipy.org site should give you some impression.\n\nDoes it have a library of algorithms\n that compares to matlab's?\n\nI don't know matlab, but the amount of stuff available in/for Python is staggering.\n\nIs Python a scripting language or does\n it compile?\n\nPython is a language, and it offers many implementations (all open-source).\nThe most popular one, CPython, compiles sources to its own bytecode which its virtual machine then executes (the compilation is very fast and happens transparently when needed, but compiled files are typically stored on disk and recompiled only when needed). That's very similar to Java/JVM or C#/.Net, except the compilation step can be subsumed with the execution step (but of course you can have a build system which compiles ahead-of-time, if you want).\nJython compiles to JVM bytecode, which a JVM then executes; Microsoft's IronPython (their first fully open source project, I believe) compiles to CRL (\".Net bytecode\") which .Net and Mono can then execute. They both support both just-in-time and ahead-of-time compilation to their respective bytecodes.\nPyPy can compile Python sources to many things, including (for a subset of Python) directly (ahead-of-time) to native machine language or (for all of Python) to an intermediate code which is then compiled to machine language in just-in-time fashion. PyPy is incredibly flexible in terms of the kind of build systems you can set up. (Its name comes from the fact that it's coded in Python itself, and that's surely still a plus in many terms, but the speed of the code it makes, and its flexibility, are its biggest strengths today).\nThese four implementations are all production quality at this time (historically, they became so in the order I've listed -- PyPy most recently, and actually pretty recently indeed, but I like what I see there very much these days).\n\nIs it a great language for prototyping\n an algorithm?\n\nI can't think of a better one; see chapter 18 of the Python Cookbook, especially the introduction by Tim Peters, for more. That intro is entirely readable in the Google Books link I just gave, and I really can't do it justice in what's already going to be a long SO answer; please click on the link and read that intro!\n\nHow long would it take me to learn\n enough of it to be productive provided\n I know C well and OO programming\n somewhat?\n\nWhen I first met Python, after browsing through the tutorial, I decided to give it a try when I had a free weekend with my family away: I'd devote one weekend (Friday 6pm to Sunday midnight, or, well, wee hours on Monday perhaps) to learning the language by doing in it a CGI web app to compute and show various kinds of bridge probabilities (as a bridge enthusiast, but known in the field mostly through my probability and computer work about it, it's a problem I've long loved: I learned Fortran back in my freshman year, though at that time as an EE major I wasn't supposed to do programming until junior year, by punching cards to solve that kind of problem;-).\nOf course I didn't expect to finish the task from scratch in 54 hours or so (minus sleep time;-) while teaching myself the language and its library (CGI and the needed algorithms I already knew well), but I wanted to see how far I would get (evaluating Python vs the other languages I was a guru in at the time, mostly perl and C++).\nLess than 24 hours later (admittedly having slept little that night, I was just too excited), I stepped back and had to admit that I was finished -- not only did my little CGI web app have all the functionality I had had in mind, but I had also made it able to give output in different natural languages by building from scratch a little templating system (I knew there were plenty -- that's why I named mine yaptu, \"Yet Another Python Templating Utility\" -- but I just didn't have time to learn anything outside of the language and standard library... rolling my own was faster;-).\nThat's when I irretrievably fell in love with Python. Not long after, I ended up leaving my existing high-flying career for a spell writing books and freelancing with Python, and a few years later I moved across an ocean and two continents to join one of the largest companies extensively using Python (my current employer, Google) -- in the meantime having re-married (to my current wife, Anna -- she was also co-author in one of my books and the first woman Member of the Python Software Foundation). Our \"vanity\" license plate reads P♥THON...;-). So, OK, I'm biased. But it all started with those <24 hours in which I accomplished more than I had hoped to do in >54 hours (despite being, like all SW developers, an incurable optimist whenever it comes to \"how long will it take me to do X\" for any SW-centered X;-).\n\nIs it OO based?\n\nYes, but multi-paradigm (like C++... but even more than C++) -- you don't have to use classes when you don't need them, and it has reasonable support for functional programming too (definitely not as deep as \"true\" FP languages like Haskell, but still very useful for many tasks).\n", "It bytecompiles, and then sends the bytecode through an interpreter.\nOfficial Tutorial\nNumPy\nYou are now set.\n", "Answer your question one by one:\nHow easy and convenient is python for scientific computing?\nOne great point of python is that it provides very intuitive way of writing code. The powerful embedded data structure such as dictionary and list would help you a lot in scientific computing. Besides, as a dynamic language, you do not need to deal with many low level detail which you have to do in C.\nDoes it have a library of algorithms that compares to matlab's? \nIndeed, python has a great number of library of algorithms. For example, you can use NumPy and SciPy to support large, multi-dimensional arrays and matrices compuation. And you can find more detail in those links:\n\nofficial site of numpy:\nhttp://numpy.scipy.org/\nwikipedia of numpy:\n http://en.wikipedia.org/wiki/NumPy\n\nBesides, python also has library to support network analysis. For example, networkx library is a great tool for graph analysis. \nIs Python a scripting language or does it compile? \nGenerally, python is designed as a scripting language. But there is also tools for compile, for example, py2exe. I recommend you to use python as a scripting language. I think you may have performance concern about python. And a usually applied solution is to write those performance critic module in c/c++, and glue them by SWIG. \nIs it a great language for prototyping an algorithm? \nSure it is. With the rich support of embedded data structure, you can quick implement some complicated algorithm with shorter code compared to C/C++. \nTypical example is as following:\n //C++ loop a one dimensional array and print value\n const int N = 100; \n int A[N];\n for (int i = 0; i < N; ++i)\n cout << i;\n\n#python loop a one dimensional array and print value\nfor i in range(100):\n print i\n\nAnd as a scripting language, you do not need compile, run, recompile, run, it would save you a lot of time. \nHow long would it take me to learn enough of it to be productive provided I know C well and OO programming somewhat? Is it OO based?\nPython is different from C. You may find it is not very convinent to write c-style code in python. But python is easy to start, most syntaxes are just plain English. Moreover, there are some great tutorials for python. For example, dive into python is very nice for beginners. \nPython provides mechanism for OO based programming. \n", "I've used Python for 6 years for scientific computing. Having come from matlab/IDL, it was very easy to do the switch since it's also interpreted. \nThere are 3rd party tools such as SciPy and Matplotlib to help specifically with data analysis /visualization. Also, if you look in Amazon there are books targeting this audience.\nPython is also very often used to teach programming because of it's simple yet powerful syntax.\n", "If you know C and some object oriented programming you'll learn python very quickly - most of the key things in just a few hours of reading / tinkering with it. Here are the main differentiators:\n- Designed to be easy to learn quickly and to encourage writing readable code.\n- Has the fewest warts of any object oriented programming language.\n- Doesn't force you to write object oriented code however.\n- Makes it easy to write scripts that can be executed stand alone or imported into others.\nObject Oriented features:\n- True polymorphism. Unlike C++ and derivatives such as Java you don't have to stand on your head to make your code polymorphic, generic and reusable - even in ways you didn't think about beforehand. This is because although it's strongly typed it's not statically typed. So as long as your objects have the expected methods or attributes that some piece of code wants, it'll work. This is known as duck typing.\n- Introspection - so you can easily check if a method or attribute is present before accessing it. Also is great for debugging.\n- You can add attributes and even methods to objects at run time. Very malleable code.\n- Supports multiple inheritance.\nProblems:\n- Typically faster than Ruby but sometimes slower than Java.\n- You have to get used to seeing the word self all over the place.\n- Hard for C style developers to let go of having to type curly braces and semi-colons. Seeing uncluttered code like that can make you feel like there's just something missing.\nThere's a programming style guide that all python developers are meant to follow:\nhttp://www.python.org/dev/peps/pep-0008/\nThere's a variant of it that's faster than the main version and supports an easy to use concurrency mechanism. It's known as Stackless Python because it does away with using the C stack. EVE Online is written in this language.\nHere's an example of something I suppose could be considered scientific programming - adjusting sound waves - it's simply cool - scroll down to the bottom for source and see how relatively simple it is.\nhttp://musicmachinery.com/2010/05/21/the-swinger/\n", "\nIs Python appropriate for algorithms focused on scientific computing?\n\nYes\n", "You asked about compiled/interpreted. If your concern here was execution speed, there is an aspect of python that doesn't seem to have been covered explicitly---you can use tools like SWIG and boost.python to make your lightning fast C/C++ packages appear in your python as modules. Once you get to the module, it will run at the speed/efficiency of the underlying C/C++ implementation. Many modules are available that take advantage of this.\nSo, you get to do all the organizational stuff in clear, flexible, easy to learn Python, and then when you get to your heavy number crunching, you get to hand off the problem to a fast, efficient routine. You get the best of both worlds.\n" ]
[ 16, 14, 11, 8, 4, 3, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002917974_python.txt
Q: Draw and move a point over an image in python Hi all I have to do a little script in Python. In this script I have a variable (that represents a coordinate) that is continuously updated to a new value. So I have to draw a red point over a image and update the point position every time the variable that contains the coordinate is updated. I tried to explain what I need doing something like this but obviously it doesn't works: import Tkinter, Image, ImageDraw, ImageTk i=0 root = Tkinter.Tk() im = Image.open("img.jpg") root.geometry("%dx%d" % (im.size[0], im.size[1])) while True: draw = ImageDraw.Draw(im) draw.ellipse((i, 0, 10, 10), fill=(255, 0, 0)) pi = ImageTk.PhotoImage(im) label = Tkinter.Label(root, image=pi) label.place(x=0, y=0, width=im.size[0], height=im.size[1]) i+=1 del draw someone may help me please? thanks very much! A: Your on the right track using a PhotoImage in a Label but instead of creating a new Label each loop, just create the label once and update its position in the loop.
Draw and move a point over an image in python
Hi all I have to do a little script in Python. In this script I have a variable (that represents a coordinate) that is continuously updated to a new value. So I have to draw a red point over a image and update the point position every time the variable that contains the coordinate is updated. I tried to explain what I need doing something like this but obviously it doesn't works: import Tkinter, Image, ImageDraw, ImageTk i=0 root = Tkinter.Tk() im = Image.open("img.jpg") root.geometry("%dx%d" % (im.size[0], im.size[1])) while True: draw = ImageDraw.Draw(im) draw.ellipse((i, 0, 10, 10), fill=(255, 0, 0)) pi = ImageTk.PhotoImage(im) label = Tkinter.Label(root, image=pi) label.place(x=0, y=0, width=im.size[0], height=im.size[1]) i+=1 del draw someone may help me please? thanks very much!
[ "Your on the right track using a PhotoImage in a Label but instead of creating a new Label each loop, just create the label once and update its position in the loop.\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0002920775_python.txt
Q: Images not loading in QWebview in PyQt4 in py2exe I have an application that displays some HTML in a QWebview, which references images on the local file system. This works fine directly running the python. When compiling via py2exe, the images no longer load. Google doesn't seem to know the answer, any ideas? A: Only png support is native, jpg (and others) is supplied via plugins. Don't recall the exact paths (and I don't know your platform) but search for the PyQt plugins folder and: Copy the plugins folder to: $yourprogram/PyQt4/plugins (along with qt.conf) Edit qt.conf, and change prefix to $yourprogram/PyQt4 You might also need to convince py2exe to also include this folder (verbatim).
Images not loading in QWebview in PyQt4 in py2exe
I have an application that displays some HTML in a QWebview, which references images on the local file system. This works fine directly running the python. When compiling via py2exe, the images no longer load. Google doesn't seem to know the answer, any ideas?
[ "Only png support is native, jpg (and others) is supplied via plugins.\nDon't recall the exact paths (and I don't know your platform) but search for the PyQt plugins folder and:\n\nCopy the plugins folder to: $yourprogram/PyQt4/plugins (along with qt.conf)\nEdit qt.conf, and change prefix to $yourprogram/PyQt4\n\nYou might also need to convince py2exe to also include this folder (verbatim).\n" ]
[ 2 ]
[]
[]
[ "py2exe", "pyqt4", "python", "qwebview" ]
stackoverflow_0002924781_py2exe_pyqt4_python_qwebview.txt
Q: Integer array in Python How I can define array of integer numbers in Python code Say if this code is ok. or no pos = [int] len = 99 for i in range (0,99): pos[i]=7 A: Why not just: pos = [7] * 99 This is the most pythonic, in my opinion. A: import array pos = array.array('l', 7 * [99]) The array module of Python's standard library is the only way to make an array that comes with Python (the third-party module numpy offers other ways, but needs do be downloaded and installed separately) -- what your Q is doing, as well as every answer so far, is building a list, not an array. In particular, there is no constraint that the pos list built in your Q and the several As contains just integers -- while, with the snippet I give, you do get that constraint (32-bit signed integers in this case, to be precise), which rigidly limits you but also saves a bunch of memory (an array of integers should take about one fifth the amount of memory that a list filled with integers will take, unless there's a lot of perennial duplication in the lists' items). BTW, if you say array when you mean list (just in case list is what you meant), you're sure to cause a lot of confusion -- saying what you mean, and meaning what you say, helps a lot in clear communication, unsurprisingly!-) A: you do not declare the type of variables in python, so no pos=[int] all you have to do: pos=[] for i in range(99): pos.append(7) A: You can simply do pos = [7] * 99 print pos #will print the whole array [7, 7, .... 7] A: If you just want to declare the array, all you have to do in python is: pos = [] If you want to fill the array with 99 7's: pos = [7] * 99 If you want to fill the array based on a pattern: pos = [i for i in range(99)] A: One way is: pos = [7 for _ in xrange(0,99)] in Python 2 or: pos = [7 for _ in range(0,99)] in Python 3. These are list comprehensions, and are easy to extend for more complex work. Also: pos = [int] doesn't make much sense. You're creating a list with the only element being the type int.
Integer array in Python
How I can define array of integer numbers in Python code Say if this code is ok. or no pos = [int] len = 99 for i in range (0,99): pos[i]=7
[ "Why not just:\npos = [7] * 99\n\nThis is the most pythonic, in my opinion.\n", "import array\n\npos = array.array('l', 7 * [99])\n\nThe array module of Python's standard library is the only way to make an array that comes with Python (the third-party module numpy offers other ways, but needs do be downloaded and installed separately) -- what your Q is doing, as well as every answer so far, is building a list, not an array.\nIn particular, there is no constraint that the pos list built in your Q and the several As contains just integers -- while, with the snippet I give, you do get that constraint (32-bit signed integers in this case, to be precise), which rigidly limits you but also saves a bunch of memory (an array of integers should take about one fifth the amount of memory that a list filled with integers will take, unless there's a lot of perennial duplication in the lists' items).\nBTW, if you say array when you mean list (just in case list is what you meant), you're sure to cause a lot of confusion -- saying what you mean, and meaning what you say, helps a lot in clear communication, unsurprisingly!-)\n", "you do not declare the type of variables in python, so no pos=[int]\nall you have to do:\npos=[]\nfor i in range(99):\n pos.append(7)\n\n", "You can simply do\npos = [7] * 99\nprint pos #will print the whole array [7, 7, .... 7]\n\n", "If you just want to declare the array, all you have to do in python is:\npos = []\n\nIf you want to fill the array with 99 7's:\npos = [7] * 99\n\nIf you want to fill the array based on a pattern:\npos = [i for i in range(99)]\n\n", "One way is:\npos = [7 for _ in xrange(0,99)]\n\nin Python 2 or:\npos = [7 for _ in range(0,99)]\n\nin Python 3. These are list comprehensions, and are easy to extend for more complex work.\nAlso:\npos = [int]\n\ndoesn't make much sense. You're creating a list with the only element being the type int.\n" ]
[ 11, 5, 4, 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002901847_python.txt
Q: Elegant Disjunctive Normal Form in Django Let's say I've defined this model: class Identifier(models.Model): user = models.ForeignKey(User) key = models.CharField(max_length=64) value = models.CharField(max_length=255) Each user will have multiple identifiers, each with a key and a value. I am 100% sure I want to keep the design like this, there are external reasons why I'm doing it that I won't go through here, so I'm not interested in changing this. I'd like to develop a function of this sort: def get_users_by_identifiers(**kwargs): # something goes here return users The function will return all users that have one of the key=value pairs specified in **kwargs. Here's an example usage: get_users_by_identifiers(a=1, b=2) This should return all users for whom a=1 or b=2. I've noticed that the way I've set this up, this amounts to a disjunctive normal form...the SQL query would be something like: SELECT DISTINCT(user_id) FROM app_identifier WHERE (key = "a" AND value = "1") OR (key = "b" AND value = "2") ... I feel like there's got to be some elegant way to take the **kwargs input and do a Django filter on it, in just 1-2 lines, to produce this result. I'm new to Django though, so I'm just not sure how to do it. Here's my function now, and I'm completely sure it's not the best way to do it :) def get_users_by_identifiers(**identifiers): users = [] for key, value in identifiers.items(): for identifier in Identifier.objects.filter(key=key, value=value): if not identifier.user in users: users.append(identifier.user) return users Any ideas? :) Thanks! A: def get_users_by_identifiers(**kwargs): q = reduce(operator.or_, Q(identifier__key=k, identifier__value=v) for (k, v) in kwargs.iteritems()) return User.objects.filter(q)
Elegant Disjunctive Normal Form in Django
Let's say I've defined this model: class Identifier(models.Model): user = models.ForeignKey(User) key = models.CharField(max_length=64) value = models.CharField(max_length=255) Each user will have multiple identifiers, each with a key and a value. I am 100% sure I want to keep the design like this, there are external reasons why I'm doing it that I won't go through here, so I'm not interested in changing this. I'd like to develop a function of this sort: def get_users_by_identifiers(**kwargs): # something goes here return users The function will return all users that have one of the key=value pairs specified in **kwargs. Here's an example usage: get_users_by_identifiers(a=1, b=2) This should return all users for whom a=1 or b=2. I've noticed that the way I've set this up, this amounts to a disjunctive normal form...the SQL query would be something like: SELECT DISTINCT(user_id) FROM app_identifier WHERE (key = "a" AND value = "1") OR (key = "b" AND value = "2") ... I feel like there's got to be some elegant way to take the **kwargs input and do a Django filter on it, in just 1-2 lines, to produce this result. I'm new to Django though, so I'm just not sure how to do it. Here's my function now, and I'm completely sure it's not the best way to do it :) def get_users_by_identifiers(**identifiers): users = [] for key, value in identifiers.items(): for identifier in Identifier.objects.filter(key=key, value=value): if not identifier.user in users: users.append(identifier.user) return users Any ideas? :) Thanks!
[ "def get_users_by_identifiers(**kwargs):\n q = reduce(operator.or_, Q(identifier__key=k, identifier__value=v)\n for (k, v) in kwargs.iteritems())\n return User.objects.filter(q)\n\n" ]
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002925991_django_python.txt
Q: Obtain Latitude and Longitude from a GeoTIFF File Using GDAL in Python, how do you get the latitude and longitude of a GeoTIFF file? GeoTIFF's do not appear to store any coordinate information. Instead, they store the XY Origin coordinates. However, the XY coordinates do not provide the latitude and longitude of the top left corner and bottom left corner. It appears I will need to do some math to solve this problem, but I don't have a clue on where to start. What procedure is required to have this performed? I know that the GetGeoTransform() method is important for this, however, I don't know what to do with it from there. A: To get the coordinates of the corners of your geotiff do the following: from osgeo import gdal ds = gdal.Open('path/to/file') width = ds.RasterXSize height = ds.RasterYSize gt = ds.GetGeoTransform() minx = gt[0] miny = gt[3] + width*gt[4] + height*gt[5] maxx = gt[0] + width*gt[1] + height*gt[2] maxy = gt[3] However, these might not be in latitude/longitude format. As Justin noted, your geotiff will be stored with some kind of coordinate system. If you don't know what coordinate system it is, you can find out by running gdalinfo: gdalinfo ~/somedir/somefile.tif Which outputs: Driver: GTiff/GeoTIFF Size is 512, 512 Coordinate System is: PROJCS["NAD27 / UTM zone 11N", GEOGCS["NAD27", DATUM["North_American_Datum_1927", SPHEROID["Clarke 1866",6378206.4,294.978698213901]], PRIMEM["Greenwich",0], UNIT["degree",0.0174532925199433]], PROJECTION["Transverse_Mercator"], PARAMETER["latitude_of_origin",0], PARAMETER["central_meridian",-117], PARAMETER["scale_factor",0.9996], PARAMETER["false_easting",500000], PARAMETER["false_northing",0], UNIT["metre",1]] Origin = (440720.000000,3751320.000000) Pixel Size = (60.000000,-60.000000) Corner Coordinates: Upper Left ( 440720.000, 3751320.000) (117d38'28.21"W, 33d54'8.47"N) Lower Left ( 440720.000, 3720600.000) (117d38'20.79"W, 33d37'31.04"N) Upper Right ( 471440.000, 3751320.000) (117d18'32.07"W, 33d54'13.08"N) Lower Right ( 471440.000, 3720600.000) (117d18'28.50"W, 33d37'35.61"N) Center ( 456080.000, 3735960.000) (117d28'27.39"W, 33d45'52.46"N) Band 1 Block=512x16 Type=Byte, ColorInterp=Gray This output may be all you need. If you want to do this programmaticly in python however, this is how you get the same info. If the coordinate system is a PROJCS like the example above you are dealing with a projected coordinate system. A projected coordiante system is a representation of the spheroidal earth's surface, but flattened and distorted onto a plane. If you want the latitude and longitude, you need to convert the coordinates to the geographic coordinate system that you want. Sadly, not all latitude/longitude pairs are created equal, being based upon different spheroidal models of the earth. In this example, I am converting to WGS84, the geographic coordinate system favoured in GPSs and used by all the popular web mapping sites. The coordinate system is defined by a well defined string. A catalogue of them is available from spatial ref, see for example WGS84. from osgeo import osr, gdal # get the existing coordinate system ds = gdal.Open('path/to/file') old_cs= osr.SpatialReference() old_cs.ImportFromWkt(ds.GetProjectionRef()) # create the new coordinate system wgs84_wkt = """ GEOGCS["WGS 84", DATUM["WGS_1984", SPHEROID["WGS 84",6378137,298.257223563, AUTHORITY["EPSG","7030"]], AUTHORITY["EPSG","6326"]], PRIMEM["Greenwich",0, AUTHORITY["EPSG","8901"]], UNIT["degree",0.01745329251994328, AUTHORITY["EPSG","9122"]], AUTHORITY["EPSG","4326"]]""" new_cs = osr.SpatialReference() new_cs .ImportFromWkt(wgs84_wkt) # create a transform object to convert between coordinate systems transform = osr.CoordinateTransformation(old_cs,new_cs) #get the point to transform, pixel (0,0) in this case width = ds.RasterXSize height = ds.RasterYSize gt = ds.GetGeoTransform() minx = gt[0] miny = gt[3] + width*gt[4] + height*gt[5] #get the coordinates in lat long latlong = transform.TransformPoint(minx,miny) Hopefully this will do what you want. A: I don't know if this is a full answer, but this site says: The x/y map dimensions are called easting and northing. For datasets in a geographic coordinate system these would hold the longitude and latitude. For projected coordinate systems they would normally be the easting and northing in the projected coordinate system. For ungeoreferenced images the easting and northing would just be the pixel/line offsets of each pixel (as implied by a unity geotransform). so they may actually be longitude and latitude.
Obtain Latitude and Longitude from a GeoTIFF File
Using GDAL in Python, how do you get the latitude and longitude of a GeoTIFF file? GeoTIFF's do not appear to store any coordinate information. Instead, they store the XY Origin coordinates. However, the XY coordinates do not provide the latitude and longitude of the top left corner and bottom left corner. It appears I will need to do some math to solve this problem, but I don't have a clue on where to start. What procedure is required to have this performed? I know that the GetGeoTransform() method is important for this, however, I don't know what to do with it from there.
[ "To get the coordinates of the corners of your geotiff do the following:\nfrom osgeo import gdal\nds = gdal.Open('path/to/file')\nwidth = ds.RasterXSize\nheight = ds.RasterYSize\ngt = ds.GetGeoTransform()\nminx = gt[0]\nminy = gt[3] + width*gt[4] + height*gt[5] \nmaxx = gt[0] + width*gt[1] + height*gt[2]\nmaxy = gt[3] \n\nHowever, these might not be in latitude/longitude format. As Justin noted, your geotiff will be stored with some kind of coordinate system. If you don't know what coordinate system it is, you can find out by running gdalinfo:\ngdalinfo ~/somedir/somefile.tif \n\nWhich outputs:\nDriver: GTiff/GeoTIFF\nSize is 512, 512\nCoordinate System is:\nPROJCS[\"NAD27 / UTM zone 11N\",\n GEOGCS[\"NAD27\",\n DATUM[\"North_American_Datum_1927\",\n SPHEROID[\"Clarke 1866\",6378206.4,294.978698213901]],\n PRIMEM[\"Greenwich\",0],\n UNIT[\"degree\",0.0174532925199433]],\n PROJECTION[\"Transverse_Mercator\"],\n PARAMETER[\"latitude_of_origin\",0],\n PARAMETER[\"central_meridian\",-117],\n PARAMETER[\"scale_factor\",0.9996],\n PARAMETER[\"false_easting\",500000],\n PARAMETER[\"false_northing\",0],\n UNIT[\"metre\",1]]\nOrigin = (440720.000000,3751320.000000)\nPixel Size = (60.000000,-60.000000)\nCorner Coordinates:\nUpper Left ( 440720.000, 3751320.000) (117d38'28.21\"W, 33d54'8.47\"N)\nLower Left ( 440720.000, 3720600.000) (117d38'20.79\"W, 33d37'31.04\"N)\nUpper Right ( 471440.000, 3751320.000) (117d18'32.07\"W, 33d54'13.08\"N)\nLower Right ( 471440.000, 3720600.000) (117d18'28.50\"W, 33d37'35.61\"N)\nCenter ( 456080.000, 3735960.000) (117d28'27.39\"W, 33d45'52.46\"N)\nBand 1 Block=512x16 Type=Byte, ColorInterp=Gray\n\nThis output may be all you need. If you want to do this programmaticly in python however, this is how you get the same info.\nIf the coordinate system is a PROJCS like the example above you are dealing with a projected coordinate system. A projected coordiante system is a representation of the spheroidal earth's surface, but flattened and distorted onto a plane. If you want the latitude and longitude, you need to convert the coordinates to the geographic coordinate system that you want.\nSadly, not all latitude/longitude pairs are created equal, being based upon different spheroidal models of the earth. In this example, I am converting to WGS84, the geographic coordinate system favoured in GPSs and used by all the popular web mapping sites. The coordinate system is defined by a well defined string. A catalogue of them is available from spatial ref, see for example WGS84.\nfrom osgeo import osr, gdal\n\n# get the existing coordinate system\nds = gdal.Open('path/to/file')\nold_cs= osr.SpatialReference()\nold_cs.ImportFromWkt(ds.GetProjectionRef())\n\n# create the new coordinate system\nwgs84_wkt = \"\"\"\nGEOGCS[\"WGS 84\",\n DATUM[\"WGS_1984\",\n SPHEROID[\"WGS 84\",6378137,298.257223563,\n AUTHORITY[\"EPSG\",\"7030\"]],\n AUTHORITY[\"EPSG\",\"6326\"]],\n PRIMEM[\"Greenwich\",0,\n AUTHORITY[\"EPSG\",\"8901\"]],\n UNIT[\"degree\",0.01745329251994328,\n AUTHORITY[\"EPSG\",\"9122\"]],\n AUTHORITY[\"EPSG\",\"4326\"]]\"\"\"\nnew_cs = osr.SpatialReference()\nnew_cs .ImportFromWkt(wgs84_wkt)\n\n# create a transform object to convert between coordinate systems\ntransform = osr.CoordinateTransformation(old_cs,new_cs) \n\n#get the point to transform, pixel (0,0) in this case\nwidth = ds.RasterXSize\nheight = ds.RasterYSize\ngt = ds.GetGeoTransform()\nminx = gt[0]\nminy = gt[3] + width*gt[4] + height*gt[5] \n\n#get the coordinates in lat long\nlatlong = transform.TransformPoint(minx,miny) \n\nHopefully this will do what you want.\n", "I don't know if this is a full answer, but this site says:\n\nThe x/y map dimensions are called easting and northing. For datasets in a geographic coordinate system these would hold the longitude and latitude. For projected coordinate systems they would normally be the easting and northing in the projected coordinate system. For ungeoreferenced images the easting and northing would just be the pixel/line offsets of each pixel (as implied by a unity geotransform).\n\nso they may actually be longitude and latitude.\n" ]
[ 102, 19 ]
[]
[]
[ "gdal", "geolocation", "math", "python", "tiff" ]
stackoverflow_0002922532_gdal_geolocation_math_python_tiff.txt
Q: Display folder contents on webpage using Python I wanted to know if there was a way I can get my python script located on a shared web hosting provider to read the contents of a folder on my desktop and list out the contents? Can this be done using tempfiles? A: Server-side web scripts have no access to the client other than through requests. If you can somehow break through the browser's protection settings to get JavaScript, Java, or Flash to read the contents of the client then you stand a fighting chance. But doing so will make many people angry and is generally considered a bad idea. A: Unless your desktop computer has a public, accessible IP, neither your app running on a shared web hosting provider, nor any other app and host on the internet, can get information from your desktop computer. Does your desktop computer fall within the tiny minority that does have such a public, accessible IP? If not, and if you're willing to run the obvious risks involved of course, you can try turning the (probably dynamically assigned) IP address that your ISP gives you into a resolvable domain name, by working with such DNS providers as DynDNS -- it can be done for free. Once you're past the hurdle of public accessibility, you need to run on your computer some server that can respond to properly authenticated requests by supplying the information you desire. For example, you could run a web server such as Apache (which is powerful indeed but perhaps a bit hard for you to set up), or the like -- and a custom app on top of it to check authentication and provide the specific information you want to make available. If you have no privacy worry (i.e., you don't mind that any hacker in the world can look at that folder's contents), you can skip the authentication, which is the really delicate and potentially fragile part (given that there's really no way for your app, running on a shared web hosting provider, to hold "secrets" very effectively). If you can clarify each of these issues, then we can help pinpoint the best approach (what to install and how on both your desktop computer, and that shared web hosting provider).
Display folder contents on webpage using Python
I wanted to know if there was a way I can get my python script located on a shared web hosting provider to read the contents of a folder on my desktop and list out the contents? Can this be done using tempfiles?
[ "Server-side web scripts have no access to the client other than through requests. If you can somehow break through the browser's protection settings to get JavaScript, Java, or Flash to read the contents of the client then you stand a fighting chance. But doing so will make many people angry and is generally considered a bad idea.\n", "Unless your desktop computer has a public, accessible IP, neither your app running on a shared web hosting provider, nor any other app and host on the internet, can get information from your desktop computer. Does your desktop computer fall within the tiny minority that does have such a public, accessible IP?\nIf not, and if you're willing to run the obvious risks involved of course, you can try turning the (probably dynamically assigned) IP address that your ISP gives you into a resolvable domain name, by working with such DNS providers as DynDNS -- it can be done for free.\nOnce you're past the hurdle of public accessibility, you need to run on your computer some server that can respond to properly authenticated requests by supplying the information you desire. For example, you could run a web server such as Apache (which is powerful indeed but perhaps a bit hard for you to set up), or the like -- and a custom app on top of it to check authentication and provide the specific information you want to make available.\nIf you have no privacy worry (i.e., you don't mind that any hacker in the world can look at that folder's contents), you can skip the authentication, which is the really delicate and potentially fragile part (given that there's really no way for your app, running on a shared web hosting provider, to hold \"secrets\" very effectively).\nIf you can clarify each of these issues, then we can help pinpoint the best approach (what to install and how on both your desktop computer, and that shared web hosting provider).\n" ]
[ 1, 0 ]
[]
[]
[ "python", "temporary_files", "web_applications" ]
stackoverflow_0002926106_python_temporary_files_web_applications.txt
Q: Python access webcam and audio input Can a python script on my server access the webcam and audio input of a user as easily and as well as a Flash plugin can? A: No: the "plugin" you mention runs in the user's browser, your server-side script (Python or otherwise) runs on the server, a completely different proposition. This relates to your other recent question about a server-side script accessing information on your desktop: your client machine tends to be very protected against possibly malicious server-side apps (never enough, but everybody keeps trying to make it more and more protected these days). A: Server-side web scripts have no access to the client other than through requests. You need to use JavaScript, Java, or Flash to access devices that the browser (and consequently user) allows them to. A: Not as easy, no. But there are extensions you can use. E.g. A Win32 Python Extension for Accessing Video Devices (e.g. a USB WebCam, a TV-Card, ...) http://videocapture.sourceforge.net/ Tutorial: http://technobabbler.com/?p=22
Python access webcam and audio input
Can a python script on my server access the webcam and audio input of a user as easily and as well as a Flash plugin can?
[ "No: the \"plugin\" you mention runs in the user's browser, your server-side script (Python or otherwise) runs on the server, a completely different proposition. This relates to your other recent question about a server-side script accessing information on your desktop: your client machine tends to be very protected against possibly malicious server-side apps (never enough, but everybody keeps trying to make it more and more protected these days).\n", "Server-side web scripts have no access to the client other than through requests. You need to use JavaScript, Java, or Flash to access devices that the browser (and consequently user) allows them to.\n", "Not as easy, no. But there are extensions you can use. E.g.\nA Win32 Python Extension for Accessing Video Devices (e.g. a USB WebCam, a TV-Card, ...)\nhttp://videocapture.sourceforge.net/\nTutorial:\nhttp://technobabbler.com/?p=22\n" ]
[ 2, 0, 0 ]
[]
[]
[ "python", "streaming", "webcam" ]
stackoverflow_0002926220_python_streaming_webcam.txt
Q: Running iPython from the OSX terminal So I'm going through the matplotlib documentation and prepared to use the iPython interactive Python shell with ipython -pylab. However I get this: Az's MBP:~ Az$ ipython -pylab -bash: ipython: command not found Did I fail to install iPython? I used easy_install as advised. Any ideas? Update Found it in /opt/local/Library/Frameworks/Python.framework/Versions/2.6/bin. Am still confused. A: Did I fail to install iPython? No, but it looks like you installed it with (darwinports or) macports -- I imagine that's where your installation of easy_install comes from, since Apple's own system Python doesn't include extensions such as easy_install, and /opt/local/... is where macports puts things. If you're OK with using macports' versions of Python and everything, you should ensure that deeply-nested bin directory is on your $PATH so you can call things from there easily in your Terminal.app. A: Maybe your ipython executable isn't in your PATH. Try locate your ipython executable on your machine and check your PATH settings. Otherwise just reinstall.
Running iPython from the OSX terminal
So I'm going through the matplotlib documentation and prepared to use the iPython interactive Python shell with ipython -pylab. However I get this: Az's MBP:~ Az$ ipython -pylab -bash: ipython: command not found Did I fail to install iPython? I used easy_install as advised. Any ideas? Update Found it in /opt/local/Library/Frameworks/Python.framework/Versions/2.6/bin. Am still confused.
[ "\nDid I fail to install iPython?\n\nNo, but it looks like you installed it with (darwinports or) macports -- I imagine that's where your installation of easy_install comes from, since Apple's own system Python doesn't include extensions such as easy_install, and /opt/local/... is where macports puts things.\nIf you're OK with using macports' versions of Python and everything, you should ensure that deeply-nested bin directory is on your $PATH so you can call things from there easily in your Terminal.app.\n", "Maybe your ipython executable isn't in your PATH. Try locate your ipython executable on your machine and check your PATH settings. Otherwise just reinstall.\n" ]
[ 4, 0 ]
[]
[]
[ "macos", "python" ]
stackoverflow_0002926053_macos_python.txt
Q: How can I refer to class variable in a function without referring to its class in Python? I have a following class: class Foo: CONSTANT = 1 def some_fn(self): a = Foo.CONSTANT # do something How can I refer to Foo.CONSTANT without referring to Foo, or refer to Foo in a generic way? (I don't want to change all references to it when renaming a class) A: Within a method of class Foo or any subclass thereof, self.CONSTANT will refer to the value defined for that class attribute in class Foo (unless it's overridden in a subclass or in the instance itself -- if you assign self.CONSTANT=23, it's the instance attribute that's created with that value, and it overrides the class attribute in future references). A: Is there any reason why self.CONSTANT doesn't suit your needs? class Foo: CONSTANT = 1 def some_fn(self): a = self.CONSTANT # do something A: In your example, self.CONSTANT will work, but if you ever assign to self.CONSTANT, that will "override" the value defined on the class. You can use self.__class__.CONSTANT to always refer to the value defined on the class. You can even assign to that.
How can I refer to class variable in a function without referring to its class in Python?
I have a following class: class Foo: CONSTANT = 1 def some_fn(self): a = Foo.CONSTANT # do something How can I refer to Foo.CONSTANT without referring to Foo, or refer to Foo in a generic way? (I don't want to change all references to it when renaming a class)
[ "Within a method of class Foo or any subclass thereof, self.CONSTANT will refer to the value defined for that class attribute in class Foo (unless it's overridden in a subclass or in the instance itself -- if you assign self.CONSTANT=23, it's the instance attribute that's created with that value, and it overrides the class attribute in future references).\n", "Is there any reason why self.CONSTANT doesn't suit your needs? \nclass Foo:\n CONSTANT = 1\n\n def some_fn(self):\n a = self.CONSTANT\n # do something\n\n", "In your example, self.CONSTANT will work, but if you ever assign to self.CONSTANT, that will \"override\" the value defined on the class.\nYou can use self.__class__.CONSTANT to always refer to the value defined on the class. You can even assign to that.\n" ]
[ 4, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002926327_python.txt
Q: Which logging library to use for cross-language (Java, C++, Python) system I have a system where a central Java controller launches analysis processes, which may be written in C++, Java, or Python (mostly they are C++). All these processes currently run on the same server. What are you suggestions to Create a central log to which all processes can write to What if in the future I push some processes to another server. How can I support distributed logging? Thanks! A: I'd recommend using the platform's native logger which is syslog on Posix and Event Log on Windows. For C++, you can use the native calls on the platform. I know Python comes with syscall wrapper on Posix and there are wrappers for Event Log in the PyWin32 extension. I assume that someone has created Java wrappers by now. Update Regarding syslog and multiple files. syslog support the concept of facilities - via facilities you can have different logs go to different files. Unfortunatley, facilities are predefined; while there are 8 generic ones LOG_LOCAL0 through LOG_LOCAL7 you cannot define arbitrary facilities. Also note that it's up to the syslog daemon to decide where to route log messages for each facility / level. You may need to adjust your syslog daemon configuration to have each facility get sent to a different file. A: Apache has cross-platform logging libraries, which allow you to log from various programming languages using similar APIs. Unfortunately they don't have a Python API, though you should be able to whip one up with log4cpp and Boost.Python. A project I work on uses one of these libraries to log to a database, which allows us "distributed logging" with a centralized place for the log messages. I have to admit I'm not a fan of this. Another project I work on uses one of these libraries to log to the native logging facility. The Windows Event Log has some features for distributed logging, but AFAIK syslog does not. Although I don't have any experience with it, a better fit may be Facebook's Scribe project. The feature set meets your requirements, including a Python API. Unfortunately it uses Thrift which doesn't work for C++ on Windows (that is, the Thrift compiler generates C++ code that only works on UNIX). You may be able to get around this problem using Cygwin, but I can't promise that approach will work. A: I'd use Apache log4cxx or Apache log4j. It's Efficient. It has Logger hierarchies to modularize your logs. It's proven tecnology for a while now. Currently, appenders exist for the console , files , GUI components, remote socket servers, NT Event Loggers , and remote UNIX Syslog daemons. It is also possible to log asynchronously. How can I support distributed logging? With remote socket servers appenders for example.
Which logging library to use for cross-language (Java, C++, Python) system
I have a system where a central Java controller launches analysis processes, which may be written in C++, Java, or Python (mostly they are C++). All these processes currently run on the same server. What are you suggestions to Create a central log to which all processes can write to What if in the future I push some processes to another server. How can I support distributed logging? Thanks!
[ "I'd recommend using the platform's native logger which is syslog on Posix and Event Log on Windows.\nFor C++, you can use the native calls on the platform.\nI know Python comes with syscall wrapper on Posix and there are wrappers for Event Log in the PyWin32 extension. I assume that someone has created Java wrappers by now.\nUpdate\nRegarding syslog and multiple files. syslog support the concept of facilities - via facilities you can have different logs go to different files. Unfortunatley, facilities are predefined; while there are 8 generic ones LOG_LOCAL0 through LOG_LOCAL7 you cannot define arbitrary facilities.\nAlso note that it's up to the syslog daemon to decide where to route log messages for each facility / level. You may need to adjust your syslog daemon configuration to have each facility get sent to a different file.\n", "Apache has cross-platform logging libraries, which allow you to log from various programming languages using similar APIs. Unfortunately they don't have a Python API, though you should be able to whip one up with log4cpp and Boost.Python.\nA project I work on uses one of these libraries to log to a database, which allows us \"distributed logging\" with a centralized place for the log messages. I have to admit I'm not a fan of this. Another project I work on uses one of these libraries to log to the native logging facility. The Windows Event Log has some features for distributed logging, but AFAIK syslog does not.\nAlthough I don't have any experience with it, a better fit may be Facebook's Scribe project. The feature set meets your requirements, including a Python API. Unfortunately it uses Thrift which doesn't work for C++ on Windows (that is, the Thrift compiler generates C++ code that only works on UNIX). You may be able to get around this problem using Cygwin, but I can't promise that approach will work.\n", "I'd use Apache log4cxx or Apache log4j.\nIt's Efficient. It has Logger hierarchies to modularize your logs. It's proven tecnology for a while now.\nCurrently, appenders exist for the console , files , GUI components, remote socket servers, NT Event Loggers , and remote UNIX Syslog daemons. It is also possible to log asynchronously.\nHow can I support distributed logging? \nWith remote socket servers appenders for example.\n" ]
[ 5, 1, 1 ]
[]
[]
[ "c++", "java", "logging", "python" ]
stackoverflow_0002885822_c++_java_logging_python.txt
Q: standard geographic tilizing/binning method? I'm trying to learn and understand more about mapping and displaying values on a map. (GIS) At the moment I'M looking to take some values and apply those values to a tile or bin on a map. Ideally I'd like the tile sizes to be uniform, like 100 meters, 500 meters, etc. Is there a standard method for creating uniform tile sizes? Or Are what are common accepted method to deal with this kind of data display? (Currently I'm using geodjango and it's related toolset geos, proj4, etc) A: It sounds like you want to be working with geospatial raster image formats, where the color of a pixel represents the value for that tile. The size of a tile (and whether it's uniform) will depend on the projection of your raster. GDAL is a library for working with geospatial raster formats.
standard geographic tilizing/binning method?
I'm trying to learn and understand more about mapping and displaying values on a map. (GIS) At the moment I'M looking to take some values and apply those values to a tile or bin on a map. Ideally I'd like the tile sizes to be uniform, like 100 meters, 500 meters, etc. Is there a standard method for creating uniform tile sizes? Or Are what are common accepted method to deal with this kind of data display? (Currently I'm using geodjango and it's related toolset geos, proj4, etc)
[ "It sounds like you want to be working with geospatial raster image formats, where the color of a pixel represents the value for that tile. \nThe size of a tile (and whether it's uniform) will depend on the projection of your raster.\nGDAL is a library for working with geospatial raster formats.\n" ]
[ 1 ]
[]
[]
[ "geodjango", "gis", "mapping", "python", "tiling" ]
stackoverflow_0002921586_geodjango_gis_mapping_python_tiling.txt
Q: problem with list return type? my list has value such as m=[['na','1','2']['ka','31','45']['ra','3','5'] d=0 r=2 t=m[d][r] print t # this is givin number i.e 2 Now when I use this value u=[] u=m[t] I am getting an err msg saying type error list does take str values... i want to use like this how can i convert that t into a integer?? please suggest.. thanks.. A: Your problem is that you can't index into a list using a string. To convert t to an integer use int: u=m[int(t)] A: Use int(t) as the index, not t itself, since t is a string and to index a variable you need an integer, not a string, as the error message is telling you.
problem with list return type?
my list has value such as m=[['na','1','2']['ka','31','45']['ra','3','5'] d=0 r=2 t=m[d][r] print t # this is givin number i.e 2 Now when I use this value u=[] u=m[t] I am getting an err msg saying type error list does take str values... i want to use like this how can i convert that t into a integer?? please suggest.. thanks..
[ "Your problem is that you can't index into a list using a string. To convert t to an integer use int:\nu=m[int(t)]\n\n", "Use int(t) as the index, not t itself, since t is a string and to index a variable you need an integer, not a string, as the error message is telling you.\n" ]
[ 3, 3 ]
[]
[]
[ "python" ]
stackoverflow_0002926788_python.txt
Q: Taking file name from list and opening it? I have list similar to this: m=[['qw','wew','23','C:/xyz/s.wav'],['qw','wew','23','C:/xyz/s2.wav'],['qw','wew','23','C:/xyz/s1.wav']] Now I want to these files win=wave.open(m[0][3],'rb') It is giving error how can I use this in this way... I want to take the files name from the list Please suggest??? A: do this: m = [['qw','wew','23','C:/xyz/s.wav'],['qw','wew','23','C:/xyz/s2.wav'],['qw','wew','23','C:/xyz/s1.wav']] fname = m[0][3] print 'fname is', repr(fname) win = wave.open(fname, 'rb') and show us (using copy/paste into an edit of your question) everything that is printed, especially (1) the result of print 'fname is', repr(fname) (2) the ERROR MESSAGE
Taking file name from list and opening it?
I have list similar to this: m=[['qw','wew','23','C:/xyz/s.wav'],['qw','wew','23','C:/xyz/s2.wav'],['qw','wew','23','C:/xyz/s1.wav']] Now I want to these files win=wave.open(m[0][3],'rb') It is giving error how can I use this in this way... I want to take the files name from the list Please suggest???
[ "do this:\nm = [['qw','wew','23','C:/xyz/s.wav'],['qw','wew','23','C:/xyz/s2.wav'],['qw','wew','23','C:/xyz/s1.wav']]\nfname = m[0][3]\nprint 'fname is', repr(fname)\nwin = wave.open(fname, 'rb')\n\nand show us (using copy/paste into an edit of your question) everything that is printed, especially\n(1) the result of print 'fname is', repr(fname)\n(2) the ERROR MESSAGE \n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0002926866_python.txt
Q: Sort by an object's type I have code that statically registers (type, handler_function) pairs at module load time, resulting in a dict like this: HANDLERS = { str: HandleStr, int: HandleInt, ParentClass: HandleCustomParent, ChildClass: HandleCustomChild } def HandleObject(obj): for data_type in sorted(HANDLERS.keys(), ???): if isinstance(obj, data_type): HANDLERS[data_type](obj) Where ChildClass inherits from ParentClass. The problem is that, since its a dict, the order isn't defined - but how do I introspect type objects to figure out a sort key? The resulting order should be child classes follow by super classes (most specific types first). E.g. str comes before basestring, and ChildClass comes before ParentClass. If types are unrelated, it doesn't matter where they go relative to each other. A: If you know you're always dealing with new-style classes: def numberofancestors(klass): return len(klass.mro()) or, if you worry there may be old-style classes in the mix: import inspect def numberofancestors(klass): return len(inspect.getmro(klass)) and then, in either case, sorted(HANDLERS, key=numberofancestors, reversed=True) will give you what you require (you don't need the .keys() part). @Ignacio's suggestion of a topological sort is theoretically correct, but since, given a class, you can easily and rapidly get the number of its precursors (AKA "ancestors"... in a weird sense of the word whereby you're one of your ancestors;-), with these numberofancestors functions, my approach is much more practical: it relies on the obvious fact that any derived class has at least one more "ancestor" than any of its bases classes, and therefore, with this key=, it will always sort before any of its bases. Unrelated classes may end up in arbitrary order (just like they might in a topological sort), but you've made it clear you don't care about this. Edit: the OP, musing in the following comments thread about optimal support for multiple inheritance cases, came up with a drastically different idea than the original one of "pre-sorting" embedded in the question, but his suggestion on how to implement that drastically idea is not optimal: [h for h in [HANDLERS.get(c) for c in type(obj).mro()] if h is not None][0] the idea is good (if multiple-inheritance support is of any interest) but the best implementation thereof would probably be (Python 2.6 or better): next(Handlers[c] for c in type(obj).mro() if c in Handlers) Normally, adict.get(k) and check for not None is faster than if k in adict: adict[k], but this is not a particularly normal case because to use get requires building a "fake" one-item list and "looping" on it to simulate assignment. More generally, building a whole list via comprehension just to take its [0]th item is excess work -- the next builtin function called on a genexp acts more like a first, as in, "give me the first item of the genexp" and does no extra work beyond that. It raises StopIteration instead of IndexError if the listcomp/genexp is empty, but that's not normally an issue; you could also have a second argument to next, to be uses as the "default value" if the genexp is empty. In 2.5 and earlier you'd have to use (thegenexp).next() instead (and there's no way to give it a default argument), but while syntactically a tad less shiny it's more or less equivalent to the 2.6-and-better construct in semantics and speed. I'm sure glad the discussion continued in the comments because I think this resulting conclusion is worthwhile and potentially useful (though maybe not in the exact environment of the OP's application, where multiple inheritance may not in fact be an issue). A: Do a topological sort with the __bases__ members of each class. A: Use collections.OrderedDict from Python 2.7 or 3.1. It's written in pure Python so you could easily plug it into or adapt it to an earlier version if necessary. An OrderedDict will maintain the order of insertion.
Sort by an object's type
I have code that statically registers (type, handler_function) pairs at module load time, resulting in a dict like this: HANDLERS = { str: HandleStr, int: HandleInt, ParentClass: HandleCustomParent, ChildClass: HandleCustomChild } def HandleObject(obj): for data_type in sorted(HANDLERS.keys(), ???): if isinstance(obj, data_type): HANDLERS[data_type](obj) Where ChildClass inherits from ParentClass. The problem is that, since its a dict, the order isn't defined - but how do I introspect type objects to figure out a sort key? The resulting order should be child classes follow by super classes (most specific types first). E.g. str comes before basestring, and ChildClass comes before ParentClass. If types are unrelated, it doesn't matter where they go relative to each other.
[ "If you know you're always dealing with new-style classes:\ndef numberofancestors(klass):\n return len(klass.mro())\n\nor, if you worry there may be old-style classes in the mix:\nimport inspect\n\ndef numberofancestors(klass):\n return len(inspect.getmro(klass))\n\nand then, in either case,\nsorted(HANDLERS, key=numberofancestors, reversed=True)\n\nwill give you what you require (you don't need the .keys() part).\n@Ignacio's suggestion of a topological sort is theoretically correct, but since, given a class, you can easily and rapidly get the number of its precursors (AKA \"ancestors\"... in a weird sense of the word whereby you're one of your ancestors;-), with these numberofancestors functions, my approach is much more practical: it relies on the obvious fact that any derived class has at least one more \"ancestor\" than any of its bases classes, and therefore, with this key=, it will always sort before any of its bases.\nUnrelated classes may end up in arbitrary order (just like they might in a topological sort), but you've made it clear you don't care about this.\nEdit: the OP, musing in the following comments thread about optimal support for multiple inheritance cases, came up with a drastically different idea than the original one of \"pre-sorting\" embedded in the question, but his suggestion on how to implement that drastically idea is not optimal:\n[h for h in [HANDLERS.get(c) for c in type(obj).mro()] if h is not None][0]\n\nthe idea is good (if multiple-inheritance support is of any interest) but the best implementation thereof would probably be (Python 2.6 or better):\nnext(Handlers[c] for c in type(obj).mro() if c in Handlers)\n\nNormally, adict.get(k) and check for not None is faster than if k in adict: adict[k], but this is not a particularly normal case because to use get requires building a \"fake\" one-item list and \"looping\" on it to simulate assignment.\nMore generally, building a whole list via comprehension just to take its [0]th item is excess work -- the next builtin function called on a genexp acts more like a first, as in, \"give me the first item of the genexp\" and does no extra work beyond that. It raises StopIteration instead of IndexError if the listcomp/genexp is empty, but that's not normally an issue; you could also have a second argument to next, to be uses as the \"default value\" if the genexp is empty.\nIn 2.5 and earlier you'd have to use (thegenexp).next() instead (and there's no way to give it a default argument), but while syntactically a tad less shiny it's more or less equivalent to the 2.6-and-better construct in semantics and speed.\nI'm sure glad the discussion continued in the comments because I think this resulting conclusion is worthwhile and potentially useful (though maybe not in the exact environment of the OP's application, where multiple inheritance may not in fact be an issue).\n", "Do a topological sort with the __bases__ members of each class.\n", "Use collections.OrderedDict from Python 2.7 or 3.1. It's written in pure Python so you could easily plug it into or adapt it to an earlier version if necessary. \nAn OrderedDict will maintain the order of insertion.\n" ]
[ 5, 1, 0 ]
[]
[]
[ "python", "sorting" ]
stackoverflow_0002926522_python_sorting.txt
Q: Django get old url In django views,From the request how would we know from which page this view was called def password_change(request): if request.method == 'POST': u=request.user u.set_password(request.POST.get('new_password')) u.save() post_change_redirect= //Need old link here return HttpResponseRedirect(post_change_redirect) A: try request.path A: Normally a variable in the query string (accessible via request.GET) is used to instruct the view where to redirect to. A: request.path will return the full path (not including the domain). e.g. /music/bands/the_beatles/
Django get old url
In django views,From the request how would we know from which page this view was called def password_change(request): if request.method == 'POST': u=request.user u.set_password(request.POST.get('new_password')) u.save() post_change_redirect= //Need old link here return HttpResponseRedirect(post_change_redirect)
[ "try request.path\n", "Normally a variable in the query string (accessible via request.GET) is used to instruct the view where to redirect to.\n", "request.path\n\nwill return the full path (not including the domain). \ne.g. /music/bands/the_beatles/\n" ]
[ 1, 1, 0 ]
[]
[]
[ "django", "django_models", "django_views", "python" ]
stackoverflow_0002927031_django_django_models_django_views_python.txt
Q: Setting attributes of a class during construction from **kwargs Python noob here, Currently I'm working with SQLAlchemy, and I have this: from __init__ import Base from sqlalchemy.schema import Column, ForeignKey from sqlalchemy.types import Integer, String from sqlalchemy.orm import relationship class User(Base): __tablename__ = "users" id = Column(Integer, primary_key=True) username = Column(String, unique=True) email = Column(String) password = Column(String) salt = Column(String) openids = relationship("OpenID", backref="users") User.__table__.create(checkfirst=True) #snip definition of OpenID class def create(**kwargs): user = User() if "username" in kwargs.keys(): user.username = kwargs['username'] if "email" in kwargs.keys(): user.username = kwargs['email'] if "password" in kwargs.keys(): user.password = kwargs['password'] return user This is in /db/users.py, so it would be used like: from db import users new_user = users.create(username="Carson", password="1234") new_user.email = "email@address.com" users.add(new_user) #this function obviously not defined yet but the code in create() is a little stupid, and I'm wondering if there's a better way to do it that doesn't require an if ladder, and that will fail if any keys are added that aren't in the User object already. Like: for attribute in kwargs.keys(): if attribute in User: setattr(user, attribute, kwargs[attribute]) else: raise Exception("blah") that way I could put this in its own function (unless one hopefully already exists?) So I wouldn't have to do the if ladder again and again, and so I could change the table structure without modifying this code. Any suggestions? A: My suggestion would be to not simplify it any further. You risk stepping on important object structures if you assign arbitrary attributes. The one simplification I would do is to drop .keys() when you use it on a dict; both containment checking and iteration already use the keys. ... On second thought, you could have a class attribute that contains known safe attributes, and then check this attribute within the function, and use setattr() on the instance. A: Actually the declarative base class already inserts the exact constructor that you are looking for, as documented in the declarative modules docs. So just doing User(username="Carson", password="1234") will do what you want and User(something_not_an_attribute='foo') will raise an exception. A: If you don't need to cover inherited attributes, def create(**kwargs): keys_ok = set(User.__dict__) user = User() for k in kwargs: if k in keys_ok: setattr(user, k, kwargs[k]) If you do need to cover inherited attributes, inspect.getmembers can help (with a custom predicate to avoid members whose names start with underscore, or others you want to ensure can't be set this way). I would also consider (at least) giving a warning if set(kwargs) - set(keys_ok) is not empty -- i.e., if some of the named arguments passed to create cannot be set as arguments in the created instance; that can't be a good thing...!-)
Setting attributes of a class during construction from **kwargs
Python noob here, Currently I'm working with SQLAlchemy, and I have this: from __init__ import Base from sqlalchemy.schema import Column, ForeignKey from sqlalchemy.types import Integer, String from sqlalchemy.orm import relationship class User(Base): __tablename__ = "users" id = Column(Integer, primary_key=True) username = Column(String, unique=True) email = Column(String) password = Column(String) salt = Column(String) openids = relationship("OpenID", backref="users") User.__table__.create(checkfirst=True) #snip definition of OpenID class def create(**kwargs): user = User() if "username" in kwargs.keys(): user.username = kwargs['username'] if "email" in kwargs.keys(): user.username = kwargs['email'] if "password" in kwargs.keys(): user.password = kwargs['password'] return user This is in /db/users.py, so it would be used like: from db import users new_user = users.create(username="Carson", password="1234") new_user.email = "email@address.com" users.add(new_user) #this function obviously not defined yet but the code in create() is a little stupid, and I'm wondering if there's a better way to do it that doesn't require an if ladder, and that will fail if any keys are added that aren't in the User object already. Like: for attribute in kwargs.keys(): if attribute in User: setattr(user, attribute, kwargs[attribute]) else: raise Exception("blah") that way I could put this in its own function (unless one hopefully already exists?) So I wouldn't have to do the if ladder again and again, and so I could change the table structure without modifying this code. Any suggestions?
[ "My suggestion would be to not simplify it any further. You risk stepping on important object structures if you assign arbitrary attributes.\nThe one simplification I would do is to drop .keys() when you use it on a dict; both containment checking and iteration already use the keys.\n...\nOn second thought, you could have a class attribute that contains known safe attributes, and then check this attribute within the function, and use setattr() on the instance.\n", "Actually the declarative base class already inserts the exact constructor that you are looking for, as documented in the declarative modules docs. So just doing User(username=\"Carson\", password=\"1234\") will do what you want and User(something_not_an_attribute='foo') will raise an exception.\n", "If you don't need to cover inherited attributes,\ndef create(**kwargs):\n keys_ok = set(User.__dict__)\n user = User()\n for k in kwargs:\n if k in keys_ok:\n setattr(user, k, kwargs[k])\n\nIf you do need to cover inherited attributes, inspect.getmembers can help (with a custom predicate to avoid members whose names start with underscore, or others you want to ensure can't be set this way).\nI would also consider (at least) giving a warning if set(kwargs) - set(keys_ok) is not empty -- i.e., if some of the named arguments passed to create cannot be set as arguments in the created instance; that can't be a good thing...!-)\n" ]
[ 2, 2, 1 ]
[]
[]
[ "class", "class_attributes", "python", "sqlalchemy" ]
stackoverflow_0002926593_class_class_attributes_python_sqlalchemy.txt
Q: Authentication using cookie key with asynchronous callback I need to write authentication function with asynchronous callback from remote Auth API. Simple authentication with login is working well, but authorization with cookie key, does not work. It should checks if in cookies present key "lp_login", fetch API url like async and execute on_response function. The code almost works, but I see two problems. First, in on_response function I need to setup secure cookie for authorized user on every page. In code user_id returns correct ID, but line: self.set_secure_cookie("user", user_id) does't work. Why it can be? And second problem. During async fetch API url, user's page has loaded before on_response setup cookie with key "user" and the page will has an unauthorized section with link to login or sign on. It will be confusing for users. To solve it, I can stop loading page for user who trying to load first page of site. Is it possible to do and how? Maybe the problem has more correct way to solve it? class BaseHandler(tornado.web.RequestHandler): @tornado.web.asynchronous def get_current_user(self): user_id = self.get_secure_cookie("user") user_cookie = self.get_cookie("lp_login") if user_id: self.set_secure_cookie("user", user_id) return Author.objects.get(id=int(user_id)) elif user_cookie: url = urlparse("http://%s" % self.request.host) domain = url.netloc.split(":")[0] try: username, hashed_password = urllib.unquote(user_cookie).rsplit(',',1) except ValueError: # check against malicious clients return None else: url = "http://%s%s%s/%s/" % (domain, "/api/user/username/", username, hashed_password) http = tornado.httpclient.AsyncHTTPClient() http.fetch(url, callback=self.async_callback(self.on_response)) else: return None def on_response(self, response): answer = tornado.escape.json_decode(response.body) username = answer['username'] if answer["has_valid_credentials"]: author = Author.objects.get(email=answer["email"]) user_id = str(author.id) print user_id # It returns needed id self.set_secure_cookie("user", user_id) # but session can's setup A: It seems you cross-posted this on the tornado mailing list here One of the problems you are running into is that you can't start the async call inside of get_current_user, you can only start an async call from something that happens inside of get or post. I've not tested it, but i think this should get you close to what you are looking for. #!/bin/python import tornado.web import tornado.http import tornado.escape import functools import logging import urllib import Author def upgrade_lp_login_cookie(method): @functools.wraps(method) def wrapper(self, *args, **kwargs): if not self.current_user and self.get_cookie('lp_login'): self.upgrade_lp_login(self.async_callback(method, self, *args, **kwargs)) else: return method(self, *args, **kwargs) return wrapper class BaseHandler(tornado.web.RequestHandler): def get_current_user(self): user_id = self.get_secure_cookie("user") if user_id: return Author.objects.get(id=int(user_id)) def upgrade_lp_login(self, callback): lp_login = self.get_cookie("lp_login") try: username, hashed_password = urllib.unquote(lp_login).rsplit(',',1) except ValueError: # check against malicious clients logging.info('invalid lp_login cookie %s' % lp_login) return callback() url = "http://%(host)s/api/user/username/%s/%s" % (self.request.host, urllib.quote(username), urllib.quote(hashed_password)) http = tornado.httpclient.AsyncHTTPClient() http.fetch(url, self.async_callback(self.finish_upgrade_lp_login, callback)) def finish_upgrade_lp_login(self, callback, response): answer = tornado.escape.json_decode(response.body) # username = answer['username'] if answer['has_valid_credentials']: # set for self.current_user, overriding previous output of self.get_current_user() self._current_user = Author.objects.get(email=answer["email"]) # set the cookie for next request self.set_secure_cookie("user", str(self.current_user.id)) # now chain to the real get/post method callback() @upgrade_lp_login_cookie def get(self): self.render('template.tmpl')
Authentication using cookie key with asynchronous callback
I need to write authentication function with asynchronous callback from remote Auth API. Simple authentication with login is working well, but authorization with cookie key, does not work. It should checks if in cookies present key "lp_login", fetch API url like async and execute on_response function. The code almost works, but I see two problems. First, in on_response function I need to setup secure cookie for authorized user on every page. In code user_id returns correct ID, but line: self.set_secure_cookie("user", user_id) does't work. Why it can be? And second problem. During async fetch API url, user's page has loaded before on_response setup cookie with key "user" and the page will has an unauthorized section with link to login or sign on. It will be confusing for users. To solve it, I can stop loading page for user who trying to load first page of site. Is it possible to do and how? Maybe the problem has more correct way to solve it? class BaseHandler(tornado.web.RequestHandler): @tornado.web.asynchronous def get_current_user(self): user_id = self.get_secure_cookie("user") user_cookie = self.get_cookie("lp_login") if user_id: self.set_secure_cookie("user", user_id) return Author.objects.get(id=int(user_id)) elif user_cookie: url = urlparse("http://%s" % self.request.host) domain = url.netloc.split(":")[0] try: username, hashed_password = urllib.unquote(user_cookie).rsplit(',',1) except ValueError: # check against malicious clients return None else: url = "http://%s%s%s/%s/" % (domain, "/api/user/username/", username, hashed_password) http = tornado.httpclient.AsyncHTTPClient() http.fetch(url, callback=self.async_callback(self.on_response)) else: return None def on_response(self, response): answer = tornado.escape.json_decode(response.body) username = answer['username'] if answer["has_valid_credentials"]: author = Author.objects.get(email=answer["email"]) user_id = str(author.id) print user_id # It returns needed id self.set_secure_cookie("user", user_id) # but session can's setup
[ "It seems you cross-posted this on the tornado mailing list here\nOne of the problems you are running into is that you can't start the async call inside of get_current_user, you can only start an async call from something that happens inside of get or post.\nI've not tested it, but i think this should get you close to what you are looking for.\n#!/bin/python\nimport tornado.web\nimport tornado.http\nimport tornado.escape\nimport functools\nimport logging\nimport urllib\n\nimport Author\n\ndef upgrade_lp_login_cookie(method):\n @functools.wraps(method)\n def wrapper(self, *args, **kwargs):\n if not self.current_user and self.get_cookie('lp_login'):\n self.upgrade_lp_login(self.async_callback(method, self, *args, **kwargs))\n else:\n return method(self, *args, **kwargs)\n return wrapper\n\n\nclass BaseHandler(tornado.web.RequestHandler):\n def get_current_user(self):\n user_id = self.get_secure_cookie(\"user\")\n if user_id:\n return Author.objects.get(id=int(user_id))\n\n def upgrade_lp_login(self, callback):\n lp_login = self.get_cookie(\"lp_login\")\n try:\n username, hashed_password = urllib.unquote(lp_login).rsplit(',',1)\n except ValueError:\n # check against malicious clients\n logging.info('invalid lp_login cookie %s' % lp_login)\n return callback()\n\n url = \"http://%(host)s/api/user/username/%s/%s\" % (self.request.host, \n urllib.quote(username), \n urllib.quote(hashed_password))\n http = tornado.httpclient.AsyncHTTPClient()\n http.fetch(url, self.async_callback(self.finish_upgrade_lp_login, callback))\n\n def finish_upgrade_lp_login(self, callback, response):\n answer = tornado.escape.json_decode(response.body)\n # username = answer['username']\n if answer['has_valid_credentials']:\n # set for self.current_user, overriding previous output of self.get_current_user()\n self._current_user = Author.objects.get(email=answer[\"email\"])\n # set the cookie for next request\n self.set_secure_cookie(\"user\", str(self.current_user.id))\n\n # now chain to the real get/post method\n callback()\n\n @upgrade_lp_login_cookie\n def get(self):\n self.render('template.tmpl')\n\n" ]
[ 3 ]
[]
[]
[ "asynchronous", "authentication", "python", "tornado" ]
stackoverflow_0002848907_asynchronous_authentication_python_tornado.txt
Q: How do you call function after client finishes download from tornado web server? I would like to be able to run some cleanup functions if and only if the client successfully completes the download of a file I'm serving using Tornado. I installed the firefox throttle tool and had it slow the connection down to dialup speed and installed this handler to generate a bunch of rubbish random text: class CrapHandler(BaseHandler): def get(self, token): crap = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(100000)) self.write(crap) print "done" I get the following output from tornado immediately after making the request: done I 100524 19:45:45 web:772] 200 GET /123 (192.168.45.108) 195.10ms The client then plods along downloading for about 20 seconds. I expected that it would print "done" after the client was done. Also, if I do the following I get pretty much the same result: class CrapHandler(BaseHandler): @tornado.web.asynchronous def get(self, token): crap = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(100000)) self.write(crap) self.finish() print "done" Am I missing something fundamental here? Can tornado even support what I'm trying to do? If not, is there an alternative that does? A: I believe you are looking for something that runs in the on_connection_close request handler method which you can override. Keep in mind that if you are running behind nginx, tornado will respond to nginx immediately, and nginx will slowly respond to the client. Also, keep in mind that adding @tornado.web.asynchronous doesn't actually make a request asynchronous. It only set's up the request to use tornado.http.AsyncHTTPClient.
How do you call function after client finishes download from tornado web server?
I would like to be able to run some cleanup functions if and only if the client successfully completes the download of a file I'm serving using Tornado. I installed the firefox throttle tool and had it slow the connection down to dialup speed and installed this handler to generate a bunch of rubbish random text: class CrapHandler(BaseHandler): def get(self, token): crap = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(100000)) self.write(crap) print "done" I get the following output from tornado immediately after making the request: done I 100524 19:45:45 web:772] 200 GET /123 (192.168.45.108) 195.10ms The client then plods along downloading for about 20 seconds. I expected that it would print "done" after the client was done. Also, if I do the following I get pretty much the same result: class CrapHandler(BaseHandler): @tornado.web.asynchronous def get(self, token): crap = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(100000)) self.write(crap) self.finish() print "done" Am I missing something fundamental here? Can tornado even support what I'm trying to do? If not, is there an alternative that does?
[ "I believe you are looking for something that runs in the on_connection_close request handler method which you can override.\nKeep in mind that if you are running behind nginx, tornado will respond to nginx immediately, and nginx will slowly respond to the client.\nAlso, keep in mind that adding @tornado.web.asynchronous doesn't actually make a request asynchronous. It only set's up the request to use tornado.http.AsyncHTTPClient.\n" ]
[ 1 ]
[]
[]
[ "python", "tornado" ]
stackoverflow_0002896082_python_tornado.txt
Q: Is there a way to convert code to a string and vice versa in Python? The original question was: Is there a way to declare macros in Python as they are declared in C: #define OBJWITHSIZE(_x) (sizeof _x)/(sizeof _x[0]) Here's what I'm trying to find out: Is there a way to avoid code duplication in Python? In one part of a program I'm writing, I have a function: def replaceProgramFilesPath(filenameBr): def getProgramFilesPath(): import os return os.environ.get("PROGRAMFILES") + chr(92) return filenameBr.replace("<ProgramFilesPath>",getProgramFilesPath() ) In another part, I've got this code embedded in a string that will later be output to a python file that will itself be run: """ def replaceProgramFilesPath(filenameBr): def getProgramFilesPath(): import os return os.environ.get("PROGRAMFILES") + chr(92) return filenameBr.replace("<ProgramFilesPath>",getProgramFilesPath() ) """ How can I build a "macro" that will avoid this duplication? A: Answering the new question. In your first python file (called, for example, first.py): import os def replaceProgramFilesPath(filenameBr): new_path = os.environ.get("PROGRAMFILES") + chr(92) return filenameBr.replace("<ProgramFilesPath>", new_path) In the second python file (called, for example, second.py): from first import replaceProgramFilesPath # now replaceProgramFilesPath can be used in this script. Note that first.py will need to be in python's search path for modules or the same directory as second.py for you to be able to do the import in second.py. A: No, Python does not support preprocessor macros like C. Your example isn't something you would need to do in Python though; you might consider providing a relevant example so people can suggest a Pythonic way to express what you need. A: While there does seem to be a library for python preprocessing called pypp, I am not entirely familiar with it. There really is no preprocessing capability for python built-in. Python code is translated into byte-code, there are no intermediate steps. If you are a beginner in python I would recommend avoiding pypp entirely. The closest equivalent of macros might be to define a global function. The python equivalent to your C style macro might be: import sys OBJWITHSIZE = lambda x: sys.getsizeof(x) / sys.getsizeof(x[0]) aList = [1, 2, 4, 5] size = OBJWITHSIZE(aList) print str(size) Note that you would rarely ever need to get the size of a python object as all allocation and deletion are handled for you in python unless you are doing something quite strange. Instead of using a lambda function you could also do this: import sys def getSize(x): return sys.getsizeof(x) / sys.getsizeof(x[0]) OBJWITHSIZE = getSize aList = [1, 2, 4, 5] size = OBJWITHSIZE(aList) print str(size) Which is essentially the same. As it has been previously mentioned, your example macro is redundant in python because you could simply write: aList = [1, 2, 4, 5] size = len(aList) print str(size) A: This is not supported at the language level. In Python, you'd usually use a normal function or a normal variable where you might use a #define in C. A: Generally speaking if you want to convert string to python code, use eval. You rarely need eval in Python. There's a module somewhere in the standard library that can tell you a bit about an objects code (doesn't work in the interp), I've never used it directly. You can find stuff on comp.lang.python that explains it. As to 'C' macros which seem to be the real focus of your question. clears throat DO NOT USE C MACROS IN PYTHON CODE. If all you want is a C macro, use the C pre processor to pre process your scripts. Duh. If you want #include, it's called import. If you want #define, use an immutable object. Think const int foo=1; instead of #define foo 1. Some objects are immutable, like tuples. You can write a function that makes a variable sufficiently immutable. Search the web for an example. I rather like static classes for some cases like that. If you want FOO(x, y) ... code ...; learn how to use functions and classes. Most uses of a 'CPP' macro in Python, can be accomplished by writing a function. You may wish to get a book on higher order functions, in order to handle more complex cases. I personally like a book called Higher Order Perl (HOP), and although it is not Python based, most of the book covers language independent ideas -- and those ideas should be required learning for every programmer. For all intents and purposes the only use of the C Pre Processor that you need in Python, that isn't quite provided out of box, is the ability to #define constants, which is often the wrong thing to do, even in C and C++. Now implementing lisp macros in python, in a smart way and actually needing them... clears throat and sweeps under rug. A: Well, for the brave, there's Metapython: http://code.google.com/p/metapython/wiki/Tutorial For instance, the following MetaPython code: $for i in range(3): print $i will expand to the following Python code: print 0 print 1 print 2 But if you have just started with Python, you probably won't need it. Just keep practicing the usual dynamic features (duck typing, callable objects, decorators, generators...) and you won't feel any need for C-style macros. A: You can write this into the second file instead of replicating the code string """ from firstFile import replaceProgramFilesPath """
Is there a way to convert code to a string and vice versa in Python?
The original question was: Is there a way to declare macros in Python as they are declared in C: #define OBJWITHSIZE(_x) (sizeof _x)/(sizeof _x[0]) Here's what I'm trying to find out: Is there a way to avoid code duplication in Python? In one part of a program I'm writing, I have a function: def replaceProgramFilesPath(filenameBr): def getProgramFilesPath(): import os return os.environ.get("PROGRAMFILES") + chr(92) return filenameBr.replace("<ProgramFilesPath>",getProgramFilesPath() ) In another part, I've got this code embedded in a string that will later be output to a python file that will itself be run: """ def replaceProgramFilesPath(filenameBr): def getProgramFilesPath(): import os return os.environ.get("PROGRAMFILES") + chr(92) return filenameBr.replace("<ProgramFilesPath>",getProgramFilesPath() ) """ How can I build a "macro" that will avoid this duplication?
[ "Answering the new question.\nIn your first python file (called, for example, first.py):\nimport os\n\ndef replaceProgramFilesPath(filenameBr):\n new_path = os.environ.get(\"PROGRAMFILES\") + chr(92)\n return filenameBr.replace(\"<ProgramFilesPath>\", new_path)\n\nIn the second python file (called, for example, second.py):\nfrom first import replaceProgramFilesPath\n# now replaceProgramFilesPath can be used in this script.\n\nNote that first.py will need to be in python's search path for modules or the same directory as second.py for you to be able to do the import in second.py.\n", "No, Python does not support preprocessor macros like C. Your example isn't something you would need to do in Python though; you might consider providing a relevant example so people can suggest a Pythonic way to express what you need.\n", "While there does seem to be a library for python preprocessing called pypp, I am not entirely familiar with it. There really is no preprocessing capability for python built-in. Python code is translated into byte-code, there are no intermediate steps. If you are a beginner in python I would recommend avoiding pypp entirely.\nThe closest equivalent of macros might be to define a global function. The python equivalent to your C style macro might be:\nimport sys\nOBJWITHSIZE = lambda x: sys.getsizeof(x) / sys.getsizeof(x[0])\naList = [1, 2, 4, 5]\nsize = OBJWITHSIZE(aList)\nprint str(size)\n\nNote that you would rarely ever need to get the size of a python object as all allocation and deletion are handled for you in python unless you are doing something quite strange.\nInstead of using a lambda function you could also do this:\nimport sys\ndef getSize(x):\n return sys.getsizeof(x) / sys.getsizeof(x[0])\n\nOBJWITHSIZE = getSize\naList = [1, 2, 4, 5]\nsize = OBJWITHSIZE(aList)\nprint str(size)\n\nWhich is essentially the same.\nAs it has been previously mentioned, your example macro is redundant in python because you could simply write:\naList = [1, 2, 4, 5]\nsize = len(aList)\nprint str(size)\n\n", "This is not supported at the language level. In Python, you'd usually use a normal function or a normal variable where you might use a #define in C.\n", "Generally speaking if you want to convert string to python code, use eval. You rarely need eval in Python. There's a module somewhere in the standard library that can tell you a bit about an objects code (doesn't work in the interp), I've never used it directly. You can find stuff on comp.lang.python that explains it.\nAs to 'C' macros which seem to be the real focus of your question.\nclears throat DO NOT USE C MACROS IN PYTHON CODE.\n\nIf all you want is a C macro, use the C pre processor to pre process your scripts. Duh.\nIf you want #include, it's called import.\nIf you want #define, use an immutable object. Think const int foo=1; instead of #define foo 1. Some objects are immutable, like tuples. You can write a function that makes a variable sufficiently immutable. Search the web for an example. I rather like static classes for some cases like that.\nIf you want FOO(x, y) ... code ...; learn how to use functions and classes.\n\nMost uses of a 'CPP' macro in Python, can be accomplished by writing a function. You may wish to get a book on higher order functions, in order to handle more complex cases. I personally like a book called Higher Order Perl (HOP), and although it is not Python based, most of the book covers language independent ideas -- and those ideas should be required learning for every programmer.\nFor all intents and purposes the only use of the C Pre Processor that you need in Python, that isn't quite provided out of box, is the ability to #define constants, which is often the wrong thing to do, even in C and C++.\nNow implementing lisp macros in python, in a smart way and actually needing them... clears throat and sweeps under rug.\n", "Well, for the brave, there's Metapython:\nhttp://code.google.com/p/metapython/wiki/Tutorial\nFor instance, the following MetaPython code:\n\n$for i in range(3):\n print $i\n\nwill expand to the following Python code:\n\nprint 0\nprint 1\nprint 2\n\nBut if you have just started with Python, you probably won't need it. Just keep practicing the usual dynamic features (duck typing, callable objects, decorators, generators...) and you won't feel any need for C-style macros.\n", "You can write this into the second file instead of replicating the code string\n\"\"\"\nfrom firstFile import replaceProgramFilesPath\n\"\"\"\n\n" ]
[ 3, 2, 2, 2, 2, 0, 0 ]
[]
[]
[ "macros", "python" ]
stackoverflow_0002925174_macros_python.txt
Q: Python: Problem importing pycurl I am working on OpenSolaris(2009.06) OS. i recently installed the pycurl libraires using the following command: $> python setup.py install --curl-config=/usr/local/bin/curl-config the installation went perfectly fine. However now when i am trying to import the pycurl library in my python program, an error is being reported >>>import pycurl Traceback (most recent call last): File "<stdin>", line 1, in ? ImportError: ld.so.1: isapython2.4: fatal: libcurl.so.4: open failed: No such file or directory I cant figure out where exactly i am going wrong. Any help...? Thanks in advance. Shubham A: Sounds like your loader doesn't know where to find the cURL library. See your OS documentation for how to specify locations to search.
Python: Problem importing pycurl
I am working on OpenSolaris(2009.06) OS. i recently installed the pycurl libraires using the following command: $> python setup.py install --curl-config=/usr/local/bin/curl-config the installation went perfectly fine. However now when i am trying to import the pycurl library in my python program, an error is being reported >>>import pycurl Traceback (most recent call last): File "<stdin>", line 1, in ? ImportError: ld.so.1: isapython2.4: fatal: libcurl.so.4: open failed: No such file or directory I cant figure out where exactly i am going wrong. Any help...? Thanks in advance. Shubham
[ "Sounds like your loader doesn't know where to find the cURL library. See your OS documentation for how to specify locations to search.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0002927738_python.txt
Q: Downloading from links in an rss feed I am trying to create a directory with news articles collected from an rss feed, meaning that whenever there is a link to an article within the rss feed, I would like for it to be downloaded in a directory with the title of the specific article as the filename as as a text file. Is that something Python can help me do ? Thank you for your help :-) A: You can parse RSS feeds with feedparser and download files with urllib2. If you need to parse HTML use BeautifulSoup. If you have any problems with those, post more specific questions. A: Of course. BeautifulSoup, lxml, urllib2, urlgrabber.
Downloading from links in an rss feed
I am trying to create a directory with news articles collected from an rss feed, meaning that whenever there is a link to an article within the rss feed, I would like for it to be downloaded in a directory with the title of the specific article as the filename as as a text file. Is that something Python can help me do ? Thank you for your help :-)
[ "You can parse RSS feeds with feedparser and download files with urllib2. If you need to parse HTML use BeautifulSoup. If you have any problems with those, post more specific questions.\n", "Of course. BeautifulSoup, lxml, urllib2, urlgrabber.\n" ]
[ 2, 1 ]
[]
[]
[ "python", "rss" ]
stackoverflow_0002927543_python_rss.txt
Q: Running a batch file with parameters in Python OR F# I searched the site, but I didn't see anything quite matching what I was looking for. I created a stand-alone application that uses a web service I created. To run the client I use: C:/scriptsdirecotry> "run-client.bat" param1 param2 param3 param4 How would I go about coding this in Python or F#. It seems like it should be pretty simple, but I haven't seen anything online that quite matches what I'm looking for. A: Python is similar. import os os.system("run-client.bat param1 param2") If you need asynchronous behavior or redirected standard streams. from subprocess import * p = Popen(['run-client.bat', param1, param2], stdout=PIPE, stderr=PIPE) output, errors = p.communicate() p.wait() # wait for process to terminate A: In F#, you could use the Process class from the System.Diagnostics namespace. The simplest way to run the command should be this: open System.Diagnostics Process.Start("run-client.bat", "param1 param2") However, if you need to provide more parameters, you may need to create ProcessStartInfo object first (it allows you to specify more options). A: Or you can use fsi.exe to call a F# script (.fsx). Given the following code in file "Script.fsx" #light printfn "You used following arguments: " for arg in fsi.CommandLineArgs do printfn "\t%s" arg printfn "Done!" You can call it from the command line using the syntax: fsi --exec .\Script.fsx hello world The FSharp interactive will then return You used following arguments: .\Script.fsx hello world Done! There is more information about fsi.exe command line options at msdn: http://msdn.microsoft.com/en-us/library/dd233172.aspx
Running a batch file with parameters in Python OR F#
I searched the site, but I didn't see anything quite matching what I was looking for. I created a stand-alone application that uses a web service I created. To run the client I use: C:/scriptsdirecotry> "run-client.bat" param1 param2 param3 param4 How would I go about coding this in Python or F#. It seems like it should be pretty simple, but I haven't seen anything online that quite matches what I'm looking for.
[ "Python is similar.\nimport os\nos.system(\"run-client.bat param1 param2\")\n\nIf you need asynchronous behavior or redirected standard streams.\nfrom subprocess import *\np = Popen(['run-client.bat', param1, param2], stdout=PIPE, stderr=PIPE)\noutput, errors = p.communicate()\np.wait() # wait for process to terminate\n\n", "In F#, you could use the Process class from the System.Diagnostics namespace. The simplest way to run the command should be this:\nopen System.Diagnostics\nProcess.Start(\"run-client.bat\", \"param1 param2\")\n\nHowever, if you need to provide more parameters, you may need to create ProcessStartInfo object first (it allows you to specify more options).\n", "Or you can use fsi.exe to call a F# script (.fsx). Given the following code in file \"Script.fsx\"\n#light\n\nprintfn \"You used following arguments: \"\nfor arg in fsi.CommandLineArgs do\n printfn \"\\t%s\" arg\n\nprintfn \"Done!\"\n\nYou can call it from the command line using the syntax:\nfsi --exec .\\Script.fsx hello world\n\nThe FSharp interactive will then return\nYou used following arguments:\n .\\Script.fsx\n hello\n world\nDone!\n\nThere is more information about fsi.exe command line options at msdn: http://msdn.microsoft.com/en-us/library/dd233172.aspx\n" ]
[ 14, 8, 2 ]
[]
[]
[ "batch_file", "f#", "python", "web_services", "windows" ]
stackoverflow_0002916758_batch_file_f#_python_web_services_windows.txt
Q: Issue in exec method I am a having two python files file1.py and file2.py. I am using exec() to get the method/Variables defined in the file2.py. file1.py have a class as given below class one: def __init__(self): self.HOOK = None exec(file2.py) self.HOOK = Generate ### call the hook method #### self.HOOK() file2.py looks like as (There is no class define in file2.py) def Generate() do 1 do 2 hello() def Hello() print "hello" Now the problem is as When i run script it is giving a error global name Hello not found. If i remove Hello() from Generate method in file2.py then its work fine. I cant use import file2.py in file1.py,because in file2.py the only one method name (Generate) is fix (its taken as requirement). So apart from Genarate method user can define any method and can call this in generate method, because this approach is not working so i have to write whole code into generate method only and code is also repetitive. Any help is really appreciable... A: Try this: # file1.py from file2 import Generate class one: def __init__(self): self.HOOK = Generate ### call the hook method #### self.HOOK() In your second file: # file2.py def Generate(): # do 1 # do 2 hello() def hello() print "hello" A: From what you have posted, it looks like you define a function def hello(): print "hello" and then tries to call another function Hello() Notice that python cares a lot about capital and noncapital letters. A: You can safely write from file2 import Generate in file1.py, that will do the trick - it will import only the Generate method from file2 into the current namespace, so all the other methods the user has defined in file2 won't clutter the namespace of file1.
Issue in exec method
I am a having two python files file1.py and file2.py. I am using exec() to get the method/Variables defined in the file2.py. file1.py have a class as given below class one: def __init__(self): self.HOOK = None exec(file2.py) self.HOOK = Generate ### call the hook method #### self.HOOK() file2.py looks like as (There is no class define in file2.py) def Generate() do 1 do 2 hello() def Hello() print "hello" Now the problem is as When i run script it is giving a error global name Hello not found. If i remove Hello() from Generate method in file2.py then its work fine. I cant use import file2.py in file1.py,because in file2.py the only one method name (Generate) is fix (its taken as requirement). So apart from Genarate method user can define any method and can call this in generate method, because this approach is not working so i have to write whole code into generate method only and code is also repetitive. Any help is really appreciable...
[ "Try this:\n# file1.py\nfrom file2 import Generate\n\nclass one:\n def __init__(self):\n self.HOOK = Generate\n ### call the hook method ####\n self.HOOK()\n\nIn your second file:\n# file2.py\ndef Generate():\n # do 1\n # do 2\n hello()\n\ndef hello()\n print \"hello\"\n\n", "From what you have posted, it looks like you define a function\ndef hello():\n print \"hello\"\n\nand then tries to call another function\nHello()\n\nNotice that python cares a lot about capital and noncapital letters.\n", "You can safely write from file2 import Generate in file1.py, that will do the trick - it will import only the Generate method from file2 into the current namespace, so all the other methods the user has defined in file2 won't clutter the namespace of file1.\n" ]
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002927005_python.txt
Q: Starting Tornado Web I'm quite new to using Tornado Web as a web server, and am having a little difficulty keeping it running. I normally use Django and Nginx, and am used to start/stop/restarting the server. However with Tornado I'm having trouble telling it to "run" without directly executing my main python file for the site, ie "python ~/path/to/server.py". I'm sure I'm getting this completely wrong - is there a way of 'bootstrapping' my script so that when Nginx starts, Tornado starts? Any help would be appreciated! A: A better way to do it is using supervisord as it is also written in python A: No, there is not a way to have nginx spawn your tornado instance. Typically you would use an external framework like daemontools or a system init script to run the tornado process.
Starting Tornado Web
I'm quite new to using Tornado Web as a web server, and am having a little difficulty keeping it running. I normally use Django and Nginx, and am used to start/stop/restarting the server. However with Tornado I'm having trouble telling it to "run" without directly executing my main python file for the site, ie "python ~/path/to/server.py". I'm sure I'm getting this completely wrong - is there a way of 'bootstrapping' my script so that when Nginx starts, Tornado starts? Any help would be appreciated!
[ "A better way to do it is using supervisord as it is also written in python\n", "No, there is not a way to have nginx spawn your tornado instance.\nTypically you would use an external framework like daemontools or a system init script to run the tornado process.\n" ]
[ 3, 2 ]
[]
[]
[ "python", "tornado", "ubuntu" ]
stackoverflow_0002864420_python_tornado_ubuntu.txt
Q: Different work of the script in Windows and in FreeBSD I'm writing some script, that works with web-servers. So, I have the following code: client = suds.client.Client(WSDLfile) client.service.Login('mylogin', 'mypass') print client.options.transport.cookiejar ####### sessnum = str(client.options.transport.cookiejar).split(' ')[1] client = suds.client.Client( WSDLfile, headers= { 'Set-Cookie' : sessnum } ) When running in FreeBSD, it returns <cookielib.CookieJar[<Cookie sessnum=9WAXQ25D37XY535F6SZ3GXKSCTZG8CVJ for .IP.IP.IP.IP/>]> but in Windows it returns <cookielib.CookieJar[]> How can I fix it? A: AFAIK client.options.transport.cookiejar is an iterable so what happens on each system when you have: for c in client.options.transport.cookiejar: print client.options.transport.cookiejar Failing that, what if in your Windows system you don't have cookies allowed? That may stop the session from being saved.
Different work of the script in Windows and in FreeBSD
I'm writing some script, that works with web-servers. So, I have the following code: client = suds.client.Client(WSDLfile) client.service.Login('mylogin', 'mypass') print client.options.transport.cookiejar ####### sessnum = str(client.options.transport.cookiejar).split(' ')[1] client = suds.client.Client( WSDLfile, headers= { 'Set-Cookie' : sessnum } ) When running in FreeBSD, it returns <cookielib.CookieJar[<Cookie sessnum=9WAXQ25D37XY535F6SZ3GXKSCTZG8CVJ for .IP.IP.IP.IP/>]> but in Windows it returns <cookielib.CookieJar[]> How can I fix it?
[ "AFAIK client.options.transport.cookiejar is an iterable so what happens on each system when you have:\nfor c in client.options.transport.cookiejar:\n print client.options.transport.cookiejar\n\nFailing that, what if in your Windows system you don't have cookies allowed? That may stop the session from being saved.\n" ]
[ 2 ]
[]
[]
[ "cookies", "python", "suds" ]
stackoverflow_0002904098_cookies_python_suds.txt
Q: Python finding n consecutive numbers in a list I want to know how to find if there is a certain amount of consecutive numbers in a row in my list e.g. For example if I am looking for two 1's then: list = [1, 1, 1, 4, 6] #original list list = ["true", "true", 1, 4, 6] #after my function has been through the list. If I am looking for three 1's then: list = [1, 1, 1, 4, 6] #original list list = ["true", "true", "true", 4, 6] #after my function has been through the list. I have tried: list = [1, 1, 2, 1] 1,1,1 in list #typed into shell, returns "(1, 1, True)" Any help would be greatly appreciated, I mainly would like to understand whats going on, and how to check if the next element in the list is the same as the first x amount. A: It is a bad idea to assign to list. Use a different name. To find the largest number of consecutive equal values you can use itertools.groupby >>> import itertools >>> l = [1, 1, 1, 4, 6] >>> max(len(list(v)) for g,v in itertools.groupby(l)) 3 To search only for consecutive 1s: >>> max(len(list(v)) for g,v in itertools.groupby(l, lambda x: x == 1) if g) 3 A: >>> def find_repeats(L, num_repeats): ... idx = 0 ... while idx < len(L): ... if [L[idx]]*num_repeats == L[idx:idx+num_repeats]: ... L[idx:idx+num_repeats] = [True]*num_repeats ... idx += num_repeats ... else: ... idx += 1 ... return L ... >>> L=[1,1,1,4,6] >>> print find_repeats(L, 2) [True, True, 1, 4, 6] >>> L=[1,1,1,4,6] >>> print find_repeats(L, 3) [True, True, True, 4, 6] >>> Here is a version that lets you also specify which number should be matched and stops after the first replacement >>> def find_repeats(L, required_number, num_repeats, stop_after_match=False): ... idx = 0 ... while idx < len(L): ... if [required_number]*num_repeats == L[idx:idx+num_repeats]: ... L[idx:idx+num_repeats] = [True]*num_repeats ... idx += num_repeats ... if stop_after_match: ... break ... else: ... idx += 1 ... return L ... >>> L=[1,1,1,4,6] >>> print find_repeats(L, 1, 2) [True, True, 1, 4, 6] >>> L=[1,1,1,4,6] >>> print find_repeats(L, 1, 3) [True, True, True, 4, 6] >>> L=[1,1,1,4,4,4,6] >>> print find_repeats(L, 1, 3) [True, True, True, 4, 4, 4, 6] >>> L=[1,1,1,4,4,4,6] >>> print find_repeats(L, 4, 3) [1, 1, 1, True, True, True, 6] A: I cannot understand what are you trying to do, but I prepared a quick, and not very good script, but it does what you need. def repeated(num, lyst): # the 'out' list will contain the array you are looking for out = [] # go through the list (notice that you go until "one before # the end" because you peek one forward) for k in range(len(lyst)-1): if lyst[k] == lyst[k+1] == num: # if the numbers are equal, add True (as a bool, but you could # also pass the actual string "True", as you have it in your question) out.append(True) else: # if they are not the same, add the number itself out.append(lyst[k]) # check the last element: if it is true, we are done (because it was the same as the # last one), if not, then we add the last number to the list (because it was not the # same) if out[-1] != True: out.append(lyst[-1]) # return the list return out Use it like: print repeated(1, [1, 1, 1, 4, 6])
Python finding n consecutive numbers in a list
I want to know how to find if there is a certain amount of consecutive numbers in a row in my list e.g. For example if I am looking for two 1's then: list = [1, 1, 1, 4, 6] #original list list = ["true", "true", 1, 4, 6] #after my function has been through the list. If I am looking for three 1's then: list = [1, 1, 1, 4, 6] #original list list = ["true", "true", "true", 4, 6] #after my function has been through the list. I have tried: list = [1, 1, 2, 1] 1,1,1 in list #typed into shell, returns "(1, 1, True)" Any help would be greatly appreciated, I mainly would like to understand whats going on, and how to check if the next element in the list is the same as the first x amount.
[ "It is a bad idea to assign to list. Use a different name.\nTo find the largest number of consecutive equal values you can use itertools.groupby\n>>> import itertools\n>>> l = [1, 1, 1, 4, 6]\n>>> max(len(list(v)) for g,v in itertools.groupby(l)) \n3\n\nTo search only for consecutive 1s:\n>>> max(len(list(v)) for g,v in itertools.groupby(l, lambda x: x == 1) if g) \n3\n\n", ">>> def find_repeats(L, num_repeats):\n... idx = 0\n... while idx < len(L):\n... if [L[idx]]*num_repeats == L[idx:idx+num_repeats]:\n... L[idx:idx+num_repeats] = [True]*num_repeats\n... idx += num_repeats\n... else:\n... idx += 1\n... return L\n... \n>>> L=[1,1,1,4,6]\n>>> print find_repeats(L, 2)\n[True, True, 1, 4, 6]\n>>> L=[1,1,1,4,6]\n>>> print find_repeats(L, 3)\n[True, True, True, 4, 6]\n>>> \n\nHere is a version that lets you also specify which number should be matched and stops after the first replacement\n>>> def find_repeats(L, required_number, num_repeats, stop_after_match=False):\n... idx = 0\n... while idx < len(L):\n... if [required_number]*num_repeats == L[idx:idx+num_repeats]:\n... L[idx:idx+num_repeats] = [True]*num_repeats\n... idx += num_repeats\n... if stop_after_match:\n... break\n... else:\n... idx += 1\n... return L\n... \n>>> L=[1,1,1,4,6]\n>>> print find_repeats(L, 1, 2)\n[True, True, 1, 4, 6]\n>>> L=[1,1,1,4,6]\n>>> print find_repeats(L, 1, 3)\n[True, True, True, 4, 6]\n>>> L=[1,1,1,4,4,4,6]\n>>> print find_repeats(L, 1, 3)\n[True, True, True, 4, 4, 4, 6]\n>>> L=[1,1,1,4,4,4,6]\n>>> print find_repeats(L, 4, 3)\n[1, 1, 1, True, True, True, 6]\n\n", "I cannot understand what are you trying to do, but I prepared a quick, and not very good script, but it does what you need.\ndef repeated(num, lyst):\n # the 'out' list will contain the array you are looking for\n out = []\n # go through the list (notice that you go until \"one before\n # the end\" because you peek one forward)\n for k in range(len(lyst)-1):\n if lyst[k] == lyst[k+1] == num:\n # if the numbers are equal, add True (as a bool, but you could\n # also pass the actual string \"True\", as you have it in your question)\n out.append(True)\n else:\n # if they are not the same, add the number itself\n out.append(lyst[k])\n # check the last element: if it is true, we are done (because it was the same as the\n # last one), if not, then we add the last number to the list (because it was not the\n # same)\n if out[-1] != True:\n out.append(lyst[-1])\n # return the list \n return out\n\nUse it like:\nprint repeated(1, [1, 1, 1, 4, 6])\n\n" ]
[ 11, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002927213_python.txt
Q: Encrypt text using a number Project Euler I have recently begun to solve some of the Project Euler riddles. I found the discussion forum in the site a bit frustrating (most of the discussions are closed and poorly-threaded), So I have decided to publish my Python solutions on launchpad for discussion. The problem is that it seems quite unethical to publish these solutions, as it would let other people gain reputation without doing the programming work, which the site deeply discourages. My Encryption problem I want to encrypt my answers so that only those who have already solved the riddles can see my code. The logical key would be the answer to the riddle, which is always numeric. In order to prevent brute-force attacks on my answers, I want to find an encryption algorithm that takes a significantly long time (few seconds) to run. Do you know any such algorithm? I would fancy a Python package, which I can attach to the code, over an external program that might have portability issues. Thanks, Adam A: It sounds like people will have to write their own decryption utility, or use something off-the-shelf, or use off-the-shelf components to decrypt your posts. PBKDF2 is a standardized algorithm for password-based key derivation, defined in PKCS #5. Basically, you can tune "iterations" parameter so that deriving the key from a password (the answer to the Euler problem) would take several seconds. The key can then be used for any common symmetric encryption algorithm, like AES-128. This has the advantage that most crypto libraries already support PBKDF2. In fact, you might find mail clients that support password-based encryption for S/MIME messages. Then you could just post an S/MIME and people could read it with the mail client. Unfortunately, my mail client (Thunderbird) only supports public-key encryption. A: I think Yin Zhu pegged the social aspect of it and Whirlwind the technical. Using your preferred approach of: python decrypt.py --problem=123 --key=1234567 the key number is readily available to Google, and even without that, slamming through a million keys (assuming a median key length of 5 decimal digits yields less than 20 bits of key) is pretty fast. If I wanted to be more clever I could use plain-text assumptions (e.g. import, for) and vastly reduce my search space. For all the trouble you're probably best off using something really complicated like: >>> print codecs.getencoder('rot_13')('import codecs')[0] vzcbeg pbqrpf And if you want the solution to Project Euler problem 123, you'll have to beat it out of me... A: Yes, you can do this with virtually any symmetric encryption algorithm: DSA, or AES, for example; just use the integer as the key, and pad the key out to the required length of the encryption algorithm's key, and use that key to decrypt the answer. Keep in mind that if you extend a short key, the encryption won't be very good. The strength of the encryption has a lot more to do with key length and the algorithm itself than how long it takes to run. This question seems to have some examples of libraries to use with python. A: Just use triple DES and use different keys for each iteration, use the number to generate a each of the 3 keys. Pad up the key length with some text, and you're good. Tripple DES was designed to increase effectiveness against brute force. It's not the world's most secure option, but I'll keep most bruter's at bay. A: If you encrypt your answers, those who have solved the problem simply do not want to see your answers with such effort, provided that they already have plenty of answers to see in the answer page. Those who haven't cannot see. Then your work becomes less useful. Btw, there are many places providing answers to Project Euler, e.g. Haskell answers, Clojure answers, F# answers. If somebody only wants the answer to a question, he/she could simply run the program. Provided that Python is so popular, google "Python Euler xx" would give you plenty of blogs solving a specific problem. A: The simplest approach would be to hash the answer using a secure hash function such as SHA-1, then provide the hash so users can verify their answer. If you want to make brute-forcing more difficult, iterate the hash - eg, provide the result of n recursive applications of SHA1, where n is some parameter you choose to make it difficult to brute-force. If the number of possible answers is small, though, it'll be difficult to impossible to prevent someone from brute-forcing it even with an expensive hash function. Edit: Sorry, I misread your original question. If you want to encrypt your answer, you could do that by using the resulting hash, above, as the encryption key for your answer, rather than posting the hash. A: If you want an encryption routine that is easy to use and distribute, I recommend Paul Rubin's p3.py. It's probably on the fast side, for how secure it is, but since you seem to be in need of a hurdle to be jumped rather than a siege-resistant wall, it may be a good choice for your purposes. You could also look into rijndael.py, which is an implementation of AES, and slower than p3.py.
Encrypt text using a number
Project Euler I have recently begun to solve some of the Project Euler riddles. I found the discussion forum in the site a bit frustrating (most of the discussions are closed and poorly-threaded), So I have decided to publish my Python solutions on launchpad for discussion. The problem is that it seems quite unethical to publish these solutions, as it would let other people gain reputation without doing the programming work, which the site deeply discourages. My Encryption problem I want to encrypt my answers so that only those who have already solved the riddles can see my code. The logical key would be the answer to the riddle, which is always numeric. In order to prevent brute-force attacks on my answers, I want to find an encryption algorithm that takes a significantly long time (few seconds) to run. Do you know any such algorithm? I would fancy a Python package, which I can attach to the code, over an external program that might have portability issues. Thanks, Adam
[ "It sounds like people will have to write their own decryption utility, or use something off-the-shelf, or use off-the-shelf components to decrypt your posts.\nPBKDF2 is a standardized algorithm for password-based key derivation, defined in PKCS #5. Basically, you can tune \"iterations\" parameter so that deriving the key from a password (the answer to the Euler problem) would take several seconds. The key can then be used for any common symmetric encryption algorithm, like AES-128.\nThis has the advantage that most crypto libraries already support PBKDF2. In fact, you might find mail clients that support password-based encryption for S/MIME messages. Then you could just post an S/MIME and people could read it with the mail client. Unfortunately, my mail client (Thunderbird) only supports public-key encryption.\n", "I think Yin Zhu pegged the social aspect of it and Whirlwind the technical. Using your preferred approach of:\npython decrypt.py --problem=123 --key=1234567\n\nthe key number is readily available to Google, and even without that, slamming through a million keys (assuming a median key length of 5 decimal digits yields less than 20 bits of key) is pretty fast. If I wanted to be more clever I could use plain-text assumptions (e.g. import, for) and vastly reduce my search space.\nFor all the trouble you're probably best off using something really complicated like:\n>>> print codecs.getencoder('rot_13')('import codecs')[0]\nvzcbeg pbqrpf \n\nAnd if you want the solution to Project Euler problem 123, you'll have to beat it out of me...\n", "Yes, you can do this with virtually any symmetric encryption algorithm: DSA, or AES, for example; just use the integer as the key, and pad the key out to the required length of the encryption algorithm's key, and use that key to decrypt the answer.\nKeep in mind that if you extend a short key, the encryption won't be very good. The strength of the encryption has a lot more to do with key length and the algorithm itself than how long it takes to run.\nThis question seems to have some examples of libraries to use with python.\n", "Just use triple DES and use different keys for each iteration, use the number to generate a each of the 3 keys. Pad up the key length with some text, and you're good.\nTripple DES was designed to increase effectiveness against brute force.\nIt's not the world's most secure option, but I'll keep most bruter's at bay.\n", "If you encrypt your answers, those who have solved the problem simply do not want to see your answers with such effort, provided that they already have plenty of answers to see in the answer page. Those who haven't cannot see. Then your work becomes less useful. \nBtw, there are many places providing answers to Project Euler, e.g. Haskell answers, Clojure answers, F# answers. If somebody only wants the answer to a question, he/she could simply run the program. Provided that Python is so popular, google \"Python Euler xx\" would give you plenty of blogs solving a specific problem. \n", "The simplest approach would be to hash the answer using a secure hash function such as SHA-1, then provide the hash so users can verify their answer. If you want to make brute-forcing more difficult, iterate the hash - eg, provide the result of n recursive applications of SHA1, where n is some parameter you choose to make it difficult to brute-force.\nIf the number of possible answers is small, though, it'll be difficult to impossible to prevent someone from brute-forcing it even with an expensive hash function.\nEdit: Sorry, I misread your original question. If you want to encrypt your answer, you could do that by using the resulting hash, above, as the encryption key for your answer, rather than posting the hash.\n", "If you want an encryption routine that is easy to use and distribute, I recommend Paul Rubin's p3.py. It's probably on the fast side, for how secure it is, but since you seem to be in need of a hurdle to be jumped rather than a siege-resistant wall, it may be a good choice for your purposes.\nYou could also look into rijndael.py, which is an implementation of AES, and slower than p3.py.\n" ]
[ 4, 2, 1, 0, 0, 0, 0 ]
[]
[]
[ "algorithm", "encryption", "python" ]
stackoverflow_0002925781_algorithm_encryption_python.txt
Q: directory and file related doubts? i have a directory with around 1000 files....i want to run a same code for each of these file... my code requires the file name to be inputted. i have written code to copy the information of one into other in other format... please suggest a method to copy all 1000 files one by one without need to change the file name every time and i have a field serial_num which need to be continous i.e if 1st file has upto 30 then while coping other file it should continue from 30not from 0 again require help thanks.. from string import Template from string import Formatter import pickle f=open("C:/begpython/wavnk/text0004.lab",'r') p='C:/begpython/wavnk/text0004.wav' f1=open("C:/begpython/text.txt",'a') m=[] i=0 k=f.readline() while k is not '': k=f.readline() k=k.rstrip('\n') mi=k.split(' ') m=m+[mi] i=i+1 y=0 x=[] j=1 t=(i-2) while j<t: k=j-1 l=j+1 if j==120 or j==i: j=j+1 else: x=[] x = x + [y, m[j][2], m[k][2], m[l][2], m[j][0], m[l][0], p] y=y+1 #f1.writelines(str(x)+'\n') for item in x: f1.write(str(item)+' ') f1.write(str('\n')) j=j+1 f.close() f1.close() my code..... and i have files name in series like text0001.....text1500.lab and want to run them at a time without need to call them everytime by changin name enter code here A: Why not just use an iterator over the list of files in the directory? I would post some example code but I do get the feeling that you're getting everyone else here to do your whole job for you. A: You could take a look at the glob module as well. It's this easy: import glob list_of_files = glob.glob('C:/begpython/wavnk/*.lab') And yes, it works on windows as well. However, it only finds the matching files, doesn't read them or anything. By the looks of your code example, you may or may not be interested in the python csv module as well. A: You can list the contents of the directory with [listdir][1]. You can the filter on extension with something like allnames = listdir... inputnames = [name for name in allnames \ where os.path.[splitext][2](name)\[1\] == ".lab" ] You can also look at the filter() or map() built-in functions. http://docs.python.org/library/os.path.html#os.path.splitext
directory and file related doubts?
i have a directory with around 1000 files....i want to run a same code for each of these file... my code requires the file name to be inputted. i have written code to copy the information of one into other in other format... please suggest a method to copy all 1000 files one by one without need to change the file name every time and i have a field serial_num which need to be continous i.e if 1st file has upto 30 then while coping other file it should continue from 30not from 0 again require help thanks.. from string import Template from string import Formatter import pickle f=open("C:/begpython/wavnk/text0004.lab",'r') p='C:/begpython/wavnk/text0004.wav' f1=open("C:/begpython/text.txt",'a') m=[] i=0 k=f.readline() while k is not '': k=f.readline() k=k.rstrip('\n') mi=k.split(' ') m=m+[mi] i=i+1 y=0 x=[] j=1 t=(i-2) while j<t: k=j-1 l=j+1 if j==120 or j==i: j=j+1 else: x=[] x = x + [y, m[j][2], m[k][2], m[l][2], m[j][0], m[l][0], p] y=y+1 #f1.writelines(str(x)+'\n') for item in x: f1.write(str(item)+' ') f1.write(str('\n')) j=j+1 f.close() f1.close() my code..... and i have files name in series like text0001.....text1500.lab and want to run them at a time without need to call them everytime by changin name enter code here
[ "Why not just use an iterator over the list of files in the directory? I would post some example code but I do get the feeling that you're getting everyone else here to do your whole job for you.\n", "You could take a look at the glob module as well. It's this easy: \nimport glob\nlist_of_files = glob.glob('C:/begpython/wavnk/*.lab')\n\nAnd yes, it works on windows as well.\nHowever, it only finds the matching files, doesn't read them or anything.\nBy the looks of your code example, you may or may not be interested in the python\ncsv module as well. \n", "You can list the contents of the directory with [listdir][1].\nYou can the filter on extension with something like\nallnames = listdir...\ninputnames = [name for name in allnames \\\n where os.path.[splitext][2](name)\\[1\\] == \".lab\" ]\n\nYou can also look at the filter() or map() built-in functions.\nhttp://docs.python.org/library/os.path.html#os.path.splitext\n" ]
[ 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002928324_python.txt
Q: Python - from file to data structure? I have large file comprising ~100,000 lines. Each line corresponds to a cluster and each entry within each line is a reference i.d. for another file (protein structure in this case), e.g. 1hgn 1dju 3nmj 8kfn 9opu 7gfb 4bui I need to read in the file as a list of lists where each line is a sublist, thus preserving the integrity of the cluster, e.g. nested_list = [['1hgn', '1dju', '3nmj', '8kfn'], ['9opu', '7gfb'], ['4bui']] My current code creates a nested list but the entries within each list are a single string and not comma separated. Therefore, I cannot splice the list with indices so easily. Any help greatly appreciated. Thanks, S :-) A: Super simple: with open('myfile', 'r') as f: data = [line.split() for line in f] A: You'll want to investigate the str.split() method. >>> '1hgn 1dju 3nmj 8kfn'.split() ['1hgn', '1dju', '3nmj', '8kfn']
Python - from file to data structure?
I have large file comprising ~100,000 lines. Each line corresponds to a cluster and each entry within each line is a reference i.d. for another file (protein structure in this case), e.g. 1hgn 1dju 3nmj 8kfn 9opu 7gfb 4bui I need to read in the file as a list of lists where each line is a sublist, thus preserving the integrity of the cluster, e.g. nested_list = [['1hgn', '1dju', '3nmj', '8kfn'], ['9opu', '7gfb'], ['4bui']] My current code creates a nested list but the entries within each list are a single string and not comma separated. Therefore, I cannot splice the list with indices so easily. Any help greatly appreciated. Thanks, S :-)
[ "Super simple:\nwith open('myfile', 'r') as f:\n data = [line.split() for line in f]\n\n", "You'll want to investigate the str.split() method.\n>>> '1hgn 1dju 3nmj 8kfn'.split()\n['1hgn', '1dju', '3nmj', '8kfn']\n\n" ]
[ 13, 6 ]
[]
[]
[ "python", "string" ]
stackoverflow_0002928883_python_string.txt
Q: How to print unsorted dictionary in python? I have this dict in python; d={} d['b']='beta' d['g']='gamma' d['a']='alpha' when i print the dict; for k,v in d.items(): print k i get this; a b g it seems like python sorts the dict automatically! how can i get the original unsorted list? Gath A: Dicts don't work like that: CPython implementation detail: Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions. You could use a list with 2-tuples instead: d = [('b', 'beta'), ('g', 'gamma'), ('a', 'alpha')] A similar but better solution is outlined in Wayne's answer. A: As has been mentioned, dicts don't order or unorder the items you put in. It's "magic" as to how it's ordered when you retrieve it. If you want to keep an order -sorted or not- you need to also bind a list or tuple. This will give you the same dict result with a list that retains order: greek = ['beta', 'gamma', 'alpha'] d = {} for x in greek: d[x[0]] = x Simply change [] to () if you have no need to change the original list/order. A: Don't use a dictionary. Or use the Python 2.7/3.1 OrderedDict type. A: There is no order in dictionaries to speak of, there is no original unsorted list. A: No, python does not sort dict, it would be too expensive. The order of items() is arbitrary. From python docs: CPython implementation detail: Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions.
How to print unsorted dictionary in python?
I have this dict in python; d={} d['b']='beta' d['g']='gamma' d['a']='alpha' when i print the dict; for k,v in d.items(): print k i get this; a b g it seems like python sorts the dict automatically! how can i get the original unsorted list? Gath
[ "Dicts don't work like that:\n\nCPython implementation detail: Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions.\n\nYou could use a list with 2-tuples instead:\nd = [('b', 'beta'), ('g', 'gamma'), ('a', 'alpha')]\n\nA similar but better solution is outlined in Wayne's answer.\n", "As has been mentioned, dicts don't order or unorder the items you put in. It's \"magic\" as to how it's ordered when you retrieve it. If you want to keep an order -sorted or not- you need to also bind a list or tuple.\nThis will give you the same dict result with a list that retains order:\ngreek = ['beta', 'gamma', 'alpha']\nd = {}\nfor x in greek:\n d[x[0]] = x\n\nSimply change [] to () if you have no need to change the original list/order.\n", "Don't use a dictionary. Or use the Python 2.7/3.1 OrderedDict type.\n", "There is no order in dictionaries to speak of, there is no original unsorted list.\n", "No, python does not sort dict, it would be too expensive. The order of items() is arbitrary. From python docs:\n\nCPython implementation detail: Keys\n and values are listed in an arbitrary\n order which is non-random, varies\n across Python implementations, and\n depends on the dictionary’s history of\n insertions and deletions.\n\n" ]
[ 11, 11, 6, 2, 1 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0002928686_dictionary_python.txt
Q: Inspiration and influence of the else clause of loop statements? Python loop statements may have an else clause which is executed if and only if the loop is not terminated by a break. In other words, when the condition becomes False (with while) or when the iterator is exhausted (with for). Does this loop-else construct originate from another language (either theoretical or actually implemented)? Has it been taken up in any newer language? Maybe I should ask the former of Guido, but surely he is too busy for such a futile inquiry. ;-) Related discussion and examples: Pythonic ways to use ‘else’ in a for loop A: A similar feature is found in Common Lisp's LOOP macro, described here by Peter Seibel: ...LOOP provides two keywords, initially and finally, that introduce code to be run outside the loop's main body. After the initially or finally, these clauses consist of all the Lisp forms up to the start of the next loop clause or the end of the loop. All the initially forms are combined into a single prologue, which runs once, immediately after all the local loop variables are initialized and before the body of the loop. The finally forms are similarly combined into a epilogue to be run after the last iteration of the loop body. Both the prologue and epilogue code can refer to local loop variables. The prologue is always run, even if the loop body iterates zero times. The loop can return without running the epilogue if any of the following happens: A return clause executes. RETURN , RETURN-FROM, or another transfer of control construct is called from within a Lisp form within the body... For example, part of a Python sample found in the linked question: for v in known_variables: if self.bindings[v] is cell: return v else: raise CannotSimplify might look something like this: (loop for v in known-variables when (eq (gethash v (slot-value self bindings)) cell) do (return v) finally (signal cannot-simplify)) Another observation: Common Lisp's condition system is also unique. Someone, once, asked where it came from and was pointed to Kent Pitman's paper, where he says got it from Maclisp. Similarly, Common Lisp's weird-looking FORMAT function apparently came from Multics via Dan Weinreb. The common thread is that language features don't tend to follow from the ancestor language that most inspired this language, but are taken by individuals who loved them to whatever new language they're working on. So if you want to find out the actual source of Python's for-else, I'd look for who added it, and see what language they worked on prior to that. A: I just came across a pretty good lead buried in the comments of this far more general question. User ΤΖΩΤΖΙΟΥ wrote: Anyone remember the FOR var … NEXT var … END FOR var of Sinclair QL's SuperBasic? Everything between NEXT and END FOR would execute at the end of the loop, unless an EXIT FOR was issued. That syntax was cleaner :) An OCR rendition of Sinclair QL User Guide happens to float on the internet. It reads: A NEXT statement may be placed in a loop. It causes control to go to the statement which is just after the opening keyword FOR or REPeat. It should be considered as a kind of opposite to the EXIT statement. By a curious coincidence, the two words NEXT and EXIT both contain EXT. Think of an EXTension to loops and: N means "Now start again" I means "It's ended" A fascinating example follows: The sheriff has a gun loaded with six bullets and he is to fire at the bandit but two more conditions apply: If he hits the bandit he stops firing and returns to Dodge City. If he runs out of bullets before he hits the bandit, he tells his partner to watch the bandit while he (sheriff) returns to Dodge City. 100 REMark Western FOR with Epilogue 110 FOR bullets = 1 TO 6 120 PRINT "Take aim" 130 PRINT "FIRE A SHOT" 140 LET hit= RND(0 TO 1) 150 IF hit = 1 THEN EXIT bullets 160 NEXT bullets 170 PRINT "Watch Bandit" 180 END FOR bullets 190 PRINT "Return to Dodge City" So, under a different (and arguably less disturbing) syntax, it's exactly the same semantics. Wikipedia tells us that the Sinclair QL launched in February 1984 as the successor to the Sinclair ZX Spectrum, but failed to achieve commercial success.
Inspiration and influence of the else clause of loop statements?
Python loop statements may have an else clause which is executed if and only if the loop is not terminated by a break. In other words, when the condition becomes False (with while) or when the iterator is exhausted (with for). Does this loop-else construct originate from another language (either theoretical or actually implemented)? Has it been taken up in any newer language? Maybe I should ask the former of Guido, but surely he is too busy for such a futile inquiry. ;-) Related discussion and examples: Pythonic ways to use ‘else’ in a for loop
[ "A similar feature is found in Common Lisp's LOOP macro, described here by Peter Seibel:\n\n...LOOP provides two keywords, initially and finally, that introduce code to be run outside the loop's main body.\nAfter the initially or finally, these clauses consist of all the Lisp forms up to the start of the next loop clause or the end of the loop. All the initially forms are combined into a single prologue, which runs once, immediately after all the local loop variables are initialized and before the body of the loop. The finally forms are similarly combined into a epilogue to be run after the last iteration of the loop body. Both the prologue and epilogue code can refer to local loop variables.\nThe prologue is always run, even if the loop body iterates zero times. The loop can return without running the epilogue if any of the following happens:\n\nA return clause executes.\nRETURN , RETURN-FROM, or another transfer of control construct is called from within a Lisp form within the body...\n\n\nFor example, part of a Python sample found in the linked question:\nfor v in known_variables:\n if self.bindings[v] is cell:\n return v\nelse:\n raise CannotSimplify\n\nmight look something like this:\n(loop for v in known-variables\n when (eq (gethash v (slot-value self bindings)) cell)\n do (return v)\n finally (signal cannot-simplify))\n\nAnother observation:\nCommon Lisp's condition system is also unique. Someone, once, asked where it came from and was pointed to Kent Pitman's paper, where he says got it from Maclisp. Similarly, Common Lisp's weird-looking FORMAT function apparently came from Multics via Dan Weinreb.\nThe common thread is that language features don't tend to follow from the ancestor language that most inspired this language, but are taken by individuals who loved them to whatever new language they're working on. So if you want to find out the actual source of Python's for-else, I'd look for who added it, and see what language they worked on prior to that.\n", "I just came across a pretty good lead buried in the comments of this far more general question. User ΤΖΩΤΖΙΟΥ wrote:\n\nAnyone remember the FOR var … NEXT var\n… END FOR var of Sinclair QL's\nSuperBasic? Everything between NEXT\nand END FOR would execute at the end\nof the loop, unless an EXIT FOR was\nissued. That syntax was cleaner :)\n\nAn OCR rendition of Sinclair QL User Guide happens to float on the internet. It reads:\n\nA NEXT statement may be placed in a\nloop. It causes control to go to the\nstatement which is just after the\nopening keyword FOR or REPeat. It\nshould be considered as a kind of\nopposite to the EXIT statement. By a\ncurious coincidence, the two words\nNEXT and EXIT both contain EXT. Think\nof an EXTension to loops and:\n\nN means \"Now start again\"\nI means \"It's ended\"\n\n\nA fascinating example follows:\n\nThe sheriff has a gun loaded with six\nbullets and he is to fire at the\nbandit but two more conditions apply:\n\nIf he hits the bandit he stops\nfiring and returns to Dodge City.\n\nIf he runs out of bullets before he hits the\nbandit, he tells his partner to watch\nthe bandit while he (sheriff) returns\nto Dodge City.\n\n\n\n100 REMark Western FOR with Epilogue\n110 FOR bullets = 1 TO 6\n120 PRINT \"Take aim\"\n130 PRINT \"FIRE A SHOT\"\n140 LET hit= RND(0 TO 1)\n150 IF hit = 1 THEN EXIT bullets\n160 NEXT bullets\n170 PRINT \"Watch Bandit\"\n180 END FOR bullets\n190 PRINT \"Return to Dodge City\"\n\nSo, under a different (and arguably less disturbing) syntax, it's exactly the same semantics.\nWikipedia tells us that the Sinclair QL launched in February 1984 as the successor to the Sinclair ZX Spectrum, but failed to achieve commercial success.\n" ]
[ 4, 2 ]
[]
[]
[ "history", "if_statement", "loops", "python" ]
stackoverflow_0002924485_history_if_statement_loops_python.txt
Q: Potential Django Bug In QuerySet.query? Disclaimer: I'm still learning Django, so I might be missing something here, but I can't see what it would be... I'm running Python 2.6.1 and Django 1.2.1. (InteractiveConsole) >>> from myproject.myapp.models import * >>> qs = Identifier.objects.filter(Q(key="a") | Q(key="b")) >>> print qs.query SELECT `app_identifier`.`id`, `app_identifier`.`user_id`, `app_identifier`.`key`, `app_identifier`.`value` FROM `app_identifier` WHERE (`app_identifier`.`key` = a OR `app_identifier`.`key` = b ) >>> Notice that it doesn't put quotes around "a" or "b"! Now, I've determined that the query executes fine. So, in reality, it must be doing so. But, it's pretty annoying that printing out the query prints it wrong. Especially if I did something like this... >>> qs = Identifier.objects.filter(Q(key=") AND") | Q(key="\"x\"); DROP TABLE `app_identifier`")) >>> print qs.query SELECT `app_identifier`.`id`, `app_identifier`.`user_id`, `app_identifier`.`key`, `app_identifier`.`value` FROM `app_identifier` WHERE (`app_identifier`.`key` = ) AND OR `app_identifier`.`key` = "x"); DROP TABLE `app_identifier` ) >>> Which, as you can see, not only creates completely malformed SQL code, but also has the seeds of a SQL injection attack. Now, obviously this wouldn't actually work, for quite a number of reasons (1. The syntax is all wrong, intentionally, to show the oddity of Django's behavior. 2. Django won't actually execute the query like this, it will actually put quotes and slashes and all that in there like it's supposed to). But, this really makes debugging confusing, and it makes me wonder if something's gone wrong with my Django installation. Does this happen for you? If so/not, what version of Python and Django do you have? Any thoughts? A: Ok, I just figured it out. It's not a bug. Browsing the source of django/db/models/sql/query.py: 160 def __str__(self): 161 """ 162 Returns the query as a string of SQL with the parameter values 163 substituted in. 164 165 Parameter values won't necessarily be quoted correctly, since that is 166 done by the database interface at execution time. 167 """ 168 sql, params = self.get_compiler(DEFAULT_DB_ALIAS).as_sql() 169 return sql % params (http://code.djangoproject.com/browser/django/trunk/django/db/models/sql/query.py) Everything's working properly. :)
Potential Django Bug In QuerySet.query?
Disclaimer: I'm still learning Django, so I might be missing something here, but I can't see what it would be... I'm running Python 2.6.1 and Django 1.2.1. (InteractiveConsole) >>> from myproject.myapp.models import * >>> qs = Identifier.objects.filter(Q(key="a") | Q(key="b")) >>> print qs.query SELECT `app_identifier`.`id`, `app_identifier`.`user_id`, `app_identifier`.`key`, `app_identifier`.`value` FROM `app_identifier` WHERE (`app_identifier`.`key` = a OR `app_identifier`.`key` = b ) >>> Notice that it doesn't put quotes around "a" or "b"! Now, I've determined that the query executes fine. So, in reality, it must be doing so. But, it's pretty annoying that printing out the query prints it wrong. Especially if I did something like this... >>> qs = Identifier.objects.filter(Q(key=") AND") | Q(key="\"x\"); DROP TABLE `app_identifier`")) >>> print qs.query SELECT `app_identifier`.`id`, `app_identifier`.`user_id`, `app_identifier`.`key`, `app_identifier`.`value` FROM `app_identifier` WHERE (`app_identifier`.`key` = ) AND OR `app_identifier`.`key` = "x"); DROP TABLE `app_identifier` ) >>> Which, as you can see, not only creates completely malformed SQL code, but also has the seeds of a SQL injection attack. Now, obviously this wouldn't actually work, for quite a number of reasons (1. The syntax is all wrong, intentionally, to show the oddity of Django's behavior. 2. Django won't actually execute the query like this, it will actually put quotes and slashes and all that in there like it's supposed to). But, this really makes debugging confusing, and it makes me wonder if something's gone wrong with my Django installation. Does this happen for you? If so/not, what version of Python and Django do you have? Any thoughts?
[ "Ok, I just figured it out. It's not a bug. Browsing the source of django/db/models/sql/query.py:\n160 def __str__(self):\n161 \"\"\"\n162 Returns the query as a string of SQL with the parameter values\n163 substituted in.\n164 \n165 Parameter values won't necessarily be quoted correctly, since that is\n166 done by the database interface at execution time.\n167 \"\"\"\n168 sql, params = self.get_compiler(DEFAULT_DB_ALIAS).as_sql()\n169 return sql % params\n\n(http://code.djangoproject.com/browser/django/trunk/django/db/models/sql/query.py)\nEverything's working properly. :)\n" ]
[ 11 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002926483_django_python.txt
Q: Doubling binary digits How to double a number of binary digits in an integer? For example, if bin(x)="1001" then bin(y) must be "11000011". Is there any smart and fast algorithm ? UPDATE: Here is an elegant solution: ''.join([''.join(i) for i in zip(X,X)]) where X is bin(int_x)[2:] However, I am interested in a more faster way and for the integers of any size. Maybe an arithmetical transformation should help. A: Here's one way that should be reasonably fast: convert your number to a binary string, then reinterpret the result as being in base 4. Now to make sure that all the '1's are doubled properly, multiply the result by 3. >>> x = 9 >>> bin(x) '0b1001' >>> y = int(bin(x)[2:], 4)*3 >>> bin(y) '0b11000011' A: (Reference http://graphics.stanford.edu/~seander/bithacks.html#Interleave64bitOps): If your number is below 256, you may use @magic def double_digits_holger8(x): m = (x * 0x0101010101010101 & 0x8040201008040201) * 0x0102040810204081 return ((m >> 49) & 0x5555) | ((m >> 48) & 0xAAAA) and if it is below 65536, @more_magic def double_digits_binmag16(x): x = (x | x << 8) & 0x00FF00FF x = (x | x << 4) & 0x0F0F0F0F x = (x | x << 2) & 0x33333333 x = (x | x << 1) & 0x55555555 return x | x << 1 Comparison with other solutions (the function must take an integer and return an integer for fair comparison): Method Time per 256 calls -------------------------------- Do nothing 46.2 usec Holger8 256 usec BinMag16 360 usec Mark 367 usec # http://stackoverflow.com/questions/2928886/doubling-binary-digits/2929198#2929198 Max 720 usec # http://stackoverflow.com/questions/2928886/doubling-binary-digits/2928938#2928938 Peter 1.08 msec # http://stackoverflow.com/questions/2928886/doubling-binary-digits/2928973#2928973 Phiµµ w/o Log 1.11 msec # http://stackoverflow.com/questions/2928886/doubling-binary-digits/2929106#2929106 Jim16 1.26 msec # http://stackoverflow.com/questions/2928886/doubling-binary-digits/2929038#2929038 Elegant 1.66 msec # int(''.join([''.join(i) for i in zip(X,X)]),2) More Elegant 2.05 msec # int(''.join(chain(*zip(X, X))), 2) Benchmark source code can be found in http://gist.github.com/417172. A: The straightforward solution just using integer arithmetic would be: def doubledigits(n): result = 0 power = 1 while n > 0: if n%2==1: result += 3*power power *= 4 n //= 2 return result A: any_number - int str(n) - produces string from int. str::replace(pattern, replaced_value) - replaces all patterns in string to replaced_value. int(str) - makes int from string. n=any_number result_number = int(str(n).replace("0","00").replace("1","11")) A: $ python2.6 Python 2.6.5 (r265:79063, Mar 25 2010, 14:13:28) >>> def dd(n): return eval("0b" + "".join(d * 2 for d in str(bin(n))[2:])) ... >>> dd(9) 195 A: y = 0; for(i = 15; i >= 0; i--) { if((1 << i) & x) { y |= 3; } y <<= 2; } A: def doubledigits(x): from math import log print (bin(x)) numdigits = x.bit_length() result = 1 << (numdigits*2) for i in range(numdigits, -1, -1): mask = 1 << i if (x & mask > 0): rmask = 0b11 << (2*i) result = result | rmask return result should do it.
Doubling binary digits
How to double a number of binary digits in an integer? For example, if bin(x)="1001" then bin(y) must be "11000011". Is there any smart and fast algorithm ? UPDATE: Here is an elegant solution: ''.join([''.join(i) for i in zip(X,X)]) where X is bin(int_x)[2:] However, I am interested in a more faster way and for the integers of any size. Maybe an arithmetical transformation should help.
[ "Here's one way that should be reasonably fast: convert your number to a binary string, then reinterpret the result as being in base 4. Now to make sure that all the '1's are doubled properly, multiply the result by 3.\n>>> x = 9\n>>> bin(x)\n'0b1001'\n>>> y = int(bin(x)[2:], 4)*3\n>>> bin(y)\n'0b11000011'\n\n", "(Reference http://graphics.stanford.edu/~seander/bithacks.html#Interleave64bitOps):\nIf your number is below 256, you may use\n@magic\ndef double_digits_holger8(x):\n m = (x * 0x0101010101010101 & 0x8040201008040201) * 0x0102040810204081\n return ((m >> 49) & 0x5555) | ((m >> 48) & 0xAAAA)\n\nand if it is below 65536,\n@more_magic\ndef double_digits_binmag16(x):\n x = (x | x << 8) & 0x00FF00FF\n x = (x | x << 4) & 0x0F0F0F0F\n x = (x | x << 2) & 0x33333333\n x = (x | x << 1) & 0x55555555\n return x | x << 1\n\nComparison with other solutions (the function must take an integer and return an integer for fair comparison):\nMethod Time per 256 calls\n--------------------------------\nDo nothing 46.2 usec \nHolger8 256 usec\nBinMag16 360 usec\nMark 367 usec # http://stackoverflow.com/questions/2928886/doubling-binary-digits/2929198#2929198\nMax 720 usec # http://stackoverflow.com/questions/2928886/doubling-binary-digits/2928938#2928938\nPeter 1.08 msec # http://stackoverflow.com/questions/2928886/doubling-binary-digits/2928973#2928973\nPhiµµ w/o Log 1.11 msec # http://stackoverflow.com/questions/2928886/doubling-binary-digits/2929106#2929106\nJim16 1.26 msec # http://stackoverflow.com/questions/2928886/doubling-binary-digits/2929038#2929038\nElegant 1.66 msec # int(''.join([''.join(i) for i in zip(X,X)]),2)\nMore Elegant 2.05 msec # int(''.join(chain(*zip(X, X))), 2)\n\nBenchmark source code can be found in http://gist.github.com/417172.\n", "The straightforward solution just using integer arithmetic would be:\ndef doubledigits(n):\n result = 0\n power = 1\n while n > 0:\n if n%2==1:\n result += 3*power\n power *= 4\n n //= 2\n return result\n\n", "any_number - int \nstr(n) - produces string from int.\nstr::replace(pattern, replaced_value) - replaces all patterns in string to replaced_value.\nint(str) - makes int from string.\nn=any_number\nresult_number = int(str(n).replace(\"0\",\"00\").replace(\"1\",\"11\"))\n\n", "$ python2.6\nPython 2.6.5 (r265:79063, Mar 25 2010, 14:13:28)\n>>> def dd(n): return eval(\"0b\" + \"\".join(d * 2 for d in str(bin(n))[2:]))\n...\n>>> dd(9)\n195\n\n", "y = 0;\nfor(i = 15; i >= 0; i--) {\n if((1 << i) & x) {\n y |= 3;\n }\n y <<= 2;\n}\n\n", "def doubledigits(x):\n from math import log\n print (bin(x))\n numdigits = x.bit_length()\n result = 1 << (numdigits*2)\n for i in range(numdigits, -1, -1):\n mask = 1 << i\n if (x & mask > 0):\n rmask = 0b11 << (2*i)\n result = result | rmask\n return result\n\nshould do it.\n" ]
[ 20, 16, 11, 4, 1, 0, 0 ]
[]
[]
[ "algorithm", "binary", "math", "python" ]
stackoverflow_0002928886_algorithm_binary_math_python.txt
Q: OpenGL GL_LINE_STRIP gives error 1281 (Invalid value) after glEnd I have no idea what is wrong with the simple code. The function is for use with python and ctypes. extern "C" void add_lines(bool antialias,GLdouble coordinates[][2],int array_size,GLdouble w,GLdouble r,GLdouble g, GLdouble b,GLdouble a){ glDisable(GL_TEXTURE_2D); if (antialias){ glEnable(GL_LINE_SMOOTH); //Enable line smoothing. } glColor4d(r,g,b,a); glLineWidth(w); glBegin(GL_LINE_STRIP); for (int x = 0; x < array_size; x++) { glVertex2d(coordinates[x][0],coordinates[x][1]); } glEnd(); std::cout << glGetError(); if (antialias){ glDisable(GL_LINE_SMOOTH); //Disable line smoothing. } glEnable(GL_TEXTURE_2D); } std::cout << glGetError(); gives out 1281 each time. Thankyou. A: glGetError() is sticky: once the error gets set by some function, it will stay at that error value until you call glGetError(). So, the error is likely being caused elsewhere. Check the value of glGetError() on function entry, and then after each function call to find out where it's being set. A: Are you sure the error is not triggered before glEnd? glGetError will report the last GL error, which might be caused earlier in program execution.
OpenGL GL_LINE_STRIP gives error 1281 (Invalid value) after glEnd
I have no idea what is wrong with the simple code. The function is for use with python and ctypes. extern "C" void add_lines(bool antialias,GLdouble coordinates[][2],int array_size,GLdouble w,GLdouble r,GLdouble g, GLdouble b,GLdouble a){ glDisable(GL_TEXTURE_2D); if (antialias){ glEnable(GL_LINE_SMOOTH); //Enable line smoothing. } glColor4d(r,g,b,a); glLineWidth(w); glBegin(GL_LINE_STRIP); for (int x = 0; x < array_size; x++) { glVertex2d(coordinates[x][0],coordinates[x][1]); } glEnd(); std::cout << glGetError(); if (antialias){ glDisable(GL_LINE_SMOOTH); //Disable line smoothing. } glEnable(GL_TEXTURE_2D); } std::cout << glGetError(); gives out 1281 each time. Thankyou.
[ "glGetError() is sticky: once the error gets set by some function, it will stay at that error value until you call glGetError(). So, the error is likely being caused elsewhere. Check the value of glGetError() on function entry, and then after each function call to find out where it's being set.\n", "Are you sure the error is not triggered before glEnd? glGetError will report the last GL error, which might be caused earlier in program execution.\n" ]
[ 4, 0 ]
[]
[]
[ "c++", "ctypes", "opengl", "python" ]
stackoverflow_0002929598_c++_ctypes_opengl_python.txt
Q: Django 1.2: Dates in admin forms don't work with Locales (I10N=True) I have an application in Django 1.2. Language is selectable (I18N and Locale = True) When I select the english lang. in the site, the admin works OK. But when I change to any other language this is what happens with date inputs (spanish example): Correctly, the input accepts the spanish format %d/%m/%Y (Even selecting from the calendar, the date inserts as expected). But when I save the form and load it again, the date shows in the english form: %Y-%m-%d The real problem is that when I load the form to change any other text field and try to save it I get an error telling me to enter a valid date, so I have to write all dates again or change the language in the site to use the admin. I haven't specified anything for DATE_INPUT_FORMATS in settings nor have I overridden forms or models. Surely I am missing something but I can't find it. Can anybody give me a hint? A: Adding this to your settings should solve the part you call "the real problem": DATE_INPUT_FORMATS = ( '%d/%m/%Y', '%d/%m/%y', # '25/10/2006', '25/10/06' '%Y-%m-%d', '%y-%m-%d', # '2006-10-25', '06-10-25' ) DATETIME_INPUT_FORMATS = ( '%d/%m/%Y %H:%M:%S', # '25/10/2006 14:30:59' '%d/%m/%Y %H:%M', # '25/10/2006 14:30' '%d/%m/%y %H:%M:%S', # '25/10/06 14:30:59' '%d/%m/%y %H:%M', # '25/10/06 14:30' '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' ) But it's a problem with Django. I opened a ticket about the issue, but you should comment, because your example shows it is even more serious problem then I thought it was (because as it turned out not all localization accepts both "universal" and "localized" date input formats). Update: I forgot to add that you can pass localize=True to your date widgets, and they are supposed to then always display dates in localized format. There are some examples of how to do this in this bug report. I just posted a message about the issue to django-developers mailing list.
Django 1.2: Dates in admin forms don't work with Locales (I10N=True)
I have an application in Django 1.2. Language is selectable (I18N and Locale = True) When I select the english lang. in the site, the admin works OK. But when I change to any other language this is what happens with date inputs (spanish example): Correctly, the input accepts the spanish format %d/%m/%Y (Even selecting from the calendar, the date inserts as expected). But when I save the form and load it again, the date shows in the english form: %Y-%m-%d The real problem is that when I load the form to change any other text field and try to save it I get an error telling me to enter a valid date, so I have to write all dates again or change the language in the site to use the admin. I haven't specified anything for DATE_INPUT_FORMATS in settings nor have I overridden forms or models. Surely I am missing something but I can't find it. Can anybody give me a hint?
[ "Adding this to your settings should solve the part you call \"the real problem\":\nDATE_INPUT_FORMATS = ( \n '%d/%m/%Y', '%d/%m/%y', # '25/10/2006', '25/10/06'\n '%Y-%m-%d', '%y-%m-%d', # '2006-10-25', '06-10-25'\n)\n\nDATETIME_INPUT_FORMATS = (\n '%d/%m/%Y %H:%M:%S', # '25/10/2006 14:30:59'\n '%d/%m/%Y %H:%M', # '25/10/2006 14:30'\n '%d/%m/%y %H:%M:%S', # '25/10/06 14:30:59'\n '%d/%m/%y %H:%M', # '25/10/06 14:30'\n '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59'\n '%Y-%m-%d %H:%M', # '2006-10-25 14:30'\n '%Y-%m-%d', # '2006-10-25'\n)\n\nBut it's a problem with Django. I opened a ticket about the issue, but you should comment, because your example shows it is even more serious problem then I thought it was (because as it turned out not all localization accepts both \"universal\" and \"localized\" date input formats).\nUpdate: I forgot to add that you can pass localize=True to your date widgets, and they are supposed to then always display dates in localized format. There are some examples of how to do this in this bug report.\nI just posted a message about the issue to django-developers mailing list.\n" ]
[ 2 ]
[]
[]
[ "date", "django", "django_admin", "python" ]
stackoverflow_0002929388_date_django_django_admin_python.txt
Q: HTTP basic authentication using sockets in python How to connect to a server using basic http auth thru sockets in python .I don't want to use urllib/urllib2 etc as my program does some low level socket I/O operations A: Probably the easiest place to start is using makefile() to get a simpler file-like interface to the socket. import socket, base64 host= 'www.example.com' path= '/' username= 'fred' password= 'bloggs' token= base64.encodestring('%s:%s' % (username, password)).strip() lines= [ 'GET %s HTTP/1.1' % path, 'Host: %s' % host, 'Authorization: Basic %s' % token, 'Connection: close', ] s= socket.socket() s.connect((host, 80)) f= s.makefile('rwb', bufsize=0) f.write('\r\n'.join(lines)+'\r\n\r\n') response= f.read() f.close() s.close() You'll have to do a lot more work than that if you need to interpret the returned response to pick out the HTML or auth-required headers, and handle redirects, errors, transfer-encoding and all that right. HTTP can be complex! Are you sure you need to use a low-level socket? A: Look e.g. at urllib's sources, specifically the http_error_401 function (and the dispatching around it of course): make the HTTP request, watch for a 401 response, extract its realm, check that its scheme is basic, try again with the user and password for that realm (cfr function retry_http_basic_auth in that same source file). Lots of work of course, but that's the price of programming "down to the bare metal" as you require.
HTTP basic authentication using sockets in python
How to connect to a server using basic http auth thru sockets in python .I don't want to use urllib/urllib2 etc as my program does some low level socket I/O operations
[ "Probably the easiest place to start is using makefile() to get a simpler file-like interface to the socket.\nimport socket, base64\n\nhost= 'www.example.com'\npath= '/'\nusername= 'fred'\npassword= 'bloggs'\ntoken= base64.encodestring('%s:%s' % (username, password)).strip()\n\nlines= [\n 'GET %s HTTP/1.1' % path,\n 'Host: %s' % host,\n 'Authorization: Basic %s' % token,\n 'Connection: close',\n]\n\ns= socket.socket()\ns.connect((host, 80))\nf= s.makefile('rwb', bufsize=0)\nf.write('\\r\\n'.join(lines)+'\\r\\n\\r\\n')\nresponse= f.read()\nf.close()\ns.close()\n\nYou'll have to do a lot more work than that if you need to interpret the returned response to pick out the HTML or auth-required headers, and handle redirects, errors, transfer-encoding and all that right. HTTP can be complex! Are you sure you need to use a low-level socket?\n", "Look e.g. at urllib's sources, specifically the http_error_401 function (and the dispatching around it of course): make the HTTP request, watch for a 401 response, extract its realm, check that its scheme is basic, try again with the user and password for that realm (cfr function retry_http_basic_auth in that same source file). Lots of work of course, but that's the price of programming \"down to the bare metal\" as you require.\n" ]
[ 5, 2 ]
[]
[]
[ "basic_authentication", "networking", "python", "sockets" ]
stackoverflow_0002929532_basic_authentication_networking_python_sockets.txt
Q: Cross platform /dev/null in Python I'm using the following code to hide stderr on Linux/OSX for a Python library I do not control that writes to stderr by default: f = open("/dev/null","w") zookeeper.set_log_stream(f) Is there an easy cross platform alternative to /dev/null? Ideally it would not consume memory since this is a long running process. A: How about os.devnull ? import os f = open(os.devnull,"w") zookeeper.set_log_stream(f) A: class Devnull(object): def write(self, *_): pass zookeeper.set_log_stream(Devnull()) Opening os.devnull is fine too of course, but this way every output operation occurs (as a noop) "in process" -- no context switch to the OS and back, and also no buffering (while some buffering is normally used by an open) and thus even less memory consumption. A: >>> import os >>> os.devnull 'nul' A: Create your own file-like object which doesn't do anything? class FakeSink(object): def write(self, *args): pass def writelines(self, *args): pass def close(self, *args): pass A: Cheap solution warning! class DevNull(): def __init__(self, *args): self.closed = False self.mode = "w" self.name = "<null>" self.encoding = None self.errors = None self.newlines = None self.softspace = 0 def close(self): self.closed == True @open_files_only def flush(self): pass @open_files_only def next(self): raise IOError("Invalid operation") @open_files_only def read(size = 0): raise IOError("Invalid operation") @open_files_only def readline(self): raise IOError("Invalid operation") @open_files_only def readlines(self): raise IOError("Invalid operation") @open_files_only def xreadlines(self): raise IOError("Invalid operation") @open_files_only def seek(self): raise IOError("Invalid operation") @open_files_only def tell(self): return 0 @open_files_only def truncate(self): pass @open_files_only def write(self): pass @open_files_only def writelines(self): pass def open_files_only(fun): def wrapper(self, *args): if self.closed: raise IOError("File is closed") else: fun(self, *args) return wrapper
Cross platform /dev/null in Python
I'm using the following code to hide stderr on Linux/OSX for a Python library I do not control that writes to stderr by default: f = open("/dev/null","w") zookeeper.set_log_stream(f) Is there an easy cross platform alternative to /dev/null? Ideally it would not consume memory since this is a long running process.
[ "How about os.devnull ?\nimport os\nf = open(os.devnull,\"w\")\nzookeeper.set_log_stream(f)\n\n", "class Devnull(object):\n def write(self, *_): pass\n\nzookeeper.set_log_stream(Devnull())\n\nOpening os.devnull is fine too of course, but this way every output operation occurs (as a noop) \"in process\" -- no context switch to the OS and back, and also no buffering (while some buffering is normally used by an open) and thus even less memory consumption.\n", ">>> import os\n>>> os.devnull\n'nul'\n\n", "Create your own file-like object which doesn't do anything?\nclass FakeSink(object):\n def write(self, *args):\n pass\n def writelines(self, *args):\n pass\n def close(self, *args):\n pass\n\n", "Cheap solution warning!\nclass DevNull():\n def __init__(self, *args):\n self.closed = False\n self.mode = \"w\"\n self.name = \"<null>\"\n self.encoding = None\n self.errors = None\n self.newlines = None\n self.softspace = 0\n def close(self):\n self.closed == True\n @open_files_only\n def flush(self):\n pass\n @open_files_only\n def next(self):\n raise IOError(\"Invalid operation\")\n @open_files_only\n def read(size = 0):\n raise IOError(\"Invalid operation\")\n @open_files_only\n def readline(self):\n raise IOError(\"Invalid operation\")\n @open_files_only\n def readlines(self):\n raise IOError(\"Invalid operation\")\n @open_files_only\n def xreadlines(self):\n raise IOError(\"Invalid operation\")\n @open_files_only\n def seek(self):\n raise IOError(\"Invalid operation\")\n @open_files_only\n def tell(self):\n return 0\n @open_files_only\n def truncate(self):\n pass\n @open_files_only\n def write(self):\n pass\n @open_files_only\n def writelines(self):\n pass\n\ndef open_files_only(fun):\n def wrapper(self, *args):\n if self.closed:\n raise IOError(\"File is closed\")\n else:\n fun(self, *args)\n return wrapper\n\n" ]
[ 170, 48, 7, 5, 2 ]
[]
[]
[ "python" ]
stackoverflow_0002929899_python.txt
Q: command line arg? This is a module named XYZ. def func(x) ..... ..... if __name__=="__main__": print func(sys.argv[1]) Now I have imported this module in another code and want to use the func. How can i use it? import XYZ After this, where to give the argument, and syntax on how to call it, please? A: import XYZ print XYZ.func(foo) A: import XYZ XYZ.func('blah') or import XYZ XYZ.func(sys.argv[1]) A: The following will bring the name func into your current namespace so you can use it directly without the module prefix: from XYZ import func func(sys.argv[1]) You can also import the module and call the function using its fully qualified name: import XYZ XYZ.func(sys.argv[1]) There are a couple of other options as well, for more details read the definitive article on Importing Python Modules
command line arg?
This is a module named XYZ. def func(x) ..... ..... if __name__=="__main__": print func(sys.argv[1]) Now I have imported this module in another code and want to use the func. How can i use it? import XYZ After this, where to give the argument, and syntax on how to call it, please?
[ "import XYZ\nprint XYZ.func(foo)\n\n", "import XYZ\nXYZ.func('blah')\n\nor\nimport XYZ\nXYZ.func(sys.argv[1])\n\n", "The following will bring the name func into your current namespace so you can use it directly without the module prefix:\nfrom XYZ import func\nfunc(sys.argv[1])\n\nYou can also import the module and call the function using its fully qualified name:\nimport XYZ\nXYZ.func(sys.argv[1])\n\nThere are a couple of other options as well, for more details read the definitive article on Importing Python Modules\n" ]
[ 4, 2, 1 ]
[]
[]
[ "import", "module", "python", "syntax" ]
stackoverflow_0002929550_import_module_python_syntax.txt
Q: How to debug ctypes call of c++ dll? in my python project I call a c++ dll using ctypes library. That c++ dll consists on a wrapper dll that calls methods of a c# com interop dll. Sometimes I have a COM exception. I like to see what it corresponds exactlly but I don't know how to do it? How can I attach the c++ debugger to this situation? Thanks in advance A: I don't know about your direct question, but maybe you could get around it by using comtypes to go straight from COM to Python instead sticking C++ in between. Then all you have to do is: >>> from comtypes import client, COMError >>> myclassinst = client.CreateObject('MyCOMClass.MyCOMClass') >>> try: ... myclassinst.DoInvalidOperation() ... except COMError as e: ... print e.args ... print e.hresult ... print e.text ... (-2147205118, None, (u'MyCOMClass: An Error Message', u'MyCOMClass.MyCOMClass.1', None, 0, None)) -2147205118 None
How to debug ctypes call of c++ dll?
in my python project I call a c++ dll using ctypes library. That c++ dll consists on a wrapper dll that calls methods of a c# com interop dll. Sometimes I have a COM exception. I like to see what it corresponds exactlly but I don't know how to do it? How can I attach the c++ debugger to this situation? Thanks in advance
[ "I don't know about your direct question, but maybe you could get around it by using comtypes to go straight from COM to Python instead sticking C++ in between.\nThen all you have to do is:\n>>> from comtypes import client, COMError\n>>> myclassinst = client.CreateObject('MyCOMClass.MyCOMClass')\n>>> try:\n... myclassinst.DoInvalidOperation()\n... except COMError as e:\n... print e.args\n... print e.hresult\n... print e.text\n...\n(-2147205118, None, (u'MyCOMClass: An Error Message', u'MyCOMClass.MyCOMClass.1', None, 0, None))\n-2147205118\nNone\n\n" ]
[ 0 ]
[]
[]
[ "c#", "c++", "dll", "python" ]
stackoverflow_0002929970_c#_c++_dll_python.txt
Q: Ruby GTK fails without display (Python is OK) it seems that Ruby GTK apps are unable to run in nongraphical environment.. while python apps are able to. oversimplified examples (even without the gtk main loop), demonstrating this behavior: gtktest.py: #! /usr/bin/python import gtk print('the end') gtktest.rb: #! /usr/bin/ruby require "gtk2" puts('the end') X window environment: $ ./gtktest.py the end $ ./gtktest.rb the end non X environment: $ ./gtktest.py /usr/lib/pymodules/python2.5/gtk-2.0/gtk/__init__.py:57: GtkWarning: could not open display warnings.warn(str(e), _gtk.Warning) the end $ ./gtktest.rb /usr/lib/ruby/1.8/gtk2.rb:12:in `init': Cannot open display: (Gtk::InitError) from /usr/lib/ruby/1.8/gtk2.rb:12 from ./gtktest.rb:2:in `require' from ./gtktest.rb:2 as you can see, python version runs succesfully with a warning, ruby one fails immediately on gtk importing (python one works even with a gtk main loop, with VTE terminal doing some text processing) is someone aware of a possibility do have those ruby gtk apps running in non-X ? environment: debian squeeze, python-gtk2, libgtk2-ruby A: Yes you can, setup Xvfb.
Ruby GTK fails without display (Python is OK)
it seems that Ruby GTK apps are unable to run in nongraphical environment.. while python apps are able to. oversimplified examples (even without the gtk main loop), demonstrating this behavior: gtktest.py: #! /usr/bin/python import gtk print('the end') gtktest.rb: #! /usr/bin/ruby require "gtk2" puts('the end') X window environment: $ ./gtktest.py the end $ ./gtktest.rb the end non X environment: $ ./gtktest.py /usr/lib/pymodules/python2.5/gtk-2.0/gtk/__init__.py:57: GtkWarning: could not open display warnings.warn(str(e), _gtk.Warning) the end $ ./gtktest.rb /usr/lib/ruby/1.8/gtk2.rb:12:in `init': Cannot open display: (Gtk::InitError) from /usr/lib/ruby/1.8/gtk2.rb:12 from ./gtktest.rb:2:in `require' from ./gtktest.rb:2 as you can see, python version runs succesfully with a warning, ruby one fails immediately on gtk importing (python one works even with a gtk main loop, with VTE terminal doing some text processing) is someone aware of a possibility do have those ruby gtk apps running in non-X ? environment: debian squeeze, python-gtk2, libgtk2-ruby
[ "Yes you can, setup Xvfb.\n" ]
[ 2 ]
[]
[]
[ "gtk", "gtk2", "python", "ruby" ]
stackoverflow_0002929774_gtk_gtk2_python_ruby.txt
Q: ctypes and PySide I'm building an app with PySide, there's some image manipulation that needs to be done and using Python code for this is way too slow. Therefore I hacked out a .dll file that will do it for me. The function definition is as follows: extern "C" { QRectF get_image_slant(QImage *img, float slantangle, float offset) { Now I can load this function in via ctypes. But I can't seem to get ctypes to accept a QImage. I tried calling it like this: ext.get_image_slant(QImage(), 0, 0) And the reply I get is: File "<stdin>", line 1, in <module> ctypes.ArgumentError: argument 1: <type 'exceptions.TypeError'>: Don't know how to convert parameter 1 I tired casting the QImage to a c_void_p and it doesn't like that either. From what I can tell QImage() in python should map exactly to a QImage * in C, but Python doesn't seem to understand that.. Is there any way to force the casting? A: Since ctypes for C++ isn't working very well, I would recommend using PySide's own wrapper - Shiboken. They actually use it to wrap the Qt libs themselves. Since your code deals with Qt object, this seems like the perfect choice for you.
ctypes and PySide
I'm building an app with PySide, there's some image manipulation that needs to be done and using Python code for this is way too slow. Therefore I hacked out a .dll file that will do it for me. The function definition is as follows: extern "C" { QRectF get_image_slant(QImage *img, float slantangle, float offset) { Now I can load this function in via ctypes. But I can't seem to get ctypes to accept a QImage. I tried calling it like this: ext.get_image_slant(QImage(), 0, 0) And the reply I get is: File "<stdin>", line 1, in <module> ctypes.ArgumentError: argument 1: <type 'exceptions.TypeError'>: Don't know how to convert parameter 1 I tired casting the QImage to a c_void_p and it doesn't like that either. From what I can tell QImage() in python should map exactly to a QImage * in C, but Python doesn't seem to understand that.. Is there any way to force the casting?
[ "Since ctypes for C++ isn't working very well, I would recommend using PySide's own wrapper - Shiboken. They actually use it to wrap the Qt libs themselves. Since your code deals with Qt object, this seems like the perfect choice for you.\n" ]
[ 1 ]
[]
[]
[ "ctypes", "pyside", "python", "qt4" ]
stackoverflow_0002930154_ctypes_pyside_python_qt4.txt
Q: Reading numeric Excel data as text using xlrd in Python I am trying to read in an Excel file using xlrd, and I am wondering if there is a way to ignore the cell formatting used in Excel file, and just import all data as text? Here is the code I am using for far: import xlrd xls_file = 'xltest.xls' xls_workbook = xlrd.open_workbook(xls_file) xls_sheet = xls_workbook.sheet_by_index(0) raw_data = [['']*xls_sheet.ncols for _ in range(xls_sheet.nrows)] raw_str = '' feild_delim = ',' text_delim = '"' for rnum in range(xls_sheet.nrows): for cnum in range(xls_sheet.ncols): raw_data[rnum][cnum] = str(xls_sheet.cell(rnum,cnum).value) for rnum in range(len(raw_data)): for cnum in range(len(raw_data[rnum])): if (cnum == len(raw_data[rnum]) - 1): feild_delim = '\n' else: feild_delim = ',' raw_str += text_delim + raw_data[rnum][cnum] + text_delim + feild_delim final_csv = open('FINAL.csv', 'w') final_csv.write(raw_str) final_csv.close() This code is functional, but there are certain fields, such as a zip code, that are imported as numbers, so they have the decimal zero suffix. For example, is there is a zip code of '79854' in the Excel file, it will be imported as '79854.0'. I have tried finding a solution in this xlrd spec, but was unsuccessful. A: That's because integer values in Excel are imported as floats in Python. Thus, sheet.cell(r,c).value returns a float. Try converting the values to integers but first make sure those values were integers in Excel to begin with: cell = sheet.cell(r,c) cell_value = cell.value if cell.ctype in (2,3) and int(cell_value) == cell_value: cell_value = int(cell_value) It is all in the xlrd spec. A: I know this isn't part of the question, but I would get rid of raw_str and write directly to your csv. For a large file (10,000 rows) this will save loads of time. You can also get rid of raw_data and just use one for loop.
Reading numeric Excel data as text using xlrd in Python
I am trying to read in an Excel file using xlrd, and I am wondering if there is a way to ignore the cell formatting used in Excel file, and just import all data as text? Here is the code I am using for far: import xlrd xls_file = 'xltest.xls' xls_workbook = xlrd.open_workbook(xls_file) xls_sheet = xls_workbook.sheet_by_index(0) raw_data = [['']*xls_sheet.ncols for _ in range(xls_sheet.nrows)] raw_str = '' feild_delim = ',' text_delim = '"' for rnum in range(xls_sheet.nrows): for cnum in range(xls_sheet.ncols): raw_data[rnum][cnum] = str(xls_sheet.cell(rnum,cnum).value) for rnum in range(len(raw_data)): for cnum in range(len(raw_data[rnum])): if (cnum == len(raw_data[rnum]) - 1): feild_delim = '\n' else: feild_delim = ',' raw_str += text_delim + raw_data[rnum][cnum] + text_delim + feild_delim final_csv = open('FINAL.csv', 'w') final_csv.write(raw_str) final_csv.close() This code is functional, but there are certain fields, such as a zip code, that are imported as numbers, so they have the decimal zero suffix. For example, is there is a zip code of '79854' in the Excel file, it will be imported as '79854.0'. I have tried finding a solution in this xlrd spec, but was unsuccessful.
[ "That's because integer values in Excel are imported as floats in Python. Thus, sheet.cell(r,c).value returns a float. Try converting the values to integers but first make sure those values were integers in Excel to begin with:\ncell = sheet.cell(r,c)\ncell_value = cell.value\nif cell.ctype in (2,3) and int(cell_value) == cell_value:\n cell_value = int(cell_value)\n\nIt is all in the xlrd spec.\n", "I know this isn't part of the question, but I would get rid of raw_str and write directly to your csv. For a large file (10,000 rows) this will save loads of time.\nYou can also get rid of raw_data and just use one for loop.\n" ]
[ 24, 4 ]
[]
[]
[ "csv", "excel", "python", "xlrd", "xls" ]
stackoverflow_0002739989_csv_excel_python_xlrd_xls.txt
Q: how do I instrospect appengine's datastore models? in order to dynamically create a form, i have to find the property types of a model's properties at runtime. appengine docs says that Model.properties() will return a dictionary of properties name and their class type. when i use this method in my code, only the name is returned and the classtype value is always empty. A: Model.kind() E.g., for a model like this: class LargeTextList(db.Model): large_text_list = db.ListProperty(item_type=db.Text) my_model_instance.kind() returns LargeTextList. Edit (thanks to OP for clarification): The property information you seek is there, but you'll need to escape to see it, e.g. in your template: <p>{{ my_model_instance.properties|escape }}</p> This returns: {'large_text_list': <google.appengine.ext.db.ListProperty object at 0x24b1790>} Edit2: You can also call properties() on the class itself: my_model = LargeTextList and in the template as before (be sure to use the escape filter): <p>{{ model.properties|escape }}</p>
how do I instrospect appengine's datastore models?
in order to dynamically create a form, i have to find the property types of a model's properties at runtime. appengine docs says that Model.properties() will return a dictionary of properties name and their class type. when i use this method in my code, only the name is returned and the classtype value is always empty.
[ "Model.kind()\nE.g., for a model like this:\nclass LargeTextList(db.Model):\n large_text_list = db.ListProperty(item_type=db.Text)\n\nmy_model_instance.kind() returns LargeTextList.\n\nEdit (thanks to OP for clarification):\nThe property information you seek is there, but you'll need to escape to see it, e.g. in your template:\n<p>{{ my_model_instance.properties|escape }}</p>\n\nThis returns:\n{'large_text_list': <google.appengine.ext.db.ListProperty object at 0x24b1790>}\n\n\nEdit2:\nYou can also call properties() on the class itself: \nmy_model = LargeTextList\n\nand in the template as before (be sure to use the escape filter): \n<p>{{ model.properties|escape }}</p>\n\n" ]
[ 1 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0002930352_google_app_engine_google_cloud_datastore_python.txt
Q: Python point lookup (coordinate binning?) Greetings, I am trying to bin an array of points (x, y) into an array of boxes [(x0, y0), (x1, y0), (x0, y1), (x1, y1)] (tuples are the corner points) So far I have the following routine: def isInside(self, point, x0, x1, y0, y1): pr1 = getProduct(point, (x0, y0), (x1, y0)) if pr1 >= 0: pr2 = getProduct(point, (x1, y0), (x1, y1)) if pr2 >= 0: pr3 = getProduct(point, (x1, y1), (x0, y1)) if pr3 >= 0: pr4 = getProduct(point, (x0, y1), (x0, y0)) if pr4 >= 0: return True return False def getProduct(origin, pointA, pointB): product = (pointA[0] - origin[0])*(pointB[1] - origin[1]) - (pointB[0] - origin[0])*(pointA[1] - origin[1]) return product Is there any better way then point-by-point lookup? Maybe some not-obvious numpy routine? Thank you! A: If I understand your problem correctly then the following should work assuming that your points are also 2-tuples. def in_bin(point, lower_corner, upper_corner): """ lower_corner is a 2-tuple - the coords of the lower left hand corner of the bin. upper_corner is a 2-tuple - the coords of the upper right hand corner of the bin. """ return lower_corner <= point <= upper_corner if __name__ == '__main__': p_min = (1, 1) # lower left corner of bin p_max = (5, 5) # upper right corner of bin p1 = (3, 3) # inside p2 = (1, 0) # outside p3 = (5, 6) # outside p4 = (1, 5) # inside points = [p1, p2, p3, p4] for p in points: print '%s in bin: %s' % (p, in_bin(p, x_min, x_max)) This code shows that you can compare tuples directly - there is some information in the documentation about this: http://docs.python.org/tutorial/datastructures.html#comparing-sequences-and-other-types A: Without too much change, your code can be compacted down to: def isInside(self, point, x0, x1, y0, y1): return getProduct(point, (x0, y0), (x1, y0)) >= 0 and getProduct(point, (x1, y0), (x1, y1)) >= 0 and getProduct(point, (x1, y1), (x0, y1)) >= 0 and getProduct(point, (x0, y1), (x0, y0)) >= 0 def getProduct(origin, pointA, pointB): product = (pointA[0] - origin[0])*(pointB[1] - origin[1]) - (pointB[0] - origin[0])*(pointA[1] - origin[1]) return product A: Your solution is O(N) where N is number of points. If N is large enough and you are running the query isInside a lot of times, you might considering sorting the points and then using binary search in order to find the relevant points. As always, first profile whether you really need this optimisation. A: Are you sure you need such a complicated check to begin with? def isInside(self, point, x0, y0, x1, y1): x,y = point if x0 > x1: x0,x1 = x1,x0 #these cause no if y0 > y1: y0,y1 = y1,y0 #side effect. return x0 <= x <= x1 and y0 <= y <= y1 A: I used a similar routine to do colourmapped density plots: #calculate densities rho = zeros((nx,ny)); for i in range(N): x_sample = int(round(ix[i])) y_sample = int(round(iy[i])) if (x_sample > 0) and (y_sample > 0) and (x_sample<nx) and (y_sample<ny): rho[y_sample,x_sample] = rho[y_sample,x_sample] + 1 Instead of counting density you can store the x and y samples. A: If you really do need to use getProduct... packing, unpacking and good variable names ftw! def isInside(self, point, x0, x1, y0, y1): A = x0,y0 B = x1,y0 C = x1,y1 D = x0,y1 return getProduct(point, A, B) and getProduct(point, B, C) and getProduct(point, C, D) and getProduct(point, D, A) def getProduct(origin, pointA, pointB): xA,yA = pointA xB,yB = pointB x,y = point return (xA - x)*(yB - y) - (xB - x)*(yB - y) A: Are these boxes axis aligned? i.e. are the edges parallel to the coordinate axes? If so this can be done quite efficiently with vectorized comparisons on NumPy arrays. def in_box(X, B): """ Takes an Nx2 NumPy array of points and a 4x2 NumPy array of corners that form an axis aligned box. """ xmin = B[:,0].min(); xmax = B[:,0].max() ymin = X[:,1].min(); ymax = X[:,1].max() return X[X[:,0] > xmin & X[:,0] < xmax & X[:,1] > ymin & X[:,1] < ymax] amending to >= and <= if you prefer them to be inclusive. If you need it for an arbitrary quadrilateral, matplotlib actually has a routine matplotlib.nxutils.points_inside_poly that you could use (if you have it installed) or else copy it (it's BSD-licensed). See this page for a discussion of the algorithms used and other algorithms for inside-a-polygon tests. A: Assuming that your boxes are rectangular, do not overlap, and have no gaps, then why don't you just call numpy.histogram2d? See the numpy docs.
Python point lookup (coordinate binning?)
Greetings, I am trying to bin an array of points (x, y) into an array of boxes [(x0, y0), (x1, y0), (x0, y1), (x1, y1)] (tuples are the corner points) So far I have the following routine: def isInside(self, point, x0, x1, y0, y1): pr1 = getProduct(point, (x0, y0), (x1, y0)) if pr1 >= 0: pr2 = getProduct(point, (x1, y0), (x1, y1)) if pr2 >= 0: pr3 = getProduct(point, (x1, y1), (x0, y1)) if pr3 >= 0: pr4 = getProduct(point, (x0, y1), (x0, y0)) if pr4 >= 0: return True return False def getProduct(origin, pointA, pointB): product = (pointA[0] - origin[0])*(pointB[1] - origin[1]) - (pointB[0] - origin[0])*(pointA[1] - origin[1]) return product Is there any better way then point-by-point lookup? Maybe some not-obvious numpy routine? Thank you!
[ "If I understand your problem correctly then the following should work assuming that your points are also 2-tuples.\ndef in_bin(point, lower_corner, upper_corner):\n \"\"\"\n lower_corner is a 2-tuple - the coords of the lower left hand corner of the\n bin.\n upper_corner is a 2-tuple - the coords of the upper right hand corner of the\n bin.\n \"\"\"\n return lower_corner <= point <= upper_corner\n\nif __name__ == '__main__':\n p_min = (1, 1) # lower left corner of bin\n p_max = (5, 5) # upper right corner of bin\n\n p1 = (3, 3) # inside\n p2 = (1, 0) # outside\n p3 = (5, 6) # outside\n p4 = (1, 5) # inside\n\n points = [p1, p2, p3, p4]\n\n for p in points:\n print '%s in bin: %s' % (p, in_bin(p, x_min, x_max))\n\nThis code shows that you can compare tuples directly - there is some information in the documentation about this: http://docs.python.org/tutorial/datastructures.html#comparing-sequences-and-other-types\n", "Without too much change, your code can be compacted down to:\ndef isInside(self, point, x0, x1, y0, y1):\n return getProduct(point, (x0, y0), (x1, y0)) >= 0 and\n getProduct(point, (x1, y0), (x1, y1)) >= 0 and\n getProduct(point, (x1, y1), (x0, y1)) >= 0 and\n getProduct(point, (x0, y1), (x0, y0)) >= 0\n\ndef getProduct(origin, pointA, pointB):\n product = (pointA[0] - origin[0])*(pointB[1] - origin[1]) - (pointB[0] - origin[0])*(pointA[1] - origin[1])\n return product\n\n", "Your solution is O(N) where N is number of points. If N is large enough and you are running the query isInside a lot of times, you might considering sorting the points and then using binary search in order to find the relevant points.\nAs always, first profile whether you really need this optimisation.\n", "Are you sure you need such a complicated check to begin with?\ndef isInside(self, point, x0, y0, x1, y1):\n x,y = point\n if x0 > x1: x0,x1 = x1,x0 #these cause no\n if y0 > y1: y0,y1 = y1,y0 #side effect.\n\n return x0 <= x <= x1 and y0 <= y <= y1\n\n", "I used a similar routine to do colourmapped density plots:\n#calculate densities\nrho = zeros((nx,ny));\nfor i in range(N):\n x_sample = int(round(ix[i]))\n y_sample = int(round(iy[i]))\n\n if (x_sample > 0) and (y_sample > 0) and (x_sample<nx) and (y_sample<ny):\n rho[y_sample,x_sample] = rho[y_sample,x_sample] + 1\n\nInstead of counting density you can store the x and y samples.\n", "If you really do need to use getProduct... packing, unpacking and good variable names ftw!\ndef isInside(self, point, x0, x1, y0, y1):\n A = x0,y0\n B = x1,y0\n C = x1,y1\n D = x0,y1\n\n return getProduct(point, A, B) and\n getProduct(point, B, C) and\n getProduct(point, C, D) and\n getProduct(point, D, A)\n\ndef getProduct(origin, pointA, pointB):\n xA,yA = pointA\n xB,yB = pointB\n x,y = point\n\n return (xA - x)*(yB - y) - (xB - x)*(yB - y)\n\n", "Are these boxes axis aligned? i.e. are the edges parallel to the coordinate axes? If so this can be done quite efficiently with vectorized comparisons on NumPy arrays. \ndef in_box(X, B):\n \"\"\"\n Takes an Nx2 NumPy array of points and a 4x2 NumPy array of corners that \n form an axis aligned box.\n \"\"\"\n xmin = B[:,0].min(); xmax = B[:,0].max()\n ymin = X[:,1].min(); ymax = X[:,1].max()\n return X[X[:,0] > xmin & X[:,0] < xmax & X[:,1] > ymin & X[:,1] < ymax]\n\namending to >= and <= if you prefer them to be inclusive. \nIf you need it for an arbitrary quadrilateral, matplotlib actually has a routine matplotlib.nxutils.points_inside_poly that you could use (if you have it installed) or else copy it (it's BSD-licensed). See this page for a discussion of the algorithms used and other algorithms for inside-a-polygon tests.\n", "Assuming that your boxes are rectangular, do not overlap, and have no gaps, then why don't you just call numpy.histogram2d? See the numpy docs.\n" ]
[ 2, 1, 1, 1, 1, 1, 1, 0 ]
[]
[]
[ "geometry", "numpy", "python" ]
stackoverflow_0002903878_geometry_numpy_python.txt
Q: Start local PHP script w/ local Python script The Python program I'm writing needs to start a local PHP script outside of Python's process. The program also needs to pass params to the PHP script. So far this seems to start the script: os.system( path_to_script_here param param ) However, I'm pretty certain that Python remains running until the PHP script is complete. I've also looked at the various os.spawn methods and I'm not sure which would be appropriate for my case. Any ideas? Thanks! A: See: How to start a background process in Python?
Start local PHP script w/ local Python script
The Python program I'm writing needs to start a local PHP script outside of Python's process. The program also needs to pass params to the PHP script. So far this seems to start the script: os.system( path_to_script_here param param ) However, I'm pretty certain that Python remains running until the PHP script is complete. I've also looked at the various os.spawn methods and I'm not sure which would be appropriate for my case. Any ideas? Thanks!
[ "See: How to start a background process in Python?\n" ]
[ 2 ]
[]
[]
[ "os.system", "php", "python" ]
stackoverflow_0002931061_os.system_php_python.txt
Q: Fastest way to find the rotation of a vector I have two 2D vectors, say u and v, defined by cartesian coordinates. Imagine that vectors are needles of a clock. I'm looking for the fastest way to find out, using python, if v is after or before u (or in other words find out in wich half plane is v, regarding to position of u). For the purpose of the problem if vectors are aligned answer should be before. It seems easy using some trigonometry, but I believe there should be a faster way using coordinates only. My test case: def after(u, v): """code here""" after((4,2), (6, 1)) : True after((4,2), (3, 3)) : False after((4,2), (2, 1)) : False after((4,2), (3, -3)) : True after((4,2), (-2, -5)) : True after((4,2), (-4, -2)) : False A: def after(u, v): # return sign of cross product return u[0]*v[1]<u[1]*v[0] don't know if it's fast, but it is terse A: General idea: Rotate the x-axis to coincide with v and check that the new y coordinate of u is positive. A: So you want to know what side of the line representing vector u the point at the head of vector v lies ? I hit Google (query: point on side of line) for an algorithm; found a ton, this one (read the second post) does it without trigonometry. A: If you're going by rotation, you can use simple trigonometry to figure out the rotation. Remember the three rules from high school trig class? "SOH CAH TOA" ring any bells? This is what they mean: Given the right triangle: A * | \ | \ | \ B *----* C SOH: The sine of any angle formed by ∆ABC is equal to the opposite side length divided by the length of the hypotenuse. For instance, in order to find the angle formed at point C: __ AB SIN(∠BCA) = ---- __ AC CAH: The cosine of any angle formed by ∆ABC is equal to the length of the adjacent side (not the hypotenuse) divided by the length of the hypotenuse. So, for example, to find the angle formed at point C: __ BC COS(∠BCA) = ---- __ AC TOA: The tangent of any angle formed by ∆ABC is equal to the length of the opposite side divided by the length of the adjacent side (not the hypotenuse). So, for example, to find the angle formed at point C: __ AB TAN(∠BCA) = ---- __ BC So, if you can determine any of these measurements, you can determine the rest, provided you think of the right triangle formed by the coordinate and the axes.
Fastest way to find the rotation of a vector
I have two 2D vectors, say u and v, defined by cartesian coordinates. Imagine that vectors are needles of a clock. I'm looking for the fastest way to find out, using python, if v is after or before u (or in other words find out in wich half plane is v, regarding to position of u). For the purpose of the problem if vectors are aligned answer should be before. It seems easy using some trigonometry, but I believe there should be a faster way using coordinates only. My test case: def after(u, v): """code here""" after((4,2), (6, 1)) : True after((4,2), (3, 3)) : False after((4,2), (2, 1)) : False after((4,2), (3, -3)) : True after((4,2), (-2, -5)) : True after((4,2), (-4, -2)) : False
[ "def after(u, v):\n # return sign of cross product\n return u[0]*v[1]<u[1]*v[0]\n\ndon't know if it's fast, but it is terse\n", "General idea: Rotate the x-axis to coincide with v and check that the new y coordinate of u is positive. \n", "So you want to know what side of the line representing vector u the point at the head of vector v lies ? I hit Google (query: point on side of line) for an algorithm; found a ton, this one (read the second post) does it without trigonometry.\n", "If you're going by rotation, you can use simple trigonometry to figure out the rotation.\nRemember the three rules from high school trig class? \"SOH CAH TOA\" ring any bells? This is what they mean:\nGiven the right triangle:\nA *\n | \\\n | \\\n | \\\nB *----* C\n\nSOH:\nThe sine of any angle formed by ∆ABC is equal to the opposite side length divided by the length of the hypotenuse. For instance, in order to find the angle formed at point C:\n __\n AB\nSIN(∠BCA) = ----\n __\n AC\n\nCAH:\nThe cosine of any angle formed by ∆ABC is equal to the length of the adjacent side (not the hypotenuse) divided by the length of the hypotenuse. So, for example, to find the angle formed at point C:\n __\n BC\nCOS(∠BCA) = ----\n __\n AC\n\nTOA:\nThe tangent of any angle formed by ∆ABC is equal to the length of the opposite side divided by the length of the adjacent side (not the hypotenuse). So, for example, to find the angle formed at point C:\n __\n AB\nTAN(∠BCA) = ----\n __\n BC\n\n\nSo, if you can determine any of these measurements, you can determine the rest, provided you think of the right triangle formed by the coordinate and the axes.\n" ]
[ 13, 0, 0, 0 ]
[]
[]
[ "math", "optimization", "python" ]
stackoverflow_0002930942_math_optimization_python.txt
Q: How do i make my web browser made in wx.python to parse pages(ex.Google.ro) Can somebody help me? please i really need to parse at least google. i need to parse url page. i've made a web browser and this web browser doesn't parse pages. It's made in wxpython. A: Have you looked at BeautifulSoup? http://www.crummy.com/software/BeautifulSoup/
How do i make my web browser made in wx.python to parse pages(ex.Google.ro)
Can somebody help me? please i really need to parse at least google. i need to parse url page. i've made a web browser and this web browser doesn't parse pages. It's made in wxpython.
[ "Have you looked at BeautifulSoup? http://www.crummy.com/software/BeautifulSoup/\n" ]
[ 1 ]
[]
[]
[ "parsing", "python", "wxpython", "wxwidgets" ]
stackoverflow_0002930985_parsing_python_wxpython_wxwidgets.txt
Q: Tkinter Label bound to StringVar is one click behind when updating The problem I'm running into here is that, when I click on the different file names in the Listbox, the Label changes value one click behind whatever I'm currently clicking on. What am I missing here? import Tkinter as tk class TkTest: def __init__(self, master): self.fraMain = tk.Frame(master) self.fraMain.pack() # Set up a list box containing all the paths to choose from self.lstPaths = tk.Listbox(self.fraMain) paths = [ '/path/file1', '/path/file2', '/path/file3', ] for path in paths: self.lstPaths.insert(tk.END, path) self.lstPaths.bind('<Button-1>', self.update_label) self.lstPaths.pack() self.currentpath = tk.StringVar() self.lblCurrentPath = tk.Label(self.fraMain, textvariable=self.currentpath) self.lblCurrentPath.pack() def update_label(self, event): print self.lstPaths.get(tk.ACTIVE), print self.lstPaths.curselection() self.currentpath.set(self.lstPaths.get(tk.ACTIVE)) root = tk.Tk() app = TkTest(root) root.mainloop() A: The problem has to do with the fundamental design of Tk. The short version is, bindings on specific widgets fire before the default class bindings for a widget. It is in the class bindings that the selection of a listbox is changed. This is exactly what you observe -- you are seeing the selection before the current click. The best solution is to bind to the virtual event <<ListboxSelect>> which is fired after the selection has changed. Other solutions (unique to Tk and what gives it some of its incredible power and flexibility) is to modify the order that the bindings are applied. This involves either moving the widget bindtag after the class bindtag, or adding a new bindtag after the class bindtag and binding it to that. Since binding to <<ListboxSelect>> is the better solution I won't go into details on how to modify the bindtags, though it's straight-forward and I think fairly well documented.
Tkinter Label bound to StringVar is one click behind when updating
The problem I'm running into here is that, when I click on the different file names in the Listbox, the Label changes value one click behind whatever I'm currently clicking on. What am I missing here? import Tkinter as tk class TkTest: def __init__(self, master): self.fraMain = tk.Frame(master) self.fraMain.pack() # Set up a list box containing all the paths to choose from self.lstPaths = tk.Listbox(self.fraMain) paths = [ '/path/file1', '/path/file2', '/path/file3', ] for path in paths: self.lstPaths.insert(tk.END, path) self.lstPaths.bind('<Button-1>', self.update_label) self.lstPaths.pack() self.currentpath = tk.StringVar() self.lblCurrentPath = tk.Label(self.fraMain, textvariable=self.currentpath) self.lblCurrentPath.pack() def update_label(self, event): print self.lstPaths.get(tk.ACTIVE), print self.lstPaths.curselection() self.currentpath.set(self.lstPaths.get(tk.ACTIVE)) root = tk.Tk() app = TkTest(root) root.mainloop()
[ "The problem has to do with the fundamental design of Tk. The short version is, bindings on specific widgets fire before the default class bindings for a widget. It is in the class bindings that the selection of a listbox is changed. This is exactly what you observe -- you are seeing the selection before the current click.\nThe best solution is to bind to the virtual event <<ListboxSelect>> which is fired after the selection has changed. Other solutions (unique to Tk and what gives it some of its incredible power and flexibility) is to modify the order that the bindings are applied. This involves either moving the widget bindtag after the class bindtag, or adding a new bindtag after the class bindtag and binding it to that.\nSince binding to <<ListboxSelect>> is the better solution I won't go into details on how to modify the bindtags, though it's straight-forward and I think fairly well documented.\n" ]
[ 4 ]
[]
[]
[ "label", "listbox", "python", "refresh", "tkinter" ]
stackoverflow_0002931053_label_listbox_python_refresh_tkinter.txt
Q: JavaScript cookie value can't be retrieved in Django I am trying to build a web site in both English and Bulgarian using the Django framework. My idea is the user should click on a button, the page will reload and the language will be changed. This is how I am trying to do it: In my html I hava a the button tag <button id='btn' onclick="changeLanguage();" type="button"> ... </button> An excerpt from cookies.js: function changeLanguage() { if (getCookie('language') == 'EN') { document.getElementById('btn').innerHTML = getCookie('language'); setCookie("language", 'BG'); } else { document.getElementById('btn').innerHTML = getCookie('language'); setCookie("language", 'EN'); } } function setCookie(sName, sValue, oExpires, sPath, sDomain, bSecure) { var sCookie = sName + "=" + encodeURIComponent(sValue); if (oExpires) { sCookie += "; expires=" + oExpires.toGMTString(); } if (sPath) { sCookie += "; path=" + sPath; } if (sDomain) { sCookie += "; domain=" + sDomain; } if (bSecure) { sCookie += "; secure"; } document.cookie = sCookie; } And in my views.py file this is the situation @base def index(request): if request.session['language'] == 'EN': return """<b>%s</b>""" % "Home" else request.session['language'] == 'BG': return """<b>%s</b>""" % "Начало" So I know that my JS changes the value of the language cookie but I think Django doesn't get that. On the other hand when I set and get the cookie in my Python code again the cookie is set. My question is whether there is a way to make JS and Django work together - JavaScript sets the cookie value and Python only reads it when asked and takes adequate actions? Thank you. A: The session is not the same as a cookie. Sessions are an internal Django database table, the key to which is stored in a cookie. However the rest of the data apart from the key is stored in the database. If you want to access an actual cookie that's been set by the client, you need to use the request.COOKIES dictionary: if request.COOKIES['language'] == 'EN': return """<b>%s</b>""" % "Home"
JavaScript cookie value can't be retrieved in Django
I am trying to build a web site in both English and Bulgarian using the Django framework. My idea is the user should click on a button, the page will reload and the language will be changed. This is how I am trying to do it: In my html I hava a the button tag <button id='btn' onclick="changeLanguage();" type="button"> ... </button> An excerpt from cookies.js: function changeLanguage() { if (getCookie('language') == 'EN') { document.getElementById('btn').innerHTML = getCookie('language'); setCookie("language", 'BG'); } else { document.getElementById('btn').innerHTML = getCookie('language'); setCookie("language", 'EN'); } } function setCookie(sName, sValue, oExpires, sPath, sDomain, bSecure) { var sCookie = sName + "=" + encodeURIComponent(sValue); if (oExpires) { sCookie += "; expires=" + oExpires.toGMTString(); } if (sPath) { sCookie += "; path=" + sPath; } if (sDomain) { sCookie += "; domain=" + sDomain; } if (bSecure) { sCookie += "; secure"; } document.cookie = sCookie; } And in my views.py file this is the situation @base def index(request): if request.session['language'] == 'EN': return """<b>%s</b>""" % "Home" else request.session['language'] == 'BG': return """<b>%s</b>""" % "Начало" So I know that my JS changes the value of the language cookie but I think Django doesn't get that. On the other hand when I set and get the cookie in my Python code again the cookie is set. My question is whether there is a way to make JS and Django work together - JavaScript sets the cookie value and Python only reads it when asked and takes adequate actions? Thank you.
[ "The session is not the same as a cookie. \nSessions are an internal Django database table, the key to which is stored in a cookie. However the rest of the data apart from the key is stored in the database.\nIf you want to access an actual cookie that's been set by the client, you need to use the request.COOKIES dictionary:\nif request.COOKIES['language'] == 'EN':\n return \"\"\"<b>%s</b>\"\"\" % \"Home\" \n\n" ]
[ 10 ]
[]
[]
[ "cookies", "django", "javascript", "python" ]
stackoverflow_0002931324_cookies_django_javascript_python.txt
Q: Pickling an unbound method in Python 3 I would like to pickle an unbound method in Python 3.x. I'm getting this error: >>> class A: ... def m(self): ... pass >>> import pickle >>> pickle.dumps(A.m) Traceback (most recent call last): File "<pyshell#3>", line 1, in <module> pickle.dumps(A.m) File "C:\Python31\lib\pickle.py", line 1358, in dumps Pickler(f, protocol, fix_imports=fix_imports).dump(obj) _pickle.PicklingError: Can't pickle <class 'function'>: attribute lookup builtins.function failed Does anyone have experience with this? Note: In Python 2.x it's also impossible to pickle unbound methods by default; I managed to do it there in some weird way I don't understand: I wrote a reducer with the copy_reg module for the MethodType class, which covers both bound and unbound methods. But the reducer only solved the case of the bound method, because it depended on my_method.im_self. Mysteriously it has also caused Python 2.x to be able to pickle unbound methods. This does not happen on Python 3.x. A: This cannot be done directly because in Python 3 unbound method type is gone: it is just a function: >>> print (type (A.m)) <class 'function'> Python functions are not bound to a class, so it is impossible to tell what class A.m belongs to just by looking at the expression result. Depending on what exactly you need, pickling/unpickling a tuple of (class, method-name) might be good enough: >>> print (pickle.loads (pickle.dumps ((A, 'm')))) ... (<class '__main__.A'>, 'm') You can get the method (function) from here simply by using getattr(): >>> cls, method = pickle.loads (pickle.dumps ((A, 'm'))) >>> print (getattr (cls, method)) ... <function m at 0xb78878ec>
Pickling an unbound method in Python 3
I would like to pickle an unbound method in Python 3.x. I'm getting this error: >>> class A: ... def m(self): ... pass >>> import pickle >>> pickle.dumps(A.m) Traceback (most recent call last): File "<pyshell#3>", line 1, in <module> pickle.dumps(A.m) File "C:\Python31\lib\pickle.py", line 1358, in dumps Pickler(f, protocol, fix_imports=fix_imports).dump(obj) _pickle.PicklingError: Can't pickle <class 'function'>: attribute lookup builtins.function failed Does anyone have experience with this? Note: In Python 2.x it's also impossible to pickle unbound methods by default; I managed to do it there in some weird way I don't understand: I wrote a reducer with the copy_reg module for the MethodType class, which covers both bound and unbound methods. But the reducer only solved the case of the bound method, because it depended on my_method.im_self. Mysteriously it has also caused Python 2.x to be able to pickle unbound methods. This does not happen on Python 3.x.
[ "This cannot be done directly because in Python 3 unbound method type is gone: it is just a function:\n>>> print (type (A.m))\n<class 'function'>\n\nPython functions are not bound to a class, so it is impossible to tell what class A.m belongs to just by looking at the expression result.\nDepending on what exactly you need, pickling/unpickling a tuple of (class, method-name) might be good enough:\n>>> print (pickle.loads (pickle.dumps ((A, 'm'))))\n... (<class '__main__.A'>, 'm')\n\nYou can get the method (function) from here simply by using getattr():\n>>> cls, method = pickle.loads (pickle.dumps ((A, 'm')))\n>>> print (getattr (cls, method))\n... <function m at 0xb78878ec>\n\n" ]
[ 7 ]
[]
[]
[ "methods", "pickle", "python", "python_3.x" ]
stackoverflow_0002930792_methods_pickle_python_python_3.x.txt
Q: Having a Python package install itself under a different name I'm developing a package called garlicsim. (Website.) The package is intended for Python 2.X, but I am also offerring Python 3 support on a different fork called garlicsim_py3.(1) So both of these packages live side by side on PyPI, and Python 3 users install garlicsim_py3, and Python 2 users install garlicsim. The problem is: When third party modules want to use garlicsim, they should have one package name to refer to, not two. Sure, they can do something like this: try: import garlicsim except ImportError: import garlicsim_py3 as garlicsim But I would prefer not to make the developers of these modules do this. Is there a way that garlicsim_py3 will install itself under the alias garlicsim? What I want is for a Python 3 user to be able to import garlicsim and refer to the module all the time as garlicsim, but that it will really be garlicsim_py3. I know that the Distribute project does something like this: They make it so you can import setuptools and it will be redirected into their code. I have no idea how they do it. Any ideas? (1) I've reached the decision to support Python 3 on a fork instead of in the same code base; It's important for me that the code base will be clean, and I would really not want to introduce compatibilty hacks. A: Eventually I decided not to do it, and just have the two projects have the same package name even though they have a different PyPI name.
Having a Python package install itself under a different name
I'm developing a package called garlicsim. (Website.) The package is intended for Python 2.X, but I am also offerring Python 3 support on a different fork called garlicsim_py3.(1) So both of these packages live side by side on PyPI, and Python 3 users install garlicsim_py3, and Python 2 users install garlicsim. The problem is: When third party modules want to use garlicsim, they should have one package name to refer to, not two. Sure, they can do something like this: try: import garlicsim except ImportError: import garlicsim_py3 as garlicsim But I would prefer not to make the developers of these modules do this. Is there a way that garlicsim_py3 will install itself under the alias garlicsim? What I want is for a Python 3 user to be able to import garlicsim and refer to the module all the time as garlicsim, but that it will really be garlicsim_py3. I know that the Distribute project does something like this: They make it so you can import setuptools and it will be redirected into their code. I have no idea how they do it. Any ideas? (1) I've reached the decision to support Python 3 on a fork instead of in the same code base; It's important for me that the code base will be clean, and I would really not want to introduce compatibilty hacks.
[ "Eventually I decided not to do it, and just have the two projects have the same package name even though they have a different PyPI name.\n" ]
[ 1 ]
[]
[]
[ "packaging", "python", "python_3.x", "setuptools" ]
stackoverflow_0002923704_packaging_python_python_3.x_setuptools.txt
Q: Trying to figure out URL dispatcher for sluggale URLs like stackoverflow I'm using the Tornado framework (Python). I have the sluggable URLs working. But I have 3 different entries in the URL dispatcher. I was wondering if someone could help me transform it into one line. This is what I have: (r"/post/([0-9]+)/[a-zA-Z0-9\-]+", SpotHandler), (r"/post/([0-9]+)/", SpotHandler), (r"/post/([0-9]+)", SpotHandler), I want it so that the following URLs all go to the same place. http://domain.com/post/14 http://domain.com/post/14/ http://domain.com/post/14/any-text-it-doesnt-matter-what-it-is A: r"/post/([0-9]+)(?:/[a-zA-Z_-]+|/)?" A: (r"/post/([0-9]+)/?[a-zA-Z_]*", SpotHandler), "?" means previous thing can be there but need not be. "*" means zero or more
Trying to figure out URL dispatcher for sluggale URLs like stackoverflow
I'm using the Tornado framework (Python). I have the sluggable URLs working. But I have 3 different entries in the URL dispatcher. I was wondering if someone could help me transform it into one line. This is what I have: (r"/post/([0-9]+)/[a-zA-Z0-9\-]+", SpotHandler), (r"/post/([0-9]+)/", SpotHandler), (r"/post/([0-9]+)", SpotHandler), I want it so that the following URLs all go to the same place. http://domain.com/post/14 http://domain.com/post/14/ http://domain.com/post/14/any-text-it-doesnt-matter-what-it-is
[ "r\"/post/([0-9]+)(?:/[a-zA-Z_-]+|/)?\"\n\n", "(r\"/post/([0-9]+)/?[a-zA-Z_]*\", SpotHandler),\n\"?\" means previous thing can be there but need not be.\n\"*\" means zero or more\n" ]
[ 2, 1 ]
[]
[]
[ "python", "slug", "tornado" ]
stackoverflow_0002932098_python_slug_tornado.txt
Q: decorating a function and adding functionalities preserving the number of argument I'd like to decorate a function, using a pattern like this: def deco(func): def wrap(*a,**kw): print "do something" return func(*a,**kw) return wrap The problem is that if the function decorated has a prototype like that: def function(a,b,c): return When decorated, the prototype is destroyed by the varargs, for example, calling function(1,2,3,4) wouldn't result in an exception. Is that a way to avoid that? How can define the wrap function with the same prototype as the decorated (func) one? There's something conceptually wrong? EDIT My perverse idea was to lighten the "calling of the parent method" without modifying the signature. Something like def __init__(self, something) super(ClassName, self).__init__(something) to: @extended def __init__(self, something): ... I was figuring out if this was possible and if this makes sense. EDIT As Alex pointed out, the following code doesn't give an exception: function(1,2,3,4) A: You're wrong when you state that "calling function(1,2,3,4) wouldn't result in an exception". Check it out: >>> def deco(f): ... def w(*a, **k): ... print 'do something' ... return f(*a, **k) ... return w ... >>> def f(a, b, c): return ... >>> f(1, 2, 3, 4) Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: f() takes exactly 3 arguments (4 given) >>> decorated = deco(f) >>> decorated(1, 2, 3, 4) do something Traceback (most recent call last): File "<stdin>", line 1, in ? File "<stdin>", line 4, in w TypeError: f() takes exactly 3 arguments (4 given) As you see, you get exactly the same exception as when similarly calling the undecorated f (albeit after the print you've added). For preserving the wrapped function's metadata (name, docstring, use functools.wraps. Predicting that the wrapped function will raise when called (to avoid doing other work before calling it) is always hard ("impossible" in general, as it's equivalent to the halting problem; "just hard" in specific, when you only care about raising a type-error for argument name and number mismatches and want to treat that specialized exception case differently from any other exception case -- a peculiar requirement;-0). If you're adamant that you absolutely need it (and can perhaps explain why?) I'll be glad (well, not glad, but will grit my teeth and do it, after all I've got a long weekend in front of me;-) to take you down that labyrinthine path. A: The decorator module helps you create a decorator that preserves the function signature. As a result, you will get the exception you expect when calling the function, and inspect.getargspec will give you the correct signature. It works by dynamically building a function definition and using exec. Unfortunately, there isn't an easier built-in way to do this. A: Here is a trick that involves fetching the original argument specification from the decorated function, then creating a lambda by evaling a string with the same arguments. The decorator is then wrapped in this lambda thus to the outside world it has the same parameter names and default values: import inspect, time import functools def decorator_wrapper(old_function, new_function): args, arglist, kw, default = inspect.getargspec(old_function) args = list(args) if arglist: args.append(arglist) if kw: args.append(kw) callstring = inspect.formatargspec(args, arglist, kw, default, formatvalue=lambda value: "") argstring = inspect.formatargspec(args, arglist, kw, default)[1:-1] unique_name = "_func" + str(int(time.time())) codestring = "lambda " + argstring + " : " + unique_name + callstring decorated_function = eval(codestring, {unique_name: new_function}) return functools.wraps(old_function)(decorated_function) A: By calling result=func(*a,**kw) first, you get the TypeError before printing "do something". def deco(func): def wrap(*a,**kw): result=func(*a,**kw) print "do something" return result return wrap @deco def function(a,b,c): return function(1,2,3) # do something function(1,2,3,4) # TypeError: function() takes exactly 3 arguments (4 given)
decorating a function and adding functionalities preserving the number of argument
I'd like to decorate a function, using a pattern like this: def deco(func): def wrap(*a,**kw): print "do something" return func(*a,**kw) return wrap The problem is that if the function decorated has a prototype like that: def function(a,b,c): return When decorated, the prototype is destroyed by the varargs, for example, calling function(1,2,3,4) wouldn't result in an exception. Is that a way to avoid that? How can define the wrap function with the same prototype as the decorated (func) one? There's something conceptually wrong? EDIT My perverse idea was to lighten the "calling of the parent method" without modifying the signature. Something like def __init__(self, something) super(ClassName, self).__init__(something) to: @extended def __init__(self, something): ... I was figuring out if this was possible and if this makes sense. EDIT As Alex pointed out, the following code doesn't give an exception: function(1,2,3,4)
[ "You're wrong when you state that \"calling function(1,2,3,4) wouldn't result in an exception\". Check it out:\n>>> def deco(f):\n... def w(*a, **k):\n... print 'do something'\n... return f(*a, **k)\n... return w\n... \n>>> def f(a, b, c): return\n... \n>>> f(1, 2, 3, 4)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in ?\nTypeError: f() takes exactly 3 arguments (4 given)\n>>> decorated = deco(f)\n>>> decorated(1, 2, 3, 4)\ndo something\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in ?\n File \"<stdin>\", line 4, in w\nTypeError: f() takes exactly 3 arguments (4 given)\n\nAs you see, you get exactly the same exception as when similarly calling the undecorated f (albeit after the print you've added).\nFor preserving the wrapped function's metadata (name, docstring, use functools.wraps. Predicting that the wrapped function will raise when called (to avoid doing other work before calling it) is always hard (\"impossible\" in general, as it's equivalent to the halting problem; \"just hard\" in specific, when you only care about raising a type-error for argument name and number mismatches and want to treat that specialized exception case differently from any other exception case -- a peculiar requirement;-0).\nIf you're adamant that you absolutely need it (and can perhaps explain why?) I'll be glad (well, not glad, but will grit my teeth and do it, after all I've got a long weekend in front of me;-) to take you down that labyrinthine path.\n", "The decorator module helps you create a decorator that preserves the function signature.\nAs a result, you will get the exception you expect when calling the function, and inspect.getargspec will give you the correct signature.\nIt works by dynamically building a function definition and using exec. Unfortunately, there isn't an easier built-in way to do this.\n", "Here is a trick that involves fetching the original argument specification from the decorated function, then creating a lambda by evaling a string with the same arguments. The decorator is then wrapped in this lambda thus to the outside world it has the same parameter names and default values:\nimport inspect, time\nimport functools\n\ndef decorator_wrapper(old_function, new_function):\n args, arglist, kw, default = inspect.getargspec(old_function)\n args = list(args)\n\n if arglist:\n args.append(arglist)\n\n if kw:\n args.append(kw)\n\n callstring = inspect.formatargspec(args, arglist, kw, default, formatvalue=lambda value: \"\")\n argstring = inspect.formatargspec(args, arglist, kw, default)[1:-1]\n\n unique_name = \"_func\" + str(int(time.time()))\n codestring = \"lambda \" + argstring + \" : \" + unique_name + callstring\n decorated_function = eval(codestring, {unique_name: new_function})\n\n return functools.wraps(old_function)(decorated_function)\n\n", "By calling result=func(*a,**kw) first, you get the TypeError before printing \"do something\".\ndef deco(func):\n def wrap(*a,**kw):\n result=func(*a,**kw)\n print \"do something\"\n return result\n return wrap\n\n@deco\ndef function(a,b,c): return\n\nfunction(1,2,3)\n# do something\nfunction(1,2,3,4)\n# TypeError: function() takes exactly 3 arguments (4 given)\n\n" ]
[ 4, 3, 3, 0 ]
[]
[]
[ "decorator", "python" ]
stackoverflow_0002932356_decorator_python.txt
Q: How do I use a string as a keyword argument? Specifically, I'm trying to use a string to arbitrairly filter the ORM. I've tried exec and eval solutions, but I'm running into walls. The code below doesn't work, but it's the best way I know how to explain where I'm trying to go from gblocks.models import Image f = 'image__endswith="jpg"' # Would be scripted in another area, but passed as text <user input> d = Image.objects.filter(f) #for the non-django pythonistas: d = Image.objects.filter(image__endswith="jpg") # would be the non-dynamic equivalent. A: d = Image.objects.filter(**{'image__endswith': "jpg"}) A: You'd need to split out the value from the keyword, then set up a dict using the keyword as the key, and the value as the value. You could then use the double-asterisk function paramater with the dict. So... keyword, sep, value = f.partition('=') kwargs = {keyword: value.strip('"')} d = Image.objects.filter(**kwargs) Note, this code assumes that there won't be any equals signs '=' in the keyword (they'll only be used to separate the keyword from the value), and the value will be wrapped in quotes. A: The eval option should work fine, as long as you wrap it around the entire expression, not just the f: f = 'image__endswith="jpg"' d = eval('Image.objects.filter(' + f + ')')
How do I use a string as a keyword argument?
Specifically, I'm trying to use a string to arbitrairly filter the ORM. I've tried exec and eval solutions, but I'm running into walls. The code below doesn't work, but it's the best way I know how to explain where I'm trying to go from gblocks.models import Image f = 'image__endswith="jpg"' # Would be scripted in another area, but passed as text <user input> d = Image.objects.filter(f) #for the non-django pythonistas: d = Image.objects.filter(image__endswith="jpg") # would be the non-dynamic equivalent.
[ "d = Image.objects.filter(**{'image__endswith': \"jpg\"})\n\n", "You'd need to split out the value from the keyword, then set up a dict using the keyword as the key, and the value as the value. You could then use the double-asterisk function paramater with the dict.\nSo...\nkeyword, sep, value = f.partition('=')\nkwargs = {keyword: value.strip('\"')}\nd = Image.objects.filter(**kwargs)\n\nNote, this code assumes that there won't be any equals signs '=' in the keyword (they'll only be used to separate the keyword from the value), and the value will be wrapped in quotes.\n", "The eval option should work fine, as long as you wrap it around the entire expression, not just the f:\nf = 'image__endswith=\"jpg\"'\nd = eval('Image.objects.filter(' + f + ')')\n\n" ]
[ 110, 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002932648_python.txt
Q: How do i call a method by a string name using python? I have the following class; class myStringMethod(): def __init__(self): self.func_list= [('func1','print_func1()'),('func2','print_func2()')] def print_func1(self, name): print name def print_func2(self, name): print name def call_func_by_name(self): for func in self.func_list: getattr(self, func[1])('Func Name') if __name__=='__main__': strM = myStringMethod() strM.call_func_by_name() #Nothing prints out! No functions get called out, what am i missing? gath A: your self.func_list should be: self.func_list= [('func1','print_func1'),('func2','print_func2')] And the way your code is written it will, of course, print 'Func Name'. I guess you probably meant to pass func[0] there. Working example: >>> class myStringMethod(): def __init__(self): self.func_list= [('func1','print_func1'),('func2','print_func2')] def print_func1(self, name): print(name) def print_func2(self, name): print(name) def call_func_by_name(self): for func in self.func_list: getattr(self, func[1])('Func Name') >>> myStringMethod().call_func_by_name() Func Name Func Name A: maybe offtopic, but maybe your list is actually a dict : self.functs = {'func1':'print_func1', ...} and then call with : for fn in self.functs.values() : self.__dict__[fn]('Func Name') or even if you wanted to call all 'func_' functions in your class (no func_list here) : @classmethod def call_func_by_name(cls) for n,f in cls.__dict__.values() : if n.startswith('print_') and hasattr(f,'__call__'): f('Hello')
How do i call a method by a string name using python?
I have the following class; class myStringMethod(): def __init__(self): self.func_list= [('func1','print_func1()'),('func2','print_func2()')] def print_func1(self, name): print name def print_func2(self, name): print name def call_func_by_name(self): for func in self.func_list: getattr(self, func[1])('Func Name') if __name__=='__main__': strM = myStringMethod() strM.call_func_by_name() #Nothing prints out! No functions get called out, what am i missing? gath
[ "your self.func_list should be:\nself.func_list= [('func1','print_func1'),('func2','print_func2')]\n\nAnd the way your code is written it will, of course, print 'Func Name'. I guess you probably meant to pass func[0] there.\nWorking example:\n>>> class myStringMethod():\n def __init__(self):\n self.func_list= [('func1','print_func1'),('func2','print_func2')]\n\n def print_func1(self, name):\n print(name)\n\n def print_func2(self, name):\n print(name)\n\n def call_func_by_name(self):\n for func in self.func_list:\n getattr(self, func[1])('Func Name')\n\n>>> myStringMethod().call_func_by_name()\nFunc Name\nFunc Name\n\n", "maybe offtopic, but maybe your list is actually a dict : \nself.functs = {'func1':'print_func1', ...}\n\nand then call with : \nfor fn in self.functs.values() : self.__dict__[fn]('Func Name')\n\nor even if you wanted to call all 'func_' functions in your class (no func_list here) : \n@classmethod\ndef call_func_by_name(cls)\n for n,f in cls.__dict__.values() : \n if n.startswith('print_') and hasattr(f,'__call__'): f('Hello')\n\n" ]
[ 3, 0 ]
[]
[]
[ "function", "python" ]
stackoverflow_0002930196_function_python.txt
Q: Is cropping of jpeg images using the PIL lossless? A simple questions really. If you crop a jpeg image using the Python Imaging Library, is the resulting image recompressed, or is it lossless? A: Generally not. There is a python wrapper for the lossless jpeg library. Cropping might be essentially lossless if you remove entire 8x8 pixel blocks
Is cropping of jpeg images using the PIL lossless?
A simple questions really. If you crop a jpeg image using the Python Imaging Library, is the resulting image recompressed, or is it lossless?
[ "Generally not. There is a python wrapper for the lossless jpeg library.\nCropping might be essentially lossless if you remove entire 8x8 pixel blocks\n" ]
[ 5 ]
[]
[]
[ "crop", "jpeg", "lossless", "python", "python_imaging_library" ]
stackoverflow_0002933084_crop_jpeg_lossless_python_python_imaging_library.txt
Q: Email notifications of exceptions happening in a Python app? UPDATE: This is a Django web app Hi folks, I want to set up email notifications when there is an error happening in my application. In ruby, there is a very elegant solution called ExceptionNotifier, which wraps around the exception handler and uses the built-in mailer to send an email. What is the best way of doing this in Python? I know that this is a very common issue, so would love for any tips that you folks can share! PS: Code samples, pointers to modules would be AWESOME! Thanks! A: (I'm guessing you're talking about a web app here, because ExceptionNotifier is a Rails plugin...) A Python web app using which framework? I know there's Django-hoptoad, which is actually a step above the ExecptionNotifier of Ruby, using ThoughtBot's Hoptoad. But that's just a guess that you're using Django, which you might not be... Similarly, Pylons (and by extension, Turbogears 2, I guess), has configuration options for error emails
Email notifications of exceptions happening in a Python app?
UPDATE: This is a Django web app Hi folks, I want to set up email notifications when there is an error happening in my application. In ruby, there is a very elegant solution called ExceptionNotifier, which wraps around the exception handler and uses the built-in mailer to send an email. What is the best way of doing this in Python? I know that this is a very common issue, so would love for any tips that you folks can share! PS: Code samples, pointers to modules would be AWESOME! Thanks!
[ "(I'm guessing you're talking about a web app here, because ExceptionNotifier is a Rails plugin...)\nA Python web app using which framework? I know there's Django-hoptoad, which is actually a step above the ExecptionNotifier of Ruby, using ThoughtBot's Hoptoad.\nBut that's just a guess that you're using Django, which you might not be...\nSimilarly, Pylons (and by extension, Turbogears 2, I guess), has configuration options for error emails\n" ]
[ 3 ]
[]
[]
[ "debugging", "email", "exception", "exception_handling", "python" ]
stackoverflow_0002933392_debugging_email_exception_exception_handling_python.txt
Q: Possible to call single-parameter Python function without using parentheses? The Python documentation specifies that is is legal to omit the parentheses if a function only takes a single parameter, but myfunction "Hello!" generates a syntax error. So, what's the deal? EDIT: The statement that I read only applies to generator expressions: The parentheses can be omitted on calls with only one argument. A: For your edit: If you write down a generator expression, like stuff = (f(x) for x in items) you need the brackets, just like you need the [ .. ] around a list comprehension. But when you pass something from a generator expression to a function (which is a pretty common pattern, because that's pretty much the big idea behind generators) then you don't need two sets of brackets - instead of something like s = sum((f(x) for x in items)) (outer brackets to indicate a function call, inner for the generator expression) you can just write sum(f(x) for x in items) A: You can do it with IPython -- the %autocall magic command controls this feature (as well as the -autocall command line option). Use %autocall 0 to disable the feature, %autocall 1, the default, to have it work only when an argument is present, and %autocall 2 to have it work even for argument-less callables. In [2]: %autocall 1 Automatic calling is: Smart In [3]: int '5' ------> int('5') Out[3]: 5 In [4]: %autocall 2 Automatic calling is: Full In [5]: int ------> int() Out[5]: 0 A: Without parentheses those wouldn't be functions but statements or keywords (language-intrinsic). This StackOverflow thread (with some very nice answers) contains a lead as to how one can create their own in pure Python (through advanced hackery, and not a good idea in 99.99% of the cases). A: As I understand the rule is only about the generator expressions... so for example: sum(x**2 for x in range(10)) but you would still have to write: reduce(operator.add, (x**2 for x in range(10))) This doesn't apply for generic functions though.
Possible to call single-parameter Python function without using parentheses?
The Python documentation specifies that is is legal to omit the parentheses if a function only takes a single parameter, but myfunction "Hello!" generates a syntax error. So, what's the deal? EDIT: The statement that I read only applies to generator expressions: The parentheses can be omitted on calls with only one argument.
[ "For your edit:\nIf you write down a generator expression, like stuff = (f(x) for x in items) you need the brackets, just like you need the [ .. ] around a list comprehension. \nBut when you pass something from a generator expression to a function (which is a pretty common pattern, because that's pretty much the big idea behind generators) then you don't need two sets of brackets - instead of something like s = sum((f(x) for x in items)) (outer brackets to indicate a function call, inner for the generator expression) you can just write sum(f(x) for x in items)\n", "You can do it with IPython -- the %autocall magic command controls this feature (as well as the -autocall command line option). Use %autocall 0 to disable the feature, %autocall 1, the default, to have it work only when an argument is present, and %autocall 2 to have it work even for argument-less callables.\nIn [2]: %autocall 1\nAutomatic calling is: Smart\n\nIn [3]: int '5'\n------> int('5')\nOut[3]: 5\n\nIn [4]: %autocall 2\nAutomatic calling is: Full\n\nIn [5]: int\n------> int()\nOut[5]: 0\n\n", "Without parentheses those wouldn't be functions but statements or keywords (language-intrinsic).\nThis StackOverflow thread (with some very nice answers) contains a lead as to how one can create their own in pure Python (through advanced hackery, and not a good idea in 99.99% of the cases).\n", "As I understand the rule is only about the generator expressions...\nso for example:\nsum(x**2 for x in range(10))\n\nbut you would still have to write:\nreduce(operator.add, (x**2 for x in range(10)))\n\nThis doesn't apply for generic functions though.\n" ]
[ 8, 5, 2, 0 ]
[]
[]
[ "python", "syntax" ]
stackoverflow_0002932887_python_syntax.txt
Q: Python: Using `copyreg` to define reducers for types that already have reducers (Keep in mind I'm working in Python 3, so a solution needs to work in Python 3.) I would like to use the copyreg module to teach Python how to pickle functions. When I tried to do it, the _Pickler object would still try to pickle functions using the save_global function. (Which doesn't work for unbound methods, and that's the motivation for doing this.) It seems like _Pickler first tries to look in its own dispatch for the type of the object that you want to pickle before looking in copyreg.dispatch_table. I'm not sure if this is intentional. Is there any way for me to tell Python to pickle functions with the reducer that I provide? A: The following hack seems to work in Python 3.1...: import copyreg def functionpickler(f): print('pickling', f.__name__) return f.__name__ ft = type(functionpickler) copyreg.pickle(ft, functionpickler) import pickle pickle.Pickler = pickle._Pickler del pickle.Pickler.dispatch[ft] s = pickle.dumps(functionpickler) print('Result is', s) Out of this, the two hackish lines are: pickle.Pickler = pickle._Pickler del pickle.Pickler.dispatch[ft] You need to remove the dispatch entry for functions' type because otherwise it preempts the copyreg registration; and I don't think you can do that on the C-coded Pickler so you need to set it to the Python-coded one. It would be a bit less of a hack to subclass _Pickler with a class of your own which makes its own dispatch (copying the parent's and removing the entry for the function type), and then use your subclass specifically (and its dump method) rather than pickle.dump; however it would also be a bit less convenient that this monkeypatching of pickle itself.
Python: Using `copyreg` to define reducers for types that already have reducers
(Keep in mind I'm working in Python 3, so a solution needs to work in Python 3.) I would like to use the copyreg module to teach Python how to pickle functions. When I tried to do it, the _Pickler object would still try to pickle functions using the save_global function. (Which doesn't work for unbound methods, and that's the motivation for doing this.) It seems like _Pickler first tries to look in its own dispatch for the type of the object that you want to pickle before looking in copyreg.dispatch_table. I'm not sure if this is intentional. Is there any way for me to tell Python to pickle functions with the reducer that I provide?
[ "The following hack seems to work in Python 3.1...:\nimport copyreg\ndef functionpickler(f):\n print('pickling', f.__name__)\n return f.__name__\n\nft = type(functionpickler)\ncopyreg.pickle(ft, functionpickler)\n\nimport pickle\npickle.Pickler = pickle._Pickler\ndel pickle.Pickler.dispatch[ft]\n\ns = pickle.dumps(functionpickler)\nprint('Result is', s)\n\nOut of this, the two hackish lines are:\npickle.Pickler = pickle._Pickler\ndel pickle.Pickler.dispatch[ft]\n\nYou need to remove the dispatch entry for functions' type because otherwise it preempts the copyreg registration; and I don't think you can do that on the C-coded Pickler so you need to set it to the Python-coded one.\nIt would be a bit less of a hack to subclass _Pickler with a class of your own which makes its own dispatch (copying the parent's and removing the entry for the function type), and then use your subclass specifically (and its dump method) rather than pickle.dump; however it would also be a bit less convenient that this monkeypatching of pickle itself.\n" ]
[ 1 ]
[]
[]
[ "function", "pickle", "python" ]
stackoverflow_0002932742_function_pickle_python.txt
Q: Python help reading csv file failing due to line-endings I'm trying to create this script that will check the computer host name then search a master list for the value to return a corresponding value in the csv file. Then open another file and do a find an replace. I know this should be easy but haven't done so much in python before. Here is what I have so far... masterlist.txt (tab delimited) Name UID Bob-Smith.local bobs Carmen-Jackson.local carmenj David-Kathman.local davidk Jenn-Roberts.local jennr Here is the script that I have created thus far #GET CLIENT HOST NAME import socket host = socket.gethostname() print host #IMPORT MASTER DATA import csv, sys filename = "masterlist.txt" reader = csv.reader(open(filename, "rU")) #PRINT MASTER DATA for row in reader: print row #SEARCH ON HOSTNAME AND RETURN UID #REPLACE VALUE IN FILE WITH UID #import fileinput #for line in fileinput.FileInput("filetoreplace",inplace=1): # line = line.replace("replacethistext","UID") # print line Right now, it's just set to print the master list. I'm not sure if the list needs to be parsed and placed into a dictionary or what. I really need to figure out how to search the first field for the hostname and then return the field in the second column. Thanks in advance for your help, Aaron UPDATE: I removed line 194 and last line from masterlist.txt and then re-ran the script. The results were the following: Traceback (most recent call last): File "update.py", line 3, in for row in csv.DictReader(open(fname), delimiter='\t'): File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/csv.py", line 103, in next self.fieldnames File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/csv.py", line 90, in fieldnames self._fieldnames = self.reader.next() _csv.Error: new-line character seen in unquoted field - do you need to open the file in universal-newline mode? The current script being used is... import csv fname = "masterlist.txt" for row in csv.DictReader(open(fname), delimiter='\t'): print(row) A: The two occurrences of '\xD5' in line 194 and the last line have nothing to do with the problem. The problem appears to be a bug, or a misleading error message, or incorrect/vague documentation, in the Python 2.6 csv module. In the file, the lines are terminated by '\x0D' aka '\r' in the Classic Mac tradition. The last line is not terminated, but that is nothing to do with the problem. The docs for csv.reader say "If csvfile is a file object, it must be opened with the ‘b’ flag on platforms where that makes a difference." It is widely known that it does make a difference on Windows. However opening the file with 'rb' or 'r' makes no difference in this case -- still the same error message. The docs for csv.Dialect.lineterminator say "The string used to terminate lines produced by the writer. It defaults to '\r\n'. Note: The reader is hard-coded to recognise either '\r' or '\n' as end-of-line, and ignores lineterminator. This behavior may change in the future." It appears to be recognising '\r' as new-line but not as end-of-line/end-of-field. The error message "_csv.Error: new-line character seen in unquoted field - do you need to open the file in universal-newline mode?" is confusing; it's recognised '\r' as a new-line, but it's not treating new-line as an end-of line (and thus implicitly end-of-field). It appears necessary to open the file in 'rU' mode to get it to "work". It's not apparent why the same '\r' recognised in universal-newline mode is any better. A: To get iterate over a reader you'd do: >>> import csv >>> for row in csv.DictReader(open(fname), delimiter='\t'): print(row) {'Name': 'Bob-Smith.local', 'UID': 'bobs'} {'Name': 'Carmen-Jackson.local', 'UID': 'carmenj'} {'Name': 'David-Kathman.local', 'UID': 'davidk'} {'Name': 'Jenn-Roberts.local', 'UID': 'jennr'} But since you want to associate Name with UID: >>> reader = csv.reader(open("masterlist.txt"), delimiter='\t') >>> _ = next(reader) # just discarding header >>> d = dict(reader) >>> d['Carmen-Jackson.local'] 'carmenj' A: I would populate a dictionary like this: >>> import csv >>> name_to_UID = {} >>> for row in csv.DictReader(open(filename, 'rU'), delimiter='\t'): name_to_UID[row['Name']] = row['UID'] >>> name_to_UID['Carmen-Jackson.local'] 'carmenj'
Python help reading csv file failing due to line-endings
I'm trying to create this script that will check the computer host name then search a master list for the value to return a corresponding value in the csv file. Then open another file and do a find an replace. I know this should be easy but haven't done so much in python before. Here is what I have so far... masterlist.txt (tab delimited) Name UID Bob-Smith.local bobs Carmen-Jackson.local carmenj David-Kathman.local davidk Jenn-Roberts.local jennr Here is the script that I have created thus far #GET CLIENT HOST NAME import socket host = socket.gethostname() print host #IMPORT MASTER DATA import csv, sys filename = "masterlist.txt" reader = csv.reader(open(filename, "rU")) #PRINT MASTER DATA for row in reader: print row #SEARCH ON HOSTNAME AND RETURN UID #REPLACE VALUE IN FILE WITH UID #import fileinput #for line in fileinput.FileInput("filetoreplace",inplace=1): # line = line.replace("replacethistext","UID") # print line Right now, it's just set to print the master list. I'm not sure if the list needs to be parsed and placed into a dictionary or what. I really need to figure out how to search the first field for the hostname and then return the field in the second column. Thanks in advance for your help, Aaron UPDATE: I removed line 194 and last line from masterlist.txt and then re-ran the script. The results were the following: Traceback (most recent call last): File "update.py", line 3, in for row in csv.DictReader(open(fname), delimiter='\t'): File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/csv.py", line 103, in next self.fieldnames File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/csv.py", line 90, in fieldnames self._fieldnames = self.reader.next() _csv.Error: new-line character seen in unquoted field - do you need to open the file in universal-newline mode? The current script being used is... import csv fname = "masterlist.txt" for row in csv.DictReader(open(fname), delimiter='\t'): print(row)
[ "The two occurrences of '\\xD5' in line 194 and the last line have nothing to do with the problem.\nThe problem appears to be a bug, or a misleading error message, or incorrect/vague documentation, in the Python 2.6 csv module.\nIn the file, the lines are terminated by '\\x0D' aka '\\r' in the Classic Mac tradition. The last line is not terminated, but that is nothing to do with the problem.\nThe docs for csv.reader say \"If csvfile is a file object, it must be opened with the ‘b’ flag on platforms where that makes a difference.\" It is widely known that it does make a difference on Windows. However opening the file with 'rb' or 'r' makes no difference in this case -- still the same error message.\nThe docs for csv.Dialect.lineterminator say \"The string used to terminate lines produced by the writer. It defaults to '\\r\\n'. Note: The reader is hard-coded to recognise either '\\r' or '\\n' as end-of-line, and ignores lineterminator. This behavior may change in the future.\" It appears to be recognising '\\r' as new-line but not as end-of-line/end-of-field.\nThe error message \"_csv.Error: new-line character seen in unquoted field - do you need to open the file in universal-newline mode?\" is confusing; it's recognised '\\r' as a new-line, but it's not treating new-line as an end-of line (and thus implicitly end-of-field). \nIt appears necessary to open the file in 'rU' mode to get it to \"work\". It's not apparent why the same '\\r' recognised in universal-newline mode is any better.\n", "To get iterate over a reader you'd do:\n>>> import csv\n>>> for row in csv.DictReader(open(fname), delimiter='\\t'):\n print(row)\n\n\n{'Name': 'Bob-Smith.local', 'UID': 'bobs'}\n{'Name': 'Carmen-Jackson.local', 'UID': 'carmenj'}\n{'Name': 'David-Kathman.local', 'UID': 'davidk'}\n{'Name': 'Jenn-Roberts.local', 'UID': 'jennr'}\n\nBut since you want to associate Name with UID:\n>>> reader = csv.reader(open(\"masterlist.txt\"), delimiter='\\t')\n>>> _ = next(reader) # just discarding header\n>>> d = dict(reader)\n>>> d['Carmen-Jackson.local']\n'carmenj'\n\n", "I would populate a dictionary like this:\n>>> import csv\n>>> name_to_UID = {}\n>>> for row in csv.DictReader(open(filename, 'rU'), delimiter='\\t'):\n name_to_UID[row['Name']] = row['UID']\n>>> name_to_UID['Carmen-Jackson.local']\n'carmenj'\n\n" ]
[ 20, 2, 2 ]
[]
[]
[ "csv", "line_endings", "python", "universal" ]
stackoverflow_0002930673_csv_line_endings_python_universal.txt
Q: SQL Alchemy MVC and cross controller joins When using SQL Alchemy for abstracting your data access layer and using controllers as the way to access objects from that abstraction layer, how should joins be handled? So for example, say you have an Orders controller class that manages Order objects such that it provides getOrder, saveOrder, etc methods and likewise a similar controller for User objects. First of all do you even need these controllers? Should you instead just treat SQL Alchemy as "the" thing for handling data access. Why bother with object oriented controller stuff there when you instead have a clean declarative way to obtain and persist objects without having to write SQL directly either. Well one reason could be that perhaps you may want to replace SQL Alchemy with direct SQL or Storm or whatever else. So having controller classes there to act as an intermediate layer helps limit what would need to change then. Anyway - back to the main question - so assuming you have these two controllers, now lets say you want the list of orders for a certain set of users meeting some criteria. How do you go about doing this? Generally you don't want the controllers crossing domains - the Orders controllers knows only about Orders and the User controller just about Users - they don't mess with each other. You also don't want to go fetch all the Users that match and then feed a big list of user ids to the Orders controller to go find the matching Orders. What's needed is a join. Here's where I'm stuck - that seems to mean either the controllers must cross domains or perhaps they should be done away with altogether and you simply do the join via SQL Alchemy directly and get the resulting User and / or Order objects as needed. Thoughts? A: Controllers are meant to encapsulate features for your convienience. Not to bind your hands. If you want to join, simply join. Use the controller that you think is logically fittest to make the query.
SQL Alchemy MVC and cross controller joins
When using SQL Alchemy for abstracting your data access layer and using controllers as the way to access objects from that abstraction layer, how should joins be handled? So for example, say you have an Orders controller class that manages Order objects such that it provides getOrder, saveOrder, etc methods and likewise a similar controller for User objects. First of all do you even need these controllers? Should you instead just treat SQL Alchemy as "the" thing for handling data access. Why bother with object oriented controller stuff there when you instead have a clean declarative way to obtain and persist objects without having to write SQL directly either. Well one reason could be that perhaps you may want to replace SQL Alchemy with direct SQL or Storm or whatever else. So having controller classes there to act as an intermediate layer helps limit what would need to change then. Anyway - back to the main question - so assuming you have these two controllers, now lets say you want the list of orders for a certain set of users meeting some criteria. How do you go about doing this? Generally you don't want the controllers crossing domains - the Orders controllers knows only about Orders and the User controller just about Users - they don't mess with each other. You also don't want to go fetch all the Users that match and then feed a big list of user ids to the Orders controller to go find the matching Orders. What's needed is a join. Here's where I'm stuck - that seems to mean either the controllers must cross domains or perhaps they should be done away with altogether and you simply do the join via SQL Alchemy directly and get the resulting User and / or Order objects as needed. Thoughts?
[ "Controllers are meant to encapsulate features for your convienience. Not to bind your hands. If you want to join, simply join. Use the controller that you think is logically fittest to make the query.\n" ]
[ 2 ]
[]
[]
[ "controllers", "dns", "model_view_controller", "python", "sqlalchemy" ]
stackoverflow_0002933796_controllers_dns_model_view_controller_python_sqlalchemy.txt
Q: how i can open different linux terminal to output differnt kinds of debug information in python? I need output different information to different terminal instances instead of print them in same output stream, say std.err or std.out. for example: I have 5 kinds of information say A-E need to be displayed on different terminal windows on same desktop, looks like [terminal 1] <- for displaying information A [terminal 2] <- for displaying information B [terminal 3] <- for displaying information C [terminal 4] <- for displaying information D [terminal 5] <- for displaying information E I know I can output them into different files, then open terminals read the file in loop, but what I want is python program can open terminal by program itself and print to them directly when it is needed. Is it possible? Thanks! KC [edit] the best solution for this case is using SOCKET as the IPC I think if the resource is not a matter, it will come with best compatible capability - a server client mode. and the pipe / subprocess will also be the useful solutions under same platform A: Open a pipe, then fork off a terminal running cat reading from the read end of the pipe, and write into the write end of the pipe. A: Using the subprocess module, just run several instances of whichever terminal program you like, each running "cat", using subprocess.Popen. Pass stdin=subprocess.PIPE in addition to the terminal command to Popen. Then you can just write to each terminal's stdin attribute. Something along the lines of (untested!): import subprocess p = subprocess.Popen('xterm -e "cat > /dev/null"', stdin=subprocess.PIPE) p.stdin.write("Hello World!")
how i can open different linux terminal to output differnt kinds of debug information in python?
I need output different information to different terminal instances instead of print them in same output stream, say std.err or std.out. for example: I have 5 kinds of information say A-E need to be displayed on different terminal windows on same desktop, looks like [terminal 1] <- for displaying information A [terminal 2] <- for displaying information B [terminal 3] <- for displaying information C [terminal 4] <- for displaying information D [terminal 5] <- for displaying information E I know I can output them into different files, then open terminals read the file in loop, but what I want is python program can open terminal by program itself and print to them directly when it is needed. Is it possible? Thanks! KC [edit] the best solution for this case is using SOCKET as the IPC I think if the resource is not a matter, it will come with best compatible capability - a server client mode. and the pipe / subprocess will also be the useful solutions under same platform
[ "Open a pipe, then fork off a terminal running cat reading from the read end of the pipe, and write into the write end of the pipe.\n", "Using the subprocess module, just run several instances of whichever terminal program you like, each running \"cat\", using subprocess.Popen. Pass stdin=subprocess.PIPE in addition to the terminal command to Popen. Then you can just write to each terminal's stdin attribute.\nSomething along the lines of (untested!):\nimport subprocess\np = subprocess.Popen('xterm -e \"cat > /dev/null\"', stdin=subprocess.PIPE)\np.stdin.write(\"Hello World!\")\n\n" ]
[ 3, 1 ]
[]
[]
[ "python", "stream", "terminal" ]
stackoverflow_0002933601_python_stream_terminal.txt
Q: Python os.path.walk() method I'm currently using the walk method in a uni assignment. It's all working fine, but I was hoping that someone could explain something to me. in the example below, what is the a parameter used for on the myvisit method? >>> from os.path import walk >>> def myvisit(a, dir, files): ... print dir,": %d files"%len(files) >>> walk('/etc', myvisit, None) /etc : 193 files /etc/default : 12 files /etc/cron.d : 6 files /etc/rc.d : 6 files /etc/rc.d/rc0.d : 18 files /etc/rc.d/rc1.d : 27 files /etc/rc.d/rc2.d : 42 files /etc/rc.d/rc3.d : 17 files /etc/rc.d/rcS.d : 13 files A: The first argument to your callback function is the last argument of the os.path.walk function. Its most obvious use is to allow you to keep state between the successive calls to the helper function (in your case, myvisit). os.path.walk is a deprecated function. You really should use os.walk, which has no need for either a callback function or helper arguments (like a in your example). for directory, dirnames, filenames in os.walk(some_path): # run here your code A: It's the argument you gave to walk, None in the example in your question
Python os.path.walk() method
I'm currently using the walk method in a uni assignment. It's all working fine, but I was hoping that someone could explain something to me. in the example below, what is the a parameter used for on the myvisit method? >>> from os.path import walk >>> def myvisit(a, dir, files): ... print dir,": %d files"%len(files) >>> walk('/etc', myvisit, None) /etc : 193 files /etc/default : 12 files /etc/cron.d : 6 files /etc/rc.d : 6 files /etc/rc.d/rc0.d : 18 files /etc/rc.d/rc1.d : 27 files /etc/rc.d/rc2.d : 42 files /etc/rc.d/rc3.d : 17 files /etc/rc.d/rcS.d : 13 files
[ "The first argument to your callback function is the last argument of the os.path.walk function. Its most obvious use is to allow you to keep state between the successive calls to the helper function (in your case, myvisit).\nos.path.walk is a deprecated function. You really should use os.walk, which has no need for either a callback function or helper arguments (like a in your example).\nfor directory, dirnames, filenames in os.walk(some_path):\n # run here your code\n\n", "It's the argument you gave to walk, None in the example in your question\n" ]
[ 29, 11 ]
[]
[]
[ "python" ]
stackoverflow_0002934281_python.txt
Q: Is there any way to do this without using '__init__'? class a(object): c=b()# how to call the b method d=4 def __init__(self): print self.c def b(self): return self.d+1 a() how to call the 'b' method not in the __init__ thanks the error is : Traceback (most recent call last): File "D:\zjm_code\a.py", line 12, in <module> class a(object): File "D:\zjm_code\a.py", line 13, in a c=b()# how to call the b method NameError: name 'b' is not defined A: I would use a property instead: class a(object): d=4 def __init__(self): print self.c def b(self): return self.d+1 c = property(b) a() a.c # returns a.b() A: If you want a().c to always return a().d + 1, then use property as suggested by Olivier. However, if you want a and it's derived classes to have a class attribute that's value is dynamically set to +1 of the declared (or inherited) value of c in the class, then you can use a metaclass. def meta(name, bases, class_locals): class_locals['c'] = class_locals.get('d', 0) + 1 return type.__new__(name, bases, class_locals) class A(object): __metaclass__ = meta d = 4 def __init__(self): print self.c class B(A): d = 5 >>> A() 5 >>> B() 6 >>> print A.c 5 >>> print B.c 6 A: You have defined b as in instance method (a "regular" method). Such methods can only be called on an instance of the class. In your code you attempt to call the "b" method inside the class definition. Inside a class definition you can only call static-methods and class-methods of that class, but not instance-methods. I recommend reading about the classmethod and staticmethod decorators. An example, to give you a push in the right direction: class A(object): d = 42 c = b() @classmethod def b(klass): # "class" is a Python keyword so we can't use it here return klass.d + 1 A: You can't do that directly. Firstly as Francesco says you cannot call the method b without an instance to call it on. You can change the method into a classmethod but that needs an instance of the class, which doesn't exist until you reach the end of the class definition. I think the closest you can get is to make b a classmethod and initialise c after the class has been definined: class a(object): d = 4 def __init__(self): print self.c @classmethod def b(cls): return cls.d+1 a.c = a.b()
Is there any way to do this without using '__init__'?
class a(object): c=b()# how to call the b method d=4 def __init__(self): print self.c def b(self): return self.d+1 a() how to call the 'b' method not in the __init__ thanks the error is : Traceback (most recent call last): File "D:\zjm_code\a.py", line 12, in <module> class a(object): File "D:\zjm_code\a.py", line 13, in a c=b()# how to call the b method NameError: name 'b' is not defined
[ "I would use a property instead:\nclass a(object):\n d=4\n def __init__(self):\n print self.c\n def b(self):\n return self.d+1\n c = property(b)\n\na()\na.c # returns a.b()\n\n", "If you want a().c to always return a().d + 1, then use property as suggested by Olivier. However, if you want a and it's derived classes to have a class attribute that's value is dynamically set to +1 of the declared (or inherited) value of c in the class, then you can use a metaclass.\ndef meta(name, bases, class_locals):\n class_locals['c'] = class_locals.get('d', 0) + 1\n return type.__new__(name, bases, class_locals)\n\nclass A(object):\n __metaclass__ = meta\n d = 4\n\n def __init__(self):\n print self.c\n\nclass B(A):\n d = 5\n\n\n>>> A()\n5\n>>> B()\n6\n>>> print A.c\n5\n>>> print B.c\n6\n\n", "You have defined b as in instance method (a \"regular\" method). Such methods can only be called on an instance of the class.\nIn your code you attempt to call the \"b\" method inside the class definition. Inside a class definition you can only call static-methods and class-methods of that class, but not instance-methods. I recommend reading about the classmethod and staticmethod decorators.\nAn example, to give you a push in the right direction:\nclass A(object):\n d = 42\n c = b()\n\n @classmethod\n def b(klass): # \"class\" is a Python keyword so we can't use it here\n return klass.d + 1\n\n", "You can't do that directly. Firstly as Francesco says you cannot call the method b without an instance to call it on. You can change the method into a classmethod but that needs an instance of the class, which doesn't exist until you reach the end of the class definition. \nI think the closest you can get is to make b a classmethod and initialise c after the class has been definined:\nclass a(object):\n d = 4\n def __init__(self):\n print self.c\n\n @classmethod\n def b(cls):\n return cls.d+1\n\na.c = a.b()\n\n" ]
[ 4, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002934363_python.txt
Q: Steps in list question, Python beginner The following code include the last number. >>> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> numbers[::3] [1, 4, 7, 10] Why does not includet the last number 2, like 10, 8, 6, 4, 2? >>> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> numbers[:1:-2] [10, 8, 6, 4] A: It seems that the slice operator is simply non-inclusive of the second argument. In other-words, your 1 should be a 0: >>> numbers = [1,2,3,4,5,6,7,8,9,10] >>> numbers[:1:-2] [10, 8, 6, 4] >>> numbers[:0:-2] [10, 8, 6, 4, 2] Hope that helps :) For further info, see Note 5 here. A: :: is walking over the list with N steps. So it's 1, then it goes to 4, etc. If you want to step with 2 backwards, you want [::-2] A: Python is pretty consistent in following the pattern of sequence ranges being lower inclusive, upper exclusive. That is, if you say range(1,5) --> [1,2,3,4]. The lower index is included and the upper is excluded. This helps a lot with various kinds of off-by-one and fencepost errors. See wikipedia for a brief explanation of these kinds of problems. A: Because the slice excludes the second number from the range. a[1:4] fetches elements 1, 2 and 3. Likewise, a[10:6:-1] fetches elements 10, 9, 8 and 7, but not 6.
Steps in list question, Python beginner
The following code include the last number. >>> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> numbers[::3] [1, 4, 7, 10] Why does not includet the last number 2, like 10, 8, 6, 4, 2? >>> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> numbers[:1:-2] [10, 8, 6, 4]
[ "It seems that the slice operator is simply non-inclusive of the second argument. In other-words, your 1 should be a 0:\n>>> numbers = [1,2,3,4,5,6,7,8,9,10]\n>>> numbers[:1:-2]\n[10, 8, 6, 4]\n>>> numbers[:0:-2]\n[10, 8, 6, 4, 2]\n\nHope that helps :)\nFor further info, see Note 5 here.\n", ":: is walking over the list with N steps. So it's 1, then it goes to 4, etc. If you want to step with 2 backwards, you want [::-2]\n", "Python is pretty consistent in following the pattern of sequence ranges being lower inclusive, upper exclusive. That is, if you say range(1,5) --> [1,2,3,4]. The lower index is included and the upper is excluded. This helps a lot with various kinds of off-by-one and fencepost errors. See wikipedia for a brief explanation of these kinds of problems.\n", "Because the slice excludes the second number from the range. a[1:4] fetches elements 1, 2 and 3. Likewise, a[10:6:-1] fetches elements 10, 9, 8 and 7, but not 6.\n" ]
[ 4, 2, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002934819_python.txt
Q: Wxpython cut copy paste and openfiledialog i have a web browser made in python with menu. in one menu i have cut copy paste but no functionality and i need to make them work. i need an example of class oncopy.(event menu) Open file i manage to work like this .takes file and print on screen the link to that file but how can make open dialog to open a file at least one type of file? A: if filepath is the absolute pathname of the file you got from the opendialog, try: import os os.startfile(filepath) This will open your file with its corresponding windows application to which its extension is associated (like clicking twice in the file icon) To copy a selected text in the HTML window, if you used: import wx.lib.iewin as iewin then in your Frame or Panel subclass you create your instance of the browser object in the __init__() method with: self.ie = iewin.IEHtmlWindow(self, -1, style =wx.NO_FULL_REPAINT_ON_RESIZE) and bind the copy button onclick event with an 'on_copy' method. Finally, you define the on_copy(self, event) method that should be triggered when you click the 'copy' button: def on_copy(self, event): self.selection = self.ie.GetStringSelection(asHTML=False)
Wxpython cut copy paste and openfiledialog
i have a web browser made in python with menu. in one menu i have cut copy paste but no functionality and i need to make them work. i need an example of class oncopy.(event menu) Open file i manage to work like this .takes file and print on screen the link to that file but how can make open dialog to open a file at least one type of file?
[ "if filepath is the absolute pathname of the file you got from the opendialog, try:\nimport os\nos.startfile(filepath)\n\nThis will open your file with its corresponding windows application to which its extension is associated (like clicking twice in the file icon)\nTo copy a selected text in the HTML window, if you used:\nimport wx.lib.iewin as iewin\n\nthen in your Frame or Panel subclass you create your instance of the browser object in the __init__() method with: \nself.ie = iewin.IEHtmlWindow(self, -1, style =wx.NO_FULL_REPAINT_ON_RESIZE)\n\nand bind the copy button onclick event with an 'on_copy' method.\nFinally, you define the on_copy(self, event) method that should be triggered when you click the 'copy' button:\ndef on_copy(self, event):\n self.selection = self.ie.GetStringSelection(asHTML=False)\n\n" ]
[ 0 ]
[]
[]
[ "dialog", "events", "openfiledialog", "python", "wxpython" ]
stackoverflow_0002934892_dialog_events_openfiledialog_python_wxpython.txt
Q: Change array that might contain None to an array that contains "" in python I have a python function that gets an array called row. Typically row contains things like: ["Hello","goodbye","green"] And I print it with: print "\t".join(row) Unfortunately, sometimes it contains: ["Hello",None,"green"] Which generates this error: TypeError: sequence item 2: expected string or Unicode, NoneType found Is there an easy way to replace any None elements with ""? A: You can use a conditional expression: >>> l = ["Hello", None, "green"] >>> [(x if x is not None else '') for x in l] ['Hello', '', 'green'] A slightly shorter way is: >>> [x or '' for x in l] But note that the second method also changes 0 and some other objects to the empty string. A: You can use a generator expression in place of the array: print "\t".join(fld or "" for fld in row) This will substitute the empty string for everything considered as False (None, False, 0, 0.0, ''…). A: You can also use the built-in filter function: >>> l = ["Hello", None, "green"] >>> filter(None, l) ['Hello', 'green']
Change array that might contain None to an array that contains "" in python
I have a python function that gets an array called row. Typically row contains things like: ["Hello","goodbye","green"] And I print it with: print "\t".join(row) Unfortunately, sometimes it contains: ["Hello",None,"green"] Which generates this error: TypeError: sequence item 2: expected string or Unicode, NoneType found Is there an easy way to replace any None elements with ""?
[ "You can use a conditional expression:\n>>> l = [\"Hello\", None, \"green\"]\n>>> [(x if x is not None else '') for x in l]\n['Hello', '', 'green']\n\nA slightly shorter way is:\n>>> [x or '' for x in l]\n\nBut note that the second method also changes 0 and some other objects to the empty string.\n", "You can use a generator expression in place of the array:\nprint \"\\t\".join(fld or \"\" for fld in row)\n\nThis will substitute the empty string for everything considered as False (None, False, 0, 0.0, ''…).\n", "You can also use the built-in filter function:\n>>> l = [\"Hello\", None, \"green\"]\n>>> filter(None, l)\n['Hello', 'green']\n\n" ]
[ 11, 1, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0002932304_python_string.txt
Q: What is the cleanest way to do a sort plus uniq on a Python list? Consider a Python list my_list containing ['foo', 'foo', 'bar']. What is the most Pythonic way to uniquify and sort a list ? (think cat my_list | sort | uniq) This is how I currently do it and while it works I'm sure there are better ways to do it. my_list = [] ... my_list.append("foo") my_list.append("foo") my_list.append("bar") ... my_list = set(my_list) my_list = list(my_list) my_list.sort() A: my_list = sorted(set(my_list)) A: # Python ≥ 2.4 # because of (generator expression) and itertools.groupby, sorted import itertools def sort_uniq(sequence): return (x[0] for x in itertools.groupby(sorted(sequence))) Faster: import itertools, operator import sys if sys.hexversion < 0x03000000: mapper= itertools.imap # 2.4 ≤ Python < 3 else: mapper= map # Python ≥ 3 def sort_uniq(sequence): return mapper( operator.itemgetter(0), itertools.groupby(sorted(sequence))) Both versions return an generator, so you might want to supply the result to the list type: sequence= list(sort_uniq(sequence)) Note that this will work with non-hashable items too: >>> list(sort_uniq([[0],[1],[0]])) [[0], [1]] A: The straightforward solution is provided by Ignacio—sorted(set(foo)). If you have unique data, there's a reasonable chance you don't just want to do sorted(set(...)) but rather to store a set all the time and occasionally pull out a sorted version of the values. (At that point, it starts sounding like the sort of thing people often use a database for, too.) If you have a sorted list and you want to check membership on logarithmic and add an item in worst case linear time, you can use the bisect module. If you want to keep this condition all the time and you want to simplify things or make some operations perform better, you might consider blist.sortedset. A: Others have mentioned sorted(set(my_list)), which works for hashable values such as strings, numbers and tuples, but not for unhashable types such as lists. To get a sorted list of values of any sortable type, without duplicates: from itertools import izip, islice def unique_sorted(values): "Return a sorted list of the given values, without duplicates." values = sorted(values) if not values: return [] consecutive_pairs = izip(values, islice(values, 1, len(values))) result = [a for (a, b) in consecutive_pairs if a != b] result.append(values[-1]) return result This can be further simplified using the "pairwise" or "unique_justseen" recipes from the itertools documentation.
What is the cleanest way to do a sort plus uniq on a Python list?
Consider a Python list my_list containing ['foo', 'foo', 'bar']. What is the most Pythonic way to uniquify and sort a list ? (think cat my_list | sort | uniq) This is how I currently do it and while it works I'm sure there are better ways to do it. my_list = [] ... my_list.append("foo") my_list.append("foo") my_list.append("bar") ... my_list = set(my_list) my_list = list(my_list) my_list.sort()
[ "my_list = sorted(set(my_list))\n\n", "# Python ≥ 2.4\n# because of (generator expression) and itertools.groupby, sorted\n\nimport itertools\n\ndef sort_uniq(sequence):\n return (x[0] for x in itertools.groupby(sorted(sequence)))\n\nFaster:\nimport itertools, operator\nimport sys\n\nif sys.hexversion < 0x03000000:\n mapper= itertools.imap # 2.4 ≤ Python < 3\nelse:\n mapper= map # Python ≥ 3\n\ndef sort_uniq(sequence):\n return mapper(\n operator.itemgetter(0),\n itertools.groupby(sorted(sequence)))\n\nBoth versions return an generator, so you might want to supply the result to the list type:\nsequence= list(sort_uniq(sequence))\n\nNote that this will work with non-hashable items too:\n>>> list(sort_uniq([[0],[1],[0]]))\n[[0], [1]]\n\n", "The straightforward solution is provided by Ignacio—sorted(set(foo)).\nIf you have unique data, there's a reasonable chance you don't just want to do sorted(set(...)) but rather to store a set all the time and occasionally pull out a sorted version of the values. (At that point, it starts sounding like the sort of thing people often use a database for, too.)\nIf you have a sorted list and you want to check membership on logarithmic and add an item in worst case linear time, you can use the bisect module.\nIf you want to keep this condition all the time and you want to simplify things or make some operations perform better, you might consider blist.sortedset.\n", "Others have mentioned sorted(set(my_list)), which works for hashable values such as strings, numbers and tuples, but not for unhashable types such as lists.\nTo get a sorted list of values of any sortable type, without duplicates:\nfrom itertools import izip, islice\ndef unique_sorted(values):\n \"Return a sorted list of the given values, without duplicates.\"\n values = sorted(values)\n if not values:\n return []\n consecutive_pairs = izip(values, islice(values, 1, len(values)))\n result = [a for (a, b) in consecutive_pairs if a != b]\n result.append(values[-1])\n return result\n\nThis can be further simplified using the \"pairwise\" or \"unique_justseen\" recipes from the itertools documentation.\n" ]
[ 132, 20, 6, 2 ]
[ "Can't say it is clean way to do that, but just for fun:\nmy_list = [x for x in sorted(my_list) if not x in locals()[\"_[1]\"]]\n\n" ]
[ -4 ]
[ "python", "unique" ]
stackoverflow_0002931672_python_unique.txt
Q: Partially flattening a list This is probably a really silly question but, given the example code at the bottom, how would I get a single list that retain the tuples? (I've looked at itertools but it flattens everything.) What I currently get is: ('id', 20, 'integer') ('companyname', 50, 'text') [('focus', 30, 'text'), ('fiesta', 30, 'text'), ('mondeo', 30, 'text'), ('puma', 30, 'text')] ('contact', 50, 'text') ('email', 50, 'text') Instead, I need a single level list: ('id', 20, 'integer') ('companyname', 50, 'text') ('focus', 30, 'text') ('fiesta', 30, 'text') ('mondeo', 30, 'text') ('puma', 30, 'text') ('contact', 50, 'text') ('email', 50, 'text') Code: def getproducts(): temp_list = [] product_list = ['focus', 'fiesta', 'mondeo', 'puma'] # usually this would come from a db for p in product_list: temp_list.append((p, 30, 'text')) return temp_list def createlist(): column_title_list = ( ("id", 20, "integer"), ("companyname", 50, "text"), getproducts(), ("contact", 50, "text"), ("email", 50, "text"), ) return column_title_list for item in createlist(): print item A: Can you make it into [[("id",20,"integer")], [("companyname",50,"text")], getproducts(), ...] ? If so, you just need to concatenate the lists. return sum(column_title_list, []) You could also use return [("id",20,"integer"),("companyname",50,"text")] + getproducts() + ... A: This probably isn't the answer you're looking for, but why waste time trying to find a fancy way to solve this when a straight-forward solution lets you move on and solve more interesting parts of your program? def createlist(): tmp = [] tmp.extend([("id",20,"integer"), ("companyname",50,"text")]) tmp.extend(getproducts()) tmp.extend([("contact",50,"text"), ("email",50,"text")]) return tuple(tmp) A: def createlist(): column_title_list = [ ("id",20,"integer"), ("companyname",50,"text") ] column_title_list.extend(getproducts()) column_title_list.extend( [ ("contact",50,"text"), ("email",50,"text") ] ) return column_title_list A: Try working with a list instead of a tuple. You can turn a list into a tuple, when you finished assembling it. #!/usr/bin/env python def getproducts(): temp_list=[] # usually this would come from a db product_list=['focus','fiesta','mondeo','puma'] for p in product_list: temp_list.append((p, 30, 'text')) return temp_list def createlist(): column_title_list = [ ("id", 20, "integer"), ("companyname", 50, "text") ] column_title_list += getproducts() column_title_list += [ ("contact", 50, "text"), ("email", 50, "text"), ] return tuple(column_title_list) for item in createlist(): print item This will result in: # ('id', 20, 'integer') # ('companyname', 50, 'text') # ('focus', 30, 'text') # ('fiesta', 30, 'text') # ('mondeo', 30, 'text') # ('puma', 30, 'text') # ('contact', 50, 'text') # ('email', 50, 'text')
Partially flattening a list
This is probably a really silly question but, given the example code at the bottom, how would I get a single list that retain the tuples? (I've looked at itertools but it flattens everything.) What I currently get is: ('id', 20, 'integer') ('companyname', 50, 'text') [('focus', 30, 'text'), ('fiesta', 30, 'text'), ('mondeo', 30, 'text'), ('puma', 30, 'text')] ('contact', 50, 'text') ('email', 50, 'text') Instead, I need a single level list: ('id', 20, 'integer') ('companyname', 50, 'text') ('focus', 30, 'text') ('fiesta', 30, 'text') ('mondeo', 30, 'text') ('puma', 30, 'text') ('contact', 50, 'text') ('email', 50, 'text') Code: def getproducts(): temp_list = [] product_list = ['focus', 'fiesta', 'mondeo', 'puma'] # usually this would come from a db for p in product_list: temp_list.append((p, 30, 'text')) return temp_list def createlist(): column_title_list = ( ("id", 20, "integer"), ("companyname", 50, "text"), getproducts(), ("contact", 50, "text"), ("email", 50, "text"), ) return column_title_list for item in createlist(): print item
[ "Can you make it into\n[[(\"id\",20,\"integer\")],\n [(\"companyname\",50,\"text\")],\n getproducts(),\n ...]\n\n? If so, you just need to concatenate the lists.\nreturn sum(column_title_list, [])\n\nYou could also use\nreturn [(\"id\",20,\"integer\"),(\"companyname\",50,\"text\")] + getproducts() + ...\n\n", "This probably isn't the answer you're looking for, but why waste time trying to find a fancy way to solve this when a straight-forward solution lets you move on and solve more interesting parts of your program?\ndef createlist(): \n tmp = [] \n tmp.extend([(\"id\",20,\"integer\"), (\"companyname\",50,\"text\")])\n tmp.extend(getproducts())\n tmp.extend([(\"contact\",50,\"text\"), (\"email\",50,\"text\")])\n return tuple(tmp)\n\n", "def createlist(): \n column_title_list = [ (\"id\",20,\"integer\"),\n (\"companyname\",50,\"text\") ]\n column_title_list.extend(getproducts())\n column_title_list.extend( [ (\"contact\",50,\"text\"),\n (\"email\",50,\"text\") ] )\n\n return column_title_list\n\n", "Try working with a list instead of a tuple. You can turn a list into a tuple, when you finished assembling it.\n#!/usr/bin/env python\n\ndef getproducts():\n temp_list=[]\n # usually this would come from a db\n product_list=['focus','fiesta','mondeo','puma'] \n for p in product_list:\n temp_list.append((p, 30, 'text'))\n return temp_list\n\ndef createlist(): \n column_title_list = [\n (\"id\", 20, \"integer\"),\n (\"companyname\", 50, \"text\")\n ]\n column_title_list += getproducts()\n column_title_list += [\n (\"contact\", 50, \"text\"),\n (\"email\", 50, \"text\"),\n ]\n\n return tuple(column_title_list)\n\nfor item in createlist():\n print item\n\nThis will result in:\n# ('id', 20, 'integer')\n# ('companyname', 50, 'text')\n# ('focus', 30, 'text')\n# ('fiesta', 30, 'text')\n# ('mondeo', 30, 'text')\n# ('puma', 30, 'text')\n# ('contact', 50, 'text')\n# ('email', 50, 'text')\n\n" ]
[ 2, 2, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002935291_python.txt
Q: Why does Python's 'for ... in' work differently on a list of values vs. a list of dictionaries? I'm wondering about some details of how for ... in works in Python. My understanding is for var in iterable on each iteration creates a variable, var, bound to the current value of iterable. So, if you do for c in cows; c = cows[whatever], but changing c within the loop does not affect the original value. However, it seems to work differently if you're assigning a value to a dictionary key. cows=[0,1,2,3,4,5] for c in cows: c+=2 #cows is now the same - [0,1,2,3,4,5] cows=[{'cow':0},{'cow':1},{'cow':2},{'cow':3},{'cow':4},{'cow':5}] for c in cows: c['cow']+=2 # cows is now [{'cow': 2}, {'cow': 3}, {'cow': 4}, {'cow': 5}, {'cow': 6}, {'cow': 7} #so, it's changed the original, unlike the previous example I see one can use enumerate to make the first example work, too, but that's a different story, I guess. cows=[0,1,2,3,4,5] for i,c in enumerate(cows): cows[i]+=1 # cows is now [1, 2, 3, 4, 5, 6] Why does it affect the original list values in the second example but not the first? [edit] Thanks for the answers. I was looking at this from a PHP point of view, where you can use the & symbol in foreach to specify whether you are operating on a reference to or a copy of the iterable. I see now that the real difference is a basic detail of how python works regarding immutable objects. A: It helps to picture what happens to the reference held by c in each iteration: [ 0, 1, 2, 3, 4, 5 ] ^ | c c holds a reference pointing to the first element in the list. When you do c += 2 (i.e., c = c + 2, the temporary variable c is reassigned a new value. This new value is 2, and c is rebound to this new value. The original list is left alone. [ 0, 1, 2, 3, 4, 5 ] c -> 2 Now, in the dictionary case, here's what c is bound to during the first iteration: [ {'cow':0}, {'cow':1}, {'cow':2}, {'cow':3}, {'cow':4}, {'cow':5} ] ^ | c Here, c points to the dictionary object {'cow':0}. When you do c['cow'] += 2 (i.e., c['cow'] = c['cow'] + 2), the dictionary object itself is changed, as c is not rebound to an unrelated object. That is, c still points to that first dictionary object. [ {'cow':2}, {'cow':1}, {'cow':2}, {'cow':3}, {'cow':4}, {'cow':5} ] ^ | c A: It's not actually acting differently. Changing a variable is not the same as changing the attribute of a variable. You'll see the same thing in the following example: a = 1 b = a b = 2 Here a is still 1. b was assigned a different value and is no longer the same as a a = {"hello": 1} b = a b["hello"] = 2 Here a["hello] returns 2 instead of 1. b is still the same value because we didn't assign anything to b, and thus b is the same as a. We changed the property ["hello"] of b to 2 and since a and b are the same variable a["hello"] is also 2 A: c is a temporary, disposable variable in both cases. (Keep in mind that in Python, all variables are merely references, bound to the objects they represent and capable of being rebound to different objects. Python is more consistent than certain other languages in this respect.) In your list example, each iteration rebinds c from one integer to another one, leaving the original list unchanged. In your dict example, each iteration accesses the dict to which c is temporarily bound, rebinding one of that dict's members to a different integer. In both cases, c is ignored at the end of the loop, but since you've changed a data structure other than c in the second case, you notice the changes when the loop is done. A: It's nothing to do with for ... in .... Change your code from for c in cows: to c = cows[3] (and dedent the next line) in each example and see the effect. In your first example, the list elements are int objects; they are immutable. In the second example, they are dict objects, which are mutable. A: Doing a name assignment as you have in the first loop only rebinds the name. Doing an item assigment as you have in the second loop modifies the existing object. A: In the second example, you have a list of dictionary objects. c references the dictionary object which is modified inside the loop scope. A: Regardless of looping, you have to note that: some_var = some_object binds the name some_var to the object some_object. The previous object (if any) referenced by some_var is unbound. some_var[some_index] = some_object does not bind/unbind some_var; it is just syntactic sugar for the following: some_var.__setitem__(some_index, some_object) Obviously, some_var still points to the same indexable (a sequence or a mapping) object as before, which has just been modified.
Why does Python's 'for ... in' work differently on a list of values vs. a list of dictionaries?
I'm wondering about some details of how for ... in works in Python. My understanding is for var in iterable on each iteration creates a variable, var, bound to the current value of iterable. So, if you do for c in cows; c = cows[whatever], but changing c within the loop does not affect the original value. However, it seems to work differently if you're assigning a value to a dictionary key. cows=[0,1,2,3,4,5] for c in cows: c+=2 #cows is now the same - [0,1,2,3,4,5] cows=[{'cow':0},{'cow':1},{'cow':2},{'cow':3},{'cow':4},{'cow':5}] for c in cows: c['cow']+=2 # cows is now [{'cow': 2}, {'cow': 3}, {'cow': 4}, {'cow': 5}, {'cow': 6}, {'cow': 7} #so, it's changed the original, unlike the previous example I see one can use enumerate to make the first example work, too, but that's a different story, I guess. cows=[0,1,2,3,4,5] for i,c in enumerate(cows): cows[i]+=1 # cows is now [1, 2, 3, 4, 5, 6] Why does it affect the original list values in the second example but not the first? [edit] Thanks for the answers. I was looking at this from a PHP point of view, where you can use the & symbol in foreach to specify whether you are operating on a reference to or a copy of the iterable. I see now that the real difference is a basic detail of how python works regarding immutable objects.
[ "It helps to picture what happens to the reference held by c in each iteration:\n[ 0, 1, 2, 3, 4, 5 ]\n ^\n |\n c\n\nc holds a reference pointing to the first element in the list. When you do c += 2 (i.e., c = c + 2, the temporary variable c is reassigned a new value. This new value is 2, and c is rebound to this new value. The original list is left alone.\n[ 0, 1, 2, 3, 4, 5 ]\n\n c -> 2\n\nNow, in the dictionary case, here's what c is bound to during the first iteration:\n[ {'cow':0}, {'cow':1}, {'cow':2}, {'cow':3}, {'cow':4}, {'cow':5} ]\n ^\n |\n c\n\nHere, c points to the dictionary object {'cow':0}. When you do c['cow'] += 2 (i.e., c['cow'] = c['cow'] + 2), the dictionary object itself is changed, as c is not rebound to an unrelated object. That is, c still points to that first dictionary object.\n[ {'cow':2}, {'cow':1}, {'cow':2}, {'cow':3}, {'cow':4}, {'cow':5} ]\n ^\n |\n c\n\n", "It's not actually acting differently. Changing a variable is not the same as changing the attribute of a variable. You'll see the same thing in the following example:\na = 1\nb = a\nb = 2 \n\nHere a is still 1. b was assigned a different value and is no longer the same as a\na = {\"hello\": 1}\nb = a\nb[\"hello\"] = 2 \n\nHere a[\"hello] returns 2 instead of 1. b is still the same value because we didn't assign anything to b, and thus b is the same as a. We changed the property [\"hello\"] of b to 2 and since a and b are the same variable a[\"hello\"] is also 2\n", "c is a temporary, disposable variable in both cases. (Keep in mind that in Python, all variables are merely references, bound to the objects they represent and capable of being rebound to different objects. Python is more consistent than certain other languages in this respect.)\nIn your list example, each iteration rebinds c from one integer to another one, leaving the original list unchanged.\nIn your dict example, each iteration accesses the dict to which c is temporarily bound, rebinding one of that dict's members to a different integer.\nIn both cases, c is ignored at the end of the loop, but since you've changed a data structure other than c in the second case, you notice the changes when the loop is done.\n", "It's nothing to do with for ... in .... Change your code from for c in cows: to c = cows[3] (and dedent the next line) in each example and see the effect.\nIn your first example, the list elements are int objects; they are immutable. In the second example, they are dict objects, which are mutable.\n", "Doing a name assignment as you have in the first loop only rebinds the name. Doing an item assigment as you have in the second loop modifies the existing object.\n", "In the second example, you have a list of dictionary objects. c references the dictionary object which is modified inside the loop scope.\n", "Regardless of looping, you have to note that:\nsome_var = some_object\n\nbinds the name some_var to the object some_object. The previous object (if any) referenced by some_var is unbound.\nsome_var[some_index] = some_object\n\ndoes not bind/unbind some_var; it is just syntactic sugar for the following:\nsome_var.__setitem__(some_index, some_object)\n\nObviously, some_var still points to the same indexable (a sequence or a mapping) object as before, which has just been modified.\n" ]
[ 17, 5, 4, 4, 3, 1, 1 ]
[]
[]
[ "iteration", "python" ]
stackoverflow_0002926580_iteration_python.txt
Q: Are there any Python reference counting/garbage collection gotchas when dealing with C code? Just for the sheer heck of it, I've decided to create a Scheme binding to libpython so you can embed Python in Scheme programs. I'm already able to call into Python's C API, but I haven't really thought about memory management. The way mzscheme's FFI works is that I can call a function, and if that function returns a pointer to a PyObject, then I can have it automatically increment the reference count. Then, I can register a finalizer that will decrement the reference count when the Scheme object gets garbage collected. I've looked at the documentation for reference counting, and don't see any problems with this at first glance (although it may be sub-optimal in some cases). Are there any gotchas I'm missing? Also, I'm having trouble making heads or tails of the cyclic garbage collector documentation. What things will I need to bear in mind here? In particular, how do I make Python aware that I have a reference to something so it doesn't collect it while I'm still using it? A: Your link to http://docs.python.org/extending/extending.html#reference-counts is the right place. The Extending and Embedding and Python/C API sections of the documentation are the ones that will explain how to use the C API. Reference counting is one of the annoying parts of using the C API. The main gotcha is keeping everything straight: Depending on the API function you call, you may or may not own the reference to the object you get. Be careful to understand whether you own it (and thus cannot forget to DECREF it or give it to something that will steal it) or are borrowing it (and must INCREF it to keep it and possibly to use it during your function). The most common bugs involving this are 1) remembering incorrectly whether you own a reference returned by a particular function and 2) believing you're safe to borrow a reference for a longer time than you are. You do not have to do anything special for the cyclic garbage collector. It's just there to patch up a flaw in reference counting and doesn't require direct access. A: The biggest gotcha I know with ref counting and the C API is the __del__ thing. When you have a borrowed reference to something, you think you can get away without INCREF'ing because you don't give up the GIL while you use that reference. But, if you end up deleting an object (by, for example, removing it from a list), it's possible that you trigger a __del__ call, which might remove the reference you're borrowing from under your feet. Very tricky. If you INCREF (and then DECREF, of course) all borrowed references as soon as you get them, there shouldn't be any problem.
Are there any Python reference counting/garbage collection gotchas when dealing with C code?
Just for the sheer heck of it, I've decided to create a Scheme binding to libpython so you can embed Python in Scheme programs. I'm already able to call into Python's C API, but I haven't really thought about memory management. The way mzscheme's FFI works is that I can call a function, and if that function returns a pointer to a PyObject, then I can have it automatically increment the reference count. Then, I can register a finalizer that will decrement the reference count when the Scheme object gets garbage collected. I've looked at the documentation for reference counting, and don't see any problems with this at first glance (although it may be sub-optimal in some cases). Are there any gotchas I'm missing? Also, I'm having trouble making heads or tails of the cyclic garbage collector documentation. What things will I need to bear in mind here? In particular, how do I make Python aware that I have a reference to something so it doesn't collect it while I'm still using it?
[ "Your link to http://docs.python.org/extending/extending.html#reference-counts is the right place. The Extending and Embedding and Python/C API sections of the documentation are the ones that will explain how to use the C API.\nReference counting is one of the annoying parts of using the C API. The main gotcha is keeping everything straight: Depending on the API function you call, you may or may not own the reference to the object you get. Be careful to understand whether you own it (and thus cannot forget to DECREF it or give it to something that will steal it) or are borrowing it (and must INCREF it to keep it and possibly to use it during your function). The most common bugs involving this are 1) remembering incorrectly whether you own a reference returned by a particular function and 2) believing you're safe to borrow a reference for a longer time than you are. \nYou do not have to do anything special for the cyclic garbage collector. It's just there to patch up a flaw in reference counting and doesn't require direct access.\n", "The biggest gotcha I know with ref counting and the C API is the __del__ thing. When you have a borrowed reference to something, you think you can get away without INCREF'ing because you don't give up the GIL while you use that reference. But, if you end up deleting an object (by, for example, removing it from a list), it's possible that you trigger a __del__ call, which might remove the reference you're borrowing from under your feet. Very tricky.\nIf you INCREF (and then DECREF, of course) all borrowed references as soon as you get them, there shouldn't be any problem.\n" ]
[ 8, 3 ]
[]
[]
[ "garbage_collection", "python", "python_c_api", "reference_counting", "scheme" ]
stackoverflow_0002935186_garbage_collection_python_python_c_api_reference_counting_scheme.txt
Q: efficiently convert string (or tuple) to ctypes array I've got code that takes a PIL image and converts it to a ctypes array to pass out to a C function: w_px, h_px = img.size pixels = struct.unpack('%dI'%(w_px*h_px), img.convert('RGBA').tostring()) pixels_array = (ctypes.c_int * len(pixels))(*pixels) But I'm dealing with big images, and unpacking that many items into function arguments seems to be noticeably slow. What's the simplest thing I can do to get a reasonable speedup? I'm only converting to a tuple as an intermediate step, so if it's unnecessary, all the better. A: You can first build an uninitialized array: pixarray = (ctypes.c_int * (w_px * h_px))() and then copy the image's contents into it: # dylib in MacOSX, cdll.wincrt in Win, libc.so.? in Unix, ... clib = ctypes.CDLL('libc.dylib') _ = clib.memcpy(pixarray, im.tostring(), w_px * h_px * 4) The return value of memcpy is an address you don't care about, so I "swallowed" it by assigning it to name "single underscore" (which by convention means "I don't care about this one";-). Edit: as @Mu Mind points out in a comment, the latter fragment can usefully be simplified to use ctypes.memmove without the need to go platform-dependent to ferret out clib: just do _ = ctypes.memmove(pixarray, im.tostring(), w_px * h_px * 4)
efficiently convert string (or tuple) to ctypes array
I've got code that takes a PIL image and converts it to a ctypes array to pass out to a C function: w_px, h_px = img.size pixels = struct.unpack('%dI'%(w_px*h_px), img.convert('RGBA').tostring()) pixels_array = (ctypes.c_int * len(pixels))(*pixels) But I'm dealing with big images, and unpacking that many items into function arguments seems to be noticeably slow. What's the simplest thing I can do to get a reasonable speedup? I'm only converting to a tuple as an intermediate step, so if it's unnecessary, all the better.
[ "You can first build an uninitialized array:\npixarray = (ctypes.c_int * (w_px * h_px))()\n\nand then copy the image's contents into it:\n# dylib in MacOSX, cdll.wincrt in Win, libc.so.? in Unix, ...\nclib = ctypes.CDLL('libc.dylib')\n\n_ = clib.memcpy(pixarray, im.tostring(), w_px * h_px * 4)\n\nThe return value of memcpy is an address you don't care about, so I \"swallowed\" it by assigning it to name \"single underscore\" (which by convention means \"I don't care about this one\";-).\nEdit: as @Mu Mind points out in a comment, the latter fragment can usefully be simplified to use ctypes.memmove without the need to go platform-dependent to ferret out clib: just do\n_ = ctypes.memmove(pixarray, im.tostring(), w_px * h_px * 4)\n\n" ]
[ 7 ]
[]
[]
[ "ctypes", "python", "python_imaging_library" ]
stackoverflow_0002935616_ctypes_python_python_imaging_library.txt
Q: Running shell commands without a shell window With either subprocess.call or subprocess.Popen, executing a shell command makes a shell window quicky appear and disappear. How can I run the shell command without the shell window? A: I imagine your observation is limited to Windows, since that, I believe, is the only platform on which you'll get that "console flash" issue. If so, then the docs offer the following semi-helpful paragraph: The startupinfo and creationflags, if given, will be passed to the underlying CreateProcess() function. They can specify things such as appearance of the main window and priority for the new process. (Windows only) Unfortunately the Python online docs do not reproduce the relevant portion of the Windows API docs, so you have to locate those elsewhere, e.g. starting here on MSDN which leads you here for the creationflags, and specifically to CREATE_NO_WINDOW 0x08000000 The process is a console application that is being run without a console window. Therefore, the console handle for the application is not set. So, adding creationflags=0x08000000 to your Popen call should help (unfortunately I have no Windows-running machine on which to try this out, so you'll have to try it yourself).
Running shell commands without a shell window
With either subprocess.call or subprocess.Popen, executing a shell command makes a shell window quicky appear and disappear. How can I run the shell command without the shell window?
[ "I imagine your observation is limited to Windows, since that, I believe, is the only platform on which you'll get that \"console flash\" issue. If so, then the docs offer the following semi-helpful paragraph:\n\nThe startupinfo and creationflags, if\n given, will be passed to the\n underlying CreateProcess() function.\n They can specify things such as\n appearance of the main window and\n priority for the new process. (Windows\n only)\n\nUnfortunately the Python online docs do not reproduce the relevant portion of the Windows API docs, so you have to locate those elsewhere, e.g. starting here on MSDN which leads you here for the creationflags, and specifically to\nCREATE_NO_WINDOW\n0x08000000\n\n\nThe process is a console application\n that is being run without a console\n window. Therefore, the console handle\n for the application is not set.\n\nSo, adding creationflags=0x08000000 to your Popen call should help (unfortunately I have no Windows-running machine on which to try this out, so you'll have to try it yourself).\n" ]
[ 25 ]
[]
[]
[ "python", "shell", "subprocess", "windows" ]
stackoverflow_0002935704_python_shell_subprocess_windows.txt
Q: Web hooks in Python: Any particular library? I wanted to implement web hooks in python. Both at server end and client end. Is there any particular library for implementing web hooks? Or does django or twisted python handle this? A: You should probably mention that "web hooks" is a specific concept -- as explained at webhooks.org -- to avoid getting generic answers about the web, as I see you already have. It's hardly a popular or widespread concept, so the answerers' utter confusion is not surprising but easily predictable. On your question, I know of Hookah (from the webhooks.org site) and durian (web hooks for Django). There are specific ones, such as TracWebHooks for adding web hooks to the issue tracking service Trac, but I gather you're looking for something more general.
Web hooks in Python: Any particular library?
I wanted to implement web hooks in python. Both at server end and client end. Is there any particular library for implementing web hooks? Or does django or twisted python handle this?
[ "You should probably mention that \"web hooks\" is a specific concept -- as explained at webhooks.org -- to avoid getting generic answers about the web, as I see you already have. It's hardly a popular or widespread concept, so the answerers' utter confusion is not surprising but easily predictable.\nOn your question, I know of Hookah (from the webhooks.org site) and durian (web hooks for Django). There are specific ones, such as TracWebHooks for adding web hooks to the issue tracking service Trac, but I gather you're looking for something more general.\n" ]
[ 7 ]
[]
[]
[ "python", "webhooks" ]
stackoverflow_0002935596_python_webhooks.txt
Q: Recalling import in module I'm still learning python and after playing around with pygame I noticed I'm re-importing things in modules I'm importing that I've already imported. import pygame For instance I have some classes in a separate file, but I must also import pygame into that file too for them to work. Does it actually import the code twice? Will it slow down my program? Or does it just pull the same import from cache, but if it does that, why would I need to import it again? Is there anything like (load) in lisp that just pulls in the code like it is part of the main file? Thank You A: Subsequent imports pull the cached module reference from sys.modules. You need to import in order to add the module to the current namespace/scope. A: When Python imports a module, it first checks the module registry (sys.modules) to see if the module is already imported. If that’s the case, Python uses the existing module object as is. http://effbot.org/zone/import-confusion.htm A: Got it! Okay I found what I was looking for. I just found it clunky to have to re-import code I already imported, especially when the file isn't a library or something, just split up code. found it here: http://norvig.com/python-lisp.html execfile("file.py") Answers my problem perfectly. It parses a file and executes the code in it. Using it I was able to take out the extra import statements and it runs perfectly :D
Recalling import in module
I'm still learning python and after playing around with pygame I noticed I'm re-importing things in modules I'm importing that I've already imported. import pygame For instance I have some classes in a separate file, but I must also import pygame into that file too for them to work. Does it actually import the code twice? Will it slow down my program? Or does it just pull the same import from cache, but if it does that, why would I need to import it again? Is there anything like (load) in lisp that just pulls in the code like it is part of the main file? Thank You
[ "Subsequent imports pull the cached module reference from sys.modules. You need to import in order to add the module to the current namespace/scope.\n", "\nWhen Python imports a module, it first checks the module registry (sys.modules) to see if the module is already imported. If that’s the case, Python uses the existing module object as is.\n\n\nhttp://effbot.org/zone/import-confusion.htm\n\n", "Got it!\nOkay I found what I was looking for. I just found it clunky to have to re-import code I already imported, especially when the file isn't a library or something, just split up code.\nfound it here: http://norvig.com/python-lisp.html\nexecfile(\"file.py\")\n\nAnswers my problem perfectly. It parses a file and executes the code in it. Using it I was able to take out the extra import statements and it runs perfectly :D\n" ]
[ 2, 2, 0 ]
[]
[]
[ "feedback", "pygame", "python" ]
stackoverflow_0002936027_feedback_pygame_python.txt
Q: can a python script know that another instance of the same script is running... and then talk to it? I'd like to prevent multiple instances of the same long-running python command-line script from running at the same time, and I'd like the new instance to be able to send data to the original instance before the new instance commits suicide. How can I do this in a cross-platform way? Specifically, I'd like to enable the following behavior: "foo.py" is launched from the command line, and it will stay running for a long time-- days or weeks until the machine is rebooted or the parent process kills it. every few minutes the same script is launched again, but with different command-line parameters when launched, the script should see if any other instances are running. if other instances are running, then instance #2 should send its command-line parameters to instance #1, and then instance #2 should exit. instance #1, if it receives command-line parameters from another script, should spin up a new thread and (using the command-line parameters sent in the step above) start performing the work that instance #2 was going to perform. So I'm looking for two things: how can a python program know another instance of itself is running, and then how can one python command-line program communicate with another? Making this more complicated, the same script needs to run on both Windows and Linux, so ideally the solution would use only the Python standard library and not any OS-specific calls. Although if I need to have a Windows codepath and an *nix codepath (and a big if statement in my code to choose one or the other), that's OK if a "same code" solution isn't possible. I realize I could probably work out a file-based approach (e.g. instance #1 watches a directory for changes and each instance drops a file into that directory when it wants to do work) but I'm a little concerned about cleaning up those files after a non-graceful machine shutdown. I'd ideally be able to use an in-memory solution. But again I'm flexible, if a persistent-file-based approach is the only way to do it, I'm open to that option. More details: I'm trying to do this because our servers are using a monitoring tool which supports running python scripts to collect monitoring data (e.g. results of a database query or web service call) which the monitoring tool then indexes for later use. Some of these scripts are very expensive to start up but cheap to run after startup (e.g. making a DB connection vs. running a query). So we've chosen to keep them running in an infinite loop until the parent process kills them. This works great, but on larger servers 100 instances of the same script may be running, even if they're only gathering data every 20 minutes each. This wreaks havoc with RAM, DB connection limits, etc. We want to switch from 100 processes with 1 thread to one process with 100 threads, each executing the work that, previously, one script was doing. But changing how the scripts are invoked by the monitoring tool is not possible. We need to keep invocation the same (launch a process with different command-line parameters) but but change the scripts to recognize that another one is active, and have the "new" script send its work instructions (from the command line params) over to the "old" script. BTW, this is not something I want to do on a one-script basis. Instead, I want to package this behavior into a library which many script authors can leverage-- my goal is to enable script authors to write simple, single-threaded scripts which are unaware of multi-instance issues, and to handle the multi-threading and single-instancing under the covers. A: The Alex Martelli approach of setting up a communications channel is the appropriate one. I would use a multiprocessing.connection.Listener to create a listener, in your choice. Documentation at: http://docs.python.org/library/multiprocessing.html#multiprocessing-listeners-clients Rather than using AF_INET (sockets) you may elect to use AF_UNIX for Linux and AF_PIPE for Windows. Hopefully a small "if" wouldn't hurt. Edit: I guess an example wouldn't hurt. It is a basic one, though. #!/usr/bin/env python from multiprocessing.connection import Listener, Client import socket from array import array from sys import argv def myloop(address): try: listener = Listener(*address) conn = listener.accept() serve(conn) except socket.error, e: conn = Client(*address) conn.send('this is a client') conn.send('close') def serve(conn): while True: msg = conn.recv() if msg.upper() == 'CLOSE': break print msg conn.close() if __name__ == '__main__': address = ('/tmp/testipc', 'AF_UNIX') myloop(address) This works on OS X, so it needs testing with both Linux and (after substituting the right address) Windows. A lot of caveats exists from a security point, the main one being that conn.recv unpickles its data, so you are almost always better of with recv_bytes. A: The general approach is to have the script, on startup, set up a communication channel in a way that's guaranteed to be exclusive (other attempts to set up the same channel fail in a predictable way) so that further instances of the script can detect the first one's running and talk to it. Your requirements for cross-platform functionality strongly point towards using a socket as the communication channel in question: you can designate a "well known port" that's reserved for your script, say 12345, and open a socket on that port listening to localhost only (127.0.0.1). If the attempt to open that socket fails, because the port in question is "taken", then you can connect to that port number instead, and that will let you communicate with the existing script. If you're not familiar with socket programming, there's a good HOWTO doc here. You can also look at the relevant chapter in Python in a Nutshell (I'm biased about that one, of course;-). A: Perhaps try using sockets for communication? A: Sounds like your best bet is sticking with a pid file but have it not only contain the process Id - have it also include the port number that the prior instance is listening on. So when starting up check for the pid file and if present see if a process with that Id is running - if so send your data to it and quit otherwise overwrite the pid file with the current process's info.
can a python script know that another instance of the same script is running... and then talk to it?
I'd like to prevent multiple instances of the same long-running python command-line script from running at the same time, and I'd like the new instance to be able to send data to the original instance before the new instance commits suicide. How can I do this in a cross-platform way? Specifically, I'd like to enable the following behavior: "foo.py" is launched from the command line, and it will stay running for a long time-- days or weeks until the machine is rebooted or the parent process kills it. every few minutes the same script is launched again, but with different command-line parameters when launched, the script should see if any other instances are running. if other instances are running, then instance #2 should send its command-line parameters to instance #1, and then instance #2 should exit. instance #1, if it receives command-line parameters from another script, should spin up a new thread and (using the command-line parameters sent in the step above) start performing the work that instance #2 was going to perform. So I'm looking for two things: how can a python program know another instance of itself is running, and then how can one python command-line program communicate with another? Making this more complicated, the same script needs to run on both Windows and Linux, so ideally the solution would use only the Python standard library and not any OS-specific calls. Although if I need to have a Windows codepath and an *nix codepath (and a big if statement in my code to choose one or the other), that's OK if a "same code" solution isn't possible. I realize I could probably work out a file-based approach (e.g. instance #1 watches a directory for changes and each instance drops a file into that directory when it wants to do work) but I'm a little concerned about cleaning up those files after a non-graceful machine shutdown. I'd ideally be able to use an in-memory solution. But again I'm flexible, if a persistent-file-based approach is the only way to do it, I'm open to that option. More details: I'm trying to do this because our servers are using a monitoring tool which supports running python scripts to collect monitoring data (e.g. results of a database query or web service call) which the monitoring tool then indexes for later use. Some of these scripts are very expensive to start up but cheap to run after startup (e.g. making a DB connection vs. running a query). So we've chosen to keep them running in an infinite loop until the parent process kills them. This works great, but on larger servers 100 instances of the same script may be running, even if they're only gathering data every 20 minutes each. This wreaks havoc with RAM, DB connection limits, etc. We want to switch from 100 processes with 1 thread to one process with 100 threads, each executing the work that, previously, one script was doing. But changing how the scripts are invoked by the monitoring tool is not possible. We need to keep invocation the same (launch a process with different command-line parameters) but but change the scripts to recognize that another one is active, and have the "new" script send its work instructions (from the command line params) over to the "old" script. BTW, this is not something I want to do on a one-script basis. Instead, I want to package this behavior into a library which many script authors can leverage-- my goal is to enable script authors to write simple, single-threaded scripts which are unaware of multi-instance issues, and to handle the multi-threading and single-instancing under the covers.
[ "The Alex Martelli approach of setting up a communications channel is the appropriate one. I would use a multiprocessing.connection.Listener to create a listener, in your choice. Documentation at:\nhttp://docs.python.org/library/multiprocessing.html#multiprocessing-listeners-clients\nRather than using AF_INET (sockets) you may elect to use AF_UNIX for Linux and AF_PIPE for Windows. Hopefully a small \"if\" wouldn't hurt.\nEdit: I guess an example wouldn't hurt. It is a basic one, though.\n#!/usr/bin/env python\n\nfrom multiprocessing.connection import Listener, Client\nimport socket\nfrom array import array\nfrom sys import argv\n\ndef myloop(address):\n try:\n listener = Listener(*address)\n conn = listener.accept()\n serve(conn)\n except socket.error, e:\n conn = Client(*address)\n conn.send('this is a client')\n conn.send('close')\n\ndef serve(conn):\n while True:\n msg = conn.recv()\n if msg.upper() == 'CLOSE':\n break\n print msg\n conn.close()\n\nif __name__ == '__main__':\n address = ('/tmp/testipc', 'AF_UNIX')\n myloop(address)\n\nThis works on OS X, so it needs testing with both Linux and (after substituting the right address) Windows. A lot of caveats exists from a security point, the main one being that conn.recv unpickles its data, so you are almost always better of with recv_bytes.\n", "The general approach is to have the script, on startup, set up a communication channel in a way that's guaranteed to be exclusive (other attempts to set up the same channel fail in a predictable way) so that further instances of the script can detect the first one's running and talk to it.\nYour requirements for cross-platform functionality strongly point towards using a socket as the communication channel in question: you can designate a \"well known port\" that's reserved for your script, say 12345, and open a socket on that port listening to localhost only (127.0.0.1). If the attempt to open that socket fails, because the port in question is \"taken\", then you can connect to that port number instead, and that will let you communicate with the existing script.\nIf you're not familiar with socket programming, there's a good HOWTO doc here. You can also look at the relevant chapter in Python in a Nutshell (I'm biased about that one, of course;-).\n", "Perhaps try using sockets for communication?\n", "Sounds like your best bet is sticking with a pid file but have it not only contain the process Id - have it also include the port number that the prior instance is listening on. So when starting up check for the pid file and if present see if a process with that Id is running - if so send your data to it and quit otherwise overwrite the pid file with the current process's info.\n" ]
[ 11, 9, 1, 0 ]
[]
[]
[ "command_line", "interprocess", "ipc", "multithreading", "python" ]
stackoverflow_0002935836_command_line_interprocess_ipc_multithreading_python.txt
Q: Writing csv files with python with exact formatting parameters I'm having trouble with processing some csv data files for a project. Someone suggested using python/csv reader to help break down the files, which I've had some success with, but not in a way I can use. This code is a little different from what I was trying before. I am essentially attempting to create an array. In the raw data format, the first 7 rows contain no data, and then each column contains 50 experiments, each with 4000 rows, for 200000 some rows total. What I want to do is take each column, and make it an individual csv file, with each experiment in its own column. So it would be an array of 50 columns and 4000 rows for each data type. The code here does break down the correct values, I think the logic is okay, but it is breaking down the opposite of how I want it. I want the separators without quotes (the commas and spaces) and I want the element values in quotes. Right now it is doing just the opposite for both, element values with no quotes, and the separators in quotes. I've spent several hours trying to figure out how to do this to no avail, import csv ifile = open('00_follow_maverick.csv') epistemicfile = open('00_follower_maverick_EP.csv', 'w') reader = csv.reader(ifile) colnum = 0 rownum = 0 y = 0 z = 8 for column in reader: rownum = 4000 * y + z for element in column: writer = csv.writer(epistemicfile) if y <= 50: y = y + 1 writer.writerow([element]) writer.writerow(',') rownum = x * y + z if y > 50: y = 0 z = z + 1 writer.writerow(' ') rownum = x * y + z if z >= 4008: break What is going on: I am taking each row in the raw data file in iterations of 4000, so that I can separate them with commas for the 50 experiments. When y, the experiment indicator here, reaches 50, it resets back to experiment 0, and adds 1 to z, which tells it which row to look at, by the formula of 4000 * y + z. When it completes the rows for all 50 experiments, it is finished. The problem here is that I don't know how to get python to write the actual values in quotes, and my separators outside of quotes. Any help will be most appreciated. Apologies if this seems a stupid question, I have no programming experience, this is my first attempt ever. Thank you. Sorry, I'll try to make this more clear. The original csv file has several columns, each of which are different sets of data. A miniature example of the raw file looks like: column1 column2 column3 exp1data1time1 exp1data2time1 exp1data3time1 exp1data1time2 exp1data2time2 exp1data3time2 exp2data1time1 exp2data2time1 exp2data3time1 exp2data1time2 exp2data2time2 exp2data3time2 exp3data1time1 exp3data2time1 exp3data3time1 exp3data1time2 exp3data2time2 exp3data3time2 So, the actual version has 4000 rows instead of 2 for each new experiment. There are 40 columns in the actual version, but basically, the data type in the raw file matches the column number. I want to separate each data type or column into an individual csv file. This would look like: csv file1 exp1data1time1 exp2data1time1 exp3data1time1 exp1data1time2 exp2data1time2 exp3data1time2 csv file2 exp1data2time1 exp2data2time1 exp3data2time1 exp1data2time2 exp2data2time2 exp3data2time2 csv file3 exp1data3time1 exp2data3time1 exp3data3time1 exp1data3time2 exp2data3time2 exp3data3time2 So, I'd move the raw data in the file to a new column, and each data type to its own file. Right now I'm only going to do one file, until I can move the separate experiments to separate columns in the new file. So, in the code, the above would make the 4000 into 2. I hope this makes more sense, but if not, I will try again. A: If I had a cat for each time I saw a bio or psych or chem database in this state: "each column contains 50 experiments, each with 4000 rows, for 200000 some rows total. What I want to do is take each column, and make it an individual csv file, with each experiment in its own column. So it would be an array of 50 columns and 4000 rows for each data type" I'd have way too farking many cats. I didn't even look at your code because the re-mangling you are proposing is just another problem that will have to be solved. I don't fault you, you claim to be a novice and all your peers make the same sort of error. Beginning programmers who have yet to understand how to use arrays often wind up with variable declarations like: integer response01, response02, response03, response04, ... and then very, very redundant code when they try to see if every response is - say - 1. I think this is such a seductive error in bio-informatics because it actually models the paper notations they come from rather well. Unfortunately, the sheet-of-paper model isn't the best way to model data. You should read and understand why database normalization was developed, codified and has come to dominate how people think about structured data. One Wikipedia article may not be sufficient. Using the example I excerpted let me try to explain how I think of it. Your data consists of observations; put the other way the primary datum is a singular observation. That observation has a context though: it is one of a set of 4000 observations, where each set belongs to one of 50 experiments. If you had to attach a context to each observation you'd wind up with an addressing scheme that looks like: <experiment_number, observation_number, value> In database jargon, that's a tuple, and it is capable of representing, with no ambiguity and perfect symmetry the entirety of your data. I'm not certain that I've understood the exact structure of your data, so perhaps it is something more like: <experiment_number, protocol_number, observation_number, value> where the protocol may be some form of variable treatment type - let's say pH. But note that I didn't call the protocol a pH and I don't record it as such in the database. What I would then need is an ancillary table showing the relevant parameters of the protocol, e.g.: <protocol_number, acidity, temperature, pressure> Now we've just built a "relation" that those database people like to talk about; we've also begun normalizing the data. If you need to know the pH for a given protocol, there is one and only one place to find it, in the proper row of the protocol table. Note that I've divorced the data that fit so nicely together on a data-sheet and from the observation table I can't see the pH for a particular dataum. But that's okay, because I can just look it up in my protocol table if needed. This is a "relational join" and if I needed to, I could coalesce all the various parameters from all the various tables and reconstitute the original datasheet in its original, unstructured glory. I hope this answer is of some use to you. I'm certain that I don't even know what field of study your data is from, but these principles apply across domains from drug trials to purchase requisition processing. Please understand that I'm trying to inform, per your request, and there is zero condescension intended. I welcome further questions on the matter. A: Normalization of the dataset Thanks for giving the example. You have the context I described already, perhaps I can make it more clear. column1 column2 column3 exp1data1time1 exp1data2time1 exp1data3time1 exp1data1time2 exp1data2time2 exp1data3time2 The columns are an artifice made by the last guy; that is, they carry no relevant information. When parsed into a normal form, your data looks just like my first proposed tuple: <experiment_number, time, response_number, response> where I suspect time may actually mean "subject_id" or "trial_number". It may very well look incongruous to you to conjoin all the different response values into the same dataset; indeed based on your desired output, I suspect that it does. At first blush, the objection "but the subject's response to a question about epistemic properties of chairs has no connection to their meta-epistemic beliefs regarding color", but this would be mistaken. The data are related because they have a common experimental subject, and self-correlation is an important concept in sociological analytics. For example, you may find that respondent A gives the same responses as respondent B, except all of A's responses are biased one higher because of how the subject understood the criteria. This would make a very real difference in the absolute values of the data, but I hope you can see that the question "do A and B actually have different epistemic models?" is salient and valid. One method of data modeling allows this question to be answered easily, your desired method does not. Working parsing code to follow shortly. A: The normalizing code #!/usr/bin/python """parses a csv file containing a particular data layout and normalizes The raw data set is a csv file of the form:: column1 column2 column3 exp01data01time01 exp01data02time01 exp01data03time01 exp01data01time02 exp01data02time02 exp01data03time02 where there are 40 such columns and the literal column title is added as context to the output row it is assumed that the columns are comma separated but the lexical form of the subcolumns is unspecified. Output will consist of a single CSV output stream on stdout of the form:: exp01, time01, data01, column1 for varying actual values of each field. """ import csv import sys def split_subfields(s): """returns a list of subfields of s this function is expected to be re-written to match the actual, unspecified lexical structure of s.""" return [s[0:5], s[5:11], s[11:17]] def normalise_data(reader, writer): """returns a list of the column headings from the reader""" # obtain the headings for use in normalization names = reader.next() # get the data rows, split them out by column, add the column name for row in reader: for column, datum in enumerate(row): fields = split_subfields(datum) fields.append(names[column]) writer.writerow(fields) def main(): if len(sys.argv) != 2: print >> sys.stderr, ('usage: %s input.csv' % sys.argv[0]) sys.exit(1) in_file = sys.argv[1] reader = csv.reader(open(in_file)) writer = csv.writer(sys.stdout) normalise_data(reader, writer) if __name__ == '__main__': main() Such that the command python epistem.py raw_data.csv > cooked_data.csv yields excerpted output looking like: exp01,data01,time01,column1 ... exp01,data40,time01,column40 exp01,data01,time02,column1 exp01,data01,time03,column1 ... exp02,data40,time15,column40
Writing csv files with python with exact formatting parameters
I'm having trouble with processing some csv data files for a project. Someone suggested using python/csv reader to help break down the files, which I've had some success with, but not in a way I can use. This code is a little different from what I was trying before. I am essentially attempting to create an array. In the raw data format, the first 7 rows contain no data, and then each column contains 50 experiments, each with 4000 rows, for 200000 some rows total. What I want to do is take each column, and make it an individual csv file, with each experiment in its own column. So it would be an array of 50 columns and 4000 rows for each data type. The code here does break down the correct values, I think the logic is okay, but it is breaking down the opposite of how I want it. I want the separators without quotes (the commas and spaces) and I want the element values in quotes. Right now it is doing just the opposite for both, element values with no quotes, and the separators in quotes. I've spent several hours trying to figure out how to do this to no avail, import csv ifile = open('00_follow_maverick.csv') epistemicfile = open('00_follower_maverick_EP.csv', 'w') reader = csv.reader(ifile) colnum = 0 rownum = 0 y = 0 z = 8 for column in reader: rownum = 4000 * y + z for element in column: writer = csv.writer(epistemicfile) if y <= 50: y = y + 1 writer.writerow([element]) writer.writerow(',') rownum = x * y + z if y > 50: y = 0 z = z + 1 writer.writerow(' ') rownum = x * y + z if z >= 4008: break What is going on: I am taking each row in the raw data file in iterations of 4000, so that I can separate them with commas for the 50 experiments. When y, the experiment indicator here, reaches 50, it resets back to experiment 0, and adds 1 to z, which tells it which row to look at, by the formula of 4000 * y + z. When it completes the rows for all 50 experiments, it is finished. The problem here is that I don't know how to get python to write the actual values in quotes, and my separators outside of quotes. Any help will be most appreciated. Apologies if this seems a stupid question, I have no programming experience, this is my first attempt ever. Thank you. Sorry, I'll try to make this more clear. The original csv file has several columns, each of which are different sets of data. A miniature example of the raw file looks like: column1 column2 column3 exp1data1time1 exp1data2time1 exp1data3time1 exp1data1time2 exp1data2time2 exp1data3time2 exp2data1time1 exp2data2time1 exp2data3time1 exp2data1time2 exp2data2time2 exp2data3time2 exp3data1time1 exp3data2time1 exp3data3time1 exp3data1time2 exp3data2time2 exp3data3time2 So, the actual version has 4000 rows instead of 2 for each new experiment. There are 40 columns in the actual version, but basically, the data type in the raw file matches the column number. I want to separate each data type or column into an individual csv file. This would look like: csv file1 exp1data1time1 exp2data1time1 exp3data1time1 exp1data1time2 exp2data1time2 exp3data1time2 csv file2 exp1data2time1 exp2data2time1 exp3data2time1 exp1data2time2 exp2data2time2 exp3data2time2 csv file3 exp1data3time1 exp2data3time1 exp3data3time1 exp1data3time2 exp2data3time2 exp3data3time2 So, I'd move the raw data in the file to a new column, and each data type to its own file. Right now I'm only going to do one file, until I can move the separate experiments to separate columns in the new file. So, in the code, the above would make the 4000 into 2. I hope this makes more sense, but if not, I will try again.
[ "If I had a cat for each time I saw a bio or psych or chem database in this state:\n\n\"each column contains 50 experiments,\n each with 4000 rows, for 200000 some\n rows total. What I want to do is take\n each column, and make it an individual\n csv file, with each experiment in its\n own column. So it would be an array of\n 50 columns and 4000 rows for each data\n type\"\n\nI'd have way too farking many cats.\nI didn't even look at your code because the re-mangling you are proposing is just another problem that will have to be solved. I don't fault you, you claim to be a novice and all your peers make the same sort of error. Beginning programmers who have yet to understand how to use arrays often wind up with variable declarations like:\ninteger response01, response02, response03, response04, ...\n\nand then very, very redundant code when they try to see if every response is - say - 1. I think this is such a seductive error in bio-informatics because it actually models the paper notations they come from rather well. Unfortunately, the sheet-of-paper model isn't the best way to model data.\nYou should read and understand why database normalization was developed, codified and has come to dominate how people think about structured data. One Wikipedia article may not be sufficient. Using the example I excerpted let me try to explain how I think of it. Your data consists of observations; put the other way the primary datum is a singular observation. That observation has a context though: it is one of a set of 4000 observations, where each set belongs to one of 50 experiments. If you had to attach a context to each observation you'd wind up with an addressing scheme that looks like:\n<experiment_number, observation_number, value>\n\nIn database jargon, that's a tuple, and it is capable of representing, with no ambiguity and perfect symmetry the entirety of your data. I'm not certain that I've understood the exact structure of your data, so perhaps it is something more like:\n<experiment_number, protocol_number, observation_number, value>\n\nwhere the protocol may be some form of variable treatment type - let's say pH. But note that I didn't call the protocol a pH and I don't record it as such in the database. What I would then need is an ancillary table showing the relevant parameters of the protocol, e.g.:\n<protocol_number, acidity, temperature, pressure>\n\nNow we've just built a \"relation\" that those database people like to talk about; we've also begun normalizing the data. If you need to know the pH for a given protocol, there is one and only one place to find it, in the proper row of the protocol table. Note that I've divorced the data that fit so nicely together on a data-sheet and from the observation table I can't see the pH for a particular dataum. But that's okay, because I can just look it up in my protocol table if needed. This is a \"relational join\" and if I needed to, I could coalesce all the various parameters from all the various tables and reconstitute the original datasheet in its original, unstructured glory.\nI hope this answer is of some use to you. I'm certain that I don't even know what field of study your data is from, but these principles apply across domains from drug trials to purchase requisition processing. Please understand that I'm trying to inform, per your request, and there is zero condescension intended. I welcome further questions on the matter.\n", "Normalization of the dataset\nThanks for giving the example. You have the context I described already, perhaps I can make it more clear.\ncolumn1 column2 column3\nexp1data1time1 exp1data2time1 exp1data3time1\nexp1data1time2 exp1data2time2 exp1data3time2\n\nThe columns are an artifice made by the last guy; that is, they carry no relevant information. When parsed into a normal form, your data looks just like my first proposed tuple:\n<experiment_number, time, response_number, response>\n\nwhere I suspect time may actually mean \"subject_id\" or \"trial_number\". It may very well look incongruous to you to conjoin all the different response values into the same dataset; indeed based on your desired output, I suspect that it does. At first blush, the objection \"but the subject's response to a question about epistemic properties of chairs has no connection to their meta-epistemic beliefs regarding color\", but this would be mistaken. The data are related because they have a common experimental subject, and self-correlation is an important concept in sociological analytics.\nFor example, you may find that respondent A gives the same responses as respondent B, except all of A's responses are biased one higher because of how the subject understood the criteria. This would make a very real difference in the absolute values of the data, but I hope you can see that the question \"do A and B actually have different epistemic models?\" is salient and valid. One method of data modeling allows this question to be answered easily, your desired method does not.\nWorking parsing code to follow shortly.\n", "The normalizing code\n#!/usr/bin/python\n\n\"\"\"parses a csv file containing a particular data layout and normalizes\n\n The raw data set is a csv file of the form::\n\n column1 column2 column3\n exp01data01time01 exp01data02time01 exp01data03time01\n exp01data01time02 exp01data02time02 exp01data03time02\n\n where there are 40 such columns and the literal column title\n is added as context to the output row\n\n it is assumed that the columns are comma separated but\n the lexical form of the subcolumns is unspecified.\n\n Output will consist of a single CSV output stream\n on stdout of the form::\n\n exp01, time01, data01, column1\n\n for varying actual values of each field.\n\"\"\"\n\nimport csv\nimport sys\n\ndef split_subfields(s):\n \"\"\"returns a list of subfields of s\n this function is expected to be re-written to match the actual,\n unspecified lexical structure of s.\"\"\"\n return [s[0:5], s[5:11], s[11:17]]\n\n\ndef normalise_data(reader, writer):\n \"\"\"returns a list of the column headings from the reader\"\"\"\n\n # obtain the headings for use in normalization\n names = reader.next()\n\n # get the data rows, split them out by column, add the column name\n for row in reader:\n for column, datum in enumerate(row):\n fields = split_subfields(datum)\n fields.append(names[column])\n writer.writerow(fields)\n\ndef main():\n if len(sys.argv) != 2:\n print >> sys.stderr, ('usage: %s input.csv' % sys.argv[0])\n sys.exit(1)\n\n in_file = sys.argv[1]\n\n reader = csv.reader(open(in_file))\n writer = csv.writer(sys.stdout)\n normalise_data(reader, writer)\n\nif __name__ == '__main__': main()\n\nSuch that the command python epistem.py raw_data.csv > cooked_data.csv yields excerpted output looking like:\nexp01,data01,time01,column1\n...\nexp01,data40,time01,column40\nexp01,data01,time02,column1\nexp01,data01,time03,column1\n...\nexp02,data40,time15,column40\n\n" ]
[ 2, 0, 0 ]
[]
[]
[ "csv", "database_design", "python", "relational_database" ]
stackoverflow_0002933702_csv_database_design_python_relational_database.txt
Q: App Engine - Save response from an API in the data store as file (blob) I'm banging my head against the wall with this one: What I want to do is store a file that is returned from an API in the data store as a blob. Here is the code that I use on my local machine (which of course works due to an existing file system): client.convertHtml(html, open('html.pdf', 'wb')) Since I cannot write to a file on App Engine I tried several ways to store the response, without success. Any hints on how to do this? I was trying to do it with StringIO and managed to store the response but then weren't able to store it as a blob in the data store. Thanks, Chris A: Found the error. Here is how it looks like right now (simplified). output = StringIO.StringIO() try: client.convertURI("example.com", output) Report.pdf = db.Blob(output.getvalue()) Report.put() except pdfcrowd.Error, why: logging.error('PDF creation failed %s' % why) I was trying to save the output without calling "getvalue()", that was the problem. Perhaps this is of use to someone in the future :)
App Engine - Save response from an API in the data store as file (blob)
I'm banging my head against the wall with this one: What I want to do is store a file that is returned from an API in the data store as a blob. Here is the code that I use on my local machine (which of course works due to an existing file system): client.convertHtml(html, open('html.pdf', 'wb')) Since I cannot write to a file on App Engine I tried several ways to store the response, without success. Any hints on how to do this? I was trying to do it with StringIO and managed to store the response but then weren't able to store it as a blob in the data store. Thanks, Chris
[ "Found the error. Here is how it looks like right now (simplified).\n output = StringIO.StringIO()\n\n try:\n client.convertURI(\"example.com\", output)\n Report.pdf = db.Blob(output.getvalue())\n Report.put() \n except pdfcrowd.Error, why:\n logging.error('PDF creation failed %s' % why)\n\nI was trying to save the output without calling \"getvalue()\", that was the problem. Perhaps this is of use to someone in the future :)\n" ]
[ 2 ]
[]
[]
[ "api", "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0002935918_api_google_app_engine_google_cloud_datastore_python.txt
Q: openid along with oauth? In my application, users sign in/sign out via openid ( same as stackoverflow ). I would like to open up my application a bit via oauth to third party applications. How do I create my app which is openid-consumer to make it oauth-provider? Is there some standard library etc out there? I am basically working in app engine and python. edit : Maybe I did not clearly state my problem. I am using OpenID for authentication. So I do not have user passwords, just their unique federated Identity. My application needs to use third party application. I.e. kind of application that runs inside orkut and facebook. (Do you think opensocial is a a viable option instead of OAuth??) A: OAuth python libraries are listed on this page: http://oauth.net/code/ A: OAth and OpenID are had native support by app engine sinve 1.3.4. So you can implement transparent and solid authorization/authentication mechanism.
openid along with oauth?
In my application, users sign in/sign out via openid ( same as stackoverflow ). I would like to open up my application a bit via oauth to third party applications. How do I create my app which is openid-consumer to make it oauth-provider? Is there some standard library etc out there? I am basically working in app engine and python. edit : Maybe I did not clearly state my problem. I am using OpenID for authentication. So I do not have user passwords, just their unique federated Identity. My application needs to use third party application. I.e. kind of application that runs inside orkut and facebook. (Do you think opensocial is a a viable option instead of OAuth??)
[ "OAuth python libraries are listed on this page:\nhttp://oauth.net/code/\n", "OAth and OpenID are had native support by app engine sinve 1.3.4. So you can implement transparent and solid authorization/authentication mechanism.\n" ]
[ 2, 2 ]
[]
[]
[ "google_app_engine", "oauth", "oauth_provider", "openid", "python" ]
stackoverflow_0002934326_google_app_engine_oauth_oauth_provider_openid_python.txt
Q: install python modules on shared web hosting I am using a shared hosting environment that will not give me access to the command line. Can I download the python module on my computer, compile it using python setup.py installand then simply upload a .py file to the web host? If yes, where does the install statement place the compiled file? A: This is not directly an answer to your question but.. change your hosting provider! There are very cheap hostings with shell access and I swear that running Python site without access to shell is next to impossible. Also, compiling Python library (I assume that it has some C bindings, otherwise there's not much to compile) on your local computer and uploading it to remote server without shell access might turn out to be a nightmare, because of some missing dependencies, conflicting versions of other libraries etc. Last but not least, tools like Fabric are your friends during deployment to remote servers, and without shell access you basically either can't use them, or you suffer (for example: I have a script that commits&pushes local changesets to Mercurial repository on a remote server, updates it there and restarts that app on server - how would you do this with FTP-only access :) ?)..
install python modules on shared web hosting
I am using a shared hosting environment that will not give me access to the command line. Can I download the python module on my computer, compile it using python setup.py installand then simply upload a .py file to the web host? If yes, where does the install statement place the compiled file?
[ "This is not directly an answer to your question but.. change your hosting provider! There are very cheap hostings with shell access and I swear that running Python site without access to shell is next to impossible.\nAlso, compiling Python library (I assume that it has some C bindings, otherwise there's not much to compile) on your local computer and uploading it to remote server without shell access might turn out to be a nightmare, because of some missing dependencies, conflicting versions of other libraries etc.\nLast but not least, tools like Fabric are your friends during deployment to remote servers, and without shell access you basically either can't use them, or you suffer (for example: I have a script that commits&pushes local changesets to Mercurial repository on a remote server, updates it there and restarts that app on server - how would you do this with FTP-only access :) ?).. \n" ]
[ 2 ]
[]
[]
[ "compiler_construction", "python" ]
stackoverflow_0002936222_compiler_construction_python.txt
Q: Allocation algorithm help, using Python I've been working on this general allocation algorithm for students. The pseudocode for it (a Python implementation) is: for a student in a dictionary of students: for student preference in a set of preferences (ordered from 1 to 10): let temp_project be the first preferred project check if temp_project is available if so, allocate it to him and make the project unavailable to others break Quite simply this will try to allocate projects by starting from their most preferred. The way it works, out of a set of say 100 projects, you list 10 you would want to do. So the 10th project wouldn't be the "least preferred overall" but rather the least preferred in their chosen set, which isn't so bad. Obviously if it can't allocate a project, a student just reverts to the base case which is an allocation of None, with a rank of 11. What I'm doing is calculating the allocation "quality" based on a weighted sum of the ranks. So the lower the numbers (i.e. more highly preferred projects), the better the allocation quality (i.e. more students have highly preferred projects). That's basically what I've currently got. Simple and it works. Now I'm working on this algorithm that tries to minimise the allocation weight locally (this pseudocode is a bit messy, sorry). The only reason this will probably work is because my "search space" as it is, isn't particularly large (just a very general, anecdotal observation, mind you). Since the project is only specific to my Department, we have their own limits imposed. So the number of students can't exceed 100 and the number of preferences won't exceed 10. for student in a dictionary/list/whatever of students: where i = 0 take the (i)st student, (i+1)nd student for their ranks: allocate the projects and set local_weighting(N) to be sum(student_i.alloc_proj_rank, student_i+1.alloc_proj_rank) these are the cases: if N is 2 (i.e. both ranks are 1): then i += 1 and and continue above if N > 2 (i.e. one or more ranks are greater than 1): let temp_N be N: pick student with lowest rank and then move him to his next rank and pick the other student and reallocate his project temp_N is sum of the the ranks if temp_N is < N: then allocate those projects to the students i += 1 and move on for the rest of the students Updated with respect to comments: What I'm trying to do: I'm trying to achieve a "lowest weight allocation" between groups of two students at a time (i.e. local) The weight allocation is a sum of the ranks as assigned by the students. We want students to get their highest ranked projects overall. Thus if student A has gets a project he ranked 1 and a student B gets a project she ranked 5, then their local allocation weight is 6. If we move student A to his rank 2 project and consequently, student B is moved to her rank 3 project then the weight is now 5. 5 < 6 which is better overall. Thus I start with my collection of students and then begin iterating through them I start with the first and second student and allocate them their projects Then I calculate the weight as described above. Given that the weight is equal to the rankings, if both are ranked 1, the weight 2. This is as good as it gets and we want to move on the second and third students. Now, if the weight is greater than 2, indicating that one or more projects is ranked greater than 2, we try to get a better version. Thus we take the student with the lowest rank and then move him/her down a single rank (so if he/she was rank 1, this moves him down to rank 2) And then we try to re-allocate the other student to another rank. Now if the weight is better than the previous weight, then we let that be the new weight and let them have those projects. If it's worse or equal then we just move on to the next duo of students. Locally, for students, this thing keeps trying until it's hit a minimum weight and can't do any better. Hope this explains what I'm trying to do? So, questions: This is sort of a modification of simulated annealing, but any sort of comments on this would be appreciated. How would I keep track of which student is (i) and which student is (i+1) If my overall list of students is 100, then the thing would mess up on (i+1) = 101 since there is none. How can I circumvent that? Any immediate flaws that can be spotted? Extra info: My students dictionary is designed as such: students[student_id] = Student(student_id, student_name, alloc_proj, alloc_proj_rank, preferences) where preferences is in the form of a dictionary such that preferences[rank] = {project_id} A: Seems like Assignment Problem might work for you, which can be solved using Hungarian Algorithm (as was noted in your other question: Student-Project allocation algorithms?). Apparently there is a python implementation of the hungarian algorithm: http://pypi.python.org/pypi/hungarian/0.2 I would recommend just using one well known and already implemented algorithm, rather than trying to come up with your own. If you really want to use your own algorithm and want suggestions on making it work, I suggest you clearly explain what you are trying to do, instead of just providing code. Good luck, hope that helps.
Allocation algorithm help, using Python
I've been working on this general allocation algorithm for students. The pseudocode for it (a Python implementation) is: for a student in a dictionary of students: for student preference in a set of preferences (ordered from 1 to 10): let temp_project be the first preferred project check if temp_project is available if so, allocate it to him and make the project unavailable to others break Quite simply this will try to allocate projects by starting from their most preferred. The way it works, out of a set of say 100 projects, you list 10 you would want to do. So the 10th project wouldn't be the "least preferred overall" but rather the least preferred in their chosen set, which isn't so bad. Obviously if it can't allocate a project, a student just reverts to the base case which is an allocation of None, with a rank of 11. What I'm doing is calculating the allocation "quality" based on a weighted sum of the ranks. So the lower the numbers (i.e. more highly preferred projects), the better the allocation quality (i.e. more students have highly preferred projects). That's basically what I've currently got. Simple and it works. Now I'm working on this algorithm that tries to minimise the allocation weight locally (this pseudocode is a bit messy, sorry). The only reason this will probably work is because my "search space" as it is, isn't particularly large (just a very general, anecdotal observation, mind you). Since the project is only specific to my Department, we have their own limits imposed. So the number of students can't exceed 100 and the number of preferences won't exceed 10. for student in a dictionary/list/whatever of students: where i = 0 take the (i)st student, (i+1)nd student for their ranks: allocate the projects and set local_weighting(N) to be sum(student_i.alloc_proj_rank, student_i+1.alloc_proj_rank) these are the cases: if N is 2 (i.e. both ranks are 1): then i += 1 and and continue above if N > 2 (i.e. one or more ranks are greater than 1): let temp_N be N: pick student with lowest rank and then move him to his next rank and pick the other student and reallocate his project temp_N is sum of the the ranks if temp_N is < N: then allocate those projects to the students i += 1 and move on for the rest of the students Updated with respect to comments: What I'm trying to do: I'm trying to achieve a "lowest weight allocation" between groups of two students at a time (i.e. local) The weight allocation is a sum of the ranks as assigned by the students. We want students to get their highest ranked projects overall. Thus if student A has gets a project he ranked 1 and a student B gets a project she ranked 5, then their local allocation weight is 6. If we move student A to his rank 2 project and consequently, student B is moved to her rank 3 project then the weight is now 5. 5 < 6 which is better overall. Thus I start with my collection of students and then begin iterating through them I start with the first and second student and allocate them their projects Then I calculate the weight as described above. Given that the weight is equal to the rankings, if both are ranked 1, the weight 2. This is as good as it gets and we want to move on the second and third students. Now, if the weight is greater than 2, indicating that one or more projects is ranked greater than 2, we try to get a better version. Thus we take the student with the lowest rank and then move him/her down a single rank (so if he/she was rank 1, this moves him down to rank 2) And then we try to re-allocate the other student to another rank. Now if the weight is better than the previous weight, then we let that be the new weight and let them have those projects. If it's worse or equal then we just move on to the next duo of students. Locally, for students, this thing keeps trying until it's hit a minimum weight and can't do any better. Hope this explains what I'm trying to do? So, questions: This is sort of a modification of simulated annealing, but any sort of comments on this would be appreciated. How would I keep track of which student is (i) and which student is (i+1) If my overall list of students is 100, then the thing would mess up on (i+1) = 101 since there is none. How can I circumvent that? Any immediate flaws that can be spotted? Extra info: My students dictionary is designed as such: students[student_id] = Student(student_id, student_name, alloc_proj, alloc_proj_rank, preferences) where preferences is in the form of a dictionary such that preferences[rank] = {project_id}
[ "Seems like Assignment Problem might work for you, which can be solved using Hungarian Algorithm (as was noted in your other question: Student-Project allocation algorithms?). \nApparently there is a python implementation of the hungarian algorithm: http://pypi.python.org/pypi/hungarian/0.2\nI would recommend just using one well known and already implemented algorithm, rather than trying to come up with your own.\nIf you really want to use your own algorithm and want suggestions on making it work, I suggest you clearly explain what you are trying to do, instead of just providing code.\nGood luck, hope that helps.\n" ]
[ 3 ]
[]
[]
[ "algorithm", "allocation", "python" ]
stackoverflow_0002936675_algorithm_allocation_python.txt
Q: lightweight webserver to integrate on client end I need to create a python module that will be installed on end-user machines. One of the scripts in that module should be able to receive http POSTS (usually with some JSON formatted data in the body) and then pass on that data to an appropriate python script. I can think of two ways to do this: Open a listening server socket on port 80, wait for that http request to come in, parse it and then pass that data to another python script depending on the url that arrived. This method will not require the end-user to install a webserver. End user only has to install the python module. Have a mini-webserver installed along with the python module. The webserver will do the same job as [a] via CGI without me requiring to write the CGI functionality. But then the user will have to install the web-server (ie., the hassle of yet another install). Would like to avoid that if possible. IF [b] is the easier option, what is the smallest simplest webserver there is (preferably one that can be packaged as part of the python module itself so that it does not have to be separately installed). Must be opensource of course. A: batteries included Python 2 Python 3
lightweight webserver to integrate on client end
I need to create a python module that will be installed on end-user machines. One of the scripts in that module should be able to receive http POSTS (usually with some JSON formatted data in the body) and then pass on that data to an appropriate python script. I can think of two ways to do this: Open a listening server socket on port 80, wait for that http request to come in, parse it and then pass that data to another python script depending on the url that arrived. This method will not require the end-user to install a webserver. End user only has to install the python module. Have a mini-webserver installed along with the python module. The webserver will do the same job as [a] via CGI without me requiring to write the CGI functionality. But then the user will have to install the web-server (ie., the hassle of yet another install). Would like to avoid that if possible. IF [b] is the easier option, what is the smallest simplest webserver there is (preferably one that can be packaged as part of the python module itself so that it does not have to be separately installed). Must be opensource of course.
[ "batteries included\nPython 2\nPython 3 \n" ]
[ 4 ]
[]
[]
[ "python", "webserver" ]
stackoverflow_0002936792_python_webserver.txt