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: Handle SimpleXMLRPCServer calls and Asyncore.dispatchers events from the same event-loop How can I handle Asyncore.dispatcher(s) and SimpleXMLRPCServer events from the same event-loop? P.S. I already know that some of you might recommend Twisted for this, but the problem with Twisted is that it is a little bit too...
Handle SimpleXMLRPCServer calls and Asyncore.dispatchers events from the same event-loop
How can I handle Asyncore.dispatcher(s) and SimpleXMLRPCServer events from the same event-loop? P.S. I already know that some of you might recommend Twisted for this, but the problem with Twisted is that it is a little bit too high-level library for my needs. In particular I am doing UDP flow-control by overriding Asyn...
[ "You should use Twisted for this :-). You can't put SimpleXMLRPCServer into an asynchronous loop; it's synchronous code, which expects to block.\nFlow-control with Twisted, even with UDP, is easy. Rather than overriding a method like writable(), your DatagramProtocol can call methods like stopReading / stopWritin...
[ 1 ]
[]
[]
[ "asyncore", "event_handling", "python", "rpc", "twisted" ]
stackoverflow_0007899346_asyncore_event_handling_python_rpc_twisted.txt
Q: Browser multiplayer network strategy - does this seem like a viable solution? I'm interested in producing some sort of multiplayer RPG as a purely browser based game, with little or no plugin requirements. Having done quite a bit of research I've arrived at the following plan. I'm aware that some of the tech I'm r...
Browser multiplayer network strategy - does this seem like a viable solution?
I'm interested in producing some sort of multiplayer RPG as a purely browser based game, with little or no plugin requirements. Having done quite a bit of research I've arrived at the following plan. I'm aware that some of the tech I'm referencing here is not adopted across all browsers ( specifically IE ) but I'm will...
[ "You generally get 5MB of space with the localStorage API. If you really have a 3D game with sound/music, that's going to get eaten up really quickly by your assets (how big is a good-quality mp3 these days?). You'll need to be super aggressive with compressing your assets and most likely have to come up with a mec...
[ 1 ]
[]
[]
[ "gevent", "javascript", "multiplayer", "python", "webgl" ]
stackoverflow_0007900488_gevent_javascript_multiplayer_python_webgl.txt
Q: Parsing weirdly structured XML with lxml I have a number of XML files that I need to parse. I've written some code that works, but is ugly, and I'd like to get some advice from people more experienced with XML than I am. First of all, I might be using some terms in the wrong context, because my experience with XML...
Parsing weirdly structured XML with lxml
I have a number of XML files that I need to parse. I've written some code that works, but is ugly, and I'd like to get some advice from people more experienced with XML than I am. First of all, I might be using some terms in the wrong context, because my experience with XML is limited. By element, unless specified othe...
[ "You could streamline your input code by using xpath expressions relative your element instead of a complex data-structure e.g., #1-4 cases:\n\ntag/text()\ntag/@attribute\nname(DTBoolean/*[1])\n(tag1|tag2)/*/text()\n\nWhat output data-structure to use depends on how do you like it to be used in your code later. You...
[ 3, 2, 1 ]
[]
[]
[ "lxml", "parsing", "python", "xml" ]
stackoverflow_0007894357_lxml_parsing_python_xml.txt
Q: Read write classes to files in an efficent way I have want to save classes to a file in python. I want something like this, I have a similar class in python, like this C++ struct: struct WebSites { char SiteName[100]; int Rank; }; and I want to write something like this: void write_to_...
Read write classes to files in an efficent way
I have want to save classes to a file in python. I want something like this, I have a similar class in python, like this C++ struct: struct WebSites { char SiteName[100]; int Rank; }; and I want to write something like this: void write_to_binary_file(WebSites p_Data) { fstream binary...
[ "Python has the pickle-module that can be used to serialize objects. If you use a protocol version >= 1, the data is serialized to a binary format. You can use pickle like this:\nclass WebSites(object):\n def __init__():\n self.SiteName = \"\"\n self.Rank = 0\n\nimport cPickle\n# to serialize the o...
[ 8 ]
[]
[]
[ "file", "io", "python" ]
stackoverflow_0007900944_file_io_python.txt
Q: extract item from list of dictionaries Suppose you have a list of dictionaries like this one: a = [ {'name':'pippo', 'age':'5'} , {'name':'pluto', 'age':'7'} ] What do you to extract from this list only the dict where name==pluto? To make things a little bit harder, consider that I cannot do any import A: List ...
extract item from list of dictionaries
Suppose you have a list of dictionaries like this one: a = [ {'name':'pippo', 'age':'5'} , {'name':'pluto', 'age':'7'} ] What do you to extract from this list only the dict where name==pluto? To make things a little bit harder, consider that I cannot do any import
[ "List comprehension is ideal for this:\n[d for d in a if d['name'] == 'pluto']\n\n", "Apart from list comprehension that other responses give it to you, you can also do it with a filter and a lambda:\nfilter(lambda x: x.get('name') == 'pluto',a)\n\n", ">>> [d['age'] for d in a if d['name']=='pluto']\n['7']\n\n"...
[ 40, 14, 3, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007900882_python.txt
Q: Multiprocess with WSGI I am developing an application with apache and wsgi. The structure of my app is like this: Client --> Web Server --> Dispatcher(receive http request from server) --> Worker(process the request) --> Sink(response to web server) --> Web Server --> Client Basically, there are 3 processes(dispat...
Multiprocess with WSGI
I am developing an application with apache and wsgi. The structure of my app is like this: Client --> Web Server --> Dispatcher(receive http request from server) --> Worker(process the request) --> Sink(response to web server) --> Web Server --> Client Basically, there are 3 processes(dispatcher, worker and sink) I am ...
[ "For straight proxying, see:\nhttp://pythonpaste.org/modules/proxy.html\nFor higher level abstractions look at a messaging systems such as RabbitMQ. You might also be interested in task execution systems such as Celery.\n" ]
[ 1 ]
[]
[]
[ "multiprocess", "python", "wsgi" ]
stackoverflow_0007901204_multiprocess_python_wsgi.txt
Q: Too many redirects error using Python requests HTTP requests are working fine on my localhost, but running the same HTTP requests using the python requests library on my server returns a "Too Many Redirects" error When I enter localhost/terminal/jfk in a browser, I get a json dictionary as expected. However, when...
Too many redirects error using Python requests
HTTP requests are working fine on my localhost, but running the same HTTP requests using the python requests library on my server returns a "Too Many Redirects" error When I enter localhost/terminal/jfk in a browser, I get a json dictionary as expected. However, when I run the following in python using the python requ...
[ "Asha,\nAfter you responded that this really is your site, I checked out why I was getting an empty GoDaddy.com page. The problem is that your DNS entry for splitmyri.de is returning two different A records...\nAnalyzing results, using 107.10.141.119:\nHard coding 107.10.141.119 splitmyri.de in my /etc/hosts...
[ 7, 1 ]
[]
[]
[ "dns", "http_request", "python", "python_requests", "redirect" ]
stackoverflow_0007896842_dns_http_request_python_python_requests_redirect.txt
Q: print output in 1 line separated by commas I have 1 list: mylist=[John, Stefan, Bjarke, Eric, Weirdo] I want to print the whole thing in one line separated by commas using a for loop, like: for x in mylist: print x How do I do this? A: print ','.join(mylist) or if John Stefan etc are not already strings: ...
print output in 1 line separated by commas
I have 1 list: mylist=[John, Stefan, Bjarke, Eric, Weirdo] I want to print the whole thing in one line separated by commas using a for loop, like: for x in mylist: print x How do I do this?
[ "print ','.join(mylist)\n\nor if John Stefan etc are not already strings:\nprint ','.join(str(o) for o in mylist)\n\n", "Other answers are smarter, and more 'Pythonic'. But if you really need a loop: \nfor item in mylist:\n print item + ',', # <<<---- here, have a look to the trailing coma!\n\nBut this will l...
[ 3, 1, 0, 0 ]
[]
[]
[ "for_loop", "list", "python" ]
stackoverflow_0007900714_for_loop_list_python.txt
Q: Django: nested custom template tags I have written 2 custom template tags in Django. The goal is to use one custom tag inside of another. Is it permitted? The template for custom "outer" tag looks like this: <ul> {% for type in types %} {% custom_internal_tag param1 %} {% endfor %} </ul> Which af...
Django: nested custom template tags
I have written 2 custom template tags in Django. The goal is to use one custom tag inside of another. Is it permitted? The template for custom "outer" tag looks like this: <ul> {% for type in types %} {% custom_internal_tag param1 %} {% endfor %} </ul> Which after rendering results in Invalid block ...
[ "They are definitely allowed, but that error can come up because your custom tag is not properly defined, located or loaded.\nMake sure all your custom tags are located in your app/templatetags directory and are loaded properly, usually using the @register decorator.\nReference: https://docs.djangoproject.com/en/de...
[ 9 ]
[]
[]
[ "django", "python", "templates" ]
stackoverflow_0007901598_django_python_templates.txt
Q: Configuring Python to use additional locations for site-packages Is there a way to tell Python about additional site-packages locations without modifying existing scripts? On my CentOS 5.5 server I have a Python 2.7 installation that is installed in /opt/python2.7.2 and there is a site-packages folder at /opt/pyth...
Configuring Python to use additional locations for site-packages
Is there a way to tell Python about additional site-packages locations without modifying existing scripts? On my CentOS 5.5 server I have a Python 2.7 installation that is installed in /opt/python2.7.2 and there is a site-packages folder at /opt/python2.7.2/lib/python2.7/site-packages. The reason for this is that I did...
[ "You can use the Site-specific configuration hook.\n\n\"A path configuration file is a file whose name has the form name.pth and exists in one of the four directories mentioned above; its contents are additional items (one per line) to be added to sys.path.\" \n\nIn your case, you should be able to achieve what you...
[ 52, 7 ]
[]
[]
[ "package", "python" ]
stackoverflow_0007901373_package_python.txt
Q: The results of sha1 encryption are different between python and java An application, i need sha1 encryption,but the results are different between python and java, java is correct. Because there is no byte object in python, and java byte is used for hash calculation. How to get the correct results with python? A: ...
The results of sha1 encryption are different between python and java
An application, i need sha1 encryption,but the results are different between python and java, java is correct. Because there is no byte object in python, and java byte is used for hash calculation. How to get the correct results with python?
[ "As usual, the difference is not in the digest implementation (those are well-documented and implemented correctly in all major libraries). The difference is in how you represent the resulting data.\nmd.digest() returns a byte[] with the binary data produced by the digest.\nnew String(md.digest()) tries to interpre...
[ 3 ]
[]
[]
[ "encryption", "java", "python", "sha1" ]
stackoverflow_0007901210_encryption_java_python_sha1.txt
Q: pyQt4 and inheritance For a number of reasons I am contemplating redoing an program I use at work in pyqt4 (at present it is in pygtk). After playing around with it and getting a feel for it and appreciating its philosophy with gui building I am running into some annoying ... bugs or implementation limitations O...
pyQt4 and inheritance
For a number of reasons I am contemplating redoing an program I use at work in pyqt4 (at present it is in pygtk). After playing around with it and getting a feel for it and appreciating its philosophy with gui building I am running into some annoying ... bugs or implementation limitations One of them is inheritance: ...
[ "This is not a QT issue, but a lack of understanding of how multiple inheritance works. You can absolutely use multiple inheritance, but it is a tricky subject in Python.\nIn a nutshell, in your last example, the first __init__ is called, so if you changed class D(QtGui.QMainWindow,A): to class D(A, QtGui.QMainWind...
[ 2 ]
[]
[]
[ "pyqt4", "python" ]
stackoverflow_0007901178_pyqt4_python.txt
Q: How to create page links? I know current user's location. It can be one of the following url: (1) http://myapp.appspot.com/something/something-else/ (2) http://myapp.appspot.com/something/something-else (3) http://myapp.appspot.com/something/something-else/page1 (4) http://myapp.appspot.com/something/something-els...
How to create page links?
I know current user's location. It can be one of the following url: (1) http://myapp.appspot.com/something/something-else/ (2) http://myapp.appspot.com/something/something-else (3) http://myapp.appspot.com/something/something-else/page1 (4) http://myapp.appspot.com/something/something-else/page3 (actually, addresses 1...
[ "/page2 will never work; the leading / makes it relative to the website root rather than the current directory.\npage2 should work for everything except #2; without a trailing slash, something-else is interpreted as a file rather than the current directory.\nOne solution would be to link to /something/something-els...
[ 2, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0007895022_google_app_engine_python.txt
Q: 2D Sorting with NumPy - sort 1 row and have the other follow the sorting Say I have a NumPy array: [[4 9 2] [5 1 3]] I want to sort the bottom row of this array, but have the top row follow the sorting, such that I get: [[9 2 4] [1 3 5]] I know that you can sort like this using the sorted() function, but that ...
2D Sorting with NumPy - sort 1 row and have the other follow the sorting
Say I have a NumPy array: [[4 9 2] [5 1 3]] I want to sort the bottom row of this array, but have the top row follow the sorting, such that I get: [[9 2 4] [1 3 5]] I know that you can sort like this using the sorted() function, but that requires input and output of lists. Any ideas? Thanks so much!
[ "import numpy as np\na = np.array([[4,9,2],[5,1,3]])\nidx = np.argsort(a[1])\n\nNow you can use idx to index your array:\nb=a[:,idx]\n\n", "The only (efficient) solution I can think of needs a copy of the original array. \nimport numpy as np\na = np.array([[4,9,2],[5,1,3]])\nidx = np.argsort(a[1])\n\nSo, that id...
[ 11, 1 ]
[]
[]
[ "numpy", "python", "scipy", "sorting" ]
stackoverflow_0007900171_numpy_python_scipy_sorting.txt
Q: Using Python mechanize on websites that use DHTML, AJAX, etc.? So, let's say I'm trying to create something that replies to tweets of a certain "hashtag keyword" on twitter (for example "#FirstWorldProblems") I have a script that looks like this: # apply settings, create a mechanize.Browser, etc. login() # log in...
Using Python mechanize on websites that use DHTML, AJAX, etc.?
So, let's say I'm trying to create something that replies to tweets of a certain "hashtag keyword" on twitter (for example "#FirstWorldProblems") I have a script that looks like this: # apply settings, create a mechanize.Browser, etc. login() # log into twitter # at this point we've logged into twitter, now, we will ...
[ "If your problem is actually just accessing Twitter, dmedvinsky is probably right.\nHowever, if you really want to be able to scrape websites (while allowing their javascript to run as it normally would..) you'll probably want something a bit more robust.\nWhile it's a lot of baggage, I strongly urge you to grab Qt...
[ 2 ]
[]
[]
[ "mechanize", "python" ]
stackoverflow_0007898660_mechanize_python.txt
Q: Encoding/decoding works in browser, but not in terminal Here's my code: import urllib print urllib.urlopen('http://www.indianexpress.com/news/heart-of-the-deal/811626/').read().decode('iso-8859-1') When I view the page in Firefox, the text is displayed correctly. However, on the terminal, I see issues with chara...
Encoding/decoding works in browser, but not in terminal
Here's my code: import urllib print urllib.urlopen('http://www.indianexpress.com/news/heart-of-the-deal/811626/').read().decode('iso-8859-1') When I view the page in Firefox, the text is displayed correctly. However, on the terminal, I see issues with character encoding. Here are some malformed output examples: lon...
[ "Try this (ignore unknown chars)\nimport urllib\nurl = 'http://www.indianexpress.com/news/heart-of-the-deal/811626/'\nprint urllib.urlopen(url).read().decode('iso-8859-1').encode('ascii','ignore')\n\n", "You need to use the actual charset sent by the server instead of always assuming it's ISO 8859-1. Using a capa...
[ 0, 0, 0 ]
[]
[]
[ "encoding", "python", "urllib" ]
stackoverflow_0006556724_encoding_python_urllib.txt
Q: any qr code generator library with unicode support? Possible Duplicate: Unicode Encoding and decoding issues in QRCode I need to generate qr code offline , but I need a library which supports unicode ( arabic language for example ) ... It doesn't matter which language is it written in , but I prefer python and ...
any qr code generator library with unicode support?
Possible Duplicate: Unicode Encoding and decoding issues in QRCode I need to generate qr code offline , but I need a library which supports unicode ( arabic language for example ) ... It doesn't matter which language is it written in , but I prefer python and php. can anyone suggest any? thank you
[ "ZXing has a Java-based encoder which will let you specify the character encoding you want to use to encode the text as bytes in the QR code. Be aware though that anything except ISO-8859-1 is not necessarily going to work, as this is the only encoding allowed in the spec.\n", "Have you tried http://phpqrcode.sou...
[ 1, 0 ]
[]
[]
[ "php", "python", "qr_code" ]
stackoverflow_0007896950_php_python_qr_code.txt
Q: Globally add an order_by on sqlalchemy entities? We are migrating from MySQL to Postgresql and one of the major features of MySQL that we relied on was the fact that objects came back in the order they were inserted. In Postgresql sort order is not guaranteed so we would like to just globally tell our SQLAlchemy ...
Globally add an order_by on sqlalchemy entities?
We are migrating from MySQL to Postgresql and one of the major features of MySQL that we relied on was the fact that objects came back in the order they were inserted. In Postgresql sort order is not guaranteed so we would like to just globally tell our SQLAlchemy entities to order by ID. We want to avoid updating eve...
[ "By default it already should be returning results 'in order' unless you overrode/modified the automatic 'id' column, if it's not you may need to fiddle with your mapper.\nCheck out the orm.mapper API, specifically the order_by setting. This is done on a somewhat meta-level to the schema.\n" ]
[ 1 ]
[]
[]
[ "mysql", "postgresql", "python", "sqlalchemy" ]
stackoverflow_0007893635_mysql_postgresql_python_sqlalchemy.txt
Q: Network multithread in python I'm writing a script in Python that will scrape some pages from my web server and put them in a file. I'm using mechanize.Browser() module for this particular task. However, I've found that creating one single instance of mechanize.Browser() is rather slow. Is there a way I could rela...
Network multithread in python
I'm writing a script in Python that will scrape some pages from my web server and put them in a file. I'm using mechanize.Browser() module for this particular task. However, I've found that creating one single instance of mechanize.Browser() is rather slow. Is there a way I could relatively painlessly use multihreading...
[ "Use gevent or eventlet to get concurrent network IO.\n", "If you want industrial strength Python web scraping, check out scrapy. It uses Twisted for async comms and is blindingly fast. Being able to spider through 50 pages per-second isn't an unrealistic expectation.\n" ]
[ 1, 1 ]
[]
[]
[ "mechanize", "multithreading", "python", "python_multithreading" ]
stackoverflow_0007831403_mechanize_multithreading_python_python_multithreading.txt
Q: Uploading Django Development to Dreamhost/Passenger first time "Could no import" I've been developing on my laptop. Now, I've uploaded my development project from Django 1.2/Python 2.7 up to Dreamhost created using the Passenger setup. I am using South for migration. I modified settings.py to access MySQL. Got...
Uploading Django Development to Dreamhost/Passenger first time "Could no import"
I've been developing on my laptop. Now, I've uploaded my development project from Django 1.2/Python 2.7 up to Dreamhost created using the Passenger setup. I am using South for migration. I modified settings.py to access MySQL. Got Admin working. Questions: 1) Where is the std out shown when you hit the site? (all m...
[ "\"Could not import settings 'pholdershare.settings'\"\n...usually means either settings.py has an import error or syntax error, or pholdershare has not been added to sys.path in your wsgi.py \n" ]
[ 0 ]
[]
[]
[ "django", "dreamhost", "installation", "python" ]
stackoverflow_0003249575_django_dreamhost_installation_python.txt
Q: How to parse a mixed CSV file in Python? I am dealing with a CSV file similar to this one foo; val1; position1 bar; name1; address1; phone_nbr1 bar; name2; address2; phone_nbr2 foo; val2; position2 bar; name3; address3; phone_nbr3 bar; name4; address4; phone_nbr4 bar; name5; address5; phone_nbr5 bar; name6; addres...
How to parse a mixed CSV file in Python?
I am dealing with a CSV file similar to this one foo; val1; position1 bar; name1; address1; phone_nbr1 bar; name2; address2; phone_nbr2 foo; val2; position2 bar; name3; address3; phone_nbr3 bar; name4; address4; phone_nbr4 bar; name5; address5; phone_nbr5 bar; name6; address6; phone_nbr6 foo; val3; position3 Needless ...
[ "You could collect the records from a csv.reader in two different lists, depending on their length (or whatever criterion you use to distinguish the two streams):\nlist1 = []\nlist2 = []\nwith open(\"input.csv\", \"rb\") as f:\n for record in csv.reader(f, delimiter=\";\"):\n if len(record) == 3:\n ...
[ 6, 4, 1, 0, 0, 0 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0007902658_csv_python.txt
Q: In Python, can a dict with currentThread() as key cause memory leaks? I'm debugging memory leaks in a Django application, and could something curious in django_cachepurge: from threading import currentThread _urls_to_purge = {} def add_purge_url(url): # .... _urls_to_purge.setdefault(currentThread(), se...
In Python, can a dict with currentThread() as key cause memory leaks?
I'm debugging memory leaks in a Django application, and could something curious in django_cachepurge: from threading import currentThread _urls_to_purge = {} def add_purge_url(url): # .... _urls_to_purge.setdefault(currentThread(), set()).add(url) Is such construct prone to memory leaks? I suspect so, unles...
[ "I don't know what currentThread returns, but you probably can use the built-in id or hash functions on it to get a safe value.\nIf lookup isn't enough, e.g. because you want to iterate over the container, there is weakref.WeakKeyDictionary.\n" ]
[ 1 ]
[]
[]
[ "django", "memory_leaks", "multithreading", "python" ]
stackoverflow_0007902739_django_memory_leaks_multithreading_python.txt
Q: python count items in list and keep their order of occurrance Given: a list, such as l=[4,4,4,4,5,5,5,6,7,7,7] Todo: get the count of an element and keep their occurrence order, e.g.: [(4,4),(5,3),(6,1),(7,3)] I could do it with: tmpL = [(i,l.count(i)) for i in l] tmpS = set() cntList = [x for x in tmpL if x...
python count items in list and keep their order of occurrance
Given: a list, such as l=[4,4,4,4,5,5,5,6,7,7,7] Todo: get the count of an element and keep their occurrence order, e.g.: [(4,4),(5,3),(6,1),(7,3)] I could do it with: tmpL = [(i,l.count(i)) for i in l] tmpS = set() cntList = [x for x in tmpL if x not in tmpS and not tmpS.add(x)] But is there a better way? I hav...
[ "Use groupby:\n>>> l = [4,4,4,4,5,5,5,6,7,7,7,2,2]\n>>> from itertools import groupby\n>>> [(i, l.count(i)) for i,_ in groupby(l)]\n[(4, 4), (5, 3), (6, 1), (7, 3), (2, 2)]\n\n", ">>> import itertools\n>>> [(k, len(list(g))) for k, g in itertools.groupby(l)]\n[(4, 4), (5, 3), (6, 1), (7, 3)]\n\nThis keeps the ord...
[ 11, 10, 2 ]
[]
[]
[ "python" ]
stackoverflow_0007902924_python.txt
Q: Compiling python code into a single exe I've been trying to compile python code into a single exe, and i didn't manage to do it correctly. I've tried pyinstaller, and this is the .spec file: # -*- mode: python -*- a = Analysis([os.path.join(HOMEPATH,'support\\_mountzlib.py'), os.path.join(HOMEPATH,'support\\useUn...
Compiling python code into a single exe
I've been trying to compile python code into a single exe, and i didn't manage to do it correctly. I've tried pyinstaller, and this is the .spec file: # -*- mode: python -*- a = Analysis([os.path.join(HOMEPATH,'support\\_mountzlib.py'), os.path.join(HOMEPATH,'support\\useUnicode.py'), 'programs\\toolbox.py'], ...
[ "My two cents: did you make a test using the debug option of PyInstaller?\nJust update your specfile:\nexe = EXE( pyz,\n [...]\n debug=True,\n [...])\n\n(Note: in order to avoid numerous message boxes, you may want to set console output: console=True)\nMaybe it would return some useful...
[ 2 ]
[]
[]
[ "compilation", "py2exe", "pyinstaller", "python", "python_2.7" ]
stackoverflow_0007879465_compilation_py2exe_pyinstaller_python_python_2.7.txt
Q: Django Model Inheritance query a central table I have a solution that I thought I could take care of model inheritance, but now looking at it again it doesn't actually solve my problem. What I would like is to be able to call one model and then have the fields of the children model accessible to me. With inherit...
Django Model Inheritance query a central table
I have a solution that I thought I could take care of model inheritance, but now looking at it again it doesn't actually solve my problem. What I would like is to be able to call one model and then have the fields of the children model accessible to me. With inheritance I still have to put the child model name in the...
[ "I haven't used it, but this project looks like what you're looking for:\nhttps://code.google.com/p/django-polymorphic-models/\nYou can request LessonModule.objects.all() and then .downcast() each object automatically into a ProfileImage or a Note.\nOr add the PolymorphicMetaclass to your LessonModule to always ret...
[ 2 ]
[]
[]
[ "django", "python", "sql" ]
stackoverflow_0005735124_django_python_sql.txt
Q: How to Replace Strings and Create HTML Files with Functions I have a CSV file that I have to import and take each row of the file and print out in a HTML to create 5 separate files for each 5 rows in the CSV file. Here is a link to DL the CSV file. Here is my code so far: import csv original = file('southpark.c...
How to Replace Strings and Create HTML Files with Functions
I have a CSV file that I have to import and take each row of the file and print out in a HTML to create 5 separate files for each 5 rows in the CSV file. Here is a link to DL the CSV file. Here is my code so far: import csv original = file('southpark.csv', 'rU') reader = csv.reader(original) BigList = [] html_str...
[ "Here are some hints for what appears a bit like homework.\nYou already know how to parse the csv file, so you've done quite the hardest. Now, you just have to use the content of each line correctly.\nA function is useful when you need to do execute the same task several times, or to execute similar tasks. A list i...
[ 0 ]
[]
[]
[ "function", "html", "python", "string" ]
stackoverflow_0007883505_function_html_python_string.txt
Q: Can Super deal with multiple inheritance? When inheriting from two objects like these class Foo(object): def __init__(self,a): self.a=a class Bar(object): def __init__(self,b): self.b=b I would normally do something like this class FooBar(Foo,Bar): def __init__(self,a,b): Foo.__init__(self,a) ...
Can Super deal with multiple inheritance?
When inheriting from two objects like these class Foo(object): def __init__(self,a): self.a=a class Bar(object): def __init__(self,b): self.b=b I would normally do something like this class FooBar(Foo,Bar): def __init__(self,a,b): Foo.__init__(self,a) Bar.__init__(self,b) How does super know if...
[ "Using super(), __init__() and multiple inheritance is a bit tricky.\nIn the normal flow of things, every method calls super(), with the classes that inherit only from object doing a little extra work to make sure that the method actually exists: it'll look a bit like this:\n>>> class Foo(object):\n... def frob...
[ 8, 2 ]
[]
[]
[ "multiple_inheritance", "python" ]
stackoverflow_0007903398_multiple_inheritance_python.txt
Q: Using a variable with re.compile for issn in inputList: link = journalresults.find('a', attrs={'href' : re.compile(issn + '$')}) I am trying to use the variable 'issn' with re.compile and append '$' after it but have tried umpteen combinations while searching for a resolution that all have come up unsuc...
Using a variable with re.compile
for issn in inputList: link = journalresults.find('a', attrs={'href' : re.compile(issn + '$')}) I am trying to use the variable 'issn' with re.compile and append '$' after it but have tried umpteen combinations while searching for a resolution that all have come up unsucessful. Obviously I am missing someth...
[ "Did you check what type the variable issn is? Use print >>sys.stderr, repr(issn) and check what you get. Additionally, what error message is printed? Did you debug your program, for example by using import pdb at the top and using pdb.set_trace() right before the compile statement?\n" ]
[ 0 ]
[]
[]
[ "beautifulsoup", "python", "variables" ]
stackoverflow_0007903648_beautifulsoup_python_variables.txt
Q: hadoop cluster: map task run only on one machine and not all I have a hadoop cluster of three machines where one machine acts as both master and slave. When I run wordcount-example, it run map tasks on two machines - worker1 and worker2. But when I run my own code, it runs only on one machine - worker1, how can...
hadoop cluster: map task run only on one machine and not all
I have a hadoop cluster of three machines where one machine acts as both master and slave. When I run wordcount-example, it run map tasks on two machines - worker1 and worker2. But when I run my own code, it runs only on one machine - worker1, how can I make map tasks run on all machines? Input Split Locations /d...
[ "How big is your input? Hadoop splits up the jobs into input splits, and if your file is too small, it will only have one split.\nTry a larger file-- say around 1GB in size and see how mappers you get then.\n\nYou can also check to make sure that every TaskTracker is reporting properly to the JobTracker. If there i...
[ 1 ]
[]
[]
[ "hadoop", "hadoop_streaming", "mapreduce", "python" ]
stackoverflow_0007895681_hadoop_hadoop_streaming_mapreduce_python.txt
Q: Run jasper report (created with iReport) from within python without jasperserver? Is there a way to run a jasper report from within python without using jasper server. We have jasper server up and running but there is some additional overhead by using this method and an extra layer of complexity. If it can be elim...
Run jasper report (created with iReport) from within python without jasperserver?
Is there a way to run a jasper report from within python without using jasper server. We have jasper server up and running but there is some additional overhead by using this method and an extra layer of complexity. If it can be eliminated then great if not then our current solution will have to do.
[ "You can try pyJasper: http://pypi.python.org/pypi/pyJasper/0.4\nI have no experience with that module myself.\n" ]
[ 1 ]
[]
[]
[ "jasper_reports", "python" ]
stackoverflow_0007903557_jasper_reports_python.txt
Q: create a string of variable length in python i need to create a string consisting of spaces, and the length of the string needs to be determined at runtime. here is what i am doing: suffix = "".join([' ' for x in range(0, max)]) There must be a better way, a more clever way, and an easier way. what are the ways? ...
create a string of variable length in python
i need to create a string consisting of spaces, and the length of the string needs to be determined at runtime. here is what i am doing: suffix = "".join([' ' for x in range(0, max)]) There must be a better way, a more clever way, and an easier way. what are the ways? edit: well this is simpler then i imagined. there ...
[ "Don't use max for a variable name.\nsuffix = ' ' * nb_spaces\n\n", "Use string \"multiplication.\"\nsuffix = \" \" * numSpaces\n\n", "Use string multiplication.\n>>> print \"x\" * 5\nxxxxx\n\n" ]
[ 3, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007904295_python.txt
Q: Python IRC bot with support for plugins and not command only I have just made a script in Python which will connect to my MySQL database every XX second and check for new posts on my forum. If there are any new posts, I would like to have the user's of my IRC channel notified. To do this I need to hook up my scrip...
Python IRC bot with support for plugins and not command only
I have just made a script in Python which will connect to my MySQL database every XX second and check for new posts on my forum. If there are any new posts, I would like to have the user's of my IRC channel notified. To do this I need to hook up my script with an IRC bot. I have been searching around to find an IRC bot...
[ "You could always take a look at Twisted, which is supposed to make it very easy for you to create your own IRC bot:\nhttp://twistedmatrix.com/documents/10.0.0/api/twisted.words.protocols.irc.IRC.html\n", "you should easily find a python IRC client library which would let you do (almost) anything you want directl...
[ 1, 0, 0, 0 ]
[]
[]
[ "bots", "irc", "python" ]
stackoverflow_0007530994_bots_irc_python.txt
Q: Default value of memberfunction in python class foo(): def __init__(self,a): self.A=a def foo2(self,aa=self.A): return "la" @classmethod def test(cls): d=foo() d.foo2() The memberfunction foo2 cannot find self.A nor A. Is it because A is not globally set inside the...
Default value of memberfunction in python
class foo(): def __init__(self,a): self.A=a def foo2(self,aa=self.A): return "la" @classmethod def test(cls): d=foo() d.foo2() The memberfunction foo2 cannot find self.A nor A. Is it because A is not globally set inside the class?
[ "Keyword arguments, such as aa, cannot take on a default value from self. Keyword arguments are evaluated when the method is defined, not when it is called. Typically one would achieve what you're trying by setting the default of aa to None:\nclass foo():\n def __init__(self, a):\n self.A = a\n def f...
[ 4, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007904318_python.txt
Q: Retrieving the US Postal Zip code for a street address using Python What is the most efficient way one would go about retrieving the U.S. Postal zip code for a street address using Python? Is this something that is even possible? Preferably, something that includes a local database as oppose to a remote API call o...
Retrieving the US Postal Zip code for a street address using Python
What is the most efficient way one would go about retrieving the U.S. Postal zip code for a street address using Python? Is this something that is even possible? Preferably, something that includes a local database as oppose to a remote API call of some sort. Thanks in advance for any help one may be able to offer.
[ "May be a start:\nThe Zip Code Database Project\ngooglemaps – Google Maps and Local Search APIs in Python\nGoogleMaps.geocode(query, sensor='false', oe='utf8', ll='', spn='', gl='')\n\n\nGiven a string address query, return a dictionary of information\n about that location, including its\n latitude and longitude....
[ 4, 0 ]
[]
[]
[ "gis", "python" ]
stackoverflow_0003663556_gis_python.txt
Q: How to execute a .exe file from python file I am trying to open google.com with Internet Explorer. This is my program: import subprocess arg = ['runas', '/user:Administrator', "C:\Program Files (x86)\Internet Explorer\iexplore.exe", "www.google.com"] subprocess.call(arg) I saved this file as shortform.py...
How to execute a .exe file from python file
I am trying to open google.com with Internet Explorer. This is my program: import subprocess arg = ['runas', '/user:Administrator', "C:\Program Files (x86)\Internet Explorer\iexplore.exe", "www.google.com"] subprocess.call(arg) I saved this file as shortform.py and executed it. The program worked but it doesn...
[ "Use this:\nimport subprocess\n\narg = ['runas', '/user:Administrator', \"C:\\Program Files (x86)\\Internet Explorer\\iexplore.exe www.google.com\"]\nsubprocess.call(arg)\n\n" ]
[ 1 ]
[]
[]
[ "exe", "python", "subprocess" ]
stackoverflow_0007904584_exe_python_subprocess.txt
Q: GAE unsubscribe from a user's presence Is there a way to unsubscribe from a user's presence? I no longer want to receive updates on /_ah/xmpp/presence/... for a particular user. I can't seem to find a simple API call to do that. After digging around the XMPP protocol I found this which seems to indicate that doin...
GAE unsubscribe from a user's presence
Is there a way to unsubscribe from a user's presence? I no longer want to receive updates on /_ah/xmpp/presence/... for a particular user. I can't seem to find a simple API call to do that. After digging around the XMPP protocol I found this which seems to indicate that doing a send_presence with presence type of 'uns...
[ "It seems that you can't. The docs (and the docstring) confirm that presence_type accepts a subset of the types defined in RFC 3921.\nYou can submit this as a feature request to the issue tracker.\n", "As an experiment, you could re-implement your own \"send_presence\" that does the same thing as the existing fu...
[ 3, 2 ]
[]
[]
[ "google_app_engine", "python", "xmpp" ]
stackoverflow_0007896843_google_app_engine_python_xmpp.txt
Q: Celery creates several instances of Task I'm creating a task (by subclassing celery.task.Task) that creates a connection to Twitter's streaming API. For the Twitter API calls, I am using tweepy. As I've read from the celery-documentation, 'a task is not instantiated for every request, but is registered in the task...
Celery creates several instances of Task
I'm creating a task (by subclassing celery.task.Task) that creates a connection to Twitter's streaming API. For the Twitter API calls, I am using tweepy. As I've read from the celery-documentation, 'a task is not instantiated for every request, but is registered in the task registry as a global instance.' I was expecti...
[ "The task should only be instantiated once, if you think it is not for some reason,\nI suggest you add a\nprint(\"INSTANTIATE\")\n import traceback\n traceback.print_stack()\nto the Task.__init__ method, so you could tell where this would be happening.\nI think your task could be better expressed like this:\nfr...
[ 0 ]
[]
[]
[ "celery", "django", "python", "tweepy" ]
stackoverflow_0007888885_celery_django_python_tweepy.txt
Q: Adding a Log entry for an action by a user in a Django App I need to create a log entry for changes made by a user to the database via the views in my django application. I have enabled the django-admin module and I can retrieve the logs of the changes made using the admin interface like this: from django.contrib...
Adding a Log entry for an action by a user in a Django App
I need to create a log entry for changes made by a user to the database via the views in my django application. I have enabled the django-admin module and I can retrieve the logs of the changes made using the admin interface like this: from django.contrib.admin.models import LogEntry from django.contrib.contenttypes.m...
[ "You're very close. You just need to create new LogEntry objects and save them. LogEntry has a shortcut function on objects to do this.\nfrom django.contrib.admin.models import LogEntry, ADDITION, CHANGE\n\nLogEntry.objects.log_action(\n user_id=request.user.id,\n content_type_id=ContentType.o...
[ 49 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0007905106_django_django_admin_python.txt
Q: Parsing a function from keyboard and executing it I'm writing an application in Python 3 that processes a lot of mathematical equations. In theory, I'd have to write a different function inside the code each time I need this application. I'd like to enter a function (a mathematical function) from keyboard, to save...
Parsing a function from keyboard and executing it
I'm writing an application in Python 3 that processes a lot of mathematical equations. In theory, I'd have to write a different function inside the code each time I need this application. I'd like to enter a function (a mathematical function) from keyboard, to save a lot of time and make this application more versatile...
[ "Take a look at Sage.\nIt's an awesome Python-based CAS that does exactly what you wish.\nYou can import Sage's modules and use its equation parser, as that can handle functions, variables, solve for variables, simplify, etc.\n", "Use compile, eval and exec to create and execute code objects from a string at runt...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007905296_python.txt
Q: Python Generator Indexing Optimization Let's say I have a generator that I want to pull the 10th element from but ignore the first 9. The generator is a function I've written that looks something like this: def myGenerator(arg1, arg2): for i in arg1: myState = doSomeWork(i, arg2) yield expensi...
Python Generator Indexing Optimization
Let's say I have a generator that I want to pull the 10th element from but ignore the first 9. The generator is a function I've written that looks something like this: def myGenerator(arg1, arg2): for i in arg1: myState = doSomeWork(i, arg2) yield expensiveOperation(myState) Now I can use it and g...
[ "The generator is isolated from its consumer -- it doesn't know what is being throw away. So, yes, it does the expensive operation at every step.\nI would just move the expensive operation outside the generator:\ndef myGenerator(arg1, arg2):\n for i in arg1:\n myState = doSomeWork(i, arg2)\n yield...
[ 5, 4, 1, 0 ]
[]
[]
[ "generator", "python" ]
stackoverflow_0007904816_generator_python.txt
Q: Django annotate Count query output I have confusion in result of these queries: >>> [f.count for f in Favourite.objects.annotate(count = Count('object_id'))] [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] and second one is >>> [f['count'] for f in Favourite.objects.values('object_id').annotate(count...
Django annotate Count query output
I have confusion in result of these queries: >>> [f.count for f in Favourite.objects.annotate(count = Count('object_id'))] [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] and second one is >>> [f['count'] for f in Favourite.objects.values('object_id').annotate(count=Count('object_id'))] [1, 5, 2, 1, 4, 2,...
[ "The second one is doing a group by on object_id. This is the expected behaviour. The first one is simply counting object_id for each row in the database.\n" ]
[ 4 ]
[]
[]
[ "annotations", "count", "django", "python" ]
stackoverflow_0007905334_annotations_count_django_python.txt
Q: Is REST via cross-domain AJAX a bad idea at this time (2011)? I am writing a REST service that is to be accessed by web applications, desktop clients, mobile clients etc. via a REST interface. The idea is to store objects like notes, calendar events etc. in a common hierarchy and to provide HTTP methods for creat...
Is REST via cross-domain AJAX a bad idea at this time (2011)?
I am writing a REST service that is to be accessed by web applications, desktop clients, mobile clients etc. via a REST interface. The idea is to store objects like notes, calendar events etc. in a common hierarchy and to provide HTTP methods for creating, updating and deleting documents, so this should be the ideal s...
[ "There is nothing stopping you providing responses in standard JSON (e.g. for instances where CORS is available in the browser), and in JSONP in the cases it isn't. It won't affect anything but your output.\nI would not say CORS is viable by itself as IE < 8 does not support it. I would also say that there is nothi...
[ 1 ]
[]
[]
[ "ajax", "cors", "jquery", "python", "tornado" ]
stackoverflow_0007905634_ajax_cors_jquery_python_tornado.txt
Q: selenium webdriver: form data not present after submit I have a page in which I log in and then fill in some forms. After submitting the first form, a new page appears with new forms. Some data is taken from the forms before (as it should be), but some data is missing. If I do exactly the same I do with webdriver ...
selenium webdriver: form data not present after submit
I have a page in which I log in and then fill in some forms. After submitting the first form, a new page appears with new forms. Some data is taken from the forms before (as it should be), but some data is missing. If I do exactly the same I do with webdriver by hand, everything works fine and all the data from form 1 ...
[ "Visit the cookie section of this tutorial\nhttp://readthedocs.org/docs/selenium-python/en/latest/navigating.html\n" ]
[ 1 ]
[]
[]
[ "python", "selenium", "selenium_webdriver" ]
stackoverflow_0007179983_python_selenium_selenium_webdriver.txt
Q: New instance of class with a non-None class attribute? I have a Python class that has a class attribute set to something other than None. When creating a new instance, the changes made to that attribute perpetuates through all instances. Here's some code to make sense of this: class Foo(object): a = [] b = ...
New instance of class with a non-None class attribute?
I have a Python class that has a class attribute set to something other than None. When creating a new instance, the changes made to that attribute perpetuates through all instances. Here's some code to make sense of this: class Foo(object): a = [] b = 2 foo = Foo() foo.a.append('item') foo.b = 5 Using foo....
[ "Yes, this is how it is supposed to work.\nIf a and b belong to the instance of Foo, then the correct way to do this is:\nclass Foo(object):\n def __init__(self):\n self.a = []\n self.b = 2\n\nThe following makes a and b belong to the class itself, so all instances share the same variables:\nclass Foo(obj...
[ 8, 1, 1, 0 ]
[]
[]
[ "class_instance_variables", "python", "python_2.7" ]
stackoverflow_0007903845_class_instance_variables_python_python_2.7.txt
Q: Multiple File upload and send in email - AppEngine & Blobstore Hi I am new at this so please be gentle! I have a HTML web form that I need to allow for multiple file upload using Python/Django/AppEngine. The files should be stored within the Blobstore when uploaded and then sent as attachments within an email whic...
Multiple File upload and send in email - AppEngine & Blobstore
Hi I am new at this so please be gentle! I have a HTML web form that I need to allow for multiple file upload using Python/Django/AppEngine. The files should be stored within the Blobstore when uploaded and then sent as attachments within an email which will be sent via the system. Could someone provide a simple code e...
[ "\nUploading multiple files to the blobstore\nSending mail with attachments\n\n" ]
[ 1 ]
[]
[]
[ "django_templates", "google_app_engine", "python" ]
stackoverflow_0007905848_django_templates_google_app_engine_python.txt
Q: xml-rpc python doesn't print output I'm trying to get an IBM tutorialworks example working but until now there hasn't been any luck server: import calendar, SimpleXMLRPCServer #The server object class Calendar: def getMonth(self, year, month): return calendar.month(year, month) def getYear(self, ...
xml-rpc python doesn't print output
I'm trying to get an IBM tutorialworks example working but until now there hasn't been any luck server: import calendar, SimpleXMLRPCServer #The server object class Calendar: def getMonth(self, year, month): return calendar.month(year, month) def getYear(self, year): return calendar.calendar(y...
[ "My guess is that something is blocking the low-level bind call to port 8888 in your server process. Run netstat -tlp as root if you can. If you can't, use telnet localhost 8888 to see what if anything is listening.\n" ]
[ 1 ]
[]
[]
[ "python", "simplexmlrpcserver", "xml_rpc" ]
stackoverflow_0007905954_python_simplexmlrpcserver_xml_rpc.txt
Q: PyGtk equivalent of gdk_window_ensure_native? Is there an equivalent to gdk_window_ensure_native in PyGtk? I need it to unbreak drawing OpenGl to widget in Gtk >= 2.18. A: You can get the gtk.gdk.Window of a widget/window using gtk.Widget.get_window(), and then use undocumented gtk.gdk.Window.ensure_native(), e....
PyGtk equivalent of gdk_window_ensure_native?
Is there an equivalent to gdk_window_ensure_native in PyGtk? I need it to unbreak drawing OpenGl to widget in Gtk >= 2.18.
[ "You can get the gtk.gdk.Window of a widget/window using gtk.Widget.get_window(), and then use undocumented gtk.gdk.Window.ensure_native(), e.g.: my_widget.get_window().ensure_native(). Works at least with pygtk2-2.17.0 I have available at hand.\n", "Yes, there is:\n>>> import gtk\n>>> w = gtk.Window()\n>>> w.sho...
[ 4, 1 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0007903455_gtk_pygtk_python.txt
Q: Python Gedit plugin with GTK, tree store filter runtime recursion error I have a problem writing a gedit plugin in python, using PyGTK. The basic job of the plugin is to filter a tree store basing the text typed in a text entry. The search is a 'live' search, that is, there are no button to press, the search is pe...
Python Gedit plugin with GTK, tree store filter runtime recursion error
I have a problem writing a gedit plugin in python, using PyGTK. The basic job of the plugin is to filter a tree store basing the text typed in a text entry. The search is a 'live' search, that is, there are no button to press, the search is performed on the event 'key_release_event' which is handled by the method .refi...
[ "While I don't have an exact solution to your problem, I might be able to help you focus in on what is going wrong.\nI have stumbled across the 'maximum recursion depth exceeded' as well, and like your code, there was no recursion anywhere in the code. What had happened was that I had a large set of very large tre...
[ 0 ]
[]
[]
[ "gedit", "gtk", "plugins", "pygtk", "python" ]
stackoverflow_0007905205_gedit_gtk_plugins_pygtk_python.txt
Q: I need an object to do anything Or at least, to pretend to do anything. >>> three = Three() >>> three.value() 3 >>> three.sqrt() 3 >>> three.close() 3 >>> three.someRandomFunctionWithMadeUpParameters("hello, world", math.PI, True) 3 >>> three.stopSayingThreeDamnIt() 3 Is it possible to implement class Three in Py...
I need an object to do anything
Or at least, to pretend to do anything. >>> three = Three() >>> three.value() 3 >>> three.sqrt() 3 >>> three.close() 3 >>> three.someRandomFunctionWithMadeUpParameters("hello, world", math.PI, True) 3 >>> three.stopSayingThreeDamnIt() 3 Is it possible to implement class Three in Python 2.6 ?
[ "class Three(object):\n def __getattr__(self, name):\n return lambda *args, **kw: 3\n\n", "class MetaThree(type):\n def __repr__(cls):\n return '3'\n def __getattr__(cls,key):\n return Three\n\nclass Three(object):\n __metaclass__=MetaThree\n def __init__(self,*args,**kwargs):\...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007906778_python.txt
Q: Celery - schedule periodic tasks starting at a specific time What is the best way to schedule a periodic task starting at specific datetime? (I'm not using cron for this considering I've the need to schedule about a hundred remote rsyncs, where I compute the remote vs local offset and would need to rsync each pat...
Celery - schedule periodic tasks starting at a specific time
What is the best way to schedule a periodic task starting at specific datetime? (I'm not using cron for this considering I've the need to schedule about a hundred remote rsyncs, where I compute the remote vs local offset and would need to rsync each path the second the logs are generated in each host.) By my understan...
[ "Celery seems like a good solution for your scheduling problem: Celery's PeriodicTasks have run time resolution in seconds.\nYou're using an appropriate tool here, but the crontab entry is not what you want. You want to use python's datetime.timedelta object; the crontab scheduler in celery.schedules has only minu...
[ 12 ]
[ "I've recently worked on a task that involved Celery, and I had to use it for asynchronous operation as well as scheduled tasks. Suffice to say I resorted back to the old crontab for the scheduled task, although it calls a python script that spawns a separate asynchronous task. This way I have less to maintain for ...
[ -1 ]
[ "celery", "python", "scheduled_tasks" ]
stackoverflow_0007848512_celery_python_scheduled_tasks.txt
Q: How to manipulate digits within an integer/string? I am looking for a general way to refer to particular digits in a integer or string, I need to be able to perform different operations on alternating digits and sum the result of all of those returned values. Any help is much appreciated Oh and I am a complete beg...
How to manipulate digits within an integer/string?
I am looking for a general way to refer to particular digits in a integer or string, I need to be able to perform different operations on alternating digits and sum the result of all of those returned values. Any help is much appreciated Oh and I am a complete beginner so idiot-proof answers would be appreciated. I wil...
[ "If you're starting with an integer, first convert it to a string; you can't address the digits within an integer conveniently:\n>>> myint = 979\n>>> mystr = str(myint)\n>>> mystr\n'979'\n\nAddress individual digits with their index in square brackets, starting from zero:\n>>> mystr[1]\n'7'\n\nConvert those digits ...
[ 4, 0, 0 ]
[]
[]
[ "digits", "integer", "python", "string" ]
stackoverflow_0007906846_digits_integer_python_string.txt
Q: Scrolling model dialog in gtk3? how to do it does any one know how to create a modal dialog that scrolls in from the top of the parent window (like the about window in glade 3.10). I'm using Glade 3.10 with python. I tried creating a dialog and a normal window, setting it's properties to modal and popup,... but th...
Scrolling model dialog in gtk3? how to do it
does any one know how to create a modal dialog that scrolls in from the top of the parent window (like the about window in glade 3.10). I'm using Glade 3.10 with python. I tried creating a dialog and a normal window, setting it's properties to modal and popup,... but that doesn't seem to do the trick, any ideas? Thanks...
[ "You have to set the dialog transient for the parent window.\n" ]
[ 0 ]
[]
[]
[ "glade", "gtk3", "pygtk", "python" ]
stackoverflow_0007906008_glade_gtk3_pygtk_python.txt
Q: A combinations_with_replacement function in fortran? I wrote a small module in python for get all the possibilities of x products that fit into y total cost. The module runs fine, but slow. It takes about six hours to calculate six products up to 30 iterations of each product. So, I was thinking of rewriting the s...
A combinations_with_replacement function in fortran?
I wrote a small module in python for get all the possibilities of x products that fit into y total cost. The module runs fine, but slow. It takes about six hours to calculate six products up to 30 iterations of each product. So, I was thinking of rewriting the script in FORTRAN and see if I can't milk out some better s...
[ "Don't do that. You are trying to do micro-optimization when you need to be doing algorithmic optimization. This is why I argued you should not use the exponential-time solution based on itertools, but a better, recursive solution.\n", "FWIW, the itertools documentation has a pure python equivalent for combinat...
[ 2, 0 ]
[]
[]
[ "combinatorics", "fortran", "python", "python_itertools" ]
stackoverflow_0007906461_combinatorics_fortran_python_python_itertools.txt
Q: Delete some dots on the beginning of a string in python I have some strings which starts with dots, and I want to delete it. Which is the best way. And if the next caracter isn't a "/" add it. I'm new in python and I've been trying to do something like this to erase dots but there is a syntax error. while (re.matc...
Delete some dots on the beginning of a string in python
I have some strings which starts with dots, and I want to delete it. Which is the best way. And if the next caracter isn't a "/" add it. I'm new in python and I've been trying to do something like this to erase dots but there is a syntax error. while (re.match(r'\.*', url[0]).end()) = 0: url = url[1:] ..../xxx --...
[ "To get rid of the dots:\nmystr = '...../your_string'\nmystr = '/' + mystr.lstrip('./')\n\nand the result should be:\n\n/your_string\n\nregardless of whether it begins with dots or slashes (they all will be replaced with single slash).\n", "Try with:\nbadUrl = \"..../xxx\"\nurl = \"/\" + badUrl.lstrip(\"./\")\n\n...
[ 11, 5, 4, 1 ]
[]
[]
[ "python", "regex", "string" ]
stackoverflow_0007906854_python_regex_string.txt
Q: Images that has been deleted from database,be deleted from storage,too I have these models: class Gallery(models.Model): HeadImage = models.ImageField(upload_to="gallery") class Image(models.Model): Image = models.ImageField(upload_to="gallery") Gallery = models.ForeignKey(Gallery, related_name='images')...
Images that has been deleted from database,be deleted from storage,too
I have these models: class Gallery(models.Model): HeadImage = models.ImageField(upload_to="gallery") class Image(models.Model): Image = models.ImageField(upload_to="gallery") Gallery = models.ForeignKey(Gallery, related_name='images') class Tour(models.Model): Name=models.CharField(max_length=100) Coun...
[ "You can override the delete() method on a model to do what you want.\nhttps://docs.djangoproject.com/en/dev/topics/db/models/#overriding-predefined-model-methods\nclass Image:\n #other code is here\n\n def delete(self, *args, **kwargs):\n #code to remove from file system goes here\n super(Image...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007907424_django_python.txt
Q: Finding IP addresses using regular expression in python I am trying to parse the results of the TSHARK capture Here is the line I am filtering on: Internet Protocol, Src: 10.10.52.250 (10.10.52.250), Dst: 224.0.0.2 (224.0.0.2) I am trying to extract the Src and Dst, Here is my code to do that: str(re.search("Src:...
Finding IP addresses using regular expression in python
I am trying to parse the results of the TSHARK capture Here is the line I am filtering on: Internet Protocol, Src: 10.10.52.250 (10.10.52.250), Dst: 224.0.0.2 (224.0.0.2) I am trying to extract the Src and Dst, Here is my code to do that: str(re.search("Src:\s[0-9\.]{7-15}", a, re.I|re.M).group())[5:] str(re.search("D...
[ "Looking at the Python regex howto, shouldn't that be {7,15}?\n", "for match in re.finditer(r\"\\((\\b(?:(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?))\\b\\)\", subject):\n\nThis should match any IPV4 IP address. Actual IPs are captured into group 1.\nWhile your regex may work, it is...
[ 3, 3, 2, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007907303_python_regex.txt
Q: Django ORM SELECT with join Models in django: class Key(models.Model): id = models.AutoField(primary_key=True, blank=True) name = models.CharField(max_length=50) class Record(models.Model): id = models.AutoField(primary_key=True, blank=True) project_id = models.IntegerField() nam...
Django ORM SELECT with join
Models in django: class Key(models.Model): id = models.AutoField(primary_key=True, blank=True) name = models.CharField(max_length=50) class Record(models.Model): id = models.AutoField(primary_key=True, blank=True) project_id = models.IntegerField() name = models.CharField(max_...
[ "The following selects the values related to particular record id. You can then follow the foreign keys to get the related record and key. Using select_related minimises database lookups. \n# Select all values related to a record in your view\nrecord = Record.objects.get(pk=record_id)\nvalues = Value.objects.filter...
[ 9, 2 ]
[]
[]
[ "django", "django_models", "django_orm", "python" ]
stackoverflow_0007907252_django_django_models_django_orm_python.txt
Q: python file list search (I have two matching strings but python doesn't think they are equal) if your input is john why isn't the if statement kicking in???? studentname.txt john 34 paul 37 poop 45 above is whats in studentname.txt b=a name = input('students name : ') list1=[] file=open('studentname.txt','r') f...
python file list search (I have two matching strings but python doesn't think they are equal)
if your input is john why isn't the if statement kicking in???? studentname.txt john 34 paul 37 poop 45 above is whats in studentname.txt b=a name = input('students name : ') list1=[] file=open('studentname.txt','r') for (a) in file: list1.append(a) b=a[:-3] why isn't this next if statement tripping...
[ "You are picking up newlines. Depending on the os you created the file on, you'll have different new line characters. The safest way to rid yourself of this is:\na = a.rstrip()\n\nThat will take care of any trailing whitespace.\nYou could also do:\nfor a in map(lambda x: x.rstrip(), file):\n\nAlso, don't name your ...
[ 1, 0, 0 ]
[ "Your immediate problem is as others have mentioned that you are not aware of the \\n at the end of your data. print and the repr built-in function are your friends; use them:\nif name != b:\n print repr(name), repr(b)\n\nwhereupon the cause of the problem becomes obvious.\nHere is some (untested) code that illu...
[ -3 ]
[ "file", "list", "python", "split" ]
stackoverflow_0007906173_file_list_python_split.txt
Q: How can I get (and set) current bash cursor position when using python readline? I have a python script that takes manages the stdin, stdout, and stderr of any application and allows for readline to be inserted gracefully. Think of any application that has lots of console output, but also accepts commands from std...
How can I get (and set) current bash cursor position when using python readline?
I have a python script that takes manages the stdin, stdout, and stderr of any application and allows for readline to be inserted gracefully. Think of any application that has lots of console output, but also accepts commands from stdin. In any case, my script uses these two functions: def blank_current_readline(): ...
[ "Might I suggest Python curses?\nHere is the Basic how-to\n\nThe curses module provides an interface to the curses library, the de-facto standard for portable advanced terminal handling.\nWhile curses is most widely used in the Unix environment, versions are available for DOS, OS/2, and possibly other systems as we...
[ 4 ]
[]
[]
[ "bash", "python", "readline" ]
stackoverflow_0007907827_bash_python_readline.txt
Q: How to create linux users via my own GUI application in Python? I want to write GUI aplication for creating linux users in pyGTK. In linux console it's not a problem, because of the commands useradd and adduser, but I don't know how to do that via GUI application? I want to create GUI form with 3 entries (first "n...
How to create linux users via my own GUI application in Python?
I want to write GUI aplication for creating linux users in pyGTK. In linux console it's not a problem, because of the commands useradd and adduser, but I don't know how to do that via GUI application? I want to create GUI form with 3 entries (first "name", second "password", third "confirm password") and button "add". ...
[ "You can call something like\nuseradd -m -p PASSWORD\n\nwhere PASSWORD is what you get as a result of crypt() function defined in unistd.h.\nAs you've found out yourself, in the case of Python it looks like this\nimport os \nimport crypt \n\npassword =\"testpassword\"\nencPass = crypt.crypt(Password,\"salt\")\nos.s...
[ 1 ]
[]
[]
[ "gtk", "linux", "python", "user_interface" ]
stackoverflow_0007907848_gtk_linux_python_user_interface.txt
Q: Request HTTP rest resource with custom headers and authorization? I'm working on a web service and I need a code for making an HTTP request in java using basic authentication. I found lots of code at the internet but no one worked as expected. Does anyone knows some library and/or link to do this? Here is a python...
Request HTTP rest resource with custom headers and authorization?
I'm working on a web service and I need a code for making an HTTP request in java using basic authentication. I found lots of code at the internet but no one worked as expected. Does anyone knows some library and/or link to do this? Here is a python equivalent to what I want... import urllib2 import base64 req = urlli...
[ "Yea, you just use the HttpURLConnection class. The Android team has actually put a lot of development time into making this class extremely performant and usefully. I highly recommend it!\nP.S. If you're really curious, checkout this blog post from the android dev team.\n", "You may want to check out Apache HTTP...
[ 3, 0 ]
[]
[]
[ "android", "google_app_engine", "http", "java", "python" ]
stackoverflow_0007908268_android_google_app_engine_http_java_python.txt
Q: python: finding a missing letter in the alphabet from a list - least lines of code I'm trying to find the missing letter in the alphabet from the list with the least lines of code. If the list is sorted already (using list.sort()), what is the fastest or least lines of code to find the missing letter. If I know th...
python: finding a missing letter in the alphabet from a list - least lines of code
I'm trying to find the missing letter in the alphabet from the list with the least lines of code. If the list is sorted already (using list.sort()), what is the fastest or least lines of code to find the missing letter. If I know there are only one missing letter. (This is not any type of interview questions. I actuall...
[ "Some questions:\n\nAre all the letters upper or lower case? (a/A)\nIs this the only alphabet you'll want to check?\nWhy are you doing this so often?\n\nLeast lines of code:\n# do this once, outside the loop\nalphabet=set(string.ascii_lowercase)\n# inside the loop, just 1 line:\nmissingletter=(alphabet-set(yourlist...
[ 10, 8, 7, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000704526_python.txt
Q: using python @property in __init__ , gives attribute error Is my 'fix' the correct / good practice method? I have a class Text(), that caches it's surface to render, unless font/size changes. (I left the font property from the snippet) If I attempt to use self.size in __init__ , it will fail: Traceback (most recen...
using python @property in __init__ , gives attribute error
Is my 'fix' the correct / good practice method? I have a class Text(), that caches it's surface to render, unless font/size changes. (I left the font property from the snippet) If I attempt to use self.size in __init__ , it will fail: Traceback (most recent call last): File "temp.py", line 21, in <module> t = Tex...
[ " try:\n if self._size != px: \n self._size = px\n self.dirty=True\n except:\n self._size = 14\n self.dirty = True\n\nThe except is a bad idea because you catch all exceptions. You might accidentally catch some other exception and ignore it. That would be a...
[ 6, 4 ]
[]
[]
[ "properties", "python" ]
stackoverflow_0007908295_properties_python.txt
Q: Python eggs and module as plugin I have these eggs: ~/test/lib/ ├── a-1.0-py2.7.egg │   ├── a │   │   ├── __init__.py │   │   └── __init__.pyc │   └── EGG-INFO │   └── ... ├── a.b-1.0-py2.7.egg │   ├── a │   │   └── b │   │   ├── __init__.py │   │   └── __init__.pyc │   └── EGG-INFO │   └── ... ├──...
Python eggs and module as plugin
I have these eggs: ~/test/lib/ ├── a-1.0-py2.7.egg │   ├── a │   │   ├── __init__.py │   │   └── __init__.pyc │   └── EGG-INFO │   └── ... ├── a.b-1.0-py2.7.egg │   ├── a │   │   └── b │   │   ├── __init__.py │   │   └── __init__.pyc │   └── EGG-INFO │   └── ... ├── easy-install.pth ├── site.py └── site...
[ "check your generated egg-file, if there is a module a.b. \nIf not, try do use find_packages to register your modules.\n\nfrom setuptools import setup, find_packages\nsetup(\n name='pypack',\n version='0.1',\n packages=find_packages(),\n ...\n\n\n├── a.b-1.0-py2.7.egg\n│ ├── a\n│ ├── __init__.py\n│ ...
[ 0 ]
[]
[]
[ "egg", "plugins", "python" ]
stackoverflow_0007906544_egg_plugins_python.txt
Q: creating images in reST directives I'm trying to create a reStructuredText directive that takes it's content, creates an image based on that content using PIL, and then displays the generated image in the document. What I've done so far is subclass the image directive, create the file at a certain path (say, image...
creating images in reST directives
I'm trying to create a reStructuredText directive that takes it's content, creates an image based on that content using PIL, and then displays the generated image in the document. What I've done so far is subclass the image directive, create the file at a certain path (say, images/diagram.png), and then pass images/dia...
[ "Take a look at sphinx.ext.graphviz sources (e.g. here), this Sphinx extension is doing almost the same thing you describe.\n" ]
[ 1 ]
[]
[]
[ "python", "restructuredtext" ]
stackoverflow_0007907976_python_restructuredtext.txt
Q: Building scapy packets with PacketFields shorter than 8 bits I'm trying to add a new protocol with scapy, and I'm running into difficulties building packets that store other BitEnumField "packets" that are under one byte of length. I was wondering if there is a workaround to make it work (without bundling packets ...
Building scapy packets with PacketFields shorter than 8 bits
I'm trying to add a new protocol with scapy, and I'm running into difficulties building packets that store other BitEnumField "packets" that are under one byte of length. I was wondering if there is a workaround to make it work (without bundling packets into full byte fields). Here is the example: from scapy.packet imp...
[ "I guess that a Packet is always byte aligned so you may have to use a field somehow, e.g:\nclass StatusField(FlagsField):\n name = '4 bit status'\n def __init__(self, name):\n FlagsField.__init__(self, name, 0, 4, [\"a\", \"b\", \"c\", \"d\"])\n\nclass TotalStatus(Packet):\n name = \"8 bit status\"\n fields...
[ 4 ]
[]
[]
[ "python", "scapy" ]
stackoverflow_0007897522_python_scapy.txt
Q: Numpy vectorization algorithms to find first future element greater than current element I have a time series A. I want to generate another time series B, such that B[i] = j, where j is the first index greater than i such that A[j] > A[i]. is there a fast way of doing this in numpy? Thanks. [EDITED]: preferabl...
Numpy vectorization algorithms to find first future element greater than current element
I have a time series A. I want to generate another time series B, such that B[i] = j, where j is the first index greater than i such that A[j] > A[i]. is there a fast way of doing this in numpy? Thanks. [EDITED]: preferably use only O(n) of space.
[ "Insufficiently tested, use at own risk.\nimport numpy\n\na = numpy.random.random(100)\n\n# a_by_a[i,j] = a[i] > a[j]\na_by_a = a[numpy.newaxis,:] > a[:,numpy.newaxis]\n# by taking the upper triangular, we ignore all cases where i < j\na_by_a = numpy.triu(a_by_a)\n# argmax will give the first index with the highest...
[ 9, 2 ]
[]
[]
[ "numpy", "python", "vectorization" ]
stackoverflow_0007896812_numpy_python_vectorization.txt
Q: Conditional expressions in sagemath, when defining a symbolic expression In SageMath, (version 4.7), I do this in the notebook: var("x y") dens(x, y) = 2 if y <= x else 0 and this gives no error. However, after that, dens(1, 1) returns 0, dens(1, 0.5) returns 0, and so on! In fact, I found no way to get the ans...
Conditional expressions in sagemath, when defining a symbolic expression
In SageMath, (version 4.7), I do this in the notebook: var("x y") dens(x, y) = 2 if y <= x else 0 and this gives no error. However, after that, dens(1, 1) returns 0, dens(1, 0.5) returns 0, and so on! In fact, I found no way to get the answer 2. What am I doing wrong?
[ "You're using the Sage function declaration syntax -- f(x,y) = something-or-other -- but on the right hand side you're not putting a Sage expression but a Python one. This is evaluated when it's declared. By which I mean:\nsage: var(\"x y\")\n(x, y)\nsage: bool(y <= x)\nFalse\nsage: dens = 2 if y <= x else 0\nsag...
[ 4 ]
[]
[]
[ "python", "sage" ]
stackoverflow_0007908384_python_sage.txt
Q: Deleting a list that does not meet a specific criteria? I'm a bit confused on how to approach this problem. I have a large number of lists and am looking to delete lists have contents that do not start with a specific digit. For example. say I'm looking to only keep lists that have at least one node that start wit...
Deleting a list that does not meet a specific criteria?
I'm a bit confused on how to approach this problem. I have a large number of lists and am looking to delete lists have contents that do not start with a specific digit. For example. say I'm looking to only keep lists that have at least one node that start with 4 in the following lists: ['4-7', '2-5', '2-9', '2-32', '2-...
[ "You can try a list comprehension:\nresult = [yourlist for yourlist in yourlists\n if any(node.startswith('4-') for node in yourlist)]\n\nOr a generator expression if you don't want to have the results in memory all at once:\nresult = (yourlist for yourlist in yourlists\n if any(node.startswith('4...
[ 3 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0007908902_algorithm_python.txt
Q: How to add TIMESTAMPDIFF to SqlSoup query? I have a reporting program running and using SqlSoup and have the entire query generated now by SqlSoup calls except for the MySqL Function TIMESTAMPDIFF. The actual SQL phrase should be TIMESTAMPDIFF(PERIOD, start_time, end_time) <= 60 I tried from sqlalchemy.sql.expres...
How to add TIMESTAMPDIFF to SqlSoup query?
I have a reporting program running and using SqlSoup and have the entire query generated now by SqlSoup calls except for the MySqL Function TIMESTAMPDIFF. The actual SQL phrase should be TIMESTAMPDIFF(PERIOD, start_time, end_time) <= 60 I tried from sqlalchemy.sql.expression import func and a where-clause phrase (wit...
[ "sqlalchemy.text() is your friend in this case :-)\nTry:\nsqlalchemy.func.TIMESTAMPDIFF(sqlalchemy.text('PERIOD'),rc.start_time,rc.end_time) <= 60)\n\n" ]
[ 5 ]
[]
[]
[ "python", "sqlalchemy", "sqlsoup" ]
stackoverflow_0006990021_python_sqlalchemy_sqlsoup.txt
Q: Which test could I write to force the following code I like to have my test to force my design but when I comes to collections I always run into problems. The code I want to force is the following: clientInvoices : (client, callback)-> @all (invoices)-> callback invoice \ for invoice in invoices \ ...
Which test could I write to force the following code
I like to have my test to force my design but when I comes to collections I always run into problems. The code I want to force is the following: clientInvoices : (client, callback)-> @all (invoices)-> callback invoice \ for invoice in invoices \ when invoice.data.clientId() is client.data._id() At fi...
[ "This doesn't make sense:\nfor invoice in invoices \\\nwhen invoices.data.clientId() is client.data._id()\n\nI think you must mean\nfor invoice in invoices \\\nwhen invoice.data.clientId() is client.data._id()\n\nIf that's the case, then the solution to your quandary is simply to add more assertions about the invoi...
[ 1 ]
[]
[]
[ "coffeescript", "javascript", "python", "ruby", "tdd" ]
stackoverflow_0007906495_coffeescript_javascript_python_ruby_tdd.txt
Q: How to get mail report about all unhandled exceptions inside of twisted server? I'm initialize 2 servers in one twisted script. So I want to get all unhadled exception inside of it on my mail. Is it posible? Thank you! A: You can use sys.excepthook. sys.excepthook catches all exceptions that are uncaught in your...
How to get mail report about all unhandled exceptions inside of twisted server?
I'm initialize 2 servers in one twisted script. So I want to get all unhadled exception inside of it on my mail. Is it posible? Thank you!
[ "You can use sys.excepthook. sys.excepthook catches all exceptions that are uncaught in your code. How you handle them from there is your choice.\nFor sending emails, you may be interested in the Python email module. Here are some examples.\nYou can reconstruct a traceback from an exception using the Python traceba...
[ 2 ]
[]
[]
[ "debugging", "python", "twisted" ]
stackoverflow_0007908721_debugging_python_twisted.txt
Q: finding absolute path from a relative path in python my question is pretty much what the title suggests. my research has led me to try something like this: import os pathname = os.path.abspath("some/relative/directory") print pathname this problem is that whenever i do something like this, it simply returns what...
finding absolute path from a relative path in python
my question is pretty much what the title suggests. my research has led me to try something like this: import os pathname = os.path.abspath("some/relative/directory") print pathname this problem is that whenever i do something like this, it simply returns whatever relative directory i gave it preceded by my python di...
[ "abspath is based on getcwd. Most likely, your current working directory simply isn't what you expect. \nYou can change the code that launches your script, change directories manually, or just use chdir in Python.\n", "Did you try os.path.realpath(\"my/relative/dir\")? Actually it seems the directory may not ex...
[ 3, 0 ]
[]
[]
[ "path", "python", "search" ]
stackoverflow_0007909300_path_python_search.txt
Q: Will a website recover from a Denial of Service attack on its own? I'm in a rather peculiar situation right now. To make a long story short, I'm part of a (real life) volunteer organization of about 2000 members. Our current website was built and maintained by a member who is no longer part of the organization (...
Will a website recover from a Denial of Service attack on its own?
I'm in a rather peculiar situation right now. To make a long story short, I'm part of a (real life) volunteer organization of about 2000 members. Our current website was built and maintained by a member who is no longer part of the organization (he quit). Unfortunately, he was the only one that actually had access t...
[ "More than likely the system is not truly down for good, unless the guy might have gotten pissed or the hosting provider, etc disabled it due to the traffic load. But there are a number of things to think of. But 250 connections isn't that much load, even for a shared hosting account, unless you were just floodin...
[ 1, 0 ]
[]
[]
[ "django", "dos", "python", "recover" ]
stackoverflow_0007909527_django_dos_python_recover.txt
Q: Sending commands to the server Python Hello I have written some client server code and write now I noticed I had a bug in how I am handling receiving a command These are my commands #Server Commands CMD_MSG, CMD_MULTI, CMD_IP, CMD_AUDIO, CMD_AUDIO_MULTI, CMD_FILE = range(6) I send a command like this self.client(...
Sending commands to the server Python
Hello I have written some client server code and write now I noticed I had a bug in how I am handling receiving a command These are my commands #Server Commands CMD_MSG, CMD_MULTI, CMD_IP, CMD_AUDIO, CMD_AUDIO_MULTI, CMD_FILE = range(6) I send a command like this self.client(chr(CMD_AUDIO), data) and receive like thi...
[ "Assuming you're using a stream (TCP) socket, the first rule of stream sockets is that you will not receive data in the same groups it is sent. If you send three messages of 10 bytes each, you may receive at the other end one block of 30 bytes, 30 blocks of one byte each, or anything in between. \nYou must structur...
[ 1 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0007909221_python_sockets.txt
Q: py2exe: Generated EXE doesn't load My PyQt4 application's py2exe binary flashes briefly on the screen and then disappears. I have no idea why, but here's what happened before: My application didn't display SVG images when loading (from the Exe), so I dug around a bit and saw that I had to modify my setup.py to inc...
py2exe: Generated EXE doesn't load
My PyQt4 application's py2exe binary flashes briefly on the screen and then disappears. I have no idea why, but here's what happened before: My application didn't display SVG images when loading (from the Exe), so I dug around a bit and saw that I had to modify my setup.py to include a qt.conf and some DLLs. Then the b...
[ "If I remember right, Py2exe is discontinued, so it's really not safe to use.\nI use cx_Freeze, which has never failed me once in working. It might help you out too.\nAlso, remember that paths are different when frozen vs a script. Typically, you need os.path.dirname(sys.executable) for frozen (which you can test f...
[ 1 ]
[]
[]
[ "py2exe", "pyqt4", "python" ]
stackoverflow_0007908448_py2exe_pyqt4_python.txt
Q: Learning programming as a hobbyist... the merits of C vs C++ I will admit that starting programming on your own as a newbie can seem a bit daunting. However after toying around very basically in both Python and currently C++ I'm wondering if C may be more suitable for a hobbyist. By hobbyist I mean someone who for...
Learning programming as a hobbyist... the merits of C vs C++
I will admit that starting programming on your own as a newbie can seem a bit daunting. However after toying around very basically in both Python and currently C++ I'm wondering if C may be more suitable for a hobbyist. By hobbyist I mean someone who foresees no real future in actually programming for a living but rath...
[ "You're looking at this wrong. What's your goal? If your goal is to \"learn a language\" then you are wasting your time. That is like investing your time into learning to use photoshop with no ambition to ever create any neato graphics.\nInstead of focusing on the tool, focus on what you want to do with it. If ...
[ 3, 1 ]
[]
[]
[ "c", "c++", "python" ]
stackoverflow_0007909666_c_c++_python.txt
Q: Why does this Python program involving CSV files not repeat? It works PERFECTLY... once... Idea is to take a list of names from a text file (each on a new line) and create a new CSV file based on whether or not the line starts with the text name. Here's what I've got so far: import csv lines = [] with open('outpu...
Why does this Python program involving CSV files not repeat?
It works PERFECTLY... once... Idea is to take a list of names from a text file (each on a new line) and create a new CSV file based on whether or not the line starts with the text name. Here's what I've got so far: import csv lines = [] with open('output.txt','r') as f: for line in f.readlines(): lines.app...
[ "The example you've given works for me. I wonder if you're facing a newline issue. Instead of stripping off one character in each line of output.txt, try the .strip() method. That is, instead of line[:-1], use line.strip().\nIf you're still having problems, try opening input.csv in 'rb' mode instead of just 'r'....
[ 1, 1 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0007909559_csv_python.txt
Q: Python - Run numpy without the python interpreter I have an .x3d code which references a python script. I am trying to implement certain functions which make use of the numpy module. However, I am only able to import the builtin modules from Python. I am looking for a way to import the numpy module into the script...
Python - Run numpy without the python interpreter
I have an .x3d code which references a python script. I am trying to implement certain functions which make use of the numpy module. However, I am only able to import the builtin modules from Python. I am looking for a way to import the numpy module into the script without having to call the interpreter (i.e. "test.py"...
[ "\nfind where numpy is installed on your system. For me, it's here:\n/usr/lib/pymodules/python2.7\nimport it explicitly before importing numpy\n\nimport sys\nsys.path.append('/usr/lib/pymodules/python2.7')\n... if you need help finding the correct path, check the contents of sys.path while using your python interpr...
[ 4, 3, 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0007909761_numpy_python.txt
Q: How to optimize the code of data addition to the datastore? I have the following code (for Country and City classes key_name is numeric id with addition of 'i' at the beginning): def add_country(country, country_name): if country and country_name and country_name != '': return Country.get_or_insert('i'+str(c...
How to optimize the code of data addition to the datastore?
I have the following code (for Country and City classes key_name is numeric id with addition of 'i' at the beginning): def add_country(country, country_name): if country and country_name and country_name != '': return Country.get_or_insert('i'+str(country), country_name=country_name) else: return None de...
[ "You don't need to prefix your IDs with a character - simply convert them to a string and use them as-is. Otherwise, this is probably fine, though it's hard to know without seeing how you're using it and how you fetch the objects.\n" ]
[ 0 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0007907548_google_app_engine_google_cloud_datastore_python.txt
Q: Pygame water ripple effect I have Googled for it but there are no ready scripts - as opposed to the same effect on Flash. I have checked the algorithm on The Water Effect Explained and also tested an implementation of the Perlin Noise, which provides a good simulation of the end of waves on a flat surface. I am l...
Pygame water ripple effect
I have Googled for it but there are no ready scripts - as opposed to the same effect on Flash. I have checked the algorithm on The Water Effect Explained and also tested an implementation of the Perlin Noise, which provides a good simulation of the end of waves on a flat surface. I am looking for the same implementati...
[ "After doing homework (a.k.a. research) and trying to directly convert the Java code reference posted on the question into Python, and having a very, very sad experience while trying to have Python/Numpy update a humongous array of pixel colors based on their positions for the rippling of the ripple effect (sorry, ...
[ 9, 5 ]
[]
[]
[ "effect", "image_processing", "opengl", "pygame", "python" ]
stackoverflow_0007648072_effect_image_processing_opengl_pygame_python.txt
Q: Parse html with lxml (tag h3) I'm trying to parse some html and I have some problem with this little html code. XML: <div> <p><span><a href="../url"></a></span></p> <h3 class="header"><a href="../url">Other</a></h3> <a href="../url">Other</a><br> <a class="aaaaa" href="../url">Indice</a> <p></p...
Parse html with lxml (tag h3)
I'm trying to parse some html and I have some problem with this little html code. XML: <div> <p><span><a href="../url"></a></span></p> <h3 class="header"><a href="../url">Other</a></h3> <a href="../url">Other</a><br> <a class="aaaaa" href="../url">Indice</a> <p></p> </div> code: impo...
[ "The XPath query in your example is not quite right.\nTo get a list of all h3 tags within div tags, you should use this:\nelements = tree.xpath('//div/h3')\netree.tostring(elements[0])\n\nWhich should give:\n'<h3 class=\"header\"><a href=\"../url\">Other</a></h3>\\n'\n\nTo get a list of all href attributes of a tag...
[ 4, 3 ]
[]
[]
[ "html", "lxml", "parsing", "python", "xpath" ]
stackoverflow_0007909809_html_lxml_parsing_python_xpath.txt
Q: How to Strip Python Output I want to strip platform.linux_distribution(). Output is tuple ('Ubuntu', '11.10', 'oneiric') but I want to show it as "Ubuntu 11.10 oneriric" .group(1) is not working. A: You're looking for " ".join(): >>> import platform >>> platform.linux_distribution() ('Ubuntu', '11.04', 'natty') ...
How to Strip Python Output
I want to strip platform.linux_distribution(). Output is tuple ('Ubuntu', '11.10', 'oneiric') but I want to show it as "Ubuntu 11.10 oneriric" .group(1) is not working.
[ "You're looking for \" \".join():\n>>> import platform\n>>> platform.linux_distribution()\n('Ubuntu', '11.04', 'natty')\n>>> \" \".join(platform.linux_distribution())\n'Ubuntu 11.04 natty'\n>>> \n\n", "How about this:\n\" \".join(platform.linux_distribution())\n\n", "how about:\n' '.join(platform.linux_distribu...
[ 4, 0, 0 ]
[]
[]
[ "linux", "linux_distro", "python" ]
stackoverflow_0007910296_linux_linux_distro_python.txt
Q: python: best data structure to use to store strings? I am planning to break a long document in various strings, and save them as they are (so each string can have different length, i will not break them to strings with specific length). I was planning to use an array, so as i scroll trough the document, i can just...
python: best data structure to use to store strings?
I am planning to break a long document in various strings, and save them as they are (so each string can have different length, i will not break them to strings with specific length). I was planning to use an array, so as i scroll trough the document, i can just add each string to a position of the array and increment ...
[ "All you've said you want to do with these strings is collect them in order, and then print them out in order. Based on that, a list sounds totally reasonable.\n" ]
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0007910445_python.txt
Q: Py2Exe Error: Win32com.client causes errors when trying to run created executable My script that I'm trying to create into an executable contains the following imports: import csv, time, BeautifulSoup, sys, mechanize, os, traceback, win32com.client as win32 My setup.py looks like this: from distutils.core import ...
Py2Exe Error: Win32com.client causes errors when trying to run created executable
My script that I'm trying to create into an executable contains the following imports: import csv, time, BeautifulSoup, sys, mechanize, os, traceback, win32com.client as win32 My setup.py looks like this: from distutils.core import setup import py2exe, sys, os sys.argv.append('py2exe') setup( options = {'py2exe'...
[ "This was solved by upgrading to Python 2.7. I originally had Python 2.6 installed but the update solved this issue.\n" ]
[ 0 ]
[]
[]
[ "importerror", "py2exe", "python", "win32com" ]
stackoverflow_0007899051_importerror_py2exe_python_win32com.txt
Q: Issues loading data from an iterator into a Django Model I have a webscraper that delivers dictionary objects of data to be entered into the Django model. I've written a simple script to test loading data. It operates by iterating through the dictionary object and delivering each key value into the appropriate m...
Issues loading data from an iterator into a Django Model
I have a webscraper that delivers dictionary objects of data to be entered into the Django model. I've written a simple script to test loading data. It operates by iterating through the dictionary object and delivering each key value into the appropriate model field (the keys share their names with the respective mod...
[ "You can not set an attribute by a variable value in that way. eventOjbect.k = 'hello' is just setting an attribute, k to 'hello' which the model doesn't have.\nYou are simply assigning eventObject.k = 'foo' and repeating that over and over.\nfor k in item.keys():\n setattr(eventObject, k, item[k])\n print \"...
[ 1 ]
[]
[]
[ "django", "django_models", "iterator", "python" ]
stackoverflow_0007910583_django_django_models_iterator_python.txt
Q: python pyqt4 closeEvent preventing windows restart/shutdown? i added closeEvent in my application to prevent the user from pressing alt-f4 and closing the application.My problem now is when i shutdown or restart the computer manually in the start menu, nothing happens. def closeEvent(self, event): event.i...
python pyqt4 closeEvent preventing windows restart/shutdown?
i added closeEvent in my application to prevent the user from pressing alt-f4 and closing the application.My problem now is when i shutdown or restart the computer manually in the start menu, nothing happens. def closeEvent(self, event): event.ignore() i also try this code but it didn't proceed to the if TRUE...
[ "Could you make use of QApplication.setQuitOnLastWindowClosed?\nWhen set to False, this will keep the application alive when the top-level window is closed.\n", "I'm not sure if you want to prevent the system from shutting down, or allow it to shutdown, but you should have a look at QApplication.commitData which ...
[ 0, 0 ]
[]
[]
[ "pyqt4", "python" ]
stackoverflow_0007857925_pyqt4_python.txt
Q: Impossible to set an attribute to a string? Usually, you can set an arbitrary attribute to a custom object, for instance ---------- >>> a=A() >>> a.foo=42 >>> a.__dict__ {'foo': 42} >>> ---------- On the other hand, you can't do the same binding with a string object : ---------- >>> a=str("bar") >>> a.foo=42 Tr...
Impossible to set an attribute to a string?
Usually, you can set an arbitrary attribute to a custom object, for instance ---------- >>> a=A() >>> a.foo=42 >>> a.__dict__ {'foo': 42} >>> ---------- On the other hand, you can't do the same binding with a string object : ---------- >>> a=str("bar") >>> a.foo=42 Traceback (most recent call last): File "<stdin>"...
[ "Because the str type is a type wich does not has an attribute dict. From the docs, \"Classes\" section:\n\nA class has a namespace implemented by a dictionary object.\n Class attribute references are translated to lookups in this\n dictionary, e.g., C.x is translated to C.__dict__[\"x\"]\n\nYou can also enforce ...
[ 11, 2 ]
[]
[]
[ "python" ]
stackoverflow_0007910768_python.txt
Q: Bundling GTK resources with py2exe I'm using Python 2.6 and PyGTK 2.22.6 from the all-in-one installer on Windows XP, trying to build a single-file executable (via py2exe) for my app. My problem is that when I run my app as a script (ie. not built into an .exe file, just as a loose collection of .py files), it use...
Bundling GTK resources with py2exe
I'm using Python 2.6 and PyGTK 2.22.6 from the all-in-one installer on Windows XP, trying to build a single-file executable (via py2exe) for my app. My problem is that when I run my app as a script (ie. not built into an .exe file, just as a loose collection of .py files), it uses the native-looking Windows theme, but ...
[ "Answering my own question here, but if anyone knows better feel free to answer too. Some of it seems quite fragile (eg. version numbers in paths), so comment or edit if you know a better way.\n1. Finding the files\nFirstly, I use this code to actually find the root of the GTK runtime. This is very specific to how ...
[ 8 ]
[]
[]
[ "py2exe", "pygtk", "python" ]
stackoverflow_0007884959_py2exe_pygtk_python.txt
Q: Enable Python code only for unittests? Let's say I have the following function: def f(): if TESTING: # Run expensive sanity check code ... What is the correct way to run the TESTING code block only if we are running a unittest? [edit: Is there some "global" variable I can access to find out if uni...
Enable Python code only for unittests?
Let's say I have the following function: def f(): if TESTING: # Run expensive sanity check code ... What is the correct way to run the TESTING code block only if we are running a unittest? [edit: Is there some "global" variable I can access to find out if unittests are on?]
[ "Generally, I'd suggest not doing this. Your production-code really shouldn't realize that the unit-tests exist. One reason for this, is that you could have code in your if TESTING block that makes the tests pass (accidentally), and since production runs of your code won't run these bits, could leave you exposed ...
[ 9 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0007911098_python_unit_testing.txt
Q: GAE " no attribute 'HTTPSHandler' " dev_appserver.py I am trying to use the google appengine python SKD from my ubuntu lucid. I have already compiled python2.5. But when I execute any "dev_appserver.py" command with it I get the following error: Traceback (most recent call last): File "dev_appserver.py", line 6...
GAE " no attribute 'HTTPSHandler' " dev_appserver.py
I am trying to use the google appengine python SKD from my ubuntu lucid. I have already compiled python2.5. But when I execute any "dev_appserver.py" command with it I get the following error: Traceback (most recent call last): File "dev_appserver.py", line 69, in <module> run_file(__file__, globals()) File "d...
[ "Solved the issue...just needed to build all dependencies of python using: \n\napt-get build-dep python\n\npython compiles with no error even when all the dependencies are not installed. It just skips the modules which require them and builds python.\n", "Solution for missing HTTPSHandler:\nBefore you build pytho...
[ 3, 2, 1 ]
[]
[]
[ "google_app_engine", "linux", "python" ]
stackoverflow_0003690932_google_app_engine_linux_python.txt
Q: Setting the *default* data order (C vs. Fortran) in Numpy I'm porting some MATLAB code to Numpy. This task includes stripping the MEX out of some C++ code and replacing it with equivalent calls to Numpy's C-API. One problem is that the MEX code treats the incoming data as Fortran-ordered because that's how MATLAB ...
Setting the *default* data order (C vs. Fortran) in Numpy
I'm porting some MATLAB code to Numpy. This task includes stripping the MEX out of some C++ code and replacing it with equivalent calls to Numpy's C-API. One problem is that the MEX code treats the incoming data as Fortran-ordered because that's how MATLAB orders its arrays. Numpy, on the other hand, uses a C ordering ...
[ "My approach to this problem (when I wrap fortran code with f2py) is to explicitly declare all the relevant numpy arrays in fortran order, because numpy can happily work with them transparently, and it even works well combining fortran and C order arrays. Unfortunately, it seems that numpy operations do not preserv...
[ 5 ]
[]
[]
[ "matlab", "mex", "numpy", "python" ]
stackoverflow_0007911041_matlab_mex_numpy_python.txt
Q: how to log background python script's output if some exception is not catched I have a python script running in background, and I want to log all the exception and output to a log file. I know to use logging module and try.. catch.. to log exception, but what if I missed some, is there any way to log these excepti...
how to log background python script's output if some exception is not catched
I have a python script running in background, and I want to log all the exception and output to a log file. I know to use logging module and try.. catch.. to log exception, but what if I missed some, is there any way to log these exceptions too?
[ "The usual technique is to use a try/except Exception at the highest level call (the main function). This pretty much assures that you will not have \"missed some\". Exception matches non-exiting exceptions, so it is casting a broad net.\n", "You can reassign sys.stdout and sys.stderr to file handles. They'll...
[ 2, 0 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0007911467_logging_python.txt
Q: Python string operation, extract text between html tags I have a string: <font face="ARIAL,HELVETICA" size="-2"> JUL 28 </font> (it outputs over two lines, so there must be a \n in there. I wish to extract the string that's in between the <font></font> tags. In this case, it's JUL 28, but it might be an...
Python string operation, extract text between html tags
I have a string: <font face="ARIAL,HELVETICA" size="-2"> JUL 28 </font> (it outputs over two lines, so there must be a \n in there. I wish to extract the string that's in between the <font></font> tags. In this case, it's JUL 28, but it might be another date or some other number. 1) The best way to extract t...
[ "While it may be possible to parse arbitrary HTML with regular expressions, it's often a death trap. There are great tools out there for parsing HTML, including BeautifulSoup, which is a Python lib that can handle broken as well as good HTML fairly well.\n>>> from BeautifulSoup import BeautifulSoup as BSHTML\n>>> B...
[ 15, 6, 2, 1, 0, 0 ]
[]
[]
[ "html", "parsing", "python", "string" ]
stackoverflow_0007911504_html_parsing_python_string.txt
Q: Translation from Python to Batch for a CSV program I really need help with using a batch file to do the following: I need to read in a text file line by line and, for each entry of a given CSV file that starts with an element found in the line of text file, write it into a new CSV file. Or, in other words: Read th...
Translation from Python to Batch for a CSV program
I really need help with using a batch file to do the following: I need to read in a text file line by line and, for each entry of a given CSV file that starts with an element found in the line of text file, write it into a new CSV file. Or, in other words: Read the following example.csv Page, Pageviews, Bounce Rate, /c...
[ "I just write the Batch file you need. However, I don't know the .csv file format, so I assumed several details. These are my assumptions:\n\nThe .csv file contains just ASCII text with no CR-LF separators.\nEach .csv element is separated by comma AND DO NOT CONTAIN SPACES (this limitation may be solved).\nThe size...
[ 3, 1 ]
[]
[]
[ "batch_file", "csv", "python" ]
stackoverflow_0007908097_batch_file_csv_python.txt
Q: Python, killed? OK, so I've finally started with math in python, which is (so far) surprisingly not as hard as I thought it would be(I don't know any calculus, or trigonometry, and only know basic algebra). I'm trying to create a program from scratch that factors quadratic equations. Here is what I have so far (So...
Python, killed?
OK, so I've finally started with math in python, which is (so far) surprisingly not as hard as I thought it would be(I don't know any calculus, or trigonometry, and only know basic algebra). I'm trying to create a program from scratch that factors quadratic equations. Here is what I have so far (Sorry if it's poorly wr...
[ "Modify your code a bit like this:\ndef factor(arg): \n o = arg\n n = o\n x = 2\n factors = [o]\n\n while abs(o) >= x:\n if (o) % x == 0:\n n = o / x\n factors.append(n)\n x += 1\n else:\n x += 1\n\n return factors\n\nA = int(raw_input(\"What is A in your quadr...
[ 2, 2 ]
[]
[]
[ "math", "python" ]
stackoverflow_0007911746_math_python.txt
Q: Django or pylon portability to python 3 will affect my app? I want to make my app, in django or pylons, but I came to know that Django will be supporting Python 3 in near future. So I want to know that if I will update Django that will have python3 supported then to support python 3, what changes I will need to do...
Django or pylon portability to python 3 will affect my app?
I want to make my app, in django or pylons, but I came to know that Django will be supporting Python 3 in near future. So I want to know that if I will update Django that will have python3 supported then to support python 3, what changes I will need to do? Or it will be all things done by people who are developing Djan...
[ "Being future proof is impossible, and all software that doesn't exist should be viewed as vapourware. Use what works now, today for you. Ignore what may exist tomorrow. \n" ]
[ 2 ]
[]
[]
[ "django", "portability", "python", "python_3.x" ]
stackoverflow_0007910292_django_portability_python_python_3.x.txt
Q: Comparing (similar) images with Python/PIL I'm trying to calculate the similarity (read: Levenshtein distance) of two images, using Python 2.6 and PIL. I plan to us e the python-levenshtein library for fast comparison. Main question: What is a good strategy for comparing images? My idea is something like: Convert...
Comparing (similar) images with Python/PIL
I'm trying to calculate the similarity (read: Levenshtein distance) of two images, using Python 2.6 and PIL. I plan to us e the python-levenshtein library for fast comparison. Main question: What is a good strategy for comparing images? My idea is something like: Convert to RGB (transparent -> white) (or maybe convert...
[ "Check out imgSeek:\n\nimgSeek is a collection of free open source visual similarity\n projects. The query (image you are looking for) can be expressed\n either as a rough sketch painted by the user or as another image you\n supply (or an image in your collection). The searching algorithm makes\n use of multire...
[ 5, 2 ]
[]
[]
[ "fuzzy_comparison", "fuzzy_logic", "python", "python_imaging_library" ]
stackoverflow_0002603713_fuzzy_comparison_fuzzy_logic_python_python_imaging_library.txt
Q: Is a class the best way to hold this data C++? I have a list of US States along with various properties, and within those cities with various properties and this all needs to be created dynamically on startup, currently from a text file. In python, with slightly broken syntax for readability, I would use a dict m...
Is a class the best way to hold this data C++?
I have a list of US States along with various properties, and within those cities with various properties and this all needs to be created dynamically on startup, currently from a text file. In python, with slightly broken syntax for readability, I would use a dict matrix (that sounds terrible) which could be represen...
[ "Assuming a State always has the same fields (url, users and cities), it's good practice to create a class for it. Likewise with City. Then you will end up with either:\n\nmap<string, State> for your locations, and a map<string, City> for the cities in each state, or...\nset<State> for your locations (where State...
[ 4, 0, 0 ]
[]
[]
[ "c++", "python", "types" ]
stackoverflow_0007912244_c++_python_types.txt
Q: How to test that a Python function takes less than a certain time to complete I'm using Python's unittest. I'd like to write a test that ensures a certain method completes before a certain time. I can do this by the usual calculation of the difference between timestamp after and timestamp before, but I started won...
How to test that a Python function takes less than a certain time to complete
I'm using Python's unittest. I'd like to write a test that ensures a certain method completes before a certain time. I can do this by the usual calculation of the difference between timestamp after and timestamp before, but I started wondering if is this commonly done in TDD, write tests that fail if a method / functi...
[ "You can do it with nose @timed decorator. I use it for testing functions with timing. Example:\n@timed(2.1)\ndef test():\n func_with_timeout(timeout=2)\n\n", "Some companies have tests for the speed of code, sort of a regression test, these try to catch new code that slows down the system and if they catch a ...
[ 2, 0 ]
[]
[]
[ "python", "tdd" ]
stackoverflow_0007909483_python_tdd.txt