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: Delete all characters in a multiline string up to a given pattern Using Python I need to delete all characters in a multiline string up to the first occurrence of a given pattern. In Perl this can be done using regular expressions with something like: #remove all chars up to first occurrence of cat or dog or rat $...
Delete all characters in a multiline string up to a given pattern
Using Python I need to delete all characters in a multiline string up to the first occurrence of a given pattern. In Perl this can be done using regular expressions with something like: #remove all chars up to first occurrence of cat or dog or rat $pattern = 'cat|dog|rat' $pagetext =~ s/(.*?)($pattern)/$2/xms; What'...
[ ">>> import re\n>>> s = 'hello cat!'\n>>> m = re.search('cat|dog|rat', s)\n>>> s[m.start():]\n'cat!'\n\nOf course you'll need to account for the case where there's no match in a real solution.\nOr, more cleanly:\n>>> import re\n>>> s = 'hello cat!'\n>>> p = 'cat|dog|rat'\n>>> re.sub('.*?(?=%s)' % p, '', s, 1)\n'cat...
[ 5, 4, 2, 1, 0 ]
[]
[]
[ "python", "regex", "string" ]
stackoverflow_0002658101_python_regex_string.txt
Q: Python Fabric error I'm running fabric (Django deployment to apache) and everything seems to work fine until I get to the task for installing the site: def install_site(): "Add the virtualhost file to apache" require('release', provided_by=[deploy, setup]) sudo('cd %(path)/releases/%(release)/%(release...
Python Fabric error
I'm running fabric (Django deployment to apache) and everything seems to work fine until I get to the task for installing the site: def install_site(): "Add the virtualhost file to apache" require('release', provided_by=[deploy, setup]) sudo('cd %(path)/releases/%(release)/%(release); cp %(project_name)/%(v...
[ "def install_site():\n \"Add the virtualhost file to apache\"\n require('release', provided_by=[deploy, setup])\n\n with cd('%(path)s/releases/%(release)s/%(release)s' % env):\n sudo('cp %(project_name)s/%(virtualhost_path)s/%(project_domain)s '\n '/etc/apache2/sites-available/%(proj...
[ 4, 2, 0 ]
[]
[]
[ "deployment", "django", "fabric", "python" ]
stackoverflow_0002660611_deployment_django_fabric_python.txt
Q: webob cookies I am not able to set cookies using following statements self.request.headers['Cookie'] = 'uniqueid = ',unique_identifier self.request.headers['Cookie'] = 'nickname = ',nickname as self.request.cookies is returning null dictionary in another request. environment is python on go...
webob cookies
I am not able to set cookies using following statements self.request.headers['Cookie'] = 'uniqueid = ',unique_identifier self.request.headers['Cookie'] = 'nickname = ',nickname as self.request.cookies is returning null dictionary in another request. environment is python on google app engine
[ "Changing the cookies in the request does nothing to the cookie on the client.\nYou need to set the \"Set-Cookie\" header in the response to the client.\nYou could use something like this (untested by me) Google App Engine Cookie class\n", "The WebOb Reference explains set_cookie well - if youre on a framework us...
[ 5, 4 ]
[]
[]
[ "cookies", "google_app_engine", "python", "session" ]
stackoverflow_0000999873_cookies_google_app_engine_python_session.txt
Q: Indexing over the results returned by selenium I try to index over results returned by an xpath. For example: xpath = '//a[@id="someID"]' can return a few results. I want to get a list of them. I thought that doing: numOfResults = sel.get_xpath_count(xpath) l = [] for i in range(1,numOfResults+1): l.append(sel...
Indexing over the results returned by selenium
I try to index over results returned by an xpath. For example: xpath = '//a[@id="someID"]' can return a few results. I want to get a list of them. I thought that doing: numOfResults = sel.get_xpath_count(xpath) l = [] for i in range(1,numOfResults+1): l.append(sel.get_text('(%s)[%d]'%(xpath, i))) would work becaus...
[ "Can you try the xpath /html/descendant::a[@id=\"someID\"] You can replace the /html with something else that is an ancestor of your links like id('content'). You should then be able to locate individual links using [1], [2] etc.\nFrom the XPath TR at http://www.w3.org/TR/xpath#path-abbrev:\n\nNOTE: The location pa...
[ 2, 1, 0 ]
[]
[]
[ "python", "selenium", "xpath" ]
stackoverflow_0001922211_python_selenium_xpath.txt
Q: How can I repeat something for x minutes in Python? I have a program (temptrack) where I need to download weather data every x minutes for x amount of hours. I have figured out how to download every x minutes using time.sleep(x*60), but I have no clue how to repeat this process for a certain amount of hours. UPDAT...
How can I repeat something for x minutes in Python?
I have a program (temptrack) where I need to download weather data every x minutes for x amount of hours. I have figured out how to download every x minutes using time.sleep(x*60), but I have no clue how to repeat this process for a certain amount of hours. UPDATE: Thank you to everyone who posted a solution. I marked ...
[ "Compute the time you want to stop doing whatever it is you're doing, and check each time that the time limit hasn't expired. Like this:\nfinish_time = datetime.datetime.now() + datetime.timedelta(hours=6)\nwhile datetime.datetime.now() < finish_time:\n do_something()\n sleep_for_a_bit()\n\n", "I've just fo...
[ 5, 4, 3, 0 ]
[ "Maybe I'm misunderstanding you, but just put it in a loop that runs a sufficient number of times. For example, to download every 5 minutes for 2 hours you need to download 24 times, so:\nfor i in range(24):\n download()\n sleep(5*60)\n\nIf you need it to be parameterizable, it's just:\nfrom __future__ import...
[ -2 ]
[ "python", "repeat", "time" ]
stackoverflow_0002660168_python_repeat_time.txt
Q: Python Animation Timing I'm currently working on sprite sheet tool in python that exports the organization into an xml document but I've run into some problems trying to animate a preview. I'm not quite sure how to time the frame rate with python. For example, assuming I have all of my appropriate frame data and d...
Python Animation Timing
I'm currently working on sprite sheet tool in python that exports the organization into an xml document but I've run into some problems trying to animate a preview. I'm not quite sure how to time the frame rate with python. For example, assuming I have all of my appropriate frame data and drawing functions, how would I...
[ "The easiest way to do it is with Pygame:\nimport pygame\npygame.init()\n\nclock = pygame.time.Clock()\n# or whatever loop you're using for the animation\nwhile True:\n # draw animation\n # pause so that the animation runs at 30 fps\n clock.tick(30)\n\nThe second easiest way to do it is manually:\nimport t...
[ 8, 1, 0 ]
[]
[]
[ "animation", "python", "sprite", "timing" ]
stackoverflow_0002660919_animation_python_sprite_timing.txt
Q: Underscore characters disappears on jEdit I'm using jEdit 4.3 pre 16. As I've mentioned on the title, when I'm typing, sometimes underscore characters disappears. I tried to change fonts, line highlighting etc. but it didn't work. For example when you type: if __name__ == 'main': it displays: if name == 'main'...
Underscore characters disappears on jEdit
I'm using jEdit 4.3 pre 16. As I've mentioned on the title, when I'm typing, sometimes underscore characters disappears. I tried to change fonts, line highlighting etc. but it didn't work. For example when you type: if __name__ == 'main': it displays: if name == 'main': When you click on name, it displays the unde...
[ "Some editors let you control the linespacing independently of the font size. If jEdit gives you that control, increase the linespacing just a little. The problem is that the editor doesn't realize how far below the baseline the underscores extend, and they are being overwritten with the line below.\n" ]
[ 1 ]
[]
[]
[ "jedit", "python" ]
stackoverflow_0002662173_jedit_python.txt
Q: How to store data to datastore - AppEngine I am new to Python & AppEngine. I am trying to use Feedparser to cache a feed to a datastore. My code is at http://pastebin.com/uWPdWUm2 For some reason it doesn't work - it does not add the data to the datastore. Any ideas? I am stumped. A: You just forgot to use pare...
How to store data to datastore - AppEngine
I am new to Python & AppEngine. I am trying to use Feedparser to cache a feed to a datastore. My code is at http://pastebin.com/uWPdWUm2 For some reason it doesn't work - it does not add the data to the datastore. Any ideas? I am stumped.
[ "You just forgot to use parenthesis in your model declaration.\nYour code:\nclass FeedEntry3(db.Model):\n title = db.StringProperty\n link = db.StringProperty\n content = db.TextProperty\n\nWhat it should be:\nclass FeedEntry3(db.Model):\n title = db.StringProperty()\n link = db.StringProperty()\n ...
[ 5, 0 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0002661923_google_app_engine_google_cloud_datastore_python.txt
Q: Chinese string input for python? How can I get python to work with simplified Chinese text input either as strings or raw input? A: Decode on input. u = s.decode('gb2312') A: Trivial handling of Chinese characters in python 2.6.2 32 bit on windows vista 64 bit >>> s = raw_input("Insert Chinese Text Here: ") ...
Chinese string input for python?
How can I get python to work with simplified Chinese text input either as strings or raw input?
[ "Decode on input.\nu = s.decode('gb2312')\n\n", "Trivial handling of Chinese characters in python 2.6.2 32 bit on windows vista 64 bit\n>>> s = raw_input(\"Insert Chinese Text Here: \")\n\n 你好世界\n\n>>> u'\\u4f60\\u597d\\u4e16\\u754c'\n\n>>> print s\n\n你好世界\n\n>>>\n\n" ]
[ 1, 0 ]
[]
[]
[ "cjk", "python" ]
stackoverflow_0002660902_cjk_python.txt
Q: MySQL to AppEngine I'm from Brazil and study at FATEC (college located in Brazil). I'm trying to learn about AppEngine. Now, I'm trying to load a large database from MySQL to AppEngine to perform some queries, but I don't know how i can do it. I did some testing with CSV files,but is there any way to perform the d...
MySQL to AppEngine
I'm from Brazil and study at FATEC (college located in Brazil). I'm trying to learn about AppEngine. Now, I'm trying to load a large database from MySQL to AppEngine to perform some queries, but I don't know how i can do it. I did some testing with CSV files,but is there any way to perform the direct import from MySQL?...
[ "It isn't clear from your tags, but the documented bulkloader is preferable to trying to hoist your csv files directly to the app-server.\n", "Advanced Bulk Loading by Nick Johnson is what you are looking for.\nIf you need live synchronization between App Engine and MySQL, you should look into AppRocket. AppRocke...
[ 1, 1, 0 ]
[]
[]
[ "bulk_load", "google_app_engine", "mysql", "python" ]
stackoverflow_0002650499_bulk_load_google_app_engine_mysql_python.txt
Q: Is there a Perl equivlant module to pydbg module? Could someone suggest a Perl module equivlant/or has the most funcionality of the pydbg module on Python? A: The DDD Project is a great front end to the fabulous Perl Debugger (mentioned above...) A: Have you had a look at the Perl Debugger? Edit: Forgot to me...
Is there a Perl equivlant module to pydbg module?
Could someone suggest a Perl module equivlant/or has the most funcionality of the pydbg module on Python?
[ "The DDD Project is a great front end to the fabulous Perl Debugger (mentioned above...)\n", "Have you had a look at the Perl Debugger?\nEdit: Forgot to mention that you might like to get a copy of the \"Perl Debugger Pocket Reference\" which I found to be more useful than the usual perldoc's.\n" ]
[ 4, 3 ]
[]
[]
[ "perl", "python" ]
stackoverflow_0002662099_perl_python.txt
Q: Django extending user model and displaying form I am writing website and i`d like to implement profile managment. Basic thing would be to edit some of user details by themself, like first and last name etc. Now, i had to extend User model to add my own stuff, and email address. I am having troubles with display...
Django extending user model and displaying form
I am writing website and i`d like to implement profile managment. Basic thing would be to edit some of user details by themself, like first and last name etc. Now, i had to extend User model to add my own stuff, and email address. I am having troubles with displaying form. Example will describe better what i would ...
[ "You should create another form, that excludes the fields you don't want (or simply don't specify them in the fields list). Then pass the 2 different forms to the registration and edit-profile views.\n", "Try removing 'username' and 'email' from fields in Meta:\nclass Meta: \n model = User \n fields = ('fir...
[ 0, 0, 0 ]
[]
[]
[ "django_forms", "django_models", "python" ]
stackoverflow_0002595362_django_forms_django_models_python.txt
Q: Extract anything that looks like links from large amount of data in python I have around 5 GB of html data which I want to process to find links to a set of websites and perform some additional filtering. Right now I use simple regexp for each site and iterate over them, searching for matches. In my case links can...
Extract anything that looks like links from large amount of data in python
I have around 5 GB of html data which I want to process to find links to a set of websites and perform some additional filtering. Right now I use simple regexp for each site and iterate over them, searching for matches. In my case links can be outside of "a" tags and be not well formed in many ways(like "\n" in the mid...
[ "Ways out.\n\nParallelise\nProfile your code to see where the bottleneck is. The result are often surprising. \nUse a single regexp (concatenate using |) rather than multiple ones.\n\n" ]
[ 1 ]
[]
[]
[ "html", "hyperlink", "python", "screen_scraping" ]
stackoverflow_0002662595_html_hyperlink_python_screen_scraping.txt
Q: Elegant way to take basename of directory in Python? I have several scripts that take as input a directory name, and my program creates files in those directories. Sometimes I want to take the basename of a directory given to the program and use it to make various files in the directory. For example, # directory ...
Elegant way to take basename of directory in Python?
I have several scripts that take as input a directory name, and my program creates files in those directories. Sometimes I want to take the basename of a directory given to the program and use it to make various files in the directory. For example, # directory name given by user via command-line output_dir = "..." # o...
[ "To deal with your \"trailing slash\" issue (and other issues!), sanitise user input with os.path.normpath().\nTo build paths, use os.path.join()\n", "Use os.path.join() to build up paths. For example:\n>>> import os.path\n>>> path = 'foo/bar'\n>>> os.path.join(path, 'filename')\n'foo/bar/filename'\n>>> path = '...
[ 26, 7, 2, 1, 1 ]
[]
[]
[ "directory_structure", "file_io", "filesystems", "python" ]
stackoverflow_0002663512_directory_structure_file_io_filesystems_python.txt
Q: Why would Django fcgi just die? How can I find out? I'm running Django on Linux using fcgi and Lighttpd. Every now and again (about once a day) the server just dies. I'm using the latest stable release of Django, Python and Lighttpd. The only thing I can think of is that my program is opening a lot of files and ex...
Why would Django fcgi just die? How can I find out?
I'm running Django on Linux using fcgi and Lighttpd. Every now and again (about once a day) the server just dies. I'm using the latest stable release of Django, Python and Lighttpd. The only thing I can think of is that my program is opening a lot of files and executing a lot of external processes, but I'm fairly sure ...
[ "You could edit manage.py to redirect stderr to a file, assuming runfcgi doesn't do that itself:\nimport sys\nif sys.argv[1] == \"runfcgi\":\n sys.stderr = open(\"/path/to/my/django-error.log\", \"a\")\n\n", "Is this on your server? (do you own the box?). I've had that problem on shared hosting, and the host w...
[ 2, 0, 0 ]
[]
[]
[ "crash", "django", "lighttpd", "logging", "python" ]
stackoverflow_0002600212_crash_django_lighttpd_logging_python.txt
Q: Getting a UDP socket program in Python to accept messages from a Syslog client? I'm trying to write a Syslog listener and so far so good on getting it to accept incoming messages through TCP but I also want UDP to function. This is the UDP server code I'm using, which works using a python client app. I also have a...
Getting a UDP socket program in Python to accept messages from a Syslog client?
I'm trying to write a Syslog listener and so far so good on getting it to accept incoming messages through TCP but I also want UDP to function. This is the UDP server code I'm using, which works using a python client app. I also have another app which also works just using the python client app. # Server program # UDP ...
[ "Found the problem, the code was perfect, just the Kiwi Syslog Message Generator I was using wasnt working. Along with the Kiwi Syslog Server comes an awesome probram called Log Forwarder designed to forward all sorts of event messages (way beyond what the event viewer has to offer) to a syslog server. That one als...
[ 4 ]
[]
[]
[ "python", "sockets", "syslog", "udp" ]
stackoverflow_0002663247_python_sockets_syslog_udp.txt
Q: how to measure running time of algorithms in python Possible Duplicates: Accurate timing of functions in python accurately measure time python function takes How can i mesure and compare the running times of my algorithms written in python .Also point me to a nice algorithms site/forum like stackoverflow if you ...
how to measure running time of algorithms in python
Possible Duplicates: Accurate timing of functions in python accurately measure time python function takes How can i mesure and compare the running times of my algorithms written in python .Also point me to a nice algorithms site/forum like stackoverflow if you can.
[ "For small algorithms you can use the module timeit\nfrom python documentation:\ndef test():\n \"Stupid test function\"\n L = []\n for i in range(100):\n L.append(i)\n\nif __name__=='__main__':\n from timeit import Timer\n t = Timer(\"test()\", \"from __main__ import test\")\n print t.timei...
[ 28, 25, 19, 13 ]
[ "The programming language doesn't matter; measuring the runtime complexity of an algorithm works the same way regardless of the language. Analysis of Algorithms by Stanford on Google Code University is a very good resource for teaching yourself how to analyze the runtime complexity of algorithms and code. \nIf all ...
[ -1 ]
[ "algorithm", "python" ]
stackoverflow_0002662140_algorithm_python.txt
Q: How to iterate over an instance object's data attributes, returning two values at a time? I need to return two values at a time, so I have: class IterableObject(object): def __iter__(self): for item in self.__dict__: return self.__dict__[item + 1], self.__dict__[item] So I can have: myObj1, myObj2 = ...
How to iterate over an instance object's data attributes, returning two values at a time?
I need to return two values at a time, so I have: class IterableObject(object): def __iter__(self): for item in self.__dict__: return self.__dict__[item + 1], self.__dict__[item] So I can have: myObj1, myObj2 = IterableObject() value = myObj1.balance - myObj2.balance Of course it did not work. What am ...
[ "In the itertools documentation there is an example function called pairwise that you can copy into your project:\ndef pairwise(iterable):\n \"s -> (s0,s1), (s1,s2), (s2, s3), ...\"\n a, b = tee(iterable)\n next(b, None)\n return izip(a, b)\n\nUse it like:\nfor x1, x2 in pairwise(some_iterable):\n # ...
[ 5, 1, 1 ]
[]
[]
[ "iterator", "python" ]
stackoverflow_0002629634_iterator_python.txt
Q: Is using os.path.abspath to validate an untrusted filename's location secure? I don't think I'm missing anything. Then again I'm kind of a newbie. def GET(self, filename): name = urllib.unquote(filename) full = path.abspath(path.join(STATIC_PATH, filename)) #Make sure request is not tricksy and tries ...
Is using os.path.abspath to validate an untrusted filename's location secure?
I don't think I'm missing anything. Then again I'm kind of a newbie. def GET(self, filename): name = urllib.unquote(filename) full = path.abspath(path.join(STATIC_PATH, filename)) #Make sure request is not tricksy and tries to get out of #the directory, e.g. filename = "../.ssh/id_rsa". GET OUTTA HERE ...
[ "os.path.abspath, per se, is quite secure. Your assert check will be compiled away if run under python -O, which is one risk. If your STATIC_PATH does not end with the proper directory separator, you might accidentally allow a path which just happens to have it as a prefix -- e.g., if STATIC_PATH is /foo/bar, you...
[ 6, 1, 0 ]
[]
[]
[ "python", "security" ]
stackoverflow_0002664568_python_security.txt
Q: Reading CSV files in numpy where delimiter is "," I've got a CSV file with a format that looks like this: "FieldName1", "FieldName2", "FieldName3", "FieldName4" "04/13/2010 14:45:07.008", "7.59484916392", "10", "6.552373" "04/13/2010 14:45:22.010", "6.55478493312", "9", "3.5378543" ... Note that there are ...
Reading CSV files in numpy where delimiter is ","
I've got a CSV file with a format that looks like this: "FieldName1", "FieldName2", "FieldName3", "FieldName4" "04/13/2010 14:45:07.008", "7.59484916392", "10", "6.552373" "04/13/2010 14:45:22.010", "6.55478493312", "9", "3.5378543" ... Note that there are double quote characters at the start and end of each li...
[ "The basic problem is that NumPy doesn't understand the concept of stripping quotes (whereas the csv module does). When you say delimiter='\",\"', you're telling NumPy that the column delimiter is literally a quoted comma, i.e. the quotes are around the comma, not the value, so the extra quotes you get on he first...
[ 12 ]
[]
[]
[ "csv", "delimiter", "numpy", "python" ]
stackoverflow_0002664790_csv_delimiter_numpy_python.txt
Q: Problems with South/Django: not recognizing the Django App I've got a Django project on my machine and when I try to use South to migrate the data schema, I get several odd errors. Example: $ python manage.py convert_to_south thisLocator /Library/Python/2.6/site-packages/registration/models.py:4: DeprecationWarni...
Problems with South/Django: not recognizing the Django App
I've got a Django project on my machine and when I try to use South to migrate the data schema, I get several odd errors. Example: $ python manage.py convert_to_south thisLocator /Library/Python/2.6/site-packages/registration/models.py:4: DeprecationWarning: the sha >module is deprecated; use the hashlib module instea...
[ "\nAm I doing something really stupid?\n\nWell, let's start with the \"is it plugged in\" questions:\n\nIs your project directory in your Python path?\nAre you running python manage.py and not, say, python some/path/i/am/omitting/manage.py? (This is a great way to not have the project in the Python path.)\nWhat is ...
[ 3 ]
[]
[]
[ "django_south", "macos", "migration", "python" ]
stackoverflow_0002664942_django_south_macos_migration_python.txt
Q: What is the difference between a site and an app in Django? I know a site can have many apps but all the examples I see have the site called "mysite". I figured the site would be the name of your site, like StackOverflow for example. Would you do that and then have apps like "authentication", "questions", and "se...
What is the difference between a site and an app in Django?
I know a site can have many apps but all the examples I see have the site called "mysite". I figured the site would be the name of your site, like StackOverflow for example. Would you do that and then have apps like "authentication", "questions", and "search"? Or would you really just have a site called mysite with on...
[ "Django actually has 3 concepts here:\n\nProject (I think this is what you're calling site): This is the directory that contains all the apps. They share a common runtime invocation and can refer to each other.\nApp: This is a set of views, models, and templates. Apps are often designed so they can be plugged into ...
[ 25, 8, 2, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000734255_django_python.txt
Q: wxPython - Save Items in ListCtrl My question is if we can save the items on ListCtrl so everytime someone opens the application, the items are there and if the user removes it, it also removes from the configuration. I know that I can use wx.Config and I'm trying to accomplish using that but I don't know how to r...
wxPython - Save Items in ListCtrl
My question is if we can save the items on ListCtrl so everytime someone opens the application, the items are there and if the user removes it, it also removes from the configuration. I know that I can use wx.Config and I'm trying to accomplish using that but I don't know how to read it in a way to accomplish what I wa...
[ "Using wx.Config is very easy, just create config passing name of your app and add data e.g.\nconfig = wx.Config(\"StackOverflowTest\")\nconfig.Write(\"testdata\", \"yes it works!\")\n\nNow you can read it anytime\nconfig = wx.Config(\"StackOverflowTest\")\nprint config.Read(\"testdata\")\n\nFor saving list cntrl d...
[ 3 ]
[]
[]
[ "items", "listctrl", "python", "save", "wxpython" ]
stackoverflow_0002662599_items_listctrl_python_save_wxpython.txt
Q: How should I extract % delimited tags I want to get the %tagname% from a file and copy them to a dictionary only tagname in python. A: this will get you a list of tags re.findall("%([^%]+)%", text) A: To get the list of tags, you can use the non-greedy version of the + operator, which has the advantage of bein...
How should I extract % delimited tags
I want to get the %tagname% from a file and copy them to a dictionary only tagname in python.
[ "this will get you a list of tags\nre.findall(\"%([^%]+)%\", text)\n\n", "To get the list of tags, you can use the non-greedy version of the + operator, which has the advantage of being simple:\nre.findall('%(.+?)%', text)\n\nIn fact, .+?% finds all characters of any type (a tag), and stops as soon as % is found ...
[ 7, 2 ]
[]
[]
[ "python", "text_extraction" ]
stackoverflow_0002665400_python_text_extraction.txt
Q: How can I use Perl's s/// in an expression? I got a headache looking for this: How do you use s/// in an expression as opposed to an assignment. To clarify what I mean, I'm looking for a perl equivalent of python's re.sub(...) when used in the following context: newstring = re.sub('ab', 'cd', oldstring) The only ...
How can I use Perl's s/// in an expression?
I got a headache looking for this: How do you use s/// in an expression as opposed to an assignment. To clarify what I mean, I'm looking for a perl equivalent of python's re.sub(...) when used in the following context: newstring = re.sub('ab', 'cd', oldstring) The only way I know how to do this in perl so far is: $old...
[ "You can use ($new = $old) =~ s/whatever/whateverelse/; for an exactly same functionality you are looking for:\nuse strict;\nmy $old = \"OLD\";\nmy $new;\n($new = $old) =~ s/OLD/NEW/;\nprint \"old=$old, new=$new\";\n\nProduces:\nold=OLD, new=NEW\n\nExactly what you want\nIf you're looking for a function, you can ju...
[ 11, 7, 7, 2, 1 ]
[]
[]
[ "perl", "python", "regex", "substitution", "variable_assignment" ]
stackoverflow_0002664812_perl_python_regex_substitution_variable_assignment.txt
Q: Fetch records using Group By from appengine datastore I am trying something like this: result = db.GqlQuery("SELECT * FROM myDataMode COUNT(Employee) GROUP BY(Department) WHERE Salary > :1"10000) And I am getting error : BadQueryError: Parse Error: Expected no additional symbols at symbol count Can any one pleas...
Fetch records using Group By from appengine datastore
I am trying something like this: result = db.GqlQuery("SELECT * FROM myDataMode COUNT(Employee) GROUP BY(Department) WHERE Salary > :1"10000) And I am getting error : BadQueryError: Parse Error: Expected no additional symbols at symbol count Can any one please help me.
[ "GQL isn't SQL. It doesn't have COUNT() or GROUP BY(). See the GQL reference for more information.\n", "Since GQL does not have COUNT and GROUP BY function.\nso I designed a solution for it:\nresult = db.GqlQuery( SELECT * form Employee)\n\nMake an Array which will have unique Departments from the result :\nif ...
[ 5, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002653516_google_app_engine_python.txt
Q: Any better way to generate a tuple of all possible tuples in form of (x1,y1,x2,y2)? I want to generate a tuple of tuple in form of ((x1,y1,x2,y2),...(x1,y1,x2,y2)) where x1,y1,x2,y2 are all in range of (0,8). Is there any other way rather than the following? S = list() for x1 in range(0, 8): for y1 in range(0,...
Any better way to generate a tuple of all possible tuples in form of (x1,y1,x2,y2)?
I want to generate a tuple of tuple in form of ((x1,y1,x2,y2),...(x1,y1,x2,y2)) where x1,y1,x2,y2 are all in range of (0,8). Is there any other way rather than the following? S = list() for x1 in range(0, 8): for y1 in range(0, 8): for x2 in range(0, 8): for y2 in range(0, 8): S....
[ "tuple([x1, y1, x2, y2] for x1 in range(0, 8) for x2 in range(0, 8) for y1 in range(0, 8) for y2 in range(0, 8))\n\nOr\nimport itertools\na = [range(0,8)]*4\nprint tuple(itertools.product(*a))\n\nNote that this returns a tuple of tuples. If you need a tuple of lists, use tuple(itertools.imap(list, itertools.product...
[ 8 ]
[]
[]
[ "python" ]
stackoverflow_0002666253_python.txt
Q: Problems with Routing URLs using CGI and Bottle.py I've been having difficulty getting anything more than a simple index / to return correctly using bottle.py in a CGI environment. When I try to return /hello I get a 404 response. However, if I request /index.py/hello import bottle from bottle import route @rou...
Problems with Routing URLs using CGI and Bottle.py
I've been having difficulty getting anything more than a simple index / to return correctly using bottle.py in a CGI environment. When I try to return /hello I get a 404 response. However, if I request /index.py/hello import bottle from bottle import route @route('/') def index(): return 'Index' @route('/hello'...
[ "The problem is that the <ifmodule> block is not relevant to your Apache server and the directives to mod_rewrite are not working. Start with the following .htaccess and then if you have a need, add the block according to your current apache version.\nDirectoryIndex index.py\nRewriteEngine on\nRewriteCond %{REQUEST...
[ 4 ]
[]
[]
[ ".htaccess", "bottle", "cgi", "python" ]
stackoverflow_0002664350_.htaccess_bottle_cgi_python.txt
Q: How to convert Word to images with win32com in python? I have googled an example for converting Word to Html. import win32com from win32com.client import Dispatch, constants w = win32com.client.Dispatch('Word.Application') w = win32com.client.DispatchEx('Word.Application') '''skip some code here''' wc = win3...
How to convert Word to images with win32com in python?
I have googled an example for converting Word to Html. import win32com from win32com.client import Dispatch, constants w = win32com.client.Dispatch('Word.Application') w = win32com.client.DispatchEx('Word.Application') '''skip some code here''' wc = win32com.client.constants w.ActiveDocument.SaveAs( FileName = f...
[ "You can try to print the Word document to PDF or TIFF file. I never did it myself, but if it can be done manually, most probably you can automate it.\n" ]
[ 0 ]
[]
[]
[ "image", "ms_word", "python", "windows" ]
stackoverflow_0002665895_image_ms_word_python_windows.txt
Q: How Can I Store My Images On The Server How do I store a photo on the server. I store them in a directory - "D:\zjm_code\basic_project\pinax\media\default\pinax\images\upload" but this now a lot of images. Is there another simple way? Thanks A: There are two common options. 1) Store them on the file system on th...
How Can I Store My Images On The Server
How do I store a photo on the server. I store them in a directory - "D:\zjm_code\basic_project\pinax\media\default\pinax\images\upload" but this now a lot of images. Is there another simple way? Thanks
[ "There are two common options.\n1) Store them on the file system on the server, preferably not all in one directory - but split logically.\n2) Store the images in a database, if you are using MySql you would do this using the \"blob\" type.\n", "When you store all the images in one directory it could quickly beco...
[ 1, 1 ]
[]
[]
[ "django", "photo_upload", "python" ]
stackoverflow_0002665921_django_photo_upload_python.txt
Q: TypeError: 'int' object is unsubscriptable in python >>> def merge(l1,l2): top1=0 top2=0 while l1[top1]!=None or l2[top2]!=None: if l1[top1]>l2[top2]: l.append(11[top1]) top1=top1+1 print "added"+l1[top1] else: ...
TypeError: 'int' object is unsubscriptable in python
>>> def merge(l1,l2): top1=0 top2=0 while l1[top1]!=None or l2[top2]!=None: if l1[top1]>l2[top2]: l.append(11[top1]) top1=top1+1 print "added"+l1[top1] else: l.append(l2[top2]) top2=top2+1 ...
[ "6th line of the code: you have 11 instead of l1.\n", "You have 11 instead of l1.\n" ]
[ 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0002666753_python.txt
Q: List to CSV in Python I am creating a CSV from a list of values. CSV File gets created but the csv is formed as a single column. Actually it should be multiple rows with multiple columns, instead it forms as a multiple rows with a single column. I am using the following code from random import choice import csv fi...
List to CSV in Python
I am creating a CSV from a list of values. CSV File gets created but the csv is formed as a single column. Actually it should be multiple rows with multiple columns, instead it forms as a multiple rows with a single column. I am using the following code from random import choice import csv fileObject = csv.writer(open(...
[ "If your intent is to write 175 rows, you need to use:\nfileObject.writerow(current_list)\n\ninstead of writerows. writerows is used when you have a list of rows (a list of lists), and in this case you have a single row.\n", "Are you sure about this delimiter? If my memory serves, the delimiter in a CSV file shou...
[ 6, 1 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0002666863_csv_python.txt
Q: Using multilingual and localeurl in django Using django-multilingual and localeurl. Small sample of my main page view: def main(request): #View for http://www.mysite.com/ name = Dog.objects.all()[0].full_name #this is a translated field return render_to_response("home.html", {"name" : name}) Entering http...
Using multilingual and localeurl in django
Using django-multilingual and localeurl. Small sample of my main page view: def main(request): #View for http://www.mysite.com/ name = Dog.objects.all()[0].full_name #this is a translated field return render_to_response("home.html", {"name" : name}) Entering http://www.mysite.com/ redirects me to http://www.my...
[ "I have the same problem, after rotation with positions in MIDDLEWARE_CLASSES I've got the right order:\nMIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware', \n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n...
[ 3, 1 ]
[]
[]
[ "django", "django_multilingual", "python" ]
stackoverflow_0002275966_django_django_multilingual_python.txt
Q: In SqlAlchemy, how to ignore m2m relationship attributes when merge? There is a m2m relation in my models, User and Role. I want to merge a role, but i DO NOT want this merge has any effect on user and role relation-ship. Unfortunately, for some complicate reason, role.users if not empty. I tried to set rol...
In SqlAlchemy, how to ignore m2m relationship attributes when merge?
There is a m2m relation in my models, User and Role. I want to merge a role, but i DO NOT want this merge has any effect on user and role relation-ship. Unfortunately, for some complicate reason, role.users if not empty. I tried to set role.users = None, but SA complains None is not a list. At this moment, I use...
[ "You'd better fix your code to avoid setting role.users for the item you are going to merge. But there is another way - setting cascade='none' for this relation. Then you lose an ability to save relationship from Role side, you'll have to save User with roles attribute set.\n" ]
[ 0 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0002665253_python_sqlalchemy.txt
Q: how to write bulk of data into xml file from backend and i want to bind the xml file into list? I want to write the bulk of data into xml file ,the data coming from the backend(mysql) using cgi by httpservice, read the xml file and bind it into list... can anyone send the sample code for this? Thank's in advance....
how to write bulk of data into xml file from backend and i want to bind the xml file into list?
I want to write the bulk of data into xml file ,the data coming from the backend(mysql) using cgi by httpservice, read the xml file and bind it into list... can anyone send the sample code for this? Thank's in advance..
[ "<mx:HTTPService url=\"backend-url.cgi\" id=\"service\"/>\n<mx:List dataProvider=\"{service.lastResult.yourElementName}\"/>\n\nYou should also\n\nCall service.send() from the Application's creationComplete handler\nSpecify the labelField, dataField etc for the List as applicable\n\n" ]
[ 0 ]
[]
[]
[ "apache_flex", "elips_studio", "mysql", "python" ]
stackoverflow_0002667109_apache_flex_elips_studio_mysql_python.txt
Q: python while loop def merge(l1,l2): i=0; while((l1[i]!=none)||(l2[i]!=none)): SyntaxError: invalid syntax being a newbie i can't figure out whats wrong with the abouve code. A: Replace || with or, make None upper-case (and lose the semi-colon): def merge(l1, l2): i = 0 while l1[i] != None or l2[i] != Non...
python while loop
def merge(l1,l2): i=0; while((l1[i]!=none)||(l2[i]!=none)): SyntaxError: invalid syntax being a newbie i can't figure out whats wrong with the abouve code.
[ "Replace || with or, make None upper-case (and lose the semi-colon):\ndef merge(l1, l2):\n i = 0\n while l1[i] != None or l2[i] != None:\n pass\n\n(As you can see, the parentheses were also redundant.)\nFurthermore, != None can be changed to is not None:\nwhile l1[i] is not None or l2[i] is not None:\n\n(Thank...
[ 14, 5 ]
[]
[]
[ "python", "syntax" ]
stackoverflow_0002666614_python_syntax.txt
Q: PIL 1.1.6 saves Photoshop CMYK image colour wrong I have an image. I want to resize it using PIL, but it comes out like this. Even without a resize, it still messes up the colour. Minimal code: from PIL import Image import os import urllib import webbrowser orig_url = 'http://mercedesclub.org.uk/images/stackov...
PIL 1.1.6 saves Photoshop CMYK image colour wrong
I have an image. I want to resize it using PIL, but it comes out like this. Even without a resize, it still messes up the colour. Minimal code: from PIL import Image import os import urllib import webbrowser orig_url = 'http://mercedesclub.org.uk/images/stackoverflow-question/least-popular-colours-_-500-x-500.jpg' ...
[ "Following interjay's link, the problem was fixed by upgrading to PIL 1.1.7. This includes an update to allow CMYK jpegs created by Photoshop to work correctly. But don't blame PIL, as Fredrik Lundh puts it:\n\"CMYK in JPEG is one big mess, mainly because Adobe got it wrong in Photoshop many years ago.\"\nBy the wa...
[ 4, 2, 1 ]
[]
[]
[ "image", "python", "python_imaging_library" ]
stackoverflow_0002667214_image_python_python_imaging_library.txt
Q: Simple python oo issue Have a look a this simple example. I don't quite understand why o1 prints "Hello Alex" twice. I would think that because of the default self.a is always reset to the empty list. Could someone explain to me what's the rationale here? Thank you so much. class A(object): def __init__(se...
Simple python oo issue
Have a look a this simple example. I don't quite understand why o1 prints "Hello Alex" twice. I would think that because of the default self.a is always reset to the empty list. Could someone explain to me what's the rationale here? Thank you so much. class A(object): def __init__(self, a=[]): self....
[ "Read this Pitfall about mutable default function arguments:\nhttp://www.ferg.org/projects/python_gotchas.html\nIn short, when you define\ndef __init__(self,a=[])\n\nThe list referenced by self.a by default is defined only once, at definition-time, not run-time. So each time you call o.a.append or o1.a.append, you ...
[ 12, 6 ]
[]
[]
[ "arguments", "mutable", "python" ]
stackoverflow_0002667688_arguments_mutable_python.txt
Q: Python proxy an application Does anyone know of a library that enables you to run an application inside some kind of sandbox, with virtual mouse and keyboard support. The use case would be to create some kind of visual test runner, that would replay all actions taken during recording and play them back. So far I ...
Python proxy an application
Does anyone know of a library that enables you to run an application inside some kind of sandbox, with virtual mouse and keyboard support. The use case would be to create some kind of visual test runner, that would replay all actions taken during recording and play them back. So far I found autopy, but the fact that i...
[ "On Linux, you could run autopy inside a VNC session.\nThere is also pywinauto or watsup.\n", "On Linux you can use Swinput for simulating mouse/key events. There are few Python wrappers around the X libraries: Python X Library, PyX11Remote. You may also looking for Xvfb, which allows to setup a virtual X11 serve...
[ 1, 0 ]
[]
[]
[ "events", "proxy", "python", "virtual" ]
stackoverflow_0002664944_events_proxy_python_virtual.txt
Q: What is this kind of mutual "recursion" called? My issue is with a certain style of code that very much resembles recursion, but isn't quite that. Recursion is, to quote Wikipedia, "a method of defining functions in which the function being defined is applied within its own definition". Similarly mutual recursion ...
What is this kind of mutual "recursion" called?
My issue is with a certain style of code that very much resembles recursion, but isn't quite that. Recursion is, to quote Wikipedia, "a method of defining functions in which the function being defined is applied within its own definition". Similarly mutual recursion applies another function which, directly or indirectl...
[ "As you point out, this is still mutual recursion. I don't think the \"something more\" you're asking about has a name; if it does I've never heard it.\n", "Mutual recursion is just a special case of indirect recursion.\n", "Apparently, it is called Mutual Recursion :)\nThe article even gives the same example ...
[ 2, 2, 1 ]
[]
[]
[ "closures", "mutual_recursion", "python", "recursion" ]
stackoverflow_0002667900_closures_mutual_recursion_python_recursion.txt
Q: Transferring Django Model Instances through RPC Suppose I have 2 sites that shares a common Model. What would be the best way to transfer a new Model instance created at Site A and save it in Site B's database? Could you please also recommend APIs for sending and receiving the data? A: The new version of Django ...
Transferring Django Model Instances through RPC
Suppose I have 2 sites that shares a common Model. What would be the best way to transfer a new Model instance created at Site A and save it in Site B's database? Could you please also recommend APIs for sending and receiving the data?
[ "The new version of Django supports multiple databases, perhaps you could setup the second database on site A then just save the model twice:\nmy_object.save()\nmy_object.save(using='database_b')\n\nif database A always updates database B then you should look into database replication\n", "Read up on Django's ser...
[ 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002665208_django_python.txt
Q: Pylons: question about websetup.py use reading pylons documentations I did understand that websetup:setup_app is only called when the application is setup at first time by paster script. But, I found now, setup_app is call every time that application starts. Debugging the code, this behaviour seems right because i...
Pylons: question about websetup.py use
reading pylons documentations I did understand that websetup:setup_app is only called when the application is setup at first time by paster script. But, I found now, setup_app is call every time that application starts. Debugging the code, this behaviour seems right because in appinstall.setup_config the module is load...
[ "Ok, I was wrong. The websetup is used by the setup script and before the test are executed. \nA controller make an import for a test module, and then setup_app is called.\nThanks!.\n" ]
[ 2 ]
[]
[]
[ "paster", "pylons", "python" ]
stackoverflow_0002667529_paster_pylons_python.txt
Q: redefine __and__ operator Why I can't redefine the __and__ operator? class Cut(object): def __init__(self, cut): self.cut = cut def __and__(self, other): return Cut("(" + self.cut + ") && (" + other.cut + ")") a = Cut("a>0") b = Cut("b>0") c = a and b print c.cut() I want (a>0) && ...
redefine __and__ operator
Why I can't redefine the __and__ operator? class Cut(object): def __init__(self, cut): self.cut = cut def __and__(self, other): return Cut("(" + self.cut + ") && (" + other.cut + ")") a = Cut("a>0") b = Cut("b>0") c = a and b print c.cut() I want (a>0) && (b>0), but I got b, that the us...
[ "__and__ is the binary (bitwise) & operator, not the logical and operator.\nBecause the and operator is a short-circuit operator, it can't be implemented as a function. That is, if the first argument is false, the second argument isn't evaluated at all. If you try to implement that as a function, both arguments h...
[ 13, 1 ]
[]
[]
[ "and_operator", "operators", "python", "redefine" ]
stackoverflow_0002668667_and_operator_operators_python_redefine.txt
Q: Vim syntax highlighting not working (but works in gvim?) I've followed all instructions given on this site with an empty .vim folder, but for some reason, python highlighting is not working on my system. It only highlights the comments and a few variables - nothing like the picture. http://concisionandconcinnity.b...
Vim syntax highlighting not working (but works in gvim?)
I've followed all instructions given on this site with an empty .vim folder, but for some reason, python highlighting is not working on my system. It only highlights the comments and a few variables - nothing like the picture. http://concisionandconcinnity.blogspot.com/2009/07/vim-part-i-improved-python-syntax.html Is ...
[ "If you don't want to change the colorscheme, you should check out CSApprox.vim. It allows you to use colorschemes made for gvim in vim.\nhttp://www.vim.org/scripts/script.php?script_id=2390\n", "The colorscheme used in that tutorial is only for gvim. Try changing your colorscheme.\n", "I think ubuntu installs...
[ 2, 0, 0 ]
[]
[]
[ "python", "vim" ]
stackoverflow_0002662726_python_vim.txt
Q: Python CGI Premature end of script error depending on script parameters I have a python script which should parse a file and produce some output to disk, as well as returning a webpage linking to the outputted files. When run with a file posted from the HTML form I get no HTML output back, just a 500 error page an...
Python CGI Premature end of script error depending on script parameters
I have a python script which should parse a file and produce some output to disk, as well as returning a webpage linking to the outputted files. When run with a file posted from the HTML form I get no HTML output back, just a 500 error page and the error_log contains the line: [Mon Apr 19 15:03:23 2010] [error] [client...
[ "When C library gets segmentation fault or otherwise exits in a bad way, the stdout buffer may not be flushed. Using -u option of Python interpreter or flushing it manually should solve \"Premature end of script headers\", but it won't help with actual problem.\n" ]
[ 1 ]
[]
[]
[ "cgi", "openbabel", "python" ]
stackoverflow_0002668256_cgi_openbabel_python.txt
Q: Writing a unique identifier to script? I'd like to write a subscript that adds a unique identifier (machine time) to a script everytime that it runs. However, each time I edit the script (in IDLE) the indetifiers are over-written. Is there a elegant way of doing this. The script that I wrote appears below. import ...
Writing a unique identifier to script?
I'd like to write a subscript that adds a unique identifier (machine time) to a script everytime that it runs. However, each time I edit the script (in IDLE) the indetifiers are over-written. Is there a elegant way of doing this. The script that I wrote appears below. import os, time f = open('sys_time_append.py','r')...
[ "I expect this is a dangerous thing to do, but it works:\nimport os, time\n\nprint \"Hi, \", __file__, '!'\n\nwith open(__file__, 'a') as fout:\n fout.write('\\n#'+str(time.time())+' s r\\n')\n\nNote that I get the name of the script as __file__, as well (but this isn't the full pathname, so there can be problem...
[ 0 ]
[]
[]
[ "file", "python", "rewrite" ]
stackoverflow_0002669010_file_python_rewrite.txt
Q: Getting all new messages from a Maildir in python I have a mail dir: foo@foo:~/Maildir$ ls -l total 288 drwx------ 2 foo foo 155648 2010-04-19 15:19 cur -rw------- 1 foo foo 440 2010-03-20 08:50 dovecot.index.log -rw------- 1 foo foo 112 2010-03-20 08:49 dovecot-uidlist -rw------- 1 foo foo 8 2010-03-20...
Getting all new messages from a Maildir in python
I have a mail dir: foo@foo:~/Maildir$ ls -l total 288 drwx------ 2 foo foo 155648 2010-04-19 15:19 cur -rw------- 1 foo foo 440 2010-03-20 08:50 dovecot.index.log -rw------- 1 foo foo 112 2010-03-20 08:49 dovecot-uidlist -rw------- 1 foo foo 8 2010-03-20 08:49 dovecot-uidvalidity -rw------- 1 foo foo 0 ...
[ "The folder /home/foo/Maildir/new is not a Maildir, it is part of the maildir. If you want to use mailbox.Maildir, you need to ignore the subdirectories and files which are part of the spec. Otherwise, you will not be treating it as a Maildir at all.\nThe Maildir module should read messages from new and cur, and ma...
[ 2 ]
[]
[]
[ "maildir", "python" ]
stackoverflow_0002669122_maildir_python.txt
Q: Detect and record a sound with python I'm using this program to record a sound in python: Detect & Record Audio in Python I want to change the program to start recording when sound is detected by the sound card input. Probably should compare the input sound level in chunk, but how do this? A: You could try somet...
Detect and record a sound with python
I'm using this program to record a sound in python: Detect & Record Audio in Python I want to change the program to start recording when sound is detected by the sound card input. Probably should compare the input sound level in chunk, but how do this?
[ "You could try something like this:\nbased on this question/answer\n# this is the threshold that determines whether or not sound is detected\nTHRESHOLD = 0\n\n#open your audio stream \n\n# wait until the sound data breaks some level threshold\nwhile True:\n data = stream.read(chunk)\n # check level against...
[ 13, 5, 1 ]
[]
[]
[ "audio", "detect", "python", "record" ]
stackoverflow_0002668442_audio_detect_python_record.txt
Q: Statistical analysis on large data set to be published on the web I have a non-computer related data logger, that collects data from the field. This data is stored as text files, and I manually lump the files together and organize them. The current format is through a csv file per year per logger. Each file is aro...
Statistical analysis on large data set to be published on the web
I have a non-computer related data logger, that collects data from the field. This data is stored as text files, and I manually lump the files together and organize them. The current format is through a csv file per year per logger. Each file is around 4,000,000 lines x 7 loggers x 5 years = a lot of data. some of the ...
[ "I think you can utilize your current combination(python/numpy/matplotlib) fully if the number of users are not too big. I do some similar works, and my data size a little more than 10g. Data are stored in a few sqlite files, and i use numpy to analyze data, PIL/matplotlib to generate chart files(png, gif), cherryp...
[ 1 ]
[]
[]
[ "php", "postgresql", "python", "statistics" ]
stackoverflow_0002667537_php_postgresql_python_statistics.txt
Q: What are some best practices for structuring cherrypy apps? I'm writing a cherrypy app and I was wondering what the best way is for structuring my handlers and code for larger applications? I realize assignment is simple trough cherrypy.root, but what are some practices for writing the handlers and assigning them?...
What are some best practices for structuring cherrypy apps?
I'm writing a cherrypy app and I was wondering what the best way is for structuring my handlers and code for larger applications? I realize assignment is simple trough cherrypy.root, but what are some practices for writing the handlers and assigning them? (Allow me to prove my confusion!) My initial thought is to write...
[ "CherryPy deliberately doesn't require you to subclass from a framework-provided base class so that you are free to design your own inheritance mechanism, or, more importantly, use none at all. You are certainly free to define your own base class and inherit from it; in this way, you can standardize handler constru...
[ 10, 5 ]
[]
[]
[ "cherrypy", "program_structure", "python" ]
stackoverflow_0002663218_cherrypy_program_structure_python.txt
Q: How do I make BeautifulSoup parse the contents of textarea tags as HTML? Before 3.0.5, BeautifulSoup used to treat the contents of <textarea> as HTML. It now treats it as text. The document I am parsing has HTML inside the textarea tags, and I am trying to process it. I've tried: for textarea in soup.findAll('...
How do I make BeautifulSoup parse the contents of textarea tags as HTML?
Before 3.0.5, BeautifulSoup used to treat the contents of <textarea> as HTML. It now treats it as text. The document I am parsing has HTML inside the textarea tags, and I am trying to process it. I've tried: for textarea in soup.findAll('textarea'): contents = BeautifulSoup.BeautifulSoup(textarea.contents) ...
[ "This seems to work fairly well (if I correctly understood what you wanted):\nfor textarea in soup.findAll('textarea'):\n contents = BeautifulSoup.BeautifulSoup(textarea.contents[0]).renderContents()\n textarea.replaceWith(contents)\n\n", "I'm now using the following code which mostly works. Your milage may...
[ 2, 0 ]
[]
[]
[ "beautifulsoup", "html_parsing", "python" ]
stackoverflow_0002665390_beautifulsoup_html_parsing_python.txt
Q: Python Wildcard Import Vs Named Import Ok, I have some rather odd behavior in one of my Projects and I'm hoping someone can tell me why. My file structure looks like this: MainApp.py res/ __init__.py elements/ __init__.py MainFrame.py Inside of MainFrame.py I've defined a class named RPMWindow which ...
Python Wildcard Import Vs Named Import
Ok, I have some rather odd behavior in one of my Projects and I'm hoping someone can tell me why. My file structure looks like this: MainApp.py res/ __init__.py elements/ __init__.py MainFrame.py Inside of MainFrame.py I've defined a class named RPMWindow which extends wx.Frame. In MainApp.py this works: ...
[ "You have circular imports:\nMainFrame.py is indirectly importing MainApp.py, and MainApp.py is importing MainFrame.py. As a result, when MainApp.py is importing MainFrame.py, the RPMWindow class hasn't been defined yet and you get the ImportError.\n", "i don't have time to look into why the wildcard is working f...
[ 8, 0, 0 ]
[]
[]
[ "import", "named", "python", "wildcard" ]
stackoverflow_0002669627_import_named_python_wildcard.txt
Q: Avoiding accidentally catching KeyboardInterrupt and SystemExit in Python 2.4 In Python scripts, there are many cases where a keyboard interrupt (Ctrl-C) fails to kill the process because of a bare except clause somewhere in the code: try: foo() except: bar() The standard solution in Python 2.5 or higher ...
Avoiding accidentally catching KeyboardInterrupt and SystemExit in Python 2.4
In Python scripts, there are many cases where a keyboard interrupt (Ctrl-C) fails to kill the process because of a bare except clause somewhere in the code: try: foo() except: bar() The standard solution in Python 2.5 or higher is to catch Exception rather than using bare except clauses: try: foo() except ...
[ "According to the Python documentation, the right way to handle this in Python versions earlier than 2.5 is:\ntry:\n foo()\nexcept (KeyboardInterrupt, SystemExit):\n raise\nexcept:\n bar()\n\nThat's very wordy, but at least it's a solution.\n" ]
[ 14 ]
[]
[]
[ "python", "python_2.4" ]
stackoverflow_0002669750_python_python_2.4.txt
Q: Python large variable RAM usage Say there is a dict variable that grows very large during runtime - up into millions of key:value pairs. Does this variable get stored in RAM, effectively using up all the available memory and slowing down the rest of the system? Asking the interpreter to display the entire dict i...
Python large variable RAM usage
Say there is a dict variable that grows very large during runtime - up into millions of key:value pairs. Does this variable get stored in RAM, effectively using up all the available memory and slowing down the rest of the system? Asking the interpreter to display the entire dict is a bad idea, but would it be okay as...
[ "Yes, the dict will be stored in the process memory. So if it gets large enough that there's not enough room in the system RAM, then you can expect to see massive slowdown as the system starts swapping memory to and from disk.\nOthers have said that a few million items shouldn't pose a problem; I'm not so sure. ...
[ 10, 5, 4, 2 ]
[]
[]
[ "memory", "python", "ram", "variables" ]
stackoverflow_0002670005_memory_python_ram_variables.txt
Q: Can not append a date to a list! Is there a reson why date can not append to a list? vdate = str(dates.date) vdats = vdate.split("") vdats = vdats[0] vbalance.append(vdats) just did not work? What am I doing wrong? UPDATE Error message:AttributeError: 'Decimal' object has no attribute 'append' A: Update: I'd s...
Can not append a date to a list!
Is there a reson why date can not append to a list? vdate = str(dates.date) vdats = vdate.split("") vdats = vdats[0] vbalance.append(vdats) just did not work? What am I doing wrong? UPDATE Error message:AttributeError: 'Decimal' object has no attribute 'append'
[ "Update:\nI'd say the error you get is pretty self explanatory: vbalance is just not a list. So you cannot append to it.\nWhat is the intention of your code, what do you want to achieve?\nIt might be, that you want to add to vbalance:\nvbalance += int(vdats)\n\nor that you have to create a list beforehand:\nl = lis...
[ 5, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002668822_python.txt
Q: vectorizing a for loop in numpy/scipy? I'm trying to vectorize a for loop that I have inside of a class method. The for loop has the following form: it iterates through a bunch of points and depending on whether a certain variable (called "self.condition_met" below) is true, calls a pair of functions on the point,...
vectorizing a for loop in numpy/scipy?
I'm trying to vectorize a for loop that I have inside of a class method. The for loop has the following form: it iterates through a bunch of points and depending on whether a certain variable (called "self.condition_met" below) is true, calls a pair of functions on the point, and adds the result to a list. Each point h...
[ "This only takes a couple lines of code in NumPy (the rest is just creating a data set, a couple of functions, and set-up).\nimport numpy as NP\n\n# create two functions \nfnx1 = lambda x : x**2\nfnx2 = lambda x : NP.sum(fnx1(x))\n\n# create some data\nM = NP.random.randint(10, 99, 40).reshape(8, 5)\n\n# creates in...
[ 3, 2, 0 ]
[]
[]
[ "numpy", "optimization", "python", "scipy", "vectorization" ]
stackoverflow_0002670112_numpy_optimization_python_scipy_vectorization.txt
Q: architecture python question creating a distributed crawling python app. it consists of a master server, and associated client apps that will run on client servers. the purpose of the client app is to run across a targeted site, to extract specific data. the clients need to go "deep" within the site, behind multip...
architecture python question
creating a distributed crawling python app. it consists of a master server, and associated client apps that will run on client servers. the purpose of the client app is to run across a targeted site, to extract specific data. the clients need to go "deep" within the site, behind multiple levels of forms, so each client...
[ "This sounds like a usecase for MapReduce on Hadoop.\nHadoop Map/Reduce is a software framework for easily writing applications which process vast amounts of data (multi-terabyte data-sets) in-parallel on large clusters (thousands of nodes) of commodity hardware in a reliable, fault-tolerant manner. In your case, t...
[ 3, 0, 0 ]
[]
[]
[ "architecture", "distributed", "python", "web_crawler" ]
stackoverflow_0002670323_architecture_distributed_python_web_crawler.txt
Q: Filtering python string through external program What's the cleanest way of filtering a Python string through an external program? In particular, how do you write the following function? def filter_through(s, ext_cmd): # Filters string s through ext_cmd, and returns the result. # Example usage: # filter a mul...
Filtering python string through external program
What's the cleanest way of filtering a Python string through an external program? In particular, how do you write the following function? def filter_through(s, ext_cmd): # Filters string s through ext_cmd, and returns the result. # Example usage: # filter a multiline string through tac to reverse the order. filter...
[ "Use the subprocess module.\nIn your case, you could use something like\nimport subprocess\nproc=subprocess.Popen(['tac','-'], shell=True, stdin=subprocess.PIPE,\n stdout=subprocess.PIPE, )\noutput,_=proc.communicate('one\\ntwo\\nthree\\n')\nprint output\n\nNote that the command sent is tac - s...
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0002670584_python.txt
Q: Web Security: Worst-Case Situation I currently have built a system that checks user IP, browser, and a random-string cookie to determine if he is an admin. In the worst case, someone steals my cookie, uses the same browser I do, and masks his IP to appear as mine. Is there another layer of security I should add on...
Web Security: Worst-Case Situation
I currently have built a system that checks user IP, browser, and a random-string cookie to determine if he is an admin. In the worst case, someone steals my cookie, uses the same browser I do, and masks his IP to appear as mine. Is there another layer of security I should add onto my script to make it more secure? EDI...
[ "Checking the browser is a complete and absolute waste of code. There is no point in writing a secuirty system that is trivial for an attacker to bypass. If the attacker obtains the session id via xss or sniffing the line then they will also have your \"user-agent\".\nChecking the ip address will force the attac...
[ 7, 4, 1, 1 ]
[]
[]
[ "python", "security" ]
stackoverflow_0002670346_python_security.txt
Q: Configuration files for C in linux I have an executable that run time should take configuration parameters from a script file. This way I dont need to re-compile the code for every configuration change. Right now I have all the configuration values in a .h file. Everytime I change it i need to re-compile. The pla...
Configuration files for C in linux
I have an executable that run time should take configuration parameters from a script file. This way I dont need to re-compile the code for every configuration change. Right now I have all the configuration values in a .h file. Everytime I change it i need to re-compile. The platform is C, gcc under Linux. What is the...
[ "I recommend Lua. It was designed for configuration.\n", "The simplest way would be to have a text file containing something like:\nkey = value\nkey2 = anothervalue\n....\nkeyn = etc\n\nAnd then you simply open this file and parse it, putting everything in something like a hashmap/dictionary.\nA quick search on g...
[ 5, 2, 2, 1, 1, 0, 0 ]
[]
[]
[ "c", "gcc", "linux", "lua", "python" ]
stackoverflow_0002667866_c_gcc_linux_lua_python.txt
Q: Is there a PHP equivalent function to the Python os.path.normpath()? Is there a PHP equivalent function to the Python os.path.normpath()? Or how can i get the exactly same functionality in PHP? A: Here is my 1:1 rewrite of normpath() method from Python's posixpath.py in PHP: function normpath($path) { if (em...
Is there a PHP equivalent function to the Python os.path.normpath()?
Is there a PHP equivalent function to the Python os.path.normpath()? Or how can i get the exactly same functionality in PHP?
[ "Here is my 1:1 rewrite of normpath() method from Python's posixpath.py in PHP:\nfunction normpath($path)\n{\n if (empty($path))\n return '.';\n\n if (strpos($path, '/') === 0)\n $initial_slashes = true;\n else\n $initial_slashes = false;\n if (\n ($initial_slashes) &&\n ...
[ 6, 2 ]
[]
[]
[ "path", "php", "python" ]
stackoverflow_0002670299_path_php_python.txt
Q: Intersection between bezier curve and a line segment I am writing a game in Python (with pygame) that requires me to generate random but nice-looking "sea" for each new game. After a long search I settled on an algorithm that involves Bezier curves as defined in padlib.py. I now need to figure out when the curves ...
Intersection between bezier curve and a line segment
I am writing a game in Python (with pygame) that requires me to generate random but nice-looking "sea" for each new game. After a long search I settled on an algorithm that involves Bezier curves as defined in padlib.py. I now need to figure out when the curves generated by padlib intersect a line segment. The brute fo...
[ "As a rough outline, rotate and translate the system so that the line segment lies on the X axis. Now the y coordinate is a cubic function of the parameter t. Find the 'zeros' (the analytic formulae will be found in good math texts or wikipedia). Now evaluate the x coordinates corresponding to those zero points and...
[ 10, 6 ]
[]
[]
[ "geometry", "math", "pygame", "python", "spline" ]
stackoverflow_0001813719_geometry_math_pygame_python_spline.txt
Q: Large Django application layout I am in a team developing a web-based university portal, which will be based on Django. We are still in the exploratory stages, and I am trying to find the best way to lay the project/development environment out. My initial idea is to develop the system as a Django "app", which cont...
Large Django application layout
I am in a team developing a web-based university portal, which will be based on Django. We are still in the exploratory stages, and I am trying to find the best way to lay the project/development environment out. My initial idea is to develop the system as a Django "app", which contains sub-applications to separate out...
[ "The best way that I have found to go about this is to create applications and then a project to glue them together. Most of my projects have similar apps which are included in each. Emails, notes, action reminders, user auth, etc. My preferred layout is like so:\n\nproject/\n\n\nsettings.py\nurls.py\nviews.py\n...
[ 33, 4, 4 ]
[]
[]
[ "conventions", "django", "python" ]
stackoverflow_0002670031_conventions_django_python.txt
Q: Calling Python from Java through scripting engine (jython)? I'm trying to call Jython from a Java 6 application using javax.script: import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; public class jythonEx { public static void main (String args[]) th...
Calling Python from Java through scripting engine (jython)?
I'm trying to call Jython from a Java 6 application using javax.script: import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; public class jythonEx { public static void main (String args[]) throws ScriptException { ScriptEngineManager mgr = new ...
[ "You have to register your engine first. \nFrom: ScriptEngineManager.getEngineByName:\n\n[...] first searches for a ScriptEngineFactory that has been registered as a handle [...] Returns null if no such factory was found\n\nThe user guide says to use it with JSR-223 you have to:\n\nAs of Jython 2.5.1 an implementat...
[ 15, 2 ]
[]
[]
[ "java", "javax.script", "jython", "python" ]
stackoverflow_0002671768_java_javax.script_jython_python.txt
Q: Twisted Python getPage I tried to get support on this but I am TOTALLY confused. Here's my code: from twisted.internet import reactor from twisted.web.client import getPage from twisted.web.error import Error from twisted.internet.defer import DeferredList from sys import argv class GrabPage: def __init__(self,...
Twisted Python getPage
I tried to get support on this but I am TOTALLY confused. Here's my code: from twisted.internet import reactor from twisted.web.client import getPage from twisted.web.error import Error from twisted.internet.defer import DeferredList from sys import argv class GrabPage: def __init__(self, page): self.page = page ...
[ "You're missing the basics of how Twisted operates. It all revolves around the reactor, which you're never even running. Think of the reactor like this:\n\n(source: krondo.com) \nUntil you start the reactor, by setting up deferreds all you're doing is chaining them with no events from which to fire.\nI recommend ...
[ 14 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0002671780_python_twisted.txt
Q: limits of number of files in a single directory in unix/linux using Python is it bad to output many files to the same directory in unix/linux? I run thousands of jobs on a cluster and each outputs a file, to one directory. The upper bound here is around ~50,000 files. Can IO be limited in speed in light of this?...
limits of number of files in a single directory in unix/linux using Python
is it bad to output many files to the same directory in unix/linux? I run thousands of jobs on a cluster and each outputs a file, to one directory. The upper bound here is around ~50,000 files. Can IO be limited in speed in light of this? If so, does the problem go away with a nested directory structure? Thanks.
[ "See:\nHow many files can I put in a directory?\n", "I believe that most filesystems store the names of contained files in a list (or some other linear-time access data structure) so storing large numbers of files in a single directory can cause slowness for simple operations like listing. Having a nested struct...
[ 2, 0, 0 ]
[]
[]
[ "cluster_computing", "file_io", "linux", "python", "unix" ]
stackoverflow_0002671743_cluster_computing_file_io_linux_python_unix.txt
Q: I have a tab delimeted file that I want to convert into a mysql table I have a tab delimeted file that I want to convert into a mysql table. there are 25 tab delimeted fields in the text file. I can get the values in when I construct the SQL statement word by word and get each value individually stated in the VAL...
I have a tab delimeted file that I want to convert into a mysql table
I have a tab delimeted file that I want to convert into a mysql table. there are 25 tab delimeted fields in the text file. I can get the values in when I construct the SQL statement word by word and get each value individually stated in the VALUES part but when I try to get the list as a whole it does not work. Here i...
[ "Why not just use LOAD DATA INFILE from mysql?\n", "stmt=\"%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s\" % (linex[0],linex[1],linex[2], ........ )\n....\ncursor.execute(stmt) \n....\n\n" ]
[ 2, 0 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0002671510_mysql_python.txt
Q: Python: How can I use Twisted as the transport for SUDS? I have a project that is based on Twisted used to communicate with network devices and I am adding support for a new vendor (Citrix NetScaler) whose API is SOAP. Unfortunately the support for SOAP in Twisted still relies on SOAPpy, which is badly out of dat...
Python: How can I use Twisted as the transport for SUDS?
I have a project that is based on Twisted used to communicate with network devices and I am adding support for a new vendor (Citrix NetScaler) whose API is SOAP. Unfortunately the support for SOAP in Twisted still relies on SOAPpy, which is badly out of date. In fact as of this question (I just checked), twisted.web.s...
[ "The default interpretation of transport in the context of Twisted is probably an implementation of twisted.internet.interfaces.ITransport. At this layer, you're basically dealing with raw bytes being sent and received over a socket of some sort (UDP, TCP, and SSL being the most commonly used three). This isn't r...
[ 13 ]
[]
[]
[ "python", "soap", "suds", "transport", "twisted" ]
stackoverflow_0002671228_python_soap_suds_transport_twisted.txt
Q: Multiple, Simultaneous Factories and Protocols in Twisted: Same Service, Different Ports Greetings, Forum. I'm working on a program in Python that uses Twisted to manage networking. The basis of this program is a TCP service that is to listen for connections on multiple ports. However, instead of using one Twist...
Multiple, Simultaneous Factories and Protocols in Twisted: Same Service, Different Ports
Greetings, Forum. I'm working on a program in Python that uses Twisted to manage networking. The basis of this program is a TCP service that is to listen for connections on multiple ports. However, instead of using one Twisted factory to handle a protocol object for each port, I am trying to use a separate factory fo...
[ "You can definitely do what you want -- it's hard to tell what you're doing wrong without seeing your code, but I'd bet you have clients = [] in your factory class instead of\nself.clients = []\n\nin your factory class's __init__ method.\n" ]
[ 6 ]
[]
[]
[ "factory", "protocols", "python", "twisted" ]
stackoverflow_0002671877_factory_protocols_python_twisted.txt
Q: Fast JSON serialization (and comparison with Pickle) for cluster computing in Python? I have a set of data points, each described by a dictionary. The processing of each data point is independent and I submit each one as a separate job to a cluster. Each data point has a unique name, and my cluster submission wr...
Fast JSON serialization (and comparison with Pickle) for cluster computing in Python?
I have a set of data points, each described by a dictionary. The processing of each data point is independent and I submit each one as a separate job to a cluster. Each data point has a unique name, and my cluster submission wrapper simply calls a script that takes a data point's name and a file describing all the da...
[ "marshal is fastest, but pickle per se is not -- maybe you mean cPickle (which is pretty fast, esp. with a -1 protocol). So, apart from readability issues, here's some code to show various possibilities:\nimport pickle\nimport cPickle\nimport marshal\nimport json\n\ndef maked(N=5400):\n d = {}\n for x in range(N...
[ 7, 1 ]
[]
[]
[ "cluster_computing", "json", "pickle", "python", "serialization" ]
stackoverflow_0002671668_cluster_computing_json_pickle_python_serialization.txt
Q: How should I rewrite my database execute/commit to make it amenable to unit testing? I've been trying to get started with unit-testing while working on a little cli program. My program basically parses the command line arguments and options, and decides which function to call. Each of the functions performs some o...
How should I rewrite my database execute/commit to make it amenable to unit testing?
I've been trying to get started with unit-testing while working on a little cli program. My program basically parses the command line arguments and options, and decides which function to call. Each of the functions performs some operation on a database. So, for instance, I might have a create function: def create(self,...
[ "Alex's answer covers the dependency injection approach. Another is to factor your method. As it stands, it has two phases: construct a SQL statement, and execute the SQL statement. You don't want to test the second phase: you didn't write the SQL engine or the database, you can assume they work properly. Phase...
[ 8, 6, 3, 0 ]
[]
[]
[ "database", "python", "unit_testing" ]
stackoverflow_0002671947_database_python_unit_testing.txt
Q: PyQt QAbstractListModel seems to ignore tristate flags I've been trying for a couple days to figure out why my QAbstractLisModel won't allow a user to toggle a checkable item in three states. The model returns the Qt.IsTristate and Qt.ItemIsUserCheckable in the flags() method, but when the program runs only Qt.Che...
PyQt QAbstractListModel seems to ignore tristate flags
I've been trying for a couple days to figure out why my QAbstractLisModel won't allow a user to toggle a checkable item in three states. The model returns the Qt.IsTristate and Qt.ItemIsUserCheckable in the flags() method, but when the program runs only Qt.Checked and Qt.Unchecked are toggled on edit. class cboxModel(Q...
[ "You may need to create a custom slot on the clicked() signal that cycles through the three states. Generally, tri-state elements are only able to be clicked on and off directly, and are only in the partially checked mode if sub-elements are in different states. \n", "Looks like it's a known issue, check here:\n1...
[ 0, 0 ]
[]
[]
[ "pyqt4", "python" ]
stackoverflow_0002642197_pyqt4_python.txt
Q: Why do I get a TypeError: 'module' object is not callable when trying to import the random module? I am using Python 2.6 and am trying to run a simple random number generator program (random.py): import random for i in range(5): # random float: 0.0 <= number < 1.0 print random.random(), # random flo...
Why do I get a TypeError: 'module' object is not callable when trying to import the random module?
I am using Python 2.6 and am trying to run a simple random number generator program (random.py): import random for i in range(5): # random float: 0.0 <= number < 1.0 print random.random(), # random float: 10 <= number < 20 print random.uniform(10, 20), # random integer: 100 <= number <= 1000 ...
[ "Name your file something else. In Python a script is a module, whose name is determined by the filename. So when you start out your file random.py with import random you are creating a loop in the module structure.\n", "Rename your sample program file to myrandom.py or something. You are confusing import I wo...
[ 23, 7, 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002672270_python.txt
Q: What does a leading `\x` mean in a Python string `\xaa` What is difference between 'aa' and '\xaa'? What does the \x part mean? And which chapter of the Python documentation covers this topic? A: The leading \x escape sequence means the next two characters are interpreted as hex digits for the character code, so...
What does a leading `\x` mean in a Python string `\xaa`
What is difference between 'aa' and '\xaa'? What does the \x part mean? And which chapter of the Python documentation covers this topic?
[ "The leading \\x escape sequence means the next two characters are interpreted as hex digits for the character code, so \\xaa equals chr(0xaa), i.e., chr(16 * 10 + 10) -- a small raised lowercase 'a' character.\nEscape sequences are documented in a short table here in the Python docs.\n" ]
[ 137 ]
[ "That's unicode character escaping. See \"Unicode Constructors\" on PEP 100\n" ]
[ -9 ]
[ "escaping", "python", "string" ]
stackoverflow_0002672326_escaping_python_string.txt
Q: Activate a python virtual environment using activate_this.py in a fabfile on Windows I have a Fabric task that needs to access the settings of my Django project. On Windows, I'm unable to install Fabric into the project's virtualenv (issues with Paramiko + pycrypto deps). However, I am able to install Fabric in my...
Activate a python virtual environment using activate_this.py in a fabfile on Windows
I have a Fabric task that needs to access the settings of my Django project. On Windows, I'm unable to install Fabric into the project's virtualenv (issues with Paramiko + pycrypto deps). However, I am able to install Fabric in my system-wide site-packages, no problem. I have installed Django into the project's virtual...
[ "After some digging, I found out that this is an issue with the activate_this.py script. In it's current state, virtualenv<=1.4.6, this script assumes that the path to the site-packages directory is the same for all platforms. However, the path to the site-packages directory differs between *nix like platforms and ...
[ 6, 2 ]
[]
[]
[ "django", "fabric", "python", "virtualenv", "windows_xp" ]
stackoverflow_0002643612_django_fabric_python_virtualenv_windows_xp.txt
Q: scrapy - python question Maybe not the correct place to post. But, I'm going to try anyway! I've got a couple of test python parsing scripts that I created. They work enough for me to test what I'm working on. However, I recently came across the python framework, Scrapy, which is used for web scraping. My app run...
scrapy - python question
Maybe not the correct place to post. But, I'm going to try anyway! I've got a couple of test python parsing scripts that I created. They work enough for me to test what I'm working on. However, I recently came across the python framework, Scrapy, which is used for web scraping. My app runs in a distributed process, ac...
[ "A good place to send an email would be their Google Group. There will likely be many users to help answer your general questions.\nThey also have an IRC channel for more rapid and direct interaction.\n" ]
[ 7 ]
[]
[]
[ "distributed", "python", "scrapy", "web_crawler" ]
stackoverflow_0002672401_distributed_python_scrapy_web_crawler.txt
Q: Testing for the existence of a field in a class i have a quick question. I have a 2D array that stores an instance of a class. The elements of the array are assigned a particular class based on a text file that is read earlier in the program. Since i do not know without looking in the file what class is stored at ...
Testing for the existence of a field in a class
i have a quick question. I have a 2D array that stores an instance of a class. The elements of the array are assigned a particular class based on a text file that is read earlier in the program. Since i do not know without looking in the file what class is stored at a particular element i could refer to a field that do...
[ "hasattr(x, 'foo') is a built-in binary function that checks whether object x has an attribute x.foo (whether it gets it from its class or not), which seems close to what you're asking. Whether what you're asking is actually what you should be asking is a different issue -- as @Eli's answer suggests, your design s...
[ 38, 3, 1 ]
[]
[]
[ "class", "exists", "python" ]
stackoverflow_0002672801_class_exists_python.txt
Q: Multiple counters in a single for loop : Python Is it possible in Python to run multiple counters in a single for loop as in C/C++? I would want something like -- for i,j in x,range(0,len(x)): I know Python interprets this differently and why, but how would I run two loop counters concurrently in a single for loop...
Multiple counters in a single for loop : Python
Is it possible in Python to run multiple counters in a single for loop as in C/C++? I would want something like -- for i,j in x,range(0,len(x)): I know Python interprets this differently and why, but how would I run two loop counters concurrently in a single for loop?
[ "You want zip in general, which combines two iterators, as @S.Mark says. But in this case enumerate does exactly what you need, which means you don't have to use range directly:\nfor j, i in enumerate(x):\n\nNote that this gives the index of x first, so I've reversed j, i.\n", "You might want to use zip\nfor i,j ...
[ 36, 24, 6 ]
[]
[]
[ "for_loop", "python" ]
stackoverflow_0002672936_for_loop_python.txt
Q: How can I view and print PDFs in Python? Is there a GPL or less restrictive (preferred LGPL) library to view & print PDFs? I'm using PyQt, maybe there's a possibility to render PDFs using it? A: You can try python-poppler. Poppler is a well known PDF renderer (used by Okular, among other programs) based on xpdf...
How can I view and print PDFs in Python?
Is there a GPL or less restrictive (preferred LGPL) library to view & print PDFs? I'm using PyQt, maybe there's a possibility to render PDFs using it?
[ "You can try python-poppler. Poppler is a well known PDF renderer (used by Okular, among other programs) based on xpdf. However, this particular binding is fairly new, and doesn't seem to have a real home page.\n", "You might want to check out this Qt Quarterly post - Poppler: Displaying PDF Files with Qt that ...
[ 3, 1, 0 ]
[]
[]
[ "pdf", "pyqt", "python" ]
stackoverflow_0002672854_pdf_pyqt_python.txt
Q: Match HTML tags in two strings using regex in Python I want to verify that the HTML tags present in a source string are also present in a target string. For example: >> source = '<em>Hello</em><label>What's your name</label>' >> verify_target(’<em>Hi</em><label>My name is Jim</label>') True >> verify_target('<labe...
Match HTML tags in two strings using regex in Python
I want to verify that the HTML tags present in a source string are also present in a target string. For example: >> source = '<em>Hello</em><label>What's your name</label>' >> verify_target(’<em>Hi</em><label>My name is Jim</label>') True >> verify_target('<label>My name is Jim</label><em>Hi</em>') True >> verify_targe...
[ "I would get rid of Regex and look at Beautiful Soup.\nfindAll(True) lists all the tags found in your source.\nfrom BeautifulSoup import BeautifulSoup \nsoup = BeautifulSoup(source)\nallTags = soup.findAll(True)\n[tag.name for tag in allTags ]\n[u'em', u'label']\n\nthen you just need to remove possible duplicates a...
[ 4, 1 ]
[]
[]
[ "html", "python", "regex" ]
stackoverflow_0002673059_html_python_regex.txt
Q: Sqlalchemy enumeration/type matching? how do i do enumeration in sqlachemy? im using pylons if it matters. i also want to have in code to create different object depends on the enumeration, with the same parameters, but different object class. A: SQLAlchemy 0.6 has generic Enum column type, earlier versions ha...
Sqlalchemy enumeration/type matching?
how do i do enumeration in sqlachemy? im using pylons if it matters. i also want to have in code to create different object depends on the enumeration, with the same parameters, but different object class.
[ "SQLAlchemy 0.6 has generic Enum column type, earlier versions have vendor specific types for some database drivers. And sure, you can use Integer.\nInitializing different classes based based on column value is easy. What you need for this particular case is single table inheritance.\n" ]
[ 1 ]
[]
[]
[ "pylons", "python", "sqlalchemy" ]
stackoverflow_0002672635_pylons_python_sqlalchemy.txt
Q: Log into Launchpad from python script How can I log into my Launchpad account in a python script? Any sample code would be appreciated. The login url is https://launchpad.net/+login and then redirect to something like https://login.launchpad.net/fJLVSRbxPfKTpVDr/+decide Thanks in advance! A: I would suggest look...
Log into Launchpad from python script
How can I log into my Launchpad account in a python script? Any sample code would be appreciated. The login url is https://launchpad.net/+login and then redirect to something like https://login.launchpad.net/fJLVSRbxPfKTpVDr/+decide Thanks in advance!
[ "I would suggest looking into the official launchpadlib, instead of rolling your own solution.\n", "You could check bzrlib it has some integration with launchpad.\n" ]
[ 2, 0 ]
[]
[]
[ "authentication", "python", "urllib" ]
stackoverflow_0002673036_authentication_python_urllib.txt
Q: rpy2: Converting a data.frame to a numpy array I have a data.frame in R. It contains a lot of data : gene expression levels from many (125) arrays. I'd like the data in Python, due mostly to my incompetence in R and the fact that this was supposed to be a 30 minute job. I would like the following code to work. To ...
rpy2: Converting a data.frame to a numpy array
I have a data.frame in R. It contains a lot of data : gene expression levels from many (125) arrays. I'd like the data in Python, due mostly to my incompetence in R and the fact that this was supposed to be a 30 minute job. I would like the following code to work. To understand this code, know that the variable path co...
[ "This is the most straightforward and reliable way i've found to to transfer a data frame from R to Python.\nTo begin with, I think exchanging the data through the R bindings is an unnecessary complication. R provides a simple method to export data, likewise, NumPy has decent methods for data import. The file forma...
[ 7, 4 ]
[]
[]
[ "bioconductor", "numpy", "python", "r", "rpy2" ]
stackoverflow_0002669427_bioconductor_numpy_python_r_rpy2.txt
Q: Open Python shell through SSH I'm using this tool to set up a ssh server on Windows. I'm trying to open the standard Python shell through a remote ssh connection but I simply can't get it to work. If I type 'python' in my ssh command line nothing happens, it just seems to wait for more input. My server machine how...
Open Python shell through SSH
I'm using this tool to set up a ssh server on Windows. I'm trying to open the standard Python shell through a remote ssh connection but I simply can't get it to work. If I type 'python' in my ssh command line nothing happens, it just seems to wait for more input. My server machine however, shows a new python process ru...
[ "My guess is that Python is not recognising the stdin on the SSH shell as a terminal. I don't know why that would be.\nHowever, try running \"python -i\" to overcome it.\n", "The problem is probably that you're running the Windows Python executable, which expects a Windows console environment to run in, over a ch...
[ 2, 0 ]
[]
[]
[ "python", "shell", "ssh" ]
stackoverflow_0002673570_python_shell_ssh.txt
Q: Tools to ease executing raw SQL with Django ORM I often need to execute custom sql queries in django, and manually converting query results into objects every time is kinda painful. I wonder how fellow Slackers deal with this. Maybe someone had written some kind of a library to help dealing with custom SQL in Djan...
Tools to ease executing raw SQL with Django ORM
I often need to execute custom sql queries in django, and manually converting query results into objects every time is kinda painful. I wonder how fellow Slackers deal with this. Maybe someone had written some kind of a library to help dealing with custom SQL in Django?
[ "Not exactly sure what you're looking for, but you can always add a method onto a model to execute custom SQL per the docs:\ndef my_custom_sql(self):\n from django.db import connection\n cursor = connection.cursor()\n cursor.execute(\"SELECT foo FROM bar WHERE baz = %s\", [self.baz])\n row = cursor.fetchone()\n...
[ 4, 4, 3 ]
[]
[]
[ "django", "orm", "python" ]
stackoverflow_0000619384_django_orm_python.txt
Q: How to install python package without copy everything into lib/site-packages? I want to develop a common python package, I got other packages depends on it. For example: packageA/ packageB/ packageC/ commonPackage/ packageA, packageB and packageC can all be executed directly, but they are all depend on commonPa...
How to install python package without copy everything into lib/site-packages?
I want to develop a common python package, I got other packages depends on it. For example: packageA/ packageB/ packageC/ commonPackage/ packageA, packageB and packageC can all be executed directly, but they are all depend on commonPackage. I want to install the commonPackage into lib/site-packages, but I don't wan...
[ "Oops, I just find exactly what I want here. The develop command of setuptools do what I said. Here you type \npython setup.py develop\n\nIt creates .pth rather than copying everything into site-packages.\n", "You can always take a look at virtualenv which will allow you to create a python environment for each ...
[ 2, 1 ]
[]
[]
[ "deployment", "installation", "python" ]
stackoverflow_0002672649_deployment_installation_python.txt
Q: How to handle the pylint message: Warning: Method could be a function I have a python class and ran pylint against it. One message it gave was: Warning: Method could be a function Is this telling me that it would be better to move this method out of the class because it doesn't use any instance variables? In C# ...
How to handle the pylint message: Warning: Method could be a function
I have a python class and ran pylint against it. One message it gave was: Warning: Method could be a function Is this telling me that it would be better to move this method out of the class because it doesn't use any instance variables? In C# I would make this a static method. What's the most pythonic thing to do her...
[ "Moving it to a function is common, if it doesn't touch the class at all.\nIf it manipulates class attributes, use the classmethod decorator:\n@classmethod\ndef spam(cls, ...):\n # cls is the class, you can use it to get class attributes\n\nclassmethod and staticmethod (which is the same as the former, except tha...
[ 84 ]
[]
[]
[ "oop", "pylint", "python" ]
stackoverflow_0002674035_oop_pylint_python.txt
Q: Python, PIL, crop problem Can't seem to get crop working correctly, problem is, it crops a region of correct dimensions, but always from top left corner (0, 0), instead of from my passed coordinates. image = Image.open(input) region = image.crop((1000,400,2000,600) region.save(output) In image.py from PIL, method...
Python, PIL, crop problem
Can't seem to get crop working correctly, problem is, it crops a region of correct dimensions, but always from top left corner (0, 0), instead of from my passed coordinates. image = Image.open(input) region = image.crop((1000,400,2000,600) region.save(output) In image.py from PIL, method _ImageCrop I've printed out.. ...
[ "Works For Me: Python 2.6.1, PIL 1.1.6, JPEG of size 2020x1338 pixels.\nAre you sure you mean a JPEG of 1600x2390 and not 2390x1600? The (1000,400,2000,600) box dimensions are outside the size of a 1600-wide image; if I try this I get garbage data outside the intersecting area.\n", "I`m do next:\ncover=Image.open...
[ 1, 0 ]
[]
[]
[ "crop", "python", "python_imaging_library" ]
stackoverflow_0000622783_crop_python_python_imaging_library.txt
Q: How to create a MAPI32.dll stub to be able to "send as attachment" from MS Word? Microsoft Word has "send as attachment" functionality which creates a new message in Outlook with the document attached. I would like to replace Outlook with a custom mail agent, but I do not know how to achieve this. Now my mail age...
How to create a MAPI32.dll stub to be able to "send as attachment" from MS Word?
Microsoft Word has "send as attachment" functionality which creates a new message in Outlook with the document attached. I would like to replace Outlook with a custom mail agent, but I do not know how to achieve this. Now my mail agent is simply a program that runs, and takes a file name as parameter. As far as I kno...
[ "When writing your own mapi implementation it is critical to create a dll with both the proper exports and calling conventions in order for the system stub mapi dll (c:\\windows\\system32\\mapi32.dll, should be the same as mapistub.dll) to pass calls through to your dll. MAPI functions are called with the __stdcal...
[ 1, 0 ]
[]
[]
[ "c#", "mapi", "ms_word", "outlook", "python" ]
stackoverflow_0001458690_c#_mapi_ms_word_outlook_python.txt
Q: 'Dodger'-type game I am attempting to write a game using livewires and pygame where I have a chef (only image I had, haha), avoid rocks that are falling from the sky. The rocks are supposed to fall in random places. I want it to be that 1 rock falls to begin with, then every time you successfully dodge a rock, 2 m...
'Dodger'-type game
I am attempting to write a game using livewires and pygame where I have a chef (only image I had, haha), avoid rocks that are falling from the sky. The rocks are supposed to fall in random places. I want it to be that 1 rock falls to begin with, then every time you successfully dodge a rock, 2 more rocks fall, until yo...
[ "You have declared end_game method in Rock class but you are calling it from check_catch method of Chef class.\n" ]
[ 0 ]
[]
[]
[ "livewires", "pygame", "python" ]
stackoverflow_0002674128_livewires_pygame_python.txt
Q: Resizing image with Python with locked aspect ratio How should I resize an image with Python script so that it would automatically adjust the Height ratio to the Width used? I'm using the following code: def Do(Environment): # Resize App.Do( Environment, 'Resize', { 'AspectRatio': 1.33333, ...
Resizing image with Python with locked aspect ratio
How should I resize an image with Python script so that it would automatically adjust the Height ratio to the Width used? I'm using the following code: def Do(Environment): # Resize App.Do( Environment, 'Resize', { 'AspectRatio': 1.33333, 'CurrentDimensionUnits': App.Constants.UnitsOfMe...
[ "According to this forum post,\n\nthe magic word is None\n\n– i.e. change\n'Height': 1440,\n\nto\n'Height': None, \n\nAs we found out in the comments below, you also have to set AspectRatio to None.\n" ]
[ 1 ]
[]
[]
[ "aspect_ratio", "image", "locked", "python", "resize" ]
stackoverflow_0002674300_aspect_ratio_image_locked_python_resize.txt
Q: Compiling gVim with Python 3 support I hope this is the right place to ask this question: I am trying to compile gVim with python 3 support using cygwin under windows: I changed the Make_cyg.mak files Python section to the following: ############################## # DYNAMIC_PYTHON=yes works. # DYNAMIC_PYTHON=no do...
Compiling gVim with Python 3 support
I hope this is the right place to ask this question: I am trying to compile gVim with python 3 support using cygwin under windows: I changed the Make_cyg.mak files Python section to the following: ############################## # DYNAMIC_PYTHON=yes works. # DYNAMIC_PYTHON=no does not (unresolved externals on link). ###...
[ "I have compiled vim with python3 support. Here is the Patch updated for vim 7.2.411.\nFor compilation instruction check out my 2009 September 22 mail on \n\ngroups.google.com/group/vim_dev/browse_frm/month/2009-09\n\n(adding a second hyperlink didn't work)\n", "There is a lot of things going on at once here. Fir...
[ 4, 1 ]
[]
[]
[ "compilation", "python", "python_3.x", "vim" ]
stackoverflow_0002236171_compilation_python_python_3.x_vim.txt
Q: How can I call python module inside versioned package folder? I need write python codes which run inside a host application. The python codes should be deployed under a specific folder of the host application. I must put my entry python module under the root of the specific folder. And I want put all my other pyth...
How can I call python module inside versioned package folder?
I need write python codes which run inside a host application. The python codes should be deployed under a specific folder of the host application. I must put my entry python module under the root of the specific folder. And I want put all my other python codes and c/c++ dll under a sub folder, I prefer to name the sub...
[ "If you created a .pth file, eg., X.pth and put XXX-1.0 inside as content\nXXX-1.0\\\n - xxx.py\nX.pth\n\nThen, you could import xxx\nNote: only tested on site-packages folder, I am not sure you could put your sub folder anywhere.\nEdit:\nFor example, wxPython do that way, since it can have multiple version ...
[ 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002672423_python.txt
Q: Sending messages between two Python servers I have two servers - one Django, the other likely to be written in Python - and one is putting 'tasks' into a database and another is processing these tasks. They share a database, but I want the processor to react quickly to new tasks rather than polling periodically. A...
Sending messages between two Python servers
I have two servers - one Django, the other likely to be written in Python - and one is putting 'tasks' into a database and another is processing these tasks. They share a database, but I want the processor to react quickly to new tasks rather than polling periodically. Are there any straightforward ways for two Python ...
[ "Look toward message brokers like ActiveMQ, RabbitMQ, ZeroMQ. They are designed to solve problems similar to what you've described.\nI'm working on real-time MMORPG with server part written in Python and our daemons currently queue tasks to each other using ActiveMQ with STOMP protocol.\nOn low level message broker...
[ 4, 1, 0 ]
[]
[]
[ "django", "ipc", "message_queue", "python" ]
stackoverflow_0002674400_django_ipc_message_queue_python.txt
Q: SQLAlchemy custom sorting algorithms when using SQL indexes Is it possible to write custom collation functions with indexes in SQLAlchemy? SQLite for example allows specifying the sorting function at a C level as sqlite3_create_collation(). An implementation of some of the Unicode collation algorithm has been pro...
SQLAlchemy custom sorting algorithms when using SQL indexes
Is it possible to write custom collation functions with indexes in SQLAlchemy? SQLite for example allows specifying the sorting function at a C level as sqlite3_create_collation(). An implementation of some of the Unicode collation algorithm has been provided by James Tauber here, which for example sorts all the "a"'s...
[ "Below is an example demonstrating unicode collation algorithm for sqlite:\nfrom sqlalchemy import *\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\nfrom pyuca import Collator\n\nmetadata = MetaData()\nBase = declarative_base(metadata=metadata)\n\nclass Item(Base):...
[ 1, 1 ]
[]
[]
[ "collation", "indexing", "python", "sql", "sqlalchemy" ]
stackoverflow_0002660930_collation_indexing_python_sql_sqlalchemy.txt
Q: Django view security and best-practices I've recently begun working on Django and now my app is nearing completion and i've begun to wonder about security and best-practices. I have view that generates a page and different functions in the page post AJAX requests to individual views. For example, I have a view cal...
Django view security and best-practices
I've recently begun working on Django and now my app is nearing completion and i've begun to wonder about security and best-practices. I have view that generates a page and different functions in the page post AJAX requests to individual views. For example, I have a view called show_employees and I can delete and updat...
[ "Well, instead of only using @login_required, I suggest you take a look at the permissions framework and the associated permission required decorator. This way you can fine tune access restrictions on a user or group basis. It's also easier and safer to change user behavior afterwards with permissions than with jus...
[ 11 ]
[]
[]
[ "django", "django_views", "python", "security" ]
stackoverflow_0002674479_django_django_views_python_security.txt
Q: Storing a list of objects in GAE I need to store some data that looks a little like this: xyz 123 abc 456 hij 678 rer 838 Now I would just store it as a traditional string and integer model, and put in the datastore. But the data changes regularly, and is ONLY relevant when looked at as a COLLECTION. So it needs...
Storing a list of objects in GAE
I need to store some data that looks a little like this: xyz 123 abc 456 hij 678 rer 838 Now I would just store it as a traditional string and integer model, and put in the datastore. But the data changes regularly, and is ONLY relevant when looked at as a COLLECTION. So it needs to be store as either a list of lists...
[ "You could just store them as two separate lists and only worry about combing them when you actually access them. Something like this:\nclass MyModel(db.Model):\n my_strings = db.StringListProperty()\n my_ints = db.ListProperty(int)\n\n def get_data(self):\n return zip(self.my_strings, self.my_ints)...
[ 1, 0 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0002652394_google_app_engine_google_cloud_datastore_python.txt
Q: Twisted: how-to bind a server to a specified IP address? I want to have a twisted service (started via twistd) which listens to TCP/POST request on a specified port on a specified IP address. By now I have a twisted application which listens to port 8040 on localhost. It is running fine, but I want it to only list...
Twisted: how-to bind a server to a specified IP address?
I want to have a twisted service (started via twistd) which listens to TCP/POST request on a specified port on a specified IP address. By now I have a twisted application which listens to port 8040 on localhost. It is running fine, but I want it to only listen to a certain IP address, say 10.0.0.78. How-to manage that?...
[ "What you're looking for is the interface argument to twisted.application.internet.TCPServer:\nsmsInboundServer = internet.TCPServer(8001, webserver.Site(smsInbound),\n interface='10.0.0.78')\n\n(Which it inherits from reactor.listenTCP(), since all the t.a.i.*Server classes really just forward to reactor.listen...
[ 13 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0002674799_python_twisted.txt
Q: Problem bounding name to a class in Django I've got a view function that has to decide which form to use depending on some conditions. The two forms look like that: class OpenExtraForm(forms.ModelForm): class Meta: model = Extra def __init__(self, *args, **kwargs): super(OpenExtraForm, sel...
Problem bounding name to a class in Django
I've got a view function that has to decide which form to use depending on some conditions. The two forms look like that: class OpenExtraForm(forms.ModelForm): class Meta: model = Extra def __init__(self, *args, **kwargs): super(OpenExtraForm, self).__init__(*args, **kwargs) self.field...
[ "You need to decide between FromClass and FormClass. You use FormClass everywhere except:\n if extra.is_hidden():\n FromClass = HiddenExtraForm\n\n" ]
[ 4 ]
[]
[]
[ "class", "django", "django_views", "python" ]
stackoverflow_0002675439_class_django_django_views_python.txt
Q: How to describe m2m triple-join table in model (Django) My question is pretty much the same as this question, except that ALL relationships should be many-to-many. I have the following classes in my models.py (somewhat simplified): class Profile(models.Model): # Extending the built in User model user = m...
How to describe m2m triple-join table in model (Django)
My question is pretty much the same as this question, except that ALL relationships should be many-to-many. I have the following classes in my models.py (somewhat simplified): class Profile(models.Model): # Extending the built in User model user = models.ForeignKey(User, unique=True) birthday = models.D...
[ "What about separating the two m2m relationships?\nclass Profile(models.Model):\n ...\n medias = models.ManyToManyField(Media, related_name='profiles')\n roles = models.ManyToManyField(Role, related_name='profiles')\n\nIn this way Django create two association tables for you, and you can utilize the conven...
[ 0 ]
[]
[]
[ "django", "many_to_many", "model", "model_view_controller", "python" ]
stackoverflow_0002674752_django_many_to_many_model_model_view_controller_python.txt