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 $pattern = 'cat|dog|rat' $pagetext =~ s/(.*?)($pattern)/$2/xms; What's the best way to do it in Python? A: >>> import re >>> s = 'hello cat!' >>> m = re.search('cat|dog|rat', s) >>> s[m.start():] 'cat!' Of course you'll need to account for the case where there's no match in a real solution. Or, more cleanly: >>> import re >>> s = 'hello cat!' >>> p = 'cat|dog|rat' >>> re.sub('.*?(?=%s)' % p, '', s, 1) 'cat!' For multiline, use the re.DOTALL flag. A: You want to delete all characters preceding the first occurrence of a pattern; as an example, you give "cat|dog|rat". Code that achieves this using re: re.sub("(?s).*?(cat|dog|rat)", "\\1", input_text, 1) or, if you'll be using again this regular expression: rex= re.compile("(?s).*?(cat|dog|rat)") result= rex.sub("\\1", input_text, 1) Note the non-greedy .*?. The initial (?s) allows to match newline characters too, before the word matching. Examples: >>> input_text= "I have a dog and a cat" >>> re.sub(".*?(cat|dog|rat)", "\\1", input_text, 1) 'dog and a cat' >>> re.sub("(?s).*?(cat|dog|rat)", "\\1", input_text, 1) 'I have no animals!' >>> input_text= "This is irrational" >>> re.sub("(?s).*?(cat|dog|rat)", "\\1", input_text, 1) 'rational' In case you want to do the conversion only for the words cat, dog and rat, you'll have to change the regex into: >>> re.sub(r"(?s).*?\b(cat|dog|rat)\b", "\\1", input_text, 1) 'This is irrational' A: non regex way >>> s='hello cat!' >>> pat=['cat','dog','rat'] >>> for n,i in enumerate(pat): ... m=s.find(i) ... if m != -1: print s[m:] ... cat! A: Something like this should do what you want: import re text = ' sdfda faf foo zing baz bar' match = re.search('foo|bar', text) if match: print text[match.start():] # ==> 'foo zing baz bar' A: Another option is to use look ahead s/.*?(?=$pattern)//xs: re.sub(r'(?s).*?(?=cat|dog|rat)', '', text, 1) Non-regex way: for option in 'cat dog rat'.split(): index = text.find(option) if index != -1: # found text = text[index:] break Non-regex way is almost 5 times faster (for some input): $ python -mtimeit -s'from drop_until_word import drop_re, text, options;' \ > 'drop_re(text, options)' 1000 loops, best of 3: 1.06 msec per loop $ python -mtimeit -s'from drop_until_word import drop_search, text, options;'\ > 'drop_search(text, options)' 10000 loops, best of 3: 184 usec per loop $ python -mtimeit -s'from drop_until_word import drop_find, text, options;' \ > 'drop_find(text, options)' 1000 loops, best of 3: 207 usec per loop Where drop_until_word.py is: import re def drop_re(text, options): return re.sub(r'(?s).*?(?='+'|'.join(map(re.escape, options))+')', '', text, 1) def drop_re2(text, options): return re.sub(r'(?s).*?('+'|'.join(map(re.escape, options))+')', '\\1', text, 1) def drop_search(text, options): m = re.search('|'.join(map(re.escape, options)), text) return text[m.start():] if m else text def drop_find(text, options): indexes = [i for i in (text.find(option) for option in options) if i != -1] return text[min(indexes):] if indexes else text text = open('/usr/share/dict/words').read() options = 'cat dog rat'.split() def test(): assert drop_find(text, options) == drop_re(text, options) \ == drop_re2(text, options) == drop_search(text, options) txt = 'dog before cat' r = txt for f in [drop_find, drop_re, drop_re2, drop_search]: assert r == f(txt, options), f.__name__ if __name__=="__main__": test()
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's the best way to do it in Python?
[ ">>> 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!'\n\nFor multiline, use the re.DOTALL flag.\n", "You want to delete all characters preceding the first occurrence of a pattern; as an example, you give \"cat|dog|rat\".\nCode that achieves this using re:\nre.sub(\"(?s).*?(cat|dog|rat)\", \"\\\\1\", input_text, 1)\n\nor, if you'll be using again this regular expression:\nrex= re.compile(\"(?s).*?(cat|dog|rat)\")\nresult= rex.sub(\"\\\\1\", input_text, 1)\n\nNote the non-greedy .*?. The initial (?s) allows to match newline characters too, before the word matching.\nExamples:\n>>> input_text= \"I have a dog and a cat\"\n>>> re.sub(\".*?(cat|dog|rat)\", \"\\\\1\", input_text, 1)\n'dog and a cat'\n\n>>> re.sub(\"(?s).*?(cat|dog|rat)\", \"\\\\1\", input_text, 1)\n'I have no animals!'\n\n>>> input_text= \"This is irrational\"\n>>> re.sub(\"(?s).*?(cat|dog|rat)\", \"\\\\1\", input_text, 1)\n'rational'\n\nIn case you want to do the conversion only for the words cat, dog and rat, you'll have to change the regex into:\n>>> re.sub(r\"(?s).*?\\b(cat|dog|rat)\\b\", \"\\\\1\", input_text, 1)\n'This is irrational'\n\n", "non regex way\n>>> s='hello cat!'\n>>> pat=['cat','dog','rat']\n>>> for n,i in enumerate(pat):\n... m=s.find(i)\n... if m != -1: print s[m:]\n...\ncat!\n\n", "Something like this should do what you want:\nimport re\ntext = ' sdfda faf foo zing baz bar'\nmatch = re.search('foo|bar', text)\nif match:\n print text[match.start():] # ==> 'foo zing baz bar'\n\n", "Another option is to use look ahead s/.*?(?=$pattern)//xs:\nre.sub(r'(?s).*?(?=cat|dog|rat)', '', text, 1)\n\nNon-regex way:\nfor option in 'cat dog rat'.split():\n index = text.find(option)\n if index != -1: # found\n text = text[index:]\n break\n\nNon-regex way is almost 5 times faster (for some input):\n$ python -mtimeit -s'from drop_until_word import drop_re, text, options;' \\\n> 'drop_re(text, options)'\n1000 loops, best of 3: 1.06 msec per loop\n\n$ python -mtimeit -s'from drop_until_word import drop_search, text, options;'\\\n> 'drop_search(text, options)'\n10000 loops, best of 3: 184 usec per loop\n\n$ python -mtimeit -s'from drop_until_word import drop_find, text, options;' \\\n> 'drop_find(text, options)'\n1000 loops, best of 3: 207 usec per loop\n\nWhere drop_until_word.py is:\nimport re\n\ndef drop_re(text, options):\n return re.sub(r'(?s).*?(?='+'|'.join(map(re.escape, options))+')', '',\n text, 1)\n\ndef drop_re2(text, options):\n return re.sub(r'(?s).*?('+'|'.join(map(re.escape, options))+')', '\\\\1',\n text, 1)\n\ndef drop_search(text, options):\n m = re.search('|'.join(map(re.escape, options)), text)\n return text[m.start():] if m else text\n\ndef drop_find(text, options):\n indexes = [i for i in (text.find(option) for option in options) if i != -1]\n return text[min(indexes):] if indexes else text\n\ntext = open('/usr/share/dict/words').read()\noptions = 'cat dog rat'.split()\n\ndef test():\n assert drop_find(text, options) == drop_re(text, options) \\\n == drop_re2(text, options) == drop_search(text, options)\n\n txt = 'dog before cat'\n r = txt\n for f in [drop_find, drop_re, drop_re2, drop_search]:\n assert r == f(txt, options), f.__name__\n\n\nif __name__==\"__main__\":\n test()\n\n" ]
[ 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); cp %(project_name)/%(virtualhost_path)/%(project_domain) /etc/apache2/sites-available/%(project_domain)s') sudo('cd /etc/apache2/sites-available; a2ensite %(project_domain)') I keep getting this error: [173.203.124.16] sudo: cd %(path)/releases/%(release)/%(release); [173.203.124.16] err: /bin/bash: -c: line 0: syntax error near unexpected token `(' [173.203.124.16] err: /bin/bash: -c: line 0: `cd %(path)/releases/%(release)/%(r elease);' Warning: sudo() encountered an error (return code 2) while executing 'cd %(path) /releases/%(release)/%(release);' I've gone through the fabfile.py over and over and I can't see why the error is coming...any ideas? A: def install_site(): "Add the virtualhost file to apache" require('release', provided_by=[deploy, setup]) with cd('%(path)s/releases/%(release)s/%(release)s' % env): sudo('cp %(project_name)s/%(virtualhost_path)s/%(project_domain)s ' '/etc/apache2/sites-available/%(project_domain)s' % env) with cd('/etc/apache2/sites-available'): sudo('a2ensite %(project_domain)s' % env) A: You might want to try using the cd context manager. You're probably also having problems with your string interpolation. def install_site(): # Add the virtualhost file to apache require('release', provided_by=[deploy, setup]) with cd('%s/releases/%s/%s' % (path, release, release)): sudo('cp %s/%s/%s /etc/apache2/sites-available/%s' % (project_name, virtualhost_path, project_domain, project_domain)) with cd('/etc/apache2/sites-available'): sudo('a2ensite %s' % project_domain) A: problem fixed, noticing something with the "hg archive .." command, it zips/tars the repo 2 levels deep local('hg archive --type=tgz %(release)s.tar.gz' % {'release': env.release}) results in 20100418105144.tar.gz which when u open is structured like this: 20100418105144.tar.gz /20100418105144 /repo
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)/%(virtualhost_path)/%(project_domain) /etc/apache2/sites-available/%(project_domain)s') sudo('cd /etc/apache2/sites-available; a2ensite %(project_domain)') I keep getting this error: [173.203.124.16] sudo: cd %(path)/releases/%(release)/%(release); [173.203.124.16] err: /bin/bash: -c: line 0: syntax error near unexpected token `(' [173.203.124.16] err: /bin/bash: -c: line 0: `cd %(path)/releases/%(release)/%(r elease);' Warning: sudo() encountered an error (return code 2) while executing 'cd %(path) /releases/%(release)/%(release);' I've gone through the fabfile.py over and over and I can't see why the error is coming...any ideas?
[ "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/%(project_domain)s' % env)\n with cd('/etc/apache2/sites-available'):\n sudo('a2ensite %(project_domain)s' % env) \n\n", "You might want to try using the cd context manager. You're probably also having problems with your string interpolation.\ndef install_site():\n # Add the virtualhost file to apache\n require('release', provided_by=[deploy, setup])\n\n with cd('%s/releases/%s/%s' % (path, release, release)):\n sudo('cp %s/%s/%s /etc/apache2/sites-available/%s' % (project_name, virtualhost_path, project_domain, project_domain))\n\n with cd('/etc/apache2/sites-available'):\n sudo('a2ensite %s' % project_domain)\n\n", "problem fixed, noticing something with the \"hg archive ..\" command, it zips/tars the repo 2 levels deep\nlocal('hg archive --type=tgz %(release)s.tar.gz' % {'release': env.release})\n\nresults in 20100418105144.tar.gz which when u open is structured like this:\n\n20100418105144.tar.gz\n /20100418105144\n /repo\n\n" ]
[ 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 google app engine A: Changing the cookies in the request does nothing to the cookie on the client. You need to set the "Set-Cookie" header in the response to the client. You could use something like this (untested by me) Google App Engine Cookie class A: The WebOb Reference explains set_cookie well - if youre on a framework using the WebOb Response (not valid for Google App Engine, it uses an own Repsonse)
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 using the WebOb Response (not valid for Google App Engine, it uses an own Repsonse)\n" ]
[ 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.get_text('(%s)[%d]'%(xpath, i))) would work because doing something similar with firefox's Xpath checker works: (//a[@id='someID'])[2] returns the 2nd result. Ideas why the behavior would be different and how to do such a thing with selenium Thanks A: 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. From the XPath TR at http://www.w3.org/TR/xpath#path-abbrev: NOTE: The location path //para[1] does not mean the same as the location path /descendant::para[1]. The latter selects the first descendant para element; the former selects all descendant para elements that are the first para children of their parents. A: The answer is that you need to tell selenium that you're using xpath: numOfResults = sel.get_xpath_count(xpath) l = [] for i in range(1,numOfResults+1): l.append(sel.get_text(xpath='(%s)[%d]'%(xpath, i))) A: In Selenium you normally do it without the extra brackets so your loop would look like the following numOfResults = sel.get_xpath_count(xpath) l = [] for i in range(1,numOfResults+1): l.append(sel.get_text('%s[%d]'%(xpath, i))) And that will produce a valid XPath in Selenium like //a[@id='someID'][2]
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 because doing something similar with firefox's Xpath checker works: (//a[@id='someID'])[2] returns the 2nd result. Ideas why the behavior would be different and how to do such a thing with selenium Thanks
[ "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 path //para[1] does not mean the same as the location path /descendant::para[1]. The latter selects the first descendant para element; the former selects all descendant para elements that are the first para children of their parents.\n\n", "The answer is that you need to tell selenium that you're using xpath:\nnumOfResults = sel.get_xpath_count(xpath)\nl = []\nfor i in range(1,numOfResults+1):\n l.append(sel.get_text(xpath='(%s)[%d]'%(xpath, i)))\n\n", "In Selenium you normally do it without the extra brackets so your loop would look like the following\nnumOfResults = sel.get_xpath_count(xpath)\nl = []\nfor i in range(1,numOfResults+1):\n l.append(sel.get_text('%s[%d]'%(xpath, i)))\n\nAnd that will produce a valid XPath in Selenium like //a[@id='someID'][2]\n" ]
[ 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. UPDATE: Thank you to everyone who posted a solution. I marked the example using "datetime.datetime.now() + datetime.timedelta(hours=x)" as the best answer because I could understand it the best and it seems like it will work very well for my purpose. A: 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: finish_time = datetime.datetime.now() + datetime.timedelta(hours=6) while datetime.datetime.now() < finish_time: do_something() sleep_for_a_bit() A: I've just found sched in the Python standard library. A: You are looking for a scheduler. Check this thread. A: May be a bit of overkill, but for running background tasks, especially if you need a GUI, I'd recommend checking out the PyQt route with QSystemTrayIcon and QTimer
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 the example using "datetime.datetime.now() + datetime.timedelta(hours=x)" as the best answer because I could understand it the best and it seems like it will work very well for my purpose.
[ "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 found sched in the Python standard library.\n", "You are looking for a scheduler.\nCheck this thread.\n", "May be a bit of overkill, but for running background tasks, especially if you need a GUI, I'd recommend checking out the PyQt route with QSystemTrayIcon and QTimer\n" ]
[ 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 division\nfrom math import ceil\nbetweenDLs = 5 # minutes\ntotalTime = 2*60 # minutes\nfor i in range(int(ceil(totalTime/betweenDLs))):\n download()\n sleep(betweenDLs*60)\n\n" ]
[ -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 drawing functions, how would I go about coding the timing to display it at 30 frames per second (or any other arbitrary rate). A: The easiest way to do it is with Pygame: import pygame pygame.init() clock = pygame.time.Clock() # or whatever loop you're using for the animation while True: # draw animation # pause so that the animation runs at 30 fps clock.tick(30) The second easiest way to do it is manually: import time FPS = 30 last_time = time.time() # whatever the loop is... while True: # draw animation # pause so that the animation runs at 30 fps new_time = time.time() # see how many milliseconds we have to sleep for # then divide by 1000.0 since time.sleep() uses seconds sleep_time = ((1000.0 / FPS) - (new_time - last_time)) / 1000.0 if sleep_time > 0: time.sleep(sleep_time) last_time = new_time A: There is a Timer class in the threading module. It may be more convenient than using time.sleep for some purposes. >>> from threading import Timer >>> def hello(who): ... print 'hello %s' % who ... >>> t = Timer(5.0, hello, args=('world',)) >>> t.start() # and five seconds later... hello world A: You could use select ? It's commonly used for waiting on I/O completion, but take a look at the signature: select.select(rlist, wlist, xlist[, timeout]) so, you could do something like: timeout = 30.0 while true: if select.select([], [], [], timeout): #timout reached # maybe you should recalculate your timeout ?
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 go about coding the timing to display it at 30 frames per second (or any other arbitrary rate).
[ "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 time\n\nFPS = 30\nlast_time = time.time()\n# whatever the loop is...\nwhile True:\n # draw animation\n # pause so that the animation runs at 30 fps\n new_time = time.time()\n # see how many milliseconds we have to sleep for\n # then divide by 1000.0 since time.sleep() uses seconds\n sleep_time = ((1000.0 / FPS) - (new_time - last_time)) / 1000.0\n if sleep_time > 0:\n time.sleep(sleep_time)\n last_time = new_time\n\n", "There is a Timer class in the threading module. It may be more convenient than using time.sleep for some purposes.\n>>> from threading import Timer\n>>> def hello(who):\n... print 'hello %s' % who\n... \n>>> t = Timer(5.0, hello, args=('world',))\n>>> t.start() # and five seconds later...\nhello world\n\n", "You could use select ? It's commonly used for waiting on I/O completion, but take a look at the signature:\nselect.select(rlist, wlist, xlist[, timeout])\n\nso, you could do something like:\ntimeout = 30.0\nwhile true:\n if select.select([], [], [], timeout):\n #timout reached\n # maybe you should recalculate your timeout ? \n\n" ]
[ 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': When you click on name, it displays the underscores again. Is there any solution of this problem? A: 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.
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 underscores again. Is there any solution of this problem?
[ "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 parenthesis in your model declaration. Your code: class FeedEntry3(db.Model): title = db.StringProperty link = db.StringProperty content = db.TextProperty What it should be: class FeedEntry3(db.Model): title = db.StringProperty() link = db.StringProperty() content = db.TextProperty() A: Are you sure you are getting the values correcty or at all from feed parser? Have you tried to log them. Also for purpose of discussion if you think x.put is not working then separate that out and test that only e.g. x = FeedEntry3() x.title = "test title" x.link = "test link" x.content = "test content" x.put() Have you tried that, does that work? if that works most probably you are not getting values from feedparser, debug and log that.
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 content = db.TextProperty()\n\n", "Are you sure you are getting the values correcty or at all from feed parser? Have you tried to log them. Also for purpose of discussion if you think x.put is not working then separate that out and test that only e.g.\nx = FeedEntry3()\nx.title = \"test title\"\nx.link = \"test link\"\nx.content = \"test content\"\nx.put()\n\nHave you tried that, does that work? if that works most probably you are not getting values from feedparser, debug and log that.\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: ") 你好世界 >>> u'\u4f60\u597d\u4e16\u754c' >>> print s 你好世界 >>>
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 direct import from MySQL? This database is from Pentaho BI Server (www.pentaho.com). Thank you for your attention. Regards, Daniel Naito A: 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. A: Advanced Bulk Loading by Nick Johnson is what you are looking for. If you need live synchronization between App Engine and MySQL, you should look into AppRocket. AppRocket seems to require that you have your data in App Engine before the first synchronization. It will also require some minor changes to your model. A: If you're using Pentaho BI Server as your data source, why don't you consider using Pentaho Data Integration (ETL tool) to move the data over? At the very least PDI automate any movement of data between your data source and any AppEngine bulk loader tool (it can easily trigger any app with a shell step).
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? This database is from Pentaho BI Server (www.pentaho.com). Thank you for your attention. Regards, Daniel Naito
[ "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. AppRocket seems to require that you have your data in App Engine before the first synchronization. It will also require some minor changes to your model.\n", "If you're using Pentaho BI Server as your data source, why don't you consider using Pentaho Data Integration (ETL tool) to move the data over? At the very least PDI automate any movement of data between your data source and any AppEngine bulk loader tool (it can easily trigger any app with a shell step).\n" ]
[ 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 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.
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 displaying form. Example will describe better what i would like achieve. This is mine extended user model. class UserExtended(models.Model): user = models.ForeignKey(User, unique=True) kod_pocztowy = models.CharField(max_length=6,blank=True) email = models.EmailField() This is how my form looks like. class UserCreationFormExtended(UserCreationForm): def __init__(self, *args, **kwargs): super(UserCreationFormExtended, self).__init__(*args, **kwargs) self.fields['email'].required = True self.fields['first_name'].required = False self.fields['last_name'].required = False class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email') It works fine when registering, as i need allow users to put username and email but when it goes to editing profile it displays too many fields. I would not like them to be able to edit username and email. How could i disable fields in form? Thanks for help. A: 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. A: Try removing 'username' and 'email' from fields in Meta: class Meta: model = User fields = ('first_name', 'last_name') A: What i did is i created new form and used it and it worked. It allows to edit fields from User model not only UserExtended. Thanks for help. class UserProfileForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(UserProfileForm, self).__init__(*args, **kwargs) try: self.fields['first_name'].initial = self.instance.user.first_name self.fields['last_name'].initial = self.instance.user.last_name self.fields['email'].initial = self.instance.user.email except models.User.DoesNotExist: pass email = forms.EmailField(label = "Główny adres email", help_text="", required=True) first_name = forms.CharField(label = "Imię", required=False) last_name = forms.CharField(label = "Nazwisko", required=False) kod_pocztowy = forms.RegexField('\d{2}-\d{3}', required = False, label="Kod pocztowy", error_messages={"invalid":'Poprawna wartość to np: 41-200'}) class Meta: model = UserExtended exclude = ('user') def save(self, *args, **kwargs): u = self.instance.user u.email = self.cleaned_data['email'] u.first_name = self.cleaned_data['first_name'] u.last_name = self.cleaned_data['last_name'] u.kod_pocztowy = self.cleaned_data['kod_pocztowy'] u.save() profile = super(UserProfileForm, self).save(*args, **kwargs) return profile
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 like achieve. This is mine extended user model. class UserExtended(models.Model): user = models.ForeignKey(User, unique=True) kod_pocztowy = models.CharField(max_length=6,blank=True) email = models.EmailField() This is how my form looks like. class UserCreationFormExtended(UserCreationForm): def __init__(self, *args, **kwargs): super(UserCreationFormExtended, self).__init__(*args, **kwargs) self.fields['email'].required = True self.fields['first_name'].required = False self.fields['last_name'].required = False class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email') It works fine when registering, as i need allow users to put username and email but when it goes to editing profile it displays too many fields. I would not like them to be able to edit username and email. How could i disable fields in form? Thanks for help.
[ "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 = ('first_name', 'last_name')\n\n", "What i did is i created new form and used it and it worked. It allows to edit fields from User model not only UserExtended. Thanks for help.\nclass UserProfileForm(forms.ModelForm):\ndef __init__(self, *args, **kwargs):\n super(UserProfileForm, self).__init__(*args, **kwargs)\n try: \n self.fields['first_name'].initial = self.instance.user.first_name\n self.fields['last_name'].initial = self.instance.user.last_name\n self.fields['email'].initial = self.instance.user.email\n except models.User.DoesNotExist:\n pass\n\nemail = forms.EmailField(label = \"Główny adres email\",\n help_text=\"\",\n required=True)\nfirst_name = forms.CharField(label = \"Imię\",\n required=False)\nlast_name = forms.CharField(label = \"Nazwisko\",\n required=False)\nkod_pocztowy = forms.RegexField('\\d{2}-\\d{3}',\n required = False,\n label=\"Kod pocztowy\",\n error_messages={\"invalid\":'Poprawna wartość to np: 41-200'})\n\nclass Meta:\n model = UserExtended\n exclude = ('user')\n\ndef save(self, *args, **kwargs):\n u = self.instance.user\n u.email = self.cleaned_data['email']\n u.first_name = self.cleaned_data['first_name']\n u.last_name = self.cleaned_data['last_name']\n u.kod_pocztowy = self.cleaned_data['kod_pocztowy']\n u.save()\n profile = super(UserProfileForm, self).save(*args, **kwargs)\n return profile\n\n" ]
[ 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 be outside of "a" tags and be not well formed in many ways(like "\n" in the middle of link) so I try to grab as much "links" as I can and check them later in other scripts(so no BeatifulSoup\lxml\etc). The problem is that my script is pretty slow, so I am thinking about any ways to speed it up. I am writing a set of test to check different approaches, but hope to get some advices :) Right now I am thinking about getting all links without filtering first(maybe using C module or standalone app, which doesn't use regexp but simple search to get start and end of every link) and then using regexp to match ones I need. A: Ways out. Parallelise Profile your code to see where the bottleneck is. The result are often surprising. Use a single regexp (concatenate using |) rather than multiple ones.
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 middle of link) so I try to grab as much "links" as I can and check them later in other scripts(so no BeatifulSoup\lxml\etc). The problem is that my script is pretty slow, so I am thinking about any ways to speed it up. I am writing a set of test to check different approaches, but hope to get some advices :) Right now I am thinking about getting all links without filtering first(maybe using C module or standalone app, which doesn't use regexp but simple search to get start and end of every link) and then using regexp to match ones I need.
[ "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 name given by user via command-line output_dir = "..." # obtained by OptParser, for example my_filename = output_dir + '/' + os.path.basename(output_dir) + '.my_program_output' # write stuff to my_filename The problem is that if the user gives a directory name with a trailing slash, then os.path.basename will return the empty string, which is not what I want. What is the most elegant way to deal with these slash/trailing slash issues in python? I know I can manually check for the slash at the end of output_dir and remove it if it's there, but there seems like there should be a better way. Is there? Also, is it OK to manually add '/' characters? E.g. output_dir + '/' os.path.basename() or is there a more generic way to build up paths? Thanks. A: To deal with your "trailing slash" issue (and other issues!), sanitise user input with os.path.normpath(). To build paths, use os.path.join() A: Use os.path.join() to build up paths. For example: >>> import os.path >>> path = 'foo/bar' >>> os.path.join(path, 'filename') 'foo/bar/filename' >>> path = 'foo/bar/' >>> os.path.join(path, 'filename') 'foo/bar/filename' A: You should use os.path.join() to add paths together. use os.path.dirname(os.path.join(output_dir,'')) to extract dirname, while adding a trailing slash if it was omitted. A: Manually building up paths is a bad idea for portability; it will break on Windows. You should use os.path.sep. As for your first question, using os.path.join is the right idea. A: to build the paths without writing slashes it is better to use: os.path.join(dir, subdir, file) if you want to add separators or get the separator independly of the os, then use os.sep
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 = "..." # obtained by OptParser, for example my_filename = output_dir + '/' + os.path.basename(output_dir) + '.my_program_output' # write stuff to my_filename The problem is that if the user gives a directory name with a trailing slash, then os.path.basename will return the empty string, which is not what I want. What is the most elegant way to deal with these slash/trailing slash issues in python? I know I can manually check for the slash at the end of output_dir and remove it if it's there, but there seems like there should be a better way. Is there? Also, is it OK to manually add '/' characters? E.g. output_dir + '/' os.path.basename() or is there a more generic way to build up paths? Thanks.
[ "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 = 'foo/bar/'\n>>> os.path.join(path, 'filename')\n'foo/bar/filename'\n\n", "You should use os.path.join() to add paths together.\nuse \nos.path.dirname(os.path.join(output_dir,''))\n\nto extract dirname, while adding a trailing slash if it was omitted.\n", "Manually building up paths is a bad idea for portability; it will break on Windows. You should use os.path.sep. \nAs for your first question, using os.path.join is the right idea.\n", "to build the paths without writing slashes it is better to use: \nos.path.join(dir, subdir, file)\n\nif you want to add separators or get the separator independly of the os, then use\n os.sep\n\n" ]
[ 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 executing a lot of external processes, but I'm fairly sure that side of things is watertight. Looking at the error and access logs, there's nothing exceptional happening (i.e. load isn't above normal). On those occasions where I have had exceptions from Python, these have shown up in the error.log, but when this crash happens I get nothing. Is there any way of finding out why the process died? Short of putting logging statements on every single line? Obviously I can't reproduce this so I don't know exactly where to look. Edit It's the django process that's dying. I'm running the server with manage.py runfcgi daemonize=true method=threaded host=127.0.0.1 port=12345 A: You could edit manage.py to redirect stderr to a file, assuming runfcgi doesn't do that itself: import sys if sys.argv[1] == "runfcgi": sys.stderr = open("/path/to/my/django-error.log", "a") A: Is this on your server? (do you own the box?). I've had that problem on shared hosting, and the host was just killing long processes. Do you know if your fcgi is receiving a SIGTERM? A: Have had the same problems. Not only do they die without warning or reason they leak like crazy too with threads being stuck without a master process. We solved this problem by having a cronjob run every 5 minutes that checks if the port number is up and running and if not restart. By the way, we've now (slowly migrating) given up on fcgi and moved over to uwsgi.
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 that side of things is watertight. Looking at the error and access logs, there's nothing exceptional happening (i.e. load isn't above normal). On those occasions where I have had exceptions from Python, these have shown up in the error.log, but when this crash happens I get nothing. Is there any way of finding out why the process died? Short of putting logging statements on every single line? Obviously I can't reproduce this so I don't know exactly where to look. Edit It's the django process that's dying. I'm running the server with manage.py runfcgi daemonize=true method=threaded host=127.0.0.1 port=12345
[ "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 was just killing long processes. Do you know if your fcgi is receiving a SIGTERM?\n", "Have had the same problems. Not only do they die without warning or reason they leak like crazy too with threads being stuck without a master process. We solved this problem by having a cronjob run every 5 minutes that checks if the port number is up and running and if not restart.\nBy the way, we've now (slowly migrating) given up on fcgi and moved over to uwsgi.\n" ]
[ 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 another app which also works just using the python client app. # Server program # UDP VERSION from socket import * # Set the socket parameters host = "localhost" port = 514 buf = 1024 addr = (host,port) # Create socket and bind to address UDPSock = socket(AF_INET,SOCK_DGRAM) UDPSock.bind(addr) # Receive messages while 1: data,addr = UDPSock.recvfrom(buf) if not data: print "Client has exited!" break else: print "\nReceived message '", data,"'" # Close socket UDPSock.close() Using this code I can send to the server and have it display the code. # Client program from socket import * # Set the socket parameters host = "localhost" port = 514 buf = 1024 addr = (host,port) # Create socket UDPSock = socket(AF_INET,SOCK_DGRAM) def_msg = "===Enter message to send to server==="; print "\n",def_msg # Send messages while (1): data = raw_input('>> ') if not data: break else: if(UDPSock.sendto(data,addr)): print "Sending message '",data,"'....." # Close socket UDPSock.close() I have tried the Kiwi Syslog Message Generator and Snare to send syslog messages to the UDP server and nothing comes up. Could someone help me understand? A: 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 also has a test feature... which works :)
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 VERSION from socket import * # Set the socket parameters host = "localhost" port = 514 buf = 1024 addr = (host,port) # Create socket and bind to address UDPSock = socket(AF_INET,SOCK_DGRAM) UDPSock.bind(addr) # Receive messages while 1: data,addr = UDPSock.recvfrom(buf) if not data: print "Client has exited!" break else: print "\nReceived message '", data,"'" # Close socket UDPSock.close() Using this code I can send to the server and have it display the code. # Client program from socket import * # Set the socket parameters host = "localhost" port = 514 buf = 1024 addr = (host,port) # Create socket UDPSock = socket(AF_INET,SOCK_DGRAM) def_msg = "===Enter message to send to server==="; print "\n",def_msg # Send messages while (1): data = raw_input('>> ') if not data: break else: if(UDPSock.sendto(data,addr)): print "Sending message '",data,"'....." # Close socket UDPSock.close() I have tried the Kiwi Syslog Message Generator and Snare to send syslog messages to the UDP server and nothing comes up. Could someone help me understand?
[ "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 also has a test feature... which works :)\n" ]
[ 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 can. A: For small algorithms you can use the module timeit from python documentation: def test(): "Stupid test function" L = [] for i in range(100): L.append(i) if __name__=='__main__': from timeit import Timer t = Timer("test()", "from __main__ import test") print t.timeit() Less accurately but still valid you can use module time like this: from time import time t0 = time() call_mifuntion_vers_1() t1 = time() call_mifunction_vers_2() t2 = time() print 'function vers1 takes %f' %(t1-t0) print 'function vers2 takes %f' %(t2-t1) A: The module timeit is useful for this and is included in the standard Python distribution. Example: import timeit timeit.Timer('for i in xrange(10): oct(i)').timeit() A: I am not 100% sure what is meant by "running times of my algorithms written in python", so I thought I might try to offer a broader look at some of the potential answers. Algorithms don't have running times; implementations can be timed, but an algorithm is an abstract approach to doing something. The most common and often the most valuable part of optimizing a program is analyzing the algorithm, usually using asymptotic analysis and computing the big O complexity in time, space, disk use and so forth. A computer cannot really do this step for you. This requires doing the math to figure out how something works. Optimizing this side of things is the main component to having scalable performance. You can time your specific implementation. The nicest way to do this in Python is to use timeit. The way it seems most to want to be used is to make a module with a function encapsulating what you want to call and call it from the command line with python -m timeit .... Using timeit to compare multiple snippets when doing microoptimization, but often isn't the correct tool you want for comparing two different algorithms. It is common that what you want is asymptotic analysis, but it's possible you want more complicated types of analysis. You have to know what to time. Most snippets aren't worth improving. You need to make changes where they actually count, especially when you're doing micro-optimisation and not improving the asymptotic complexity of your algorithm. If you quadruple the speed of a function in which your code spends 1% of the time, that's not a real speedup. If you make a 20% speed increase on a function in which your program spends 50% of the time, you have a real gain. To determine the time spent by a real Python program, use the stdlib profiling utilities. This will tell you where in an example program your code is spending its time. A: Using a decorator for measuring execution time for functions can be handy. There is an example at http://www.zopyx.com/blog/a-python-decorator-for-measuring-the-execution-time-of-methods. Below I've shamelessly pasted the code from the site mentioned above so that the example exists at SO in case the site is wiped off the net. import time def timeit(method): def timed(*args, **kw): ts = time.time() result = method(*args, **kw) te = time.time() print '%r (%r, %r) %2.2f sec' % \ (method.__name__, args, kw, te-ts) return result return timed class Foo(object): @timeit def foo(self, a=2, b=3): time.sleep(0.2) @timeit def f1(): time.sleep(1) print 'f1' @timeit def f2(a): time.sleep(2) print 'f2',a @timeit def f3(a, *args, **kw): time.sleep(0.3) print 'f3', args, kw f1() f2(42) f3(42, 43, foo=2) Foo().foo() // John
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.timeit()\n\nLess accurately but still valid you can use module time like this:\nfrom time import time\nt0 = time()\ncall_mifuntion_vers_1()\nt1 = time()\ncall_mifunction_vers_2()\nt2 = time()\n\nprint 'function vers1 takes %f' %(t1-t0)\nprint 'function vers2 takes %f' %(t2-t1)\n\n", "The module timeit is useful for this and is included in the standard Python distribution.\nExample:\nimport timeit\ntimeit.Timer('for i in xrange(10): oct(i)').timeit()\n\n", "I am not 100% sure what is meant by \"running times of my algorithms written in python\", so I thought I might try to offer a broader look at some of the potential answers.\n\nAlgorithms don't have running times; implementations can be timed, but an algorithm is an abstract approach to doing something. The most common and often the most valuable part of optimizing a program is analyzing the algorithm, usually using asymptotic analysis and computing the big O complexity in time, space, disk use and so forth.\nA computer cannot really do this step for you. This requires doing the math to figure out how something works. Optimizing this side of things is the main component to having scalable performance.\nYou can time your specific implementation. The nicest way to do this in Python is to use timeit. The way it seems most to want to be used is to make a module with a function encapsulating what you want to call and call it from the command line with python -m timeit ....\nUsing timeit to compare multiple snippets when doing microoptimization, but often isn't the correct tool you want for comparing two different algorithms. It is common that what you want is asymptotic analysis, but it's possible you want more complicated types of analysis.\nYou have to know what to time. Most snippets aren't worth improving. You need to make changes where they actually count, especially when you're doing micro-optimisation and not improving the asymptotic complexity of your algorithm. \nIf you quadruple the speed of a function in which your code spends 1% of the time, that's not a real speedup. If you make a 20% speed increase on a function in which your program spends 50% of the time, you have a real gain.\nTo determine the time spent by a real Python program, use the stdlib profiling utilities. This will tell you where in an example program your code is spending its time. \n\n", "Using a decorator for measuring execution time for functions can be handy. There is an example at http://www.zopyx.com/blog/a-python-decorator-for-measuring-the-execution-time-of-methods.\nBelow I've shamelessly pasted the code from the site mentioned above so that the example exists at SO in case the site is wiped off the net.\nimport time \n\ndef timeit(method):\n\n def timed(*args, **kw):\n ts = time.time()\n result = method(*args, **kw)\n te = time.time()\n\n print '%r (%r, %r) %2.2f sec' % \\\n (method.__name__, args, kw, te-ts)\n return result\n\n return timed\n\nclass Foo(object):\n\n @timeit\n def foo(self, a=2, b=3):\n time.sleep(0.2)\n\n@timeit\ndef f1():\n time.sleep(1)\n print 'f1'\n\n@timeit\ndef f2(a):\n time.sleep(2)\n print 'f2',a\n\n@timeit\ndef f3(a, *args, **kw):\n time.sleep(0.3)\n print 'f3', args, kw\n\nf1()\nf2(42)\nf3(42, 43, foo=2)\nFoo().foo()\n\n// John\n" ]
[ 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 you want to do is measure the elapsed time that a function or section of code took to run in Python, then you can use the timeit or time modules, depending on how long the code needs to run.\n" ]
[ -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 = IterableObject() value = myObj1.balance - myObj2.balance Of course it did not work. What am I doing wrong? I think I can not add value on item like that. A: In the itertools documentation there is an example function called pairwise that you can copy into your project: def pairwise(iterable): "s -> (s0,s1), (s1,s2), (s2, s3), ..." a, b = tee(iterable) next(b, None) return izip(a, b) Use it like: for x1, x2 in pairwise(some_iterable): # etc.. Note that when you iterate over a dict the items are not necessarily returned in order, so you should sort first. A: A possible solution without itertools: def pairwise(iterable): it = iter(iterable) try: while True: yield it.next(), it.next() catch StopIteration: pass >>> list(pairwise(range(6)) [(0, 1), (2, 3), (4, 5)] >>> list(pairwise(range(5)) [(0, 1), (2, 3)] This is different from the solution in the itertools documentation in the sense that the last item is never returned from the iterable if it happens to contain an odd number of elements. But I guess the solution in the itertools examples is better. A: A slight modification to your own example should give you what you want. Your original example shows that you don't know that iterating over a dictionary gives you the keys of the dictionary. "aproprty_name" + 1 will almost never give you what you want. class IterableObject: def __iter__(self): properties = (i for i in self.__dict__) While True: a = properties.next() try: b = properties.next() except StopIteration: yield (getattr(self,a), ) #for the odd number of properties case raise StopIteration yield getattr(self, a), getattr(self, b) This will not work in the example you present. You can not blindly anticipate the values being in any order that would make subtracting one from the other make sense. What you probably want is an object that returns the next two values from a list of values that you know to be an even number of values. You will have to set that list in the object. That way the paired in order sequence would be passed back in the same order. class PairedList: def __iter__(self): balances = iter(self.balances) while True: yield balances.next(), balances.next() >>> b = PairedList() >>> b.balances = (2000, 151, 1000, 255, 600, 150, 0, 20, 30, 30, 50, 10) >>> [i for i in b] [(2000, 151), (1000, 255), (600, 150), (0, 20), (30, 30), (50, 10)] >>> [(balance-withdrawal, balance, withdrawal) for balance, withdrawal in b] [(1849, 2000, 151), (745, 1000, 255), (450, 600, 150), (-20, 0, 20), (0, 30, 30), (40, 50, 10)] You might want to reread you question and example and rephrase them because as written you are creating a new object and expecting it to already contain your values. An example using my PairedList class that would do this for you would be: >>> PairedList.balances = b.balances >>> [(balance-withdrawal, balance, withdrawal) for balance, withdrawal in PairedList()] [(1849, 2000, 151), (745, 1000, 255), (450, 600, 150), (-20, 0, 20), (0, 30, 30), (40, 50, 10)] But this is almost certainly not what you want. It would by default limit you to only ever having one set of balances that you could iterate over. And would create a default set of balances for every PairedList object which will eventually come back to bite you in the butt.
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 I doing wrong? I think I can not add value on item like that.
[ "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 # etc..\n\nNote that when you iterate over a dict the items are not necessarily returned in order, so you should sort first.\n", "A possible solution without itertools:\ndef pairwise(iterable):\n it = iter(iterable)\n try:\n while True:\n yield it.next(), it.next()\n catch StopIteration:\n pass\n\n>>> list(pairwise(range(6))\n[(0, 1), (2, 3), (4, 5)]\n>>> list(pairwise(range(5))\n[(0, 1), (2, 3)]\n\nThis is different from the solution in the itertools documentation in the sense that the last item is never returned from the iterable if it happens to contain an odd number of elements. But I guess the solution in the itertools examples is better.\n", "A slight modification to your own example should give you what you want.\nYour original example shows that you don't know that iterating over a dictionary gives you the keys of the dictionary. \"aproprty_name\" + 1 will almost never give you what you want.\nclass IterableObject:\n def __iter__(self):\n properties = (i for i in self.__dict__)\n While True:\n a = properties.next()\n try:\n b = properties.next()\n except StopIteration:\n yield (getattr(self,a), ) #for the odd number of properties case\n raise StopIteration\n yield getattr(self, a), getattr(self, b)\n\nThis will not work in the example you present. You can not blindly anticipate the values being in any order that would make subtracting one from the other make sense.\nWhat you probably want is an object that returns the next two values from a list of values that you know to be an even number of values. You will have to set that list in the object. That way the paired in order sequence would be passed back in the same order.\nclass PairedList:\n def __iter__(self):\n balances = iter(self.balances)\n while True:\n yield balances.next(), balances.next()\n\n>>> b = PairedList()\n>>> b.balances = (2000, 151, 1000, 255, 600, 150, 0, 20, 30, 30, 50, 10)\n>>> [i for i in b]\n[(2000, 151), (1000, 255), (600, 150), (0, 20), (30, 30), (50, 10)]\n>>> [(balance-withdrawal, balance, withdrawal) for balance, withdrawal in b]\n[(1849, 2000, 151), (745, 1000, 255), (450, 600, 150), (-20, 0, 20), (0, 30, 30), (40, 50, 10)]\n\nYou might want to reread you question and example and rephrase them because as written you are creating a new object and expecting it to already contain your values. An example using my PairedList class that would do this for you would be:\n>>> PairedList.balances = b.balances\n>>> [(balance-withdrawal, balance, withdrawal) for balance, withdrawal in PairedList()]\n[(1849, 2000, 151), (745, 1000, 255), (450, 600, 150), (-20, 0, 20), (0, 30, 30), (40, 50, 10)]\n\nBut this is almost certainly not what you want. It would by default limit you to only ever having one set of balances that you could iterate over. And would create a default set of balances for every PairedList object which will eventually come back to bite you in the butt.\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 to get out of #the directory, e.g. filename = "../.ssh/id_rsa". GET OUTTA HERE assert full[:len(STATIC_PATH)] == STATIC_PATH, "bad path" return open(full).read() Edit: I realize this will return the wrong HTTP error code if the file doesn't exist (at least under web.py). I will fix this. A: 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'd erroneously accept a file living under /foo/barbie/ (so, unless STATIC_PATH does end with the separator character, you need a slightly stricter check for strong assurance). A: Generally speaking, dealing with these kinds of issues is a huge pain. There's always some tricky way of combining path names to create something a programmer didn't expect or plan for. A better solution is usually to make sure that your webserver is running under a user that only has access to the files it needs to have access to. I think a simple solution to the ssh issue is not to allow this user SSH access. If you really need to log in under this user, I'd consider logging in under a different account and su-ing to it. A: Make sure that either STATIC_PATH ends with a directory separator, or that the character following it in full is such.
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 assert full[:len(STATIC_PATH)] == STATIC_PATH, "bad path" return open(full).read() Edit: I realize this will return the wrong HTTP error code if the file doesn't exist (at least under web.py). I will fix this.
[ "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'd erroneously accept a file living under /foo/barbie/ (so, unless STATIC_PATH does end with the separator character, you need a slightly stricter check for strong assurance).\n", "Generally speaking, dealing with these kinds of issues is a huge pain. There's always some tricky way of combining path names to create something a programmer didn't expect or plan for.\nA better solution is usually to make sure that your webserver is running under a user that only has access to the files it needs to have access to. I think a simple solution to the ssh issue is not to allow this user SSH access. If you really need to log in under this user, I'd consider logging in under a different account and su-ing to it.\n", "Make sure that either STATIC_PATH ends with a directory separator, or that the character following it in full is such.\n" ]
[ 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 double quote characters at the start and end of each line in the CSV file, and the "," string is used to delimit fields within each line. The number of fields in the CSV file can vary from file to file. When I try to read this into numpy via: import numpy as np data = np.genfromtxt(csvfile, dtype=None, delimiter=',', names=True) all the data gets read in as string values, surrounded by double-quote characters. Not unreasonable, but not much use to me as I then have to go back and convert every column to its correct type When I use delimiter='","' instead, everything works as I'd like, except for the 1st and last fields. As the start of line and end of line characters are a single double-quote character, this isn't seen as a valid delimiter for the 1st and last fields, so they get read in as e.g. "04/13/2010 14:45:07.008 and 6.552373" - note the leading and trailing double-quote characters respectively. Because of these redundant characters, numpy assumes the 1st and last fields are both String types; I don't want that to be the case Is there a way of instructing numpy to read in files formatted in this fashion as I'd like, without having to go back and "fix" the structure of the numpy array after the initial read? A: 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 and last columns are expected. Looking at the function docs, I think you'll need to set the converters parameter to strip quotes for you (the default does not): import re import numpy as np fieldFilter = re.compile(r'^"?([^"]*)"?$') def filterTheField(s): m = fieldFilter.match(s.strip()) if m: return float(m.group(1)) else: return 0.0 # or whatever default #... # Yes, sorry, you have to know the number of columns, since the NumPy docs # don't say you can specify a default converter for all columns. convs = dict((col, filterTheField) for col in range(numColumns)) data = np.genfromtxt(csvfile, dtype=None, delimiter=',', names=True, converters=convs) Or abandon np.genfromtxt() and let csv.csvreader give you the file's contents a row at a time, as lists of strings, then you just iterate through the elements and build the matrix: reader = csv.csvreader(csvfile) result = np.array([[float(col) for col in row] for row in reader]) # BTW, column headings are in reader.fieldnames at this point. EDIT: Okay, so it looks like your file isn't all floats. In that case, you can set convs as needed in the genfromtxt case, or create a vector of conversion functions in the csv.csvreader case: reader = csv.csvreader(csvfile) converters = [datetime, float, int, float] result = np.array([[conv(col) for col, conv in zip(row, converters)] for row in reader]) # BTW, column headings are in reader.fieldnames at this point. EDIT 2: Okay, variable column count... Your data source just wants to make life difficult. Luckily, we can just use magic... reader = csv.csvreader(csvfile) result = np.array([[magic(col) for col in row] for row in reader]) ... where magic() is just a name I got off the top of my head for a function. (Psyche!) At worst, it could be something like: def magic(s): if '/' in s: return datetime(s) elif '.' in s: return float(s) else: return int(s) Maybe NumPy has a function that takes a string and returns a single element with the right type. numpy.fromstring() looks close, but it might interpret the space in your timestamps as a column separator. P.S. One downside with csvreader I see is that it doesn't discard comments; real csv files don't have comments.
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 line in the CSV file, and the "," string is used to delimit fields within each line. The number of fields in the CSV file can vary from file to file. When I try to read this into numpy via: import numpy as np data = np.genfromtxt(csvfile, dtype=None, delimiter=',', names=True) all the data gets read in as string values, surrounded by double-quote characters. Not unreasonable, but not much use to me as I then have to go back and convert every column to its correct type When I use delimiter='","' instead, everything works as I'd like, except for the 1st and last fields. As the start of line and end of line characters are a single double-quote character, this isn't seen as a valid delimiter for the 1st and last fields, so they get read in as e.g. "04/13/2010 14:45:07.008 and 6.552373" - note the leading and trailing double-quote characters respectively. Because of these redundant characters, numpy assumes the 1st and last fields are both String types; I don't want that to be the case Is there a way of instructing numpy to read in files formatted in this fashion as I'd like, without having to go back and "fix" the structure of the numpy array after the initial read?
[ "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 and last columns are expected.\nLooking at the function docs, I think you'll need to set the converters parameter to strip quotes for you (the default does not):\nimport re\nimport numpy as np\n\nfieldFilter = re.compile(r'^\"?([^\"]*)\"?$')\ndef filterTheField(s):\n m = fieldFilter.match(s.strip())\n if m:\n return float(m.group(1))\n else:\n return 0.0 # or whatever default\n\n#...\n\n# Yes, sorry, you have to know the number of columns, since the NumPy docs\n# don't say you can specify a default converter for all columns.\nconvs = dict((col, filterTheField) for col in range(numColumns))\ndata = np.genfromtxt(csvfile, dtype=None, delimiter=',', names=True, \n converters=convs)\n\nOr abandon np.genfromtxt() and let csv.csvreader give you the file's contents a row at a time, as lists of strings, then you just iterate through the elements and build the matrix:\nreader = csv.csvreader(csvfile)\nresult = np.array([[float(col) for col in row] for row in reader])\n# BTW, column headings are in reader.fieldnames at this point.\n\nEDIT: Okay, so it looks like your file isn't all floats. In that case, you can set convs as needed in the genfromtxt case, or create a vector of conversion functions in the csv.csvreader case:\nreader = csv.csvreader(csvfile)\nconverters = [datetime, float, int, float]\nresult = np.array([[conv(col) for col, conv in zip(row, converters)] \n for row in reader])\n# BTW, column headings are in reader.fieldnames at this point.\n\nEDIT 2: Okay, variable column count... Your data source just wants to make life difficult. Luckily, we can just use magic...\nreader = csv.csvreader(csvfile)\nresult = np.array([[magic(col) for col in row] for row in reader])\n\n... where magic() is just a name I got off the top of my head for a function. (Psyche!)\nAt worst, it could be something like:\ndef magic(s):\n if '/' in s:\n return datetime(s)\n elif '.' in s:\n return float(s)\n else:\n return int(s)\n\nMaybe NumPy has a function that takes a string and returns a single element with the right type. numpy.fromstring() looks close, but it might interpret the space in your timestamps as a column separator.\nP.S. One downside with csvreader I see is that it doesn't discard comments; real csv files don't have comments.\n" ]
[ 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: DeprecationWarning: the sha >module is deprecated; use the hashlib module instead import sha /Users/cm/code/thisLocator/../thisLocator/batches/models.py:6: DeprecationWarning: the md5 >module is deprecated; use hashlib instead import md5 There is no enabled application matching 'thisLocator'. I've followed the South documentation. Settings.py has it in the installed apps, I can run import south from the manage.py shell. Everyone else on my team is calling the app thisLocator. Am I doing something really stupid? A: Am I doing something really stupid? Well, let's start with the "is it plugged in" questions: Is your project directory in your Python path? Are 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.) What is the output of ./manage.py syncdb? (I use ./manage.py instead of python manage.py just in case they refer to different pythons.)
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 instead import sha /Users/cm/code/thisLocator/../thisLocator/batches/models.py:6: DeprecationWarning: the md5 >module is deprecated; use hashlib instead import md5 There is no enabled application matching 'thisLocator'. I've followed the South documentation. Settings.py has it in the installed apps, I can run import south from the manage.py shell. Everyone else on my team is calling the app thisLocator. Am I doing something really stupid?
[ "\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 the output of ./manage.py syncdb? (I use ./manage.py instead of python manage.py just in case they refer to different pythons.)\n\n" ]
[ 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 "search"? Or would you really just have a site called mysite with one app called StackOverflow? A: Django actually has 3 concepts here: Project (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. App: This is a set of views, models, and templates. Apps are often designed so they can be plugged into another project. Site: You can designate different behaviour for an app based on the site (ie: URL) being visited. This way, the same "App" can customize itself based on whether or not the user has visited 'StackOverflow.com' or 'RackOverflow.com' (or whatever the IT-targeted version will be called), even though it's the same codebase that's handling the request. How you arrange these is really up to your project. In a complicated case, you might do: Project: StackOverflowProject App: Web Version Site: StackOverflow.com Site: RackOverflow.com App: XML API Version Site: StackOverflow.com Site: RackOverflow.com Common non-app settings, libraries, auth, etc Or, for a simpler project that wants to leverage an open-source plugin: Project: StackOverflowProject App: Stackoverflow (No specific use of the sites feature... it's just one site) App: Plug-in TinyMCE editor with image upload (No specific use of the sites feature) Aside from the fact that there needs to be a Project, and at least one app, the arrangement is very flexible; you can adapt however suits best to help abstract and manage the complexity (or simplicity) of your deployment. A: From the Django documentation: Projects vs. apps What’s the difference between a project and an app? An app is a Web application that does something — e.g., a weblog system, a database of public records or a simple poll app. A project is a collection of configuration and apps for a particular Web site. A project can contain multiple apps. An app can be in multiple projects. From this link: Projects versus applications This is really more of a separate (though related) question, but understanding the distinction Django draws between a “project” and an “application” is a big part of good code layout. Roughly speaking, this is what the two terms mean: An application tries to provide a single, relatively self-contained set of related functions. An application is allowed to define a set of models (though it doesn’t have to) and to define and register custom template tags and filters (though, again, it doesn’t have to). A project is a collection of applications, installed into the same database, and all using the same settings file. In a sense, the defining aspect of a project is that it supplies a settings file which specifies the database to use, the applications to install, and other bits of configuration. A project may correspond to a single web site, but doesn’t have to — multiple projects can run on the same site. The project is also responsible for the root URL configuration, though in most cases it’s useful to just have that consist of calls to include which pull in URL configurations from inidividual applications. Views, custom manipulators, custom context processors and most other things Django lets you create can all be defined either at the level of the project or of the application, and where you do that should depend on what’s most effective for you; in general, though, they’re best placed inside an application (this increases their portability across projects). A: The answer to would you have a project with a single app called StackOverflow is an unequivocal no. A site like this might have 20+ apps. See James Bennett's "DjangoCon 2008: Reusable Apps" video presentation which explains this nicely. A: As you said, you'd have a site called StackOverflow with an auth app, questions app, etc. You should have a look at the Pinax project to see how they lay things out. It's one of the better ways to do it since it will increase the modularity and portability of your apps.
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 one app called StackOverflow?
[ "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 another project.\nSite: You can designate different behaviour for an app based on the site (ie: URL) being visited. This way, the same \"App\" can customize itself based on whether or not the user has visited 'StackOverflow.com' or 'RackOverflow.com' (or whatever the IT-targeted version will be called), even though it's the same codebase that's handling the request.\n\nHow you arrange these is really up to your project. In a complicated case, you might do:\nProject: StackOverflowProject\n App: Web Version\n Site: StackOverflow.com\n Site: RackOverflow.com\n App: XML API Version\n Site: StackOverflow.com\n Site: RackOverflow.com\n Common non-app settings, libraries, auth, etc\n\nOr, for a simpler project that wants to leverage an open-source plugin:\nProject: StackOverflowProject\n App: Stackoverflow\n (No specific use of the sites feature... it's just one site)\n App: Plug-in TinyMCE editor with image upload\n (No specific use of the sites feature)\n\nAside from the fact that there needs to be a Project, and at least one app, the arrangement is very flexible; you can adapt however suits best to help abstract and manage the complexity (or simplicity) of your deployment.\n", "From the Django documentation:\n\nProjects vs. apps\nWhat’s the difference between a project and an app? An app is a Web application that does something — e.g., a weblog system, a database of public records or a simple poll app. A project is a collection of configuration and apps for a particular Web site. A project can contain multiple apps. An app can be in multiple projects.\n\nFrom this link:\n\nProjects versus applications\nThis is really more of a separate (though related) question, but understanding the distinction Django draws between a “project” and an “application” is a big part of good code layout. Roughly speaking, this is what the two terms mean:\n\nAn application tries to provide a single, relatively self-contained set of related functions. An application is allowed to define a set of models (though it doesn’t have to) and to define and register custom template tags and filters (though, again, it doesn’t have to).\n\nA project is a collection of applications, installed into the same database, and all using the same settings file. In a sense, the defining aspect of a project is that it supplies a settings file which specifies the database to use, the applications to install, and other bits of configuration. A project may correspond to a single web site, but doesn’t have to — multiple projects can run on the same site. The project is also responsible for the root URL configuration, though in most cases it’s useful to just have that consist of calls to include which pull in URL configurations from inidividual applications.\n\n\nViews, custom manipulators, custom context processors and most other things Django lets you create can all be defined either at the level of the project or of the application, and where you do that should depend on what’s most effective for you; in general, though, they’re best placed inside an application (this increases their portability across projects).\n\n", "The answer to would you have a project with a single app called StackOverflow is an unequivocal no. A site like this might have 20+ apps.\nSee James Bennett's \"DjangoCon 2008: Reusable Apps\" video presentation which explains this nicely.\n", "As you said, you'd have a site called StackOverflow with an auth app, questions app, etc.\nYou should have a look at the Pinax project to see how they lay things out. It's one of the better ways to do it since it will increase the modularity and portability of your apps.\n" ]
[ 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 read it in a way to accomplish what I want. So what I would like to know is a proper way to write/read the wx.Config in a way that everytime someone opens the application, the items from ListCtrl are there. Thanks in advance. A: Using wx.Config is very easy, just create config passing name of your app and add data e.g. config = wx.Config("StackOverflowTest") config.Write("testdata", "yes it works!") Now you can read it anytime config = wx.Config("StackOverflowTest") print config.Read("testdata") For saving list cntrl data I would suggest that you first read all data in a python list and pickle that list into config, next time read config, unpickle data and populate list, structure wise add functions like fillList/saveList so you can be sure reading writing part are nearby and similar. e.g. you can use this skeleton import wx import cPickle class MyListCtrl(wx.ListCtrl): def __init__(self, *args, **kwargs): wx.ListCtrl.__init__(self, *args, **kwargs) self.config = wx.Config("MykoolApp") self.fillist() def filllist(self): # load rows and check for error too, if no data data = self.config.Read("list_cntrl_data") rowList = cPickle.loads(data) for row in rowList: # add this row to list cntrl pass def savelist(self): rows = [] for row in self: # add data to rows pass data = cPickle.dumps(rows) self.config.Write("list_cntrl_data", data) def onchange(self): """ on changes to list e.g. add delete call save list """ self.savelist()
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 want. So what I would like to know is a proper way to write/read the wx.Config in a way that everytime someone opens the application, the items from ListCtrl are there. Thanks in advance.
[ "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 data I would suggest that you first read all data in a python list and pickle that list into config, next time read config, unpickle data and populate list, structure wise add functions like fillList/saveList so you can be sure reading writing part are nearby and similar.\ne.g. you can use this skeleton\nimport wx\nimport cPickle\n\nclass MyListCtrl(wx.ListCtrl):\n\n def __init__(self, *args, **kwargs):\n wx.ListCtrl.__init__(self, *args, **kwargs)\n self.config = wx.Config(\"MykoolApp\")\n\n self.fillist()\n\n def filllist(self):\n # load rows and check for error too, if no data\n data = self.config.Read(\"list_cntrl_data\")\n rowList = cPickle.loads(data)\n\n for row in rowList:\n # add this row to list cntrl\n pass\n\n def savelist(self):\n rows = []\n for row in self:\n # add data to rows\n pass\n\n data = cPickle.dumps(rows)\n self.config.Write(\"list_cntrl_data\", data)\n\n def onchange(self):\n \"\"\"\n on changes to list e.g. add delete call save list\n \"\"\"\n self.savelist()\n\n" ]
[ 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 being simple: re.findall('%(.+?)%', text) In fact, .+?% finds all characters of any type (a tag), and stops as soon as % is found (that's the "non-greedy" part). In the speed test below, the non-greedy version of this answer is slower than the "not another % sign" version by a factor of almost 2, though: python -m timeit -s'import re; t="%t1% lkj lkj %long tag% lkj lkj"*1000' 're.findall("%([^%]+)%", t)' 1000 loops, best of 3: 874 usec per loop python -m timeit -s'import re; t="%t1% lkj lkj %long tag% lkj lkj"*1000' 're.findall("%(.+?)%", t)' 1000 loops, best of 3: 1.43 msec per loop
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 (that's the \"non-greedy\" part).\nIn the speed test below, the non-greedy version of this answer is slower than the \"not another % sign\" version by a factor of almost 2, though:\npython -m timeit -s'import re; t=\"%t1% lkj lkj %long tag% lkj lkj\"*1000' 're.findall(\"%([^%]+)%\", t)'\n1000 loops, best of 3: 874 usec per loop\n\npython -m timeit -s'import re; t=\"%t1% lkj lkj %long tag% lkj lkj\"*1000' 're.findall(\"%(.+?)%\", t)'\n1000 loops, best of 3: 1.43 msec per loop\n\n" ]
[ 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 way I know how to do this in perl so far is: $oldstring =~ s/ab/cd/; $newstring = $oldstring; Note the extra assignment. A: You can use ($new = $old) =~ s/whatever/whateverelse/; for an exactly same functionality you are looking for: use strict; my $old = "OLD"; my $new; ($new = $old) =~ s/OLD/NEW/; print "old=$old, new=$new"; Produces: old=OLD, new=NEW Exactly what you want If you're looking for a function, you can just define your own to avoid assignment: use strict; sub re_sub { my ($find, $replace, $old) = @_; my $new = $old; $new =~ s/$find/$replace/; return $new; } my $old = "ab"; my $new = re_sub('ab', 'cd', $old); print "new=$new\n"; Results in new=cd. A: Perl's regular expression substitution always happens 'in-place'. So you need to copy the string to a new variable and operate on the new variable: (my $newstring = $oldstring) =~ s/ab/cd/; A: You seem to have a misconception about how =~ works. =~ is a binding operator that associates a variable with a regexp operator. It does not do any assignment. The regexp operators all work by default with the topic variable $_, so s/foo/bar/; is the same as $_ =~ s/foo/bar/;. No assignment occurs. The topic variable is transformed. The case is analogous when operating on any other variable. $var =~ s/foo/bar/; transforms $var by replacing the first instance of foo with bar. No assignment occurs. The best advice I can give you is to write Python in Python and Perl in Perl. Don't expect the two languages to be the same. You could do like DVK suggests and write a subroutine that will reproduce the substitution behavior you are used to. Or you could try some idiomatic Perl. Based on your expressed desire to apply multiple transformations in one line, I've provided a couple examples you might find useful. Here I use a for loop over one item to topicalize $var and apply many hard-coded transformations: for( $var ) { s/foo/bar/; s/fizz/buzz/; s/whop/bop-a-loo-bop/; s/parkay/butter/; s/cow/burger/; } Or maybe you need to apply a variable group of transforms. I define a subroutine to loop over a list of array references that define old/new transformation pairs. This example takes advantage of Perl's list oriented argument processing to handle any number of transformations. my $foo = transform( 'abcd' => [ 'a', 'b' ], [ 'bb', 'c' ], [ 'cc', 'd' ], [ 'dd', 'DONE' ], ); sub transform { my $var = shift; for (@_ ) { my ($old, $new) = @$_; $var =~ s/$old/$new/; } return $var; } Finally a bit of messing about to provide a version of transform that modifies its first argument: my $foo = 'abcd'; transform_in_place( $foo => [ 'a', 'b' ], [ 'bb', 'c' ], [ 'cc', 'd' ], [ 'dd', 'DONE' ], ); print "$foo\n"; sub transform_in_place { for my $i (1..$#_ ) { my ($old, $new) = @{$_[$i]}; $_[0] =~ s/$old/$new/; } } For my own project I'd probably use one of the first two options depending on the needs of the particular problem. A: You want to have $newstring be the result of the substitution, right? Something like this: ($newstring = $oldstring) =~ s/ab/cd; Should work. The assignment sets $newstring to $oldstring and then evaluates to $newstring, which is what the substitution acts on. A: Based on this, am I right to assume that you cannot have two s/// in one line, one which uses the result of the other, with no intermediate assignments? – mikeY Yes you are correct. If you want to apply multiple substitutions to the same string I would do $newstring = $oldstring ; $newstring =~ s/ab/cd/ ; $newstring =~ s/xx/yy/ ; The following won't work because s// returns the number of substitutions made, not the changed string. $newstring = $oldstring) =~ s/ab/cd/ =~ s/xx/yy/ ; In summary, Perl's regex operations are very different to Python's and you are better trying to learn what Perl does from scratch rather than trying to map Python concepts onto Perl
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: $oldstring =~ s/ab/cd/; $newstring = $oldstring; Note the extra assignment.
[ "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 just define your own to avoid assignment:\nuse strict;\nsub re_sub { \n my ($find, $replace, $old) = @_;\n my $new = $old;\n $new =~ s/$find/$replace/;\n return $new;\n}\n\nmy $old = \"ab\";\nmy $new = re_sub('ab', 'cd', $old);\nprint \"new=$new\\n\";\n\nResults in new=cd.\n", "Perl's regular expression substitution always happens 'in-place'. So you need to copy the string to a new variable and operate on the new variable:\n(my $newstring = $oldstring) =~ s/ab/cd/;\n\n", "You seem to have a misconception about how =~ works. =~ is a binding operator that associates a variable with a regexp operator. It does not do any assignment.\nThe regexp operators all work by default with the topic variable $_, so s/foo/bar/; is the same as $_ =~ s/foo/bar/;. No assignment occurs. The topic variable is transformed.\nThe case is analogous when operating on any other variable. $var =~ s/foo/bar/; transforms $var by replacing the first instance of foo with bar. No assignment occurs.\nThe best advice I can give you is to write Python in Python and Perl in Perl. Don't expect the two languages to be the same.\nYou could do like DVK suggests and write a subroutine that will reproduce the substitution behavior you are used to.\nOr you could try some idiomatic Perl. Based on your expressed desire to apply multiple transformations in one line, I've provided a couple examples you might find useful.\nHere I use a for loop over one item to topicalize $var and apply many hard-coded transformations:\nfor( $var ) {\n s/foo/bar/;\n s/fizz/buzz/;\n s/whop/bop-a-loo-bop/;\n s/parkay/butter/;\n s/cow/burger/;\n}\n\nOr maybe you need to apply a variable group of transforms. I define a subroutine to loop over a list of array references that define old/new transformation pairs. This example takes advantage of Perl's list oriented argument processing to handle any number of transformations.\nmy $foo = transform(\n 'abcd' =>\n [ 'a', 'b' ], \n [ 'bb', 'c' ],\n [ 'cc', 'd' ],\n [ 'dd', 'DONE' ],\n);\n\nsub transform {\n my $var = shift;\n for (@_ ) {\n my ($old, $new) = @$_;\n $var =~ s/$old/$new/;\n }\n\n return $var;\n}\n\nFinally a bit of messing about to provide a version of transform that modifies its first argument:\nmy $foo = 'abcd';\n\ntransform_in_place(\n $foo =>\n [ 'a', 'b' ], \n [ 'bb', 'c' ],\n [ 'cc', 'd' ],\n [ 'dd', 'DONE' ],\n);\n\nprint \"$foo\\n\";\n\nsub transform_in_place {\n for my $i (1..$#_ ) {\n my ($old, $new) = @{$_[$i]};\n $_[0] =~ s/$old/$new/;\n }\n}\n\nFor my own project I'd probably use one of the first two options depending on the needs of the particular problem.\n", "You want to have $newstring be the result of the substitution, right?\nSomething like this:\n($newstring = $oldstring) =~ s/ab/cd;\n\nShould work. The assignment sets $newstring to $oldstring and then evaluates to $newstring, which is what the substitution acts on.\n", "Based on this, am I right to assume that you cannot have two s/// in one line, one which uses the result of the other, with no intermediate assignments? – mikeY\nYes you are correct.\nIf you want to apply multiple substitutions to the same string I would do \n $newstring = $oldstring ;\n $newstring =~ s/ab/cd/ ;\n $newstring =~ s/xx/yy/ ;\n\nThe following won't work because s// returns the number of substitutions made, not the changed string.\n $newstring = $oldstring) =~ s/ab/cd/ =~ s/xx/yy/ ;\n\nIn summary, Perl's regex operations are very different to Python's and you are better trying to learn what Perl does from scratch rather than trying to map Python concepts onto Perl\n" ]
[ 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 please help me. A: GQL isn't SQL. It doesn't have COUNT() or GROUP BY(). See the GQL reference for more information. A: Since GQL does not have COUNT and GROUP BY function. so I designed a solution for it: result = db.GqlQuery( SELECT * form Employee) Make an Array which will have unique Departments from the result : if result.Department not in array: array.append(result.Department) for department in array: query = db.GqlQuery(SELECT * form Employee WHERE Department = :1,department) print "In" + department + query.count() +"Employees are working"
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 result.Department not in array:\n array.append(result.Department)\nfor department in array:\n query = db.GqlQuery(SELECT * form Employee WHERE Department = :1,department)\n print \"In\" + department + query.count() +\"Employees are working\"\n\n" ]
[ 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, 8): for x2 in range(0, 8): for y2 in range(0, 8): S.append([x1,y1,x2,y2]) S = tuple(S) thanks A: 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)) Or import itertools a = [range(0,8)]*4 print tuple(itertools.product(*a)) Note that this returns a tuple of tuples. If you need a tuple of lists, use tuple(itertools.imap(list, itertools.product(*a))).
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.append([x1,y1,x2,y2]) S = tuple(S) thanks
[ "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(*a))). \n" ]
[ 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 @route('/') def index(): return 'Index' @route('/hello') def hello(): return 'Hello' if __name__ == '__main__': from wsgiref.handlers import CGIHandler CGIHandler().run(bottle.default_app()) And here is my .htaccess file DirectoryIndex index.py <ifmodule mod_rewrite.c=""> RewriteEngine on RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ /index.py/$1 [L] </ifmodule> I copied much of the code from here as I'm using DH and it seemed relevant: http://blog.coderonfire.com/2010/02/running-bottle-python-micro-framework.html Thanks for helping. A: 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. DirectoryIndex index.py RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ /index.py/$1 [L]
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') def hello(): return 'Hello' if __name__ == '__main__': from wsgiref.handlers import CGIHandler CGIHandler().run(bottle.default_app()) And here is my .htaccess file DirectoryIndex index.py <ifmodule mod_rewrite.c=""> RewriteEngine on RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ /index.py/$1 [L] </ifmodule> I copied much of the code from here as I'm using DH and it seemed relevant: http://blog.coderonfire.com/2010/02/running-bottle-python-micro-framework.html Thanks for helping.
[ "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_FILENAME} !-f\nRewriteRule ^(.*)$ /index.py/$1 [L]\n\n" ]
[ 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 = win32com.client.constants w.ActiveDocument.SaveAs( FileName = filenameout, FileFormat = wc.wdFormatHTML ) I tried looking for something like wc.wdFormatPNG as wc.wdFormatHTML in the example but failed.And I wonder does the attribute exist?Or any other better solutions?Suggestions would be appreciated. A: 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.
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 = filenameout, FileFormat = wc.wdFormatHTML ) I tried looking for something like wc.wdFormatPNG as wc.wdFormatHTML in the example but failed.And I wonder does the attribute exist?Or any other better solutions?Suggestions would be appreciated.
[ "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 the server, preferably not all in one directory - but split logically. 2) Store the images in a database, if you are using MySql you would do this using the "blob" type. A: When you store all the images in one directory it could quickly become unmanaged due to huge number of files. You can put your images in subdirectories based on md5 or sha1 hash function. Usually 2 levels of subdirs is enough. In this case your directory images/upload will contain subdirs with the names 00, 01, 02 .. FF (256 names total) and each of these 256 directories in turn will contain directories with names 00 through FF giving you in total 256*256 directories on level 2. For each uploaded file you calculate hash function (not necessary based on it's content, but on some unique data) and take [0:2] as a name of first directory and [2:4] as a name of second level directory. This would be helpful in creating directories: mkdir -p functionality in Python
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 become unmanaged due to huge number of files. You can put your images in subdirectories based on md5 or sha1 hash function. Usually 2 levels of subdirs is enough.\nIn this case your directory images/upload will contain subdirs with the names 00, 01, 02 .. FF (256 names total) and each of these 256 directories in turn will contain directories with names 00 through FF giving you in total 256*256 directories on level 2.\nFor each uploaded file you calculate hash function (not necessary based on it's content, but on some unique data) and take [0:2] as a name of first directory and [2:4] as a name of second level directory.\nThis would be helpful in creating directories: mkdir -p functionality in Python\n" ]
[ 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: l.append(l2[top2]) top2=top2+1 print "added"+l2[top2] return l >>> merge(l1,l2) Traceback (most recent call last): File "<pyshell#58>", line 1, in <module> merge(l1,l2) File "<pyshell#57>", line 6, in merge l.append(11[top1]) TypeError: 'int' object is unsubscriptable A: 6th line of the code: you have 11 instead of l1. A: You have 11 instead of l1.
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 print "added"+l2[top2] return l >>> merge(l1,l2) Traceback (most recent call last): File "<pyshell#58>", line 1, in <module> merge(l1,l2) File "<pyshell#57>", line 6, in merge l.append(11[top1]) TypeError: 'int' object is unsubscriptable
[ "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 fileObject = csv.writer(open('Insurance.csv','w'),dialect='excel',delimiter=' ') for i in range(0,175): current_list = list(choice(master_list)) fileObject.writerows(current_list) current_list = [] Thanks A: If your intent is to write 175 rows, you need to use: fileObject.writerow(current_list) instead 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. A: Are you sure about this delimiter? If my memory serves, the delimiter in a CSV file should be a comma (hence the name, Comma-Separated Values), and not a space.
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('Insurance.csv','w'),dialect='excel',delimiter=' ') for i in range(0,175): current_list = list(choice(master_list)) fileObject.writerows(current_list) current_list = [] Thanks
[ "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 should be a comma (hence the name, Comma-Separated Values), and not a space.\n" ]
[ 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://www.mysite.com/ redirects me to http://www.mysite.com/ru/ and "name" variable gets russian localization. For now it's ok... But... Entering http://www.mysite.com/en/ shows me same russian loclized variable. During my experiments with debuger I've discovered: request.LANGUAGE_CODE is changing properly according to /en/ or /ru/ url suffix (thanx to localeurl) invoking multilingual.languages.set_default_language() makes "name" variable change loclization The question is: should I change language of django-multilingual to request.LANGUAGE_CODE in each of my view myself, or it must be solved automaticly and I've done something wrong? A: I have the same problem, after rotation with positions in MIDDLEWARE_CLASSES I've got the right order: MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', #'django.middleware.locale.LocaleMiddleware', 'localeurl.middleware.LocaleURLMiddleware', 'multilingual.middleware.DefaultLanguageMiddleware', 'multilingual.flatpages.middleware.FlatpageFallbackMiddleware', 'django.middleware.common.CommonMiddleware', ) I comment #'django.middleware.locale.LocaleMiddleware' its doing the same as 'localeurl.middleware.LocaleURLMiddleware' I think. A: after removing django.middleware.locale.LocaleMiddleware it worked for me also ...
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.mysite.com/ru/ and "name" variable gets russian localization. For now it's ok... But... Entering http://www.mysite.com/en/ shows me same russian loclized variable. During my experiments with debuger I've discovered: request.LANGUAGE_CODE is changing properly according to /en/ or /ru/ url suffix (thanx to localeurl) invoking multilingual.languages.set_default_language() makes "name" variable change loclization The question is: should I change language of django-multilingual to request.LANGUAGE_CODE in each of my view myself, or it must be solved automaticly and I've done something wrong?
[ "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 #'django.middleware.locale.LocaleMiddleware',\n 'localeurl.middleware.LocaleURLMiddleware',\n 'multilingual.middleware.DefaultLanguageMiddleware',\n 'multilingual.flatpages.middleware.FlatpageFallbackMiddleware',\n 'django.middleware.common.CommonMiddleware', \n)\n\nI comment #'django.middleware.locale.LocaleMiddleware' its doing the same as 'localeurl.middleware.LocaleURLMiddleware' I think.\n", "after removing django.middleware.locale.LocaleMiddleware it worked for me also ...\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 role.users = None, but SA complains None is not a list. At this moment, I use sqlalchemy.orm.attributes.del_attribute, but I don't know if it's provided for this purpose. A: 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.
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 sqlalchemy.orm.attributes.del_attribute, but I don't know if it's provided for this purpose.
[ "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.. A: <mx:HTTPService url="backend-url.cgi" id="service"/> <mx:List dataProvider="{service.lastResult.yourElementName}"/> You should also Call service.send() from the Application's creationComplete handler Specify the labelField, dataField etc for the List as applicable
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] != None: pass (As you can see, the parentheses were also redundant.) Furthermore, != None can be changed to is not None: while l1[i] is not None or l2[i] is not None: (Thanks to @SilentGhost for pointing that out.) A: Even more Pythonic would be something like this (since it looks like you are iterating over both lists until one hits a 'None' value): for l1val,l2val in zip(l1,l2): if l1val is None or l2val is None: break ... rest of while loop goes here, using l1val and l2val instead of l1[i] and l2[i] In fact, that None sentinel looks a little weird. If this is something you tacked onto the end so you know when you are at the end of the list, then don't bother - just use Python's own iteration features (for loops automatically stop at the end of the list they are iterating over.*) for l1val,l2val in zip(l1,l2): ... body of while loop goes here, using l1val and l2val instead of l1[i] and l2[i] *-They don't really stop automatically - the list iterator raises the exception StopIteration, which is caught by the for loop as a signal to stop looping. My crystal ball is getting fuzzier, but there is one more clue, in your method name 'merge'. Let's say merge takes two lists, and each list is a list of integers, and by 'merge', you mean return a new list of the sums of the respective values in l1 and l2. Here is what merge looks like with a for loop: def merge(l1, l2): retl = [] for v1,v2 in zip(l1, l2): retl.append(v1+v2) return retl As a newbie, you should learn about and get very comfortable with a concept called "list comprehensions". Using a list comprehension, you can simplify your merge method to the simple: def merge(l1, l2): return [v1+v2 for v1,v2 in zip(l1, l2)] This is equivalent to the previous function - please study these and see how that works. And finally, in a flashing moment of Python's duck typing, run merge as-is, but this time passing it a list of lists instead of a list of ints. (Left as an exercise for the OP.)
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(Thanks to @SilentGhost for pointing that out.)\n", "Even more Pythonic would be something like this (since it looks like you are iterating over both lists until one hits a 'None' value):\nfor l1val,l2val in zip(l1,l2):\n if l1val is None or l2val is None:\n break\n ... rest of while loop goes here, using l1val and l2val\n instead of l1[i] and l2[i]\n\nIn fact, that None sentinel looks a little weird. If this is something you tacked onto the end so you know when you are at the end of the list, then don't bother - just use Python's own iteration features (for loops automatically stop at the end of the list they are iterating over.*)\nfor l1val,l2val in zip(l1,l2):\n ... body of while loop goes here, using l1val and l2val\n instead of l1[i] and l2[i]\n\n*-They don't really stop automatically - the list iterator raises the exception StopIteration, which is caught by the for loop as a signal to stop looping.\nMy crystal ball is getting fuzzier, but there is one more clue, in your method name 'merge'. Let's say merge takes two lists, and each list is a list of integers, and by 'merge', you mean return a new list of the sums of the respective values in l1 and l2. Here is what merge looks like with a for loop:\ndef merge(l1, l2):\n retl = []\n for v1,v2 in zip(l1, l2):\n retl.append(v1+v2)\n return retl\n\nAs a newbie, you should learn about and get very comfortable with a concept called \"list comprehensions\". Using a list comprehension, you can simplify your merge method to the simple:\ndef merge(l1, l2):\n return [v1+v2 for v1,v2 in zip(l1, l2)]\n\nThis is equivalent to the previous function - please study these and see how that works. And finally, in a flashing moment of Python's duck typing, run merge as-is, but this time passing it a list of lists instead of a list of ints. (Left as an exercise for the OP.)\n" ]
[ 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/stackoverflow-question/least-popular-colours-_-500-x-500.jpg' temp_fn, _ = urllib.urlretrieve(orig_url) im = Image.open(temp_fn) fn = os.tempnam() + '.jpg' im.save(fn) webbrowser.open(fn) I've tried Image.open(temp_fn).convert(format) with 'RGB', 'CMYK' and 'L' as formats, but still get weirdly coloured or grey results. When I load the image from my hard drive and I can see: >>>im.info {'adobe': 100, 'progression': 1, 'exif': 'Exif\x00\x00MM\x00*...\x7f\xff\xd9', 'adobe_transform': 100} >>>im.format 'JPEG' >>>im.mode 'CMYK' >>> im._getexif() {40961: 65535, 40962: 500, 40963: 500, 296: 2, 34665: 164, 274: 1, 305: 'Adobe Photoshop CS Macintosh', 306: '2010:02:26 12:46:54', 282: (300, 1), 283: (300, 1)} Thanks and let me know if you need any more data. A: 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: "CMYK in JPEG is one big mess, mainly because Adobe got it wrong in Photoshop many years ago." By the way, you can find which version of PIL you have by doing: >>> Image.VERSION '1.1.7' Update: to make the resulting image display in IE you need to add .convert('RGB') so that you're outputting in standard jpeg RGB format, not CMYK. A: PIL seems to have a problem loading some JPEG files in CMYK format. If you can convert the image to a more commonly supported color format (using another tool) it will help. There's a PIL patch posted here, but I haven't tried it. A: I've had problems like this when the original image was saved in CMYK mode. I had to resave the image in RGB before processing it with PIL.
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' temp_fn, _ = urllib.urlretrieve(orig_url) im = Image.open(temp_fn) fn = os.tempnam() + '.jpg' im.save(fn) webbrowser.open(fn) I've tried Image.open(temp_fn).convert(format) with 'RGB', 'CMYK' and 'L' as formats, but still get weirdly coloured or grey results. When I load the image from my hard drive and I can see: >>>im.info {'adobe': 100, 'progression': 1, 'exif': 'Exif\x00\x00MM\x00*...\x7f\xff\xd9', 'adobe_transform': 100} >>>im.format 'JPEG' >>>im.mode 'CMYK' >>> im._getexif() {40961: 65535, 40962: 500, 40963: 500, 296: 2, 34665: 164, 274: 1, 305: 'Adobe Photoshop CS Macintosh', 306: '2010:02:26 12:46:54', 282: (300, 1), 283: (300, 1)} Thanks and let me know if you need any more data.
[ "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 way, you can find which version of PIL you have by doing:\n>>> Image.VERSION \n'1.1.7' \n\nUpdate: to make the resulting image display in IE you need to add .convert('RGB') so that you're outputting in standard jpeg RGB format, not CMYK.\n", "PIL seems to have a problem loading some JPEG files in CMYK format. If you can convert the image to a more commonly supported color format (using another tool) it will help. \nThere's a PIL patch posted here, but I haven't tried it.\n", "I've had problems like this when the original image was saved in CMYK mode. I had to resave the image in RGB before processing it with PIL.\n" ]
[ 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__(self, a=[]): self.a = a o = A() o.a.append('Hello') o.a.append('Alex') print ' '.join(o.a) # >> prints Hello Alex o1 = A() o1.a.append('Hello') o1.a.append('Alex') print ' '.join(o1.a) # >> prints Hello Alex Hello Alex A: Read this Pitfall about mutable default function arguments: http://www.ferg.org/projects/python_gotchas.html In short, when you define def __init__(self,a=[]) The 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 are modifying the same list. The typical way to fix this is to say: class A(object): def __init__(self, a=None): self.a = [] if a is None else a By moving self.a=[] into the body of the __init__ function, a new empty list is created at run-time (each time __init__ is called), not at definition-time. A: Default arguments in Python, like: def blah(a="default value") are evaluated once and re-used in every call, so when you modify a you modify a globally. A possible solution is to do: def blah(a=None): if a is None a = [] You can read more about this issue on: http://www.ferg.org/projects/python_gotchas.html#contents_item_6 Basically, never use mutable objects, like lists or dictionaries on a default value for an argument.
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.a = a o = A() o.a.append('Hello') o.a.append('Alex') print ' '.join(o.a) # >> prints Hello Alex o1 = A() o1.a.append('Hello') o1.a.append('Alex') print ' '.join(o1.a) # >> prints Hello Alex Hello Alex
[ "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 are modifying the same list.\nThe typical way to fix this is to say:\nclass A(object):\n def __init__(self, a=None):\n self.a = [] if a is None else a\n\nBy moving self.a=[] into the body of the __init__ function, a new empty list is created at run-time (each time __init__ is called), not at definition-time. \n", "Default arguments in Python, like:\ndef blah(a=\"default value\")\n\nare evaluated once and re-used in every call, so when you modify a you modify a globally. A possible solution is to do:\ndef blah(a=None):\n if a is None\n a = []\n\nYou can read more about this issue on: http://www.ferg.org/projects/python_gotchas.html#contents_item_6\nBasically, never use mutable objects, like lists or dictionaries on a default value for an argument.\n" ]
[ 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 found autopy, but the fact that it controls the real mouse position is problematic, because it prevents user interaction with other tools (debugger or anything) while running. Cross platform would be nice, but either windows or os x is fine. Python would be ideal but anything that you could create python bindings for would be ok too. A: On Linux, you could run autopy inside a VNC session. There is also pywinauto or watsup. A: 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 server, so you don't have to run the tests on your physical screen. If you need to test only an application developed using Qt, GTK, Java SWT/Swing there are few test frameworks for doing this.
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 it controls the real mouse position is problematic, because it prevents user interaction with other tools (debugger or anything) while running. Cross platform would be nice, but either windows or os x is fine. Python would be ideal but anything that you could create python bindings for would be ok too.
[ "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 server, so you don't have to run the tests on your physical screen. \nIf you need to test only an application developed using Qt, GTK, Java SWT/Swing there are few test frameworks for doing this.\n" ]
[ 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 applies another function which, directly or indirectly, applies the function we are defining. The problem is that the code I am thinking of, and dealing with, does not use the same function! It uses the same code in another function (as a method or closure). The problem here is that while my code is the same, the functions are not. Take a look a the following basic mutual recursion example: def is_even(x): if x == 0: return True else: return is_odd(x - 1) def is_odd(x): if x == 0: return False else: return is_even(x - 1) This is somewhat intuitive, and very clearly mutually recursive. However, if I wrap each function up as an inner function that is created once every call, it gets less clear: def make_is_even(): def is_even(x): if x == 0: return True else: return make_is_odd()(x - 1) return is_even def make_is_odd(): def is_odd(x): if x == 0: return False else: return make_is_even()(x - 1) return is_odd def is_even2(x): return make_is_even()(x) def is_odd2(x): return make_is_odd()(x) Disregarding optimizations like implicit memoization etc., this produces a chain of function calls that isn't strictly recursive, creating and calling various new functions without ever calling the same one twice. Nonetheless all these functions follow a common template, and are just the same function created over and over again (possibly with different free variables. And again, we can come up with a directly equivalent (after all, classes are really just closures, right ;) implementation using classes. This is especially significant, since this style of [insert name here] is used in, e.g., the Composite Pattern. The difference is that with the Composite design pattern, and most uses (even of the closures), the instances are not usually created on the fly. It is still essentially the same. class EvenChecker(object): def check(self, x): if x == 0: return True else: return OddChecker().check(x - 1) class OddChecker(object): def check(self, x): if x == 0: return False else: return EvenChecker().check(x - 1) def is_even3(x): return EvenChecker().check(x) def is_odd3(x): return OddChecker().check(x) This time the chain is of object creation and method calls, but the principle is the same. (I would actually note that it's slightly different, in that Python defines a simple wrapper on a per-object basis which itself calls the very same function every time-- but this is not necessarily something we need to know, and it doesn't need to be true for other implementations of classes and objects. But yes, strictly speaking it is mutually recursive, as well as... something more, and it's that other thing that I want to know.) A: 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. A: Mutual recursion is just a special case of indirect recursion. A: Apparently, it is called Mutual Recursion :) The article even gives the same example as you, with odd? and even? functions.
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 indirectly, applies the function we are defining. The problem is that the code I am thinking of, and dealing with, does not use the same function! It uses the same code in another function (as a method or closure). The problem here is that while my code is the same, the functions are not. Take a look a the following basic mutual recursion example: def is_even(x): if x == 0: return True else: return is_odd(x - 1) def is_odd(x): if x == 0: return False else: return is_even(x - 1) This is somewhat intuitive, and very clearly mutually recursive. However, if I wrap each function up as an inner function that is created once every call, it gets less clear: def make_is_even(): def is_even(x): if x == 0: return True else: return make_is_odd()(x - 1) return is_even def make_is_odd(): def is_odd(x): if x == 0: return False else: return make_is_even()(x - 1) return is_odd def is_even2(x): return make_is_even()(x) def is_odd2(x): return make_is_odd()(x) Disregarding optimizations like implicit memoization etc., this produces a chain of function calls that isn't strictly recursive, creating and calling various new functions without ever calling the same one twice. Nonetheless all these functions follow a common template, and are just the same function created over and over again (possibly with different free variables. And again, we can come up with a directly equivalent (after all, classes are really just closures, right ;) implementation using classes. This is especially significant, since this style of [insert name here] is used in, e.g., the Composite Pattern. The difference is that with the Composite design pattern, and most uses (even of the closures), the instances are not usually created on the fly. It is still essentially the same. class EvenChecker(object): def check(self, x): if x == 0: return True else: return OddChecker().check(x - 1) class OddChecker(object): def check(self, x): if x == 0: return False else: return EvenChecker().check(x - 1) def is_even3(x): return EvenChecker().check(x) def is_odd3(x): return OddChecker().check(x) This time the chain is of object creation and method calls, but the principle is the same. (I would actually note that it's slightly different, in that Python defines a simple wrapper on a per-object basis which itself calls the very same function every time-- but this is not necessarily something we need to know, and it doesn't need to be true for other implementations of classes and objects. But yes, strictly speaking it is mutually recursive, as well as... something more, and it's that other thing that I want to know.)
[ "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 as you, with odd? and even? functions.\n" ]
[ 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 supports multiple databases, perhaps you could setup the second database on site A then just save the model twice: my_object.save() my_object.save(using='database_b') if database A always updates database B then you should look into database replication A: Read up on Django's serialization. Basically, what you want to do is serialize to some format such as XML or JSON, send that string over, then deserialize it back to an object on the receive end. Like much of Django, when you're done writing code you'll feel it was too easy.
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 serialization. Basically, what you want to do is serialize to some format such as XML or JSON, send that string over, then deserialize it back to an object on the receive end.\nLike much of Django, when you're done writing code you'll feel it was too easy.\n" ]
[ 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 in appinstall.setup_config the module is loaded (as PRJ.websetup) and as it have the setup_app attribute, the function is called. Can you point me in the right direction? A: Ok, I was wrong. The websetup is used by the setup script and before the test are executed. A controller make an import for a test module, and then setup_app is called. Thanks!.
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 loaded (as PRJ.websetup) and as it have the setup_app attribute, the function is called. Can you point me in the right direction?
[ "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) && (b>0), but I got b, that the usual behaviour of and A: __and__ is the binary (bitwise) & operator, not the logical and operator. Because 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 have to be evaluated before the function can be invoked. A: because you cannot redefine a keyword (that's what and is) in Python. __add__ is used to do something else: These methods are called to implement the binary arithmetic operations (...&...
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 usual behaviour of and
[ "__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 have to be evaluated before the function can be invoked.\n", "because you cannot redefine a keyword (that's what and is) in Python. __add__ is used to do something else:\n\nThese methods are called to implement the binary arithmetic operations (...&...\n\n" ]
[ 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.blogspot.com/2009/07/vim-part-i-improved-python-syntax.html Is there some other setting I am forgetting? I'm also using ubuntu 10.04 if that matters. A weird other note - it works in gvim, but not vim? A: 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. http://www.vim.org/scripts/script.php?script_id=2390 A: The colorscheme used in that tutorial is only for gvim. Try changing your colorscheme. A: I think ubuntu installs vim in a minimal package (vim-tiny) with some features missing. You can try to upgrade your vim to the full version: sudo apt-get install vim-full
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 there some other setting I am forgetting? I'm also using ubuntu 10.04 if that matters. A weird other note - it works in gvim, but not vim?
[ "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 vim in a minimal package (vim-tiny) with some features missing. You can try to upgrade your vim to the full version:\nsudo apt-get install vim-full\n\n" ]
[ 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 and the error_log contains the line: [Mon Apr 19 15:03:23 2010] [error] [client xxx.xxx.121.79] Premature end of script headers: uploadcml.py, referer: http://xxx.ch.cam.ac.uk:9000/ However, the files which the script should be saving are indeed saved to disk. If I run it without any arguments, the script returns the correct HTML indicating no file was parsed. All the information I have found on the web about Premature end of script headers implies it is due to either a missing header, or lack of permissions on the python script but neither can apply to me. The first lines of the script are: #!/home/nwe23/bin/bin/python import cgitb; cgitb.enable() import cgi import pybel,openbabel import random print "Content-Type: text/html" print so when run, I can see no way for it to fail to output the header, and it DOES output the header when run without a file to parse, but when given a file produces the error(but still parsed the file and saves the output to disk!). Does anyone know how this is happening and what can be done to fix it? I have tried adding wrongly-indented gibberish (such as foobar) at various points in the file, and this results in adding an indent error to the error_log wherever it is, even if its the very last line in the script. The Premature script headers error remains though. Does this mean the script is executing all the way through? [EDIT] I'm managed to get it working now, it seems one of the calls to an external C++ library through SWIG was failing, but there was no useful error message produced. I've fixed the problem with that, and now the script is working correctly. It is surprising that the only error in the error_log was about the script headers, when some remote library call had failed. I suppose that's the danger of invoking non-python code? [/EDIT] A: 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.
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 xxx.xxx.121.79] Premature end of script headers: uploadcml.py, referer: http://xxx.ch.cam.ac.uk:9000/ However, the files which the script should be saving are indeed saved to disk. If I run it without any arguments, the script returns the correct HTML indicating no file was parsed. All the information I have found on the web about Premature end of script headers implies it is due to either a missing header, or lack of permissions on the python script but neither can apply to me. The first lines of the script are: #!/home/nwe23/bin/bin/python import cgitb; cgitb.enable() import cgi import pybel,openbabel import random print "Content-Type: text/html" print so when run, I can see no way for it to fail to output the header, and it DOES output the header when run without a file to parse, but when given a file produces the error(but still parsed the file and saves the output to disk!). Does anyone know how this is happening and what can be done to fix it? I have tried adding wrongly-indented gibberish (such as foobar) at various points in the file, and this results in adding an indent error to the error_log wherever it is, even if its the very last line in the script. The Premature script headers error remains though. Does this mean the script is executing all the way through? [EDIT] I'm managed to get it working now, it seems one of the calls to an external C++ library through SWIG was failing, but there was no useful error message produced. I've fixed the problem with that, and now the script is working correctly. It is surprising that the only error in the error_log was about the script headers, when some remote library call had failed. I suppose that's the danger of invoking non-python code? [/EDIT]
[ "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 os, time f = open('sys_time_append.py','r') lines = f.readlines() f.close() fout = open('sys_time_append.py','w') for thisline in lines: fout.write(thisline) fout.write('\n#'+str(time.time())+' s r\n') fout.close() Thanks for any help. A: I expect this is a dangerous thing to do, but it works: import os, time print "Hi, ", __file__, '!' with open(__file__, 'a') as fout: fout.write('\n#'+str(time.time())+' s r\n') Note that I get the name of the script as __file__, as well (but this isn't the full pathname, so there can be problems if the cwd is changed). Or am I missing something in the reference to "editing in IDLE" that matters here? You probably can't have the script active in an editing window while it's being appended to by the script. It's impossible for the programs to know which has "control".
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') lines = f.readlines() f.close() fout = open('sys_time_append.py','w') for thisline in lines: fout.write(thisline) fout.write('\n#'+str(time.time())+' s r\n') fout.close() Thanks for any help.
[ "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 problems if the cwd is changed).\nOr am I missing something in the reference to \"editing in IDLE\" that matters here? You probably can't have the script active in an editing window while it's being appended to by the script. It's impossible for the programs to know which has \"control\".\n" ]
[ 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 08:49 dovecot-uidvalidity -rw------- 1 foo foo 0 2010-03-20 08:49 dovecot-uidvalidity.4ba48c0e drwx------ 2 foo foo 114688 2010-04-19 16:07 new drwx------ 2 foo foo 4096 2010-04-19 16:07 tmp And in python I'm trying to get all new messages (Python 2.6.5rc2). First, getting "Maildir" works: >>> import mailbox >>> md = mailbox.Maildir('/home/foo/Maildir') >>> md.iterkeys().next() '1269924477.Vfc01I4249fM708004.foo' But how do I access "Maildir/new"? This does not work: >>> md = mailbox.Maildir('/home/foo/Maildir/new') >>> md.iterkeys().next() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.6/mailbox.py", line 346, in iterkeys self._refresh() File "/usr/lib/python2.6/mailbox.py", line 467, in _refresh for entry in os.listdir(subdir_path): OSError: [Errno 2] No such file or directory: '/home/foo/Maildir/new/new' >>> Any ideas? A: 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. The Maildir module should read messages from new and cur, and may optionally move messages from new to cur when you close() or flush(). To know how this implementation does it, you will have to look at the code. References: http://en.wikipedia.org/wiki/Maildir http://docs.python.org/library/mailbox.html#maildir
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 2010-03-20 08:49 dovecot-uidvalidity.4ba48c0e drwx------ 2 foo foo 114688 2010-04-19 16:07 new drwx------ 2 foo foo 4096 2010-04-19 16:07 tmp And in python I'm trying to get all new messages (Python 2.6.5rc2). First, getting "Maildir" works: >>> import mailbox >>> md = mailbox.Maildir('/home/foo/Maildir') >>> md.iterkeys().next() '1269924477.Vfc01I4249fM708004.foo' But how do I access "Maildir/new"? This does not work: >>> md = mailbox.Maildir('/home/foo/Maildir/new') >>> md.iterkeys().next() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.6/mailbox.py", line 346, in iterkeys self._refresh() File "/usr/lib/python2.6/mailbox.py", line 467, in _refresh for entry in os.listdir(subdir_path): OSError: [Errno 2] No such file or directory: '/home/foo/Maildir/new/new' >>> Any ideas?
[ "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 may optionally move messages from new to cur when you close() or flush(). To know how this implementation does it, you will have to look at the code.\nReferences:\n\nhttp://en.wikipedia.org/wiki/Maildir\nhttp://docs.python.org/library/mailbox.html#maildir\n\n" ]
[ 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 something like this: based on this question/answer # this is the threshold that determines whether or not sound is detected THRESHOLD = 0 #open your audio stream # wait until the sound data breaks some level threshold while True: data = stream.read(chunk) # check level against threshold, you'll have to write getLevel() if getLevel(data) > THRESHOLD: break # record for however long you want # close the stream You'll probably want to play with your chunk size and threshold values until you get the desired behavior. Edit: You can use the built-in audioop package to find the root-mean-square (rms) of a sample, which is generally how you would get the level. import audioop import pyaudio chunk = 1024 p = pyaudio.PyAudio() stream = p.open(format=pyaudio.paInt16, channels=1, rate=44100, input=True, frames_per_buffer=chunk) data = stream.read(chunk) rms = audioop.rms(data, 2) #width=2 for format=paInt16 A: Detecting when there isn't silence is usually done by using the root mean square(RMS) of some chunk of the sound and comparing it with some threshold value that you set (the value will depend on how sensitive your mic is and other things so you'll have to adjust it). Also, depending on how quickly you want the mic to detect sound to be recorded, you might want to lower the chunk size, or compute the RMS for overlapping chunks of data. A: how to do it is indicated in the link you give: print "* recording" for i in range(0, 44100 / chunk * RECORD_SECONDS): data = stream.read(chunk) # check for silence here by comparing the level with 0 (or some threshold) for # the contents of data. # then write data or not to a file You have to set the threshold variable and compare with the average value (the amplitude) or other related parameter in data each time it is read in the loop. You could have two nested loops, the first one to trigger the recording and the other to continously save sound data chuncks after that.
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 threshold, you'll have to write getLevel()\n if getLevel(data) > THRESHOLD:\n break\n\n# record for however long you want\n# close the stream\n\nYou'll probably want to play with your chunk size and threshold values until you get the desired behavior.\nEdit:\nYou can use the built-in audioop package to find the root-mean-square (rms) of a sample, which is generally how you would get the level.\nimport audioop\nimport pyaudio\n\nchunk = 1024\n\np = pyaudio.PyAudio()\n\nstream = p.open(format=pyaudio.paInt16,\n channels=1,\n rate=44100,\n input=True,\n frames_per_buffer=chunk)\n\ndata = stream.read(chunk)\n\nrms = audioop.rms(data, 2) #width=2 for format=paInt16\n\n", "Detecting when there isn't silence is usually done by using the root mean square(RMS) of some chunk of the sound and comparing it with some threshold value that you set (the value will depend on how sensitive your mic is and other things so you'll have to adjust it). Also, depending on how quickly you want the mic to detect sound to be recorded, you might want to lower the chunk size, or compute the RMS for overlapping chunks of data.\n", "how to do it is indicated in the link you give:\nprint \"* recording\"\nfor i in range(0, 44100 / chunk * RECORD_SECONDS):\n data = stream.read(chunk)\n # check for silence here by comparing the level with 0 (or some threshold) for \n # the contents of data.\n # then write data or not to a file\n\nYou have to set the threshold variable and compare with the average value (the amplitude) or other related parameter in data each time it is read in the loop.\nYou could have two nested loops, the first one to trigger the recording and the other to continously save sound data chuncks after that.\n" ]
[ 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 around 4,000,000 lines x 7 loggers x 5 years = a lot of data. some of the data is organized as bins item_type, item_class, item_dimension_class, and other data is more unique, such as item_weight, item_color, date_collected, and so on ... Currently, I do statistical analysis on the data using a python/numpy/matplotlib program I wrote. It works fine, but the problem is, I'm the only one who can use it, since it and the data live on my computer. I'd like to publish the data on the web using a postgres db; however, I need to find or implement a statistical tool that'll take a large postgres table, and return statistical results within an adequate time frame. I'm not familiar with python for the web; however, I'm proficient with PHP on the web side, and python on the offline side. users should be allowed to create their own histograms, data analysis. For example, a user can search for all items that are blue shipped between week x and week y, while another user can search for sort the weight distribution of all items by hour for all year long. I was thinking of creating and indexing my own statistical tools, or automate the process somehow to emulate most queries. This seemed inefficient. I'm looking forward to hearing your ideas Thanks A: 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), cherrypy as a webserver, mako as a template language. If you need more server/client database, then you can migrate to postgresql, but you can still fully use your current programs if you go with a python web framework, like cherrypy.
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 data is organized as bins item_type, item_class, item_dimension_class, and other data is more unique, such as item_weight, item_color, date_collected, and so on ... Currently, I do statistical analysis on the data using a python/numpy/matplotlib program I wrote. It works fine, but the problem is, I'm the only one who can use it, since it and the data live on my computer. I'd like to publish the data on the web using a postgres db; however, I need to find or implement a statistical tool that'll take a large postgres table, and return statistical results within an adequate time frame. I'm not familiar with python for the web; however, I'm proficient with PHP on the web side, and python on the offline side. users should be allowed to create their own histograms, data analysis. For example, a user can search for all items that are blue shipped between week x and week y, while another user can search for sort the weight distribution of all items by hour for all year long. I was thinking of creating and indexing my own statistical tools, or automate the process somehow to emulate most queries. This seemed inefficient. I'm looking forward to hearing your ideas Thanks
[ "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), cherrypy as a webserver, mako as a template language. \nIf you need more server/client database, then you can migrate to postgresql, but you can still fully use your current programs if you go with a python web framework, like cherrypy.\n" ]
[ 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? (Allow me to prove my confusion!) My initial thought is to write a standard handler class that infers a template to run based on the current URL or class/method combination. Then I would assign one instance of that handler multiple times to the path to create pages. I don't see this working however as the recursive references wouldn't work quite right. So, given the fact that I'm already drawing blanks on how my own source code should look, I'd love some pointers and examples! Feel free to ask some detailed questions for me to clarify. While there is plenty of cherrypy tutorial material out there, it tends to only scratch the surface. A: 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 construction and configuration via the __init__ method of your class, and via class-level variables and methods. However, the preferred approach is different. For most web applications, you don't really want to vary the actual construction logic of your handlers, nor do you care much about class-level variables or methods; instead, you want reusable variables and methods per URI or per subtree of URI's or per site, not per class. You tend to vary one set of handlers from another set more by instance configuration (handler metadata) and instance methods (handler logic). Traditional class-based inheritance can do this, but it's a bit of a blunt instrument for that kind of customization. CherryPy, therefore, is designed to provide this sort of per-resource-set customization that class-based inheritance doesn't do well. It provides this through 1) the design of its configuration system, which allows you to bind metadata to a single URI, a subtree of URI's, a subtree of handlers, or a whole site with the same syntax (see http://docs.cherrypy.org/dev/intro/concepts/config.html for an overview), and 2) the hooks and tools system, which allows you to bind logic to a single URI, a subtree of URI's, a subtree of handlers, or a whole site. See http://docs.cherrypy.org/dev/intro/concepts/tools.html So, practically: do use normal attributes on cherrypy.root to build your tree of handlers: def make_app(): root = Root() root.foo = Foo() root.bars = BarCollection() return root However, don't make Root, Foo and Bar inherit from a common base class. Instead, write independent Tools to do things like "infer templates". That is, instead of: from cherrypy import expose class Foo(MyAppBase): @expose() def index(self, a, b, c): ... root.foo = Foo(template='foo.html') write: from cherrypy import expose, tools class Foo(object): @tools.render(template='foo.html') @expose() def index(self, a, b, c): ... root.foo = Foo() ...where 'tools.render' is a CherryPy Tool you have written to look up and apply the given template. This approach will allow you to override the arguments to the Tool in your config file and avoid having to repackage or patch your code: [/foo/] tools.render.template = 'foo2.html' A: This question is wildly subjective - but I'll give it a shot. First of all, always keep database and data code separate to the web code. What I do is have lots of small files with one class each in a DB/ folder which are all joined together into a Base.py file, e.g: Web/   Base.py - The main "base" class, which includes the classes in other   web files, starts the web server in __init__   Users.py - The class which includes methods generally from "DB/Users.py"   which checks permissions etc before returning (you may   wish to add DB-level security later though)   ... DB/   Base.py - The main base DB class, includes the other DB classes. Creates   new SQLAlchemy/whatever instances and create database schemas if   they don't etc. May pay to have database-wide methods   here to keep creating connections etc in one place if you   decide to change databases later   Users.py - The user/password etc DB storage class file   ... Templates/   (HTML templates go here) Static/   (Static images/CSS/javscript etc go here) Don't forget the __init__.py in each module directory of course so python can find the modules in subdirectories It doesn't always matter what methods you use for structuring code in my opinion, but be consistent. I write a document up with all my conventions with my justifications for using them and try to follow them up to the point it makes sense to, but as always a foolish consistency is the hobgoblin of small minds, as quoting the python style docs :-) Try to use classes rather than straight functions. It mightn't matter for small projects, but for anything non-trivial things can become difficult. It's my preference to have many files with a specific purpose and only a single class in a single file except where it makes sense to have multiple This one is probably controversial - I usually name my classes Class and just reference it by the module name. I'll give an example of Base.py:import Users class Base(Users.Class):   def __init__(self):   Users.Class.__init__(self) This helps to reduce problems when other modules reference each other when importing, as from Users import Users will conflict if Users.py has from Base import x so I always reference by module name. This is just a personal preference though, so do what you want :-P Hopefully you should get an idea from this post though.
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 a standard handler class that infers a template to run based on the current URL or class/method combination. Then I would assign one instance of that handler multiple times to the path to create pages. I don't see this working however as the recursive references wouldn't work quite right. So, given the fact that I'm already drawing blanks on how my own source code should look, I'd love some pointers and examples! Feel free to ask some detailed questions for me to clarify. While there is plenty of cherrypy tutorial material out there, it tends to only scratch the surface.
[ "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 construction and configuration via the __init__ method of your class, and via class-level variables and methods.\nHowever, the preferred approach is different. For most web applications, you don't really want to vary the actual construction logic of your handlers, nor do you care much about class-level variables or methods; instead, you want reusable variables and methods per URI or per subtree of URI's or per site, not per class. You tend to vary one set of handlers from another set more by instance configuration (handler metadata) and instance methods (handler logic). Traditional class-based inheritance can do this, but it's a bit of a blunt instrument for that kind of customization.\nCherryPy, therefore, is designed to provide this sort of per-resource-set customization that class-based inheritance doesn't do well. It provides this through 1) the design of its configuration system, which allows you to bind metadata to a single URI, a subtree of URI's, a subtree of handlers, or a whole site with the same syntax (see http://docs.cherrypy.org/dev/intro/concepts/config.html for an overview), and 2) the hooks and tools system, which allows you to bind logic to a single URI, a subtree of URI's, a subtree of handlers, or a whole site. See http://docs.cherrypy.org/dev/intro/concepts/tools.html\nSo, practically: do use normal attributes on cherrypy.root to build your tree of handlers:\ndef make_app():\n root = Root()\n root.foo = Foo()\n root.bars = BarCollection()\n return root\n\nHowever, don't make Root, Foo and Bar inherit from a common base class. Instead, write independent Tools to do things like \"infer templates\". That is, instead of:\nfrom cherrypy import expose\n\nclass Foo(MyAppBase):\n @expose()\n def index(self, a, b, c):\n ...\n\nroot.foo = Foo(template='foo.html')\n\nwrite:\nfrom cherrypy import expose, tools\n\nclass Foo(object):\n @tools.render(template='foo.html')\n @expose()\n def index(self, a, b, c):\n ...\n\nroot.foo = Foo()\n\n...where 'tools.render' is a CherryPy Tool you have written to look up and apply the given template. This approach will allow you to override the arguments to the Tool in your config file and avoid having to repackage or patch your code:\n[/foo/]\ntools.render.template = 'foo2.html'\n\n", "This question is wildly subjective - but I'll give it a shot.\n\nFirst of all, always keep database and data code separate to the web code. What I do is have lots of small files with one class each in a DB/ folder which are all joined together into a Base.py file, e.g:\n\nWeb/\n  Base.py - The main \"base\" class, which includes the classes in other \n  web files, starts the web server in __init__\n  Users.py - The class which includes methods generally from \"DB/Users.py\" \n  which checks permissions etc before returning (you may \n  wish to add DB-level security later though)\n  ...\nDB/\n  Base.py - The main base DB class, includes the other DB classes. Creates \n  new SQLAlchemy/whatever instances and create database schemas if \n  they don't etc. May pay to have database-wide methods\n  here to keep creating connections etc in one place if you \n  decide to change databases later \n  Users.py - The user/password etc DB storage class file\n  ...\nTemplates/\n  (HTML templates go here)\nStatic/\n  (Static images/CSS/javscript etc go here)\n\nDon't forget the __init__.py in each module directory of course so python can find the modules in subdirectories\nIt doesn't always matter what methods you use for structuring code in my opinion, but be consistent. I write a document up with all my conventions with my justifications for using them and try to follow them up to the point it makes sense to, but as always a foolish consistency is the hobgoblin of small minds, as quoting the python style docs :-)\nTry to use classes rather than straight functions. It mightn't matter for small projects, but for anything non-trivial things can become difficult. It's my preference to have many files with a specific purpose and only a single class in a single file except where it makes sense to have multiple\nThis one is probably controversial - I usually name my classes Class and just reference it by the module name. I'll give an example of Base.py:import Users\nclass Base(Users.Class):\n  def __init__(self):\n  Users.Class.__init__(self)\n\nThis helps to reduce problems when other modules reference each other when importing, as from Users import Users will conflict if Users.py has from Base import x so I always reference by module name. This is just a personal preference though, so do what you want :-P\n\nHopefully you should get an idea from this post though.\n" ]
[ 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('textarea'): contents = BeautifulSoup.BeautifulSoup(textarea.contents) textarea.replaceWith(contents.html(text=True)) But I'm getting errors. I can't find this in the documentation, and the alternative parsers aren't helping. Anyone know how I can parse the textareas as HTML? Edit: Sample HTML is: <textarea class="ks-lazyload-custom"> <div class="product-view product-view-rug"> Foobar Womble <div class="product-view-head"> <img src="tps/i1/fo-25.gif" /> </div> </div> </textarea> Error is: File "D:\src\cross\tserver\src\tools\sitecrawl\BeautifulSoup.py", line 1913, in _detectEncoding '^<\?.*encoding=[\'"](.*?)[\'"].*\?>').match(xml_data) TypeError: expected string or buffer I'm looking for a way of taking an element, extracting the contents, parsing them with BeautifulSoup, collapsing it to text, and then replacing the contents of the original element (or replacing the whole element) with that text. As for real world vs specs, it actually isn't particularly relevant here. The data needs to be parsed, I'm looking for the way to do so. A: This seems to work fairly well (if I correctly understood what you wanted): for textarea in soup.findAll('textarea'): contents = BeautifulSoup.BeautifulSoup(textarea.contents[0]).renderContents() textarea.replaceWith(contents) A: I'm now using the following code which mostly works. Your milage may vary. def _extractText(self, data, encoding): if self.isDebug: self._output("_extractText") soup = BeautifulSoup.BeautifulSoup(data, fromEncoding=encoding) comments = soup.findAll(text=lambda text:isinstance(text, BeautifulSoup.Comment)) [comment.extract() for comment in comments] [script.extract() for script in soup.findAll('script')] [css.extract() for css in soup.findAll('style')] for textarea in soup.findAll('textarea'): textarea.string = self._extractText(textarea.renderContents(), 'UTF-8') text = unicode('') for line in soup.findAll(text=True): line = line.replace('&nbsp;', ' ').strip() if line == '': continue if line.startswith('doctype'): continue if line.startswith('DOCTYPE'): continue text = text + line + '\n' return text
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) textarea.replaceWith(contents.html(text=True)) But I'm getting errors. I can't find this in the documentation, and the alternative parsers aren't helping. Anyone know how I can parse the textareas as HTML? Edit: Sample HTML is: <textarea class="ks-lazyload-custom"> <div class="product-view product-view-rug"> Foobar Womble <div class="product-view-head"> <img src="tps/i1/fo-25.gif" /> </div> </div> </textarea> Error is: File "D:\src\cross\tserver\src\tools\sitecrawl\BeautifulSoup.py", line 1913, in _detectEncoding '^<\?.*encoding=[\'"](.*?)[\'"].*\?>').match(xml_data) TypeError: expected string or buffer I'm looking for a way of taking an element, extracting the contents, parsing them with BeautifulSoup, collapsing it to text, and then replacing the contents of the original element (or replacing the whole element) with that text. As for real world vs specs, it actually isn't particularly relevant here. The data needs to be parsed, I'm looking for the way to do so.
[ "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 vary.\ndef _extractText(self, data, encoding):\n if self.isDebug: self._output(\"_extractText\")\n soup = BeautifulSoup.BeautifulSoup(data, fromEncoding=encoding)\n comments = soup.findAll(text=lambda text:isinstance(text, BeautifulSoup.Comment))\n [comment.extract() for comment in comments]\n [script.extract() for script in soup.findAll('script')]\n [css.extract() for css in soup.findAll('style')]\n for textarea in soup.findAll('textarea'):\n textarea.string = self._extractText(textarea.renderContents(), 'UTF-8')\n text = unicode('')\n for line in soup.findAll(text=True):\n line = line.replace('&nbsp;', ' ').strip() \n if line == '': continue\n if line.startswith('doctype'): continue\n if line.startswith('DOCTYPE'): continue\n text = text + line + '\\n'\n return text\n\n" ]
[ 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 extends wx.Frame. In MainApp.py this works: from res.elements.MainFrame import * And this does not: from res.elements.MainFrame import RPMWindow I realize that the wild card import won't hurt anything, but I'm more interested in understanding why the named import is failing when the wild card succeeds. When using the class name I get this traceback: Traceback (most recent call last): File "C:\myApps\eclipse\plugins\org.python.pydev.debug_1.5.6.2010033101\pysrc\pydevd.py", line 953, in <module> debugger.run(setup['file'], None, None) File "C:\myApps\eclipse\plugins\org.python.pydev.debug_1.5.6.2010033101\pysrc\pydevd.py", line 780, in run execfile(file, globals, locals) #execute the script File "C:\Documents and Settings\Daniel\workspace\RPM UI - V2\src\MainApp.py", line 2, in <module> from res.elements.MainFrame import RPMWindow File "C:\Documents and Settings\Daniel\workspace\RPM UI - V2\src\res\elements\MainFrame.py", line 2, in <module> from res.elements.MenuBar import MenuBarBuilder File "C:\Documents and Settings\Daniel\workspace\RPM UI - V2\src\res\elements\MenuBar.py", line 2, in <module> from MainApp import _, DataCache File "C:\Documents and Settings\Daniel\workspace\RPM UI - V2\src\MainApp.py", line 2, in <module> from res.elements.MainFrame import RPMWindow ImportError: cannot import name RPMWindow When using the wild card import I don't receive a traceback and my application opens. A: You have circular imports: MainFrame.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. A: i don't have time to look into why the wildcard is working for you, but what i can say about your failure with the direct name import is that you have an import cycle in your code: you are trying to import res.elements.MainFrame, but part of that code is trying to import res.elements.MenuBar which tries to import res.elements.MainFrame again. IOW, your first attempt to import res.elements.MainFrame has not completed yet before you try it again. A: You have circular imports in your code: the same module is both required by and requires the use of a certain other module, which when you think of it like that, it clearly precarious. Most of the problems can be cleared up by using import a and later referring to a.b instead of from a import b or from a import *. In particular, never use from a import *. Wildcard imports clutter your namespace and makes your code less maintainable, readable, sane, and predictable. The difference between import a and from a import * is the difference between dragging a box into a room and pouring its contents all over the floor. It would be better if you could move shared code off to its own module or somehow refactor out the need for a circular import. Circular imports always indicate a design problem.
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: from res.elements.MainFrame import * And this does not: from res.elements.MainFrame import RPMWindow I realize that the wild card import won't hurt anything, but I'm more interested in understanding why the named import is failing when the wild card succeeds. When using the class name I get this traceback: Traceback (most recent call last): File "C:\myApps\eclipse\plugins\org.python.pydev.debug_1.5.6.2010033101\pysrc\pydevd.py", line 953, in <module> debugger.run(setup['file'], None, None) File "C:\myApps\eclipse\plugins\org.python.pydev.debug_1.5.6.2010033101\pysrc\pydevd.py", line 780, in run execfile(file, globals, locals) #execute the script File "C:\Documents and Settings\Daniel\workspace\RPM UI - V2\src\MainApp.py", line 2, in <module> from res.elements.MainFrame import RPMWindow File "C:\Documents and Settings\Daniel\workspace\RPM UI - V2\src\res\elements\MainFrame.py", line 2, in <module> from res.elements.MenuBar import MenuBarBuilder File "C:\Documents and Settings\Daniel\workspace\RPM UI - V2\src\res\elements\MenuBar.py", line 2, in <module> from MainApp import _, DataCache File "C:\Documents and Settings\Daniel\workspace\RPM UI - V2\src\MainApp.py", line 2, in <module> from res.elements.MainFrame import RPMWindow ImportError: cannot import name RPMWindow When using the wild card import I don't receive a traceback and my application opens.
[ "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 for you, but what i can say about your failure with the direct name import is that you have an import cycle in your code:\nyou are trying to import res.elements.MainFrame, but part of that code is trying to import res.elements.MenuBar which tries to import res.elements.MainFrame again. IOW, your first attempt to import res.elements.MainFrame has not completed yet before you try it again.\n", "You have circular imports in your code: the same module is both required by and requires the use of a certain other module, which when you think of it like that, it clearly precarious. Most of the problems can be cleared up by using import a and later referring to a.b instead of from a import b or from a import *.\nIn particular, never use from a import *. Wildcard imports clutter your namespace and makes your code less maintainable, readable, sane, and predictable. The difference between import a and from a import * is the difference between dragging a box into a room and pouring its contents all over the floor.\nIt would be better if you could move shared code off to its own module or somehow refactor out the need for a circular import. Circular imports always indicate a design problem.\n" ]
[ 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 is to catch Exception rather than using bare except clauses: try: foo() except Exception: bar() This works because, as of Python 2.5, KeyboardInterrupt and SystemExit inherit from BaseException, not Exception. However, some installations are still running Python 2.4. How can this problem be handled in versions prior to Python 2.5? (I'm going to answer this question myself, but putting it here so people searching for it can find a solution.) A: According to the Python documentation, the right way to handle this in Python versions earlier than 2.5 is: try: foo() except (KeyboardInterrupt, SystemExit): raise except: bar() That's very wordy, but at least it's a solution.
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 Exception: bar() This works because, as of Python 2.5, KeyboardInterrupt and SystemExit inherit from BaseException, not Exception. However, some installations are still running Python 2.4. How can this problem be handled in versions prior to Python 2.5? (I'm going to answer this question myself, but putting it here so people searching for it can find a solution.)
[ "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 is a bad idea, but would it be okay as long as one key is accessed at a time? A: 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. Others have said that a few million items shouldn't pose a problem; I'm not so sure. The dict overhead itself (before counting the memory taken by the keys and values) is significant. For Python 2.6 or later, sys.getsizeof gives some useful information about how much RAM various Python structures take up. Some quick results, from Python 2.6 on a 64-bit OS X machine: >>> from sys import getsizeof >>> getsizeof(dict((n, 0) for n in range(5462)))/5462. 144.03368729403149 >>> getsizeof(dict((n, 0) for n in range(5461)))/5461. 36.053470060428495 So the dict overhead varies between 36 bytes per item and 144 bytes per item on this machine (the exact value depending on how full the dictionary's internal hash table is; here 5461 = 2**14//3 is one of the thresholds where the internal hash table is enlarged). And that's before adding the overhead for the dict items themselves; if they're all short strings (6 characters or less, say) then that still adds another >= 80 bytes per item (possibly less if many different keys share the same value). So it wouldn't take that many million dict items to exhaust RAM on a typical machine. A: The main concern with the millions of items is not the dictionary itself so much as how much space each of these items takes up. Still, unless you're doing something weird, they should probably fit. If you've got a dict with millions of keys, though, you're probably doing something wrong. You should do one or both of: Figure out what data structure you should actually be using, because a single dict is probably not the right answer. Exactly what this would be depends on what you're doing. Use a database. Your Python should come with a sqlite3 module, so that's a start. A: Yes, a Python dict is stored in RAM. A few million keys isn't an issue for modern computers, however. If you need more and more data and RAM is running out, consider using a real database. Options include a relational DB like SQLite (built-in in Python, by the way) or a key-value store like Redis. It makes little sense displaying millions of items in the interpreter, but accessing a single element should be still very efficient. A: For all I know Python uses the best hashing algorithms so you are probably going to get the best possible memory efficiency and performance. Now, whether the whole thing is kept in RAM or committed to a swap file is up to your OS and depends on the amount of RAM you have. What I'd say is best if to just try it: from random import randint a = {} for i in xrange(10*10**6): a[i] = i How is this looking when you run it? Takes about 350Mb on my system which should be manageable to say the least.
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 long as one key is accessed at a time?
[ "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. The dict overhead itself (before counting the memory taken by the keys and values) is significant. For Python 2.6 or later, sys.getsizeof gives some useful information about how much RAM various Python structures take up. Some quick results, from Python 2.6 on a 64-bit OS X machine:\n>>> from sys import getsizeof\n>>> getsizeof(dict((n, 0) for n in range(5462)))/5462.\n144.03368729403149\n>>> getsizeof(dict((n, 0) for n in range(5461)))/5461.\n36.053470060428495\n\nSo the dict overhead varies between 36 bytes per item and 144 bytes per item on this machine (the exact value depending on how full the dictionary's internal hash table is; here 5461 = 2**14//3 is one of the thresholds where the internal hash table is enlarged). And that's before adding the overhead for the dict items themselves; if they're all short strings (6 characters or less, say) then that still adds another >= 80 bytes per item (possibly less if many different keys share the same value).\nSo it wouldn't take that many million dict items to exhaust RAM on a typical machine.\n", "The main concern with the millions of items is not the dictionary itself so much as how much space each of these items takes up. Still, unless you're doing something weird, they should probably fit.\nIf you've got a dict with millions of keys, though, you're probably doing something wrong. You should do one or both of:\n\nFigure out what data structure you should actually be using, because a single dict is probably not the right answer. Exactly what this would be depends on what you're doing.\nUse a database. Your Python should come with a sqlite3 module, so that's a start.\n\n", "Yes, a Python dict is stored in RAM. A few million keys isn't an issue for modern computers, however. If you need more and more data and RAM is running out, consider using a real database. Options include a relational DB like SQLite (built-in in Python, by the way) or a key-value store like Redis.\nIt makes little sense displaying millions of items in the interpreter, but accessing a single element should be still very efficient.\n", "For all I know Python uses the best hashing algorithms so you are probably going to get the best possible memory efficiency and performance. Now, whether the whole thing is kept in RAM or committed to a swap file is up to your OS and depends on the amount of RAM you have.\nWhat I'd say is best if to just try it:\nfrom random import randint\na = {}\nfor i in xrange(10*10**6):\n a[i] = i\n\nHow is this looking when you run it? Takes about 350Mb on my system which should be manageable to say the least.\n" ]
[ 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 say the error you get is pretty self explanatory: vbalance is just not a list. So you cannot append to it. What is the intention of your code, what do you want to achieve? It might be, that you want to add to vbalance: vbalance += int(vdats) or that you have to create a list beforehand: l = list() vdate = str(dates.date) vdats = vdate.split("") vdats = vdats[0] l.append(vdats) or that you have to declare vbalance differently in your previous code. Just from what you posted I guess you get a ValueError: >>> string = "ab cd asd" >>> print string.split('') Traceback (most recent call last): Line 2, in <module> print string.split('') ValueError: empty separator Assuming vdate contains a valid string and vbalance contains a list, if you just want to split the string on the whitespaces, use: vdats = vdate.split() Otherwise you have to pass which separator you want to use, but obviously, this string cannot be empty. Documentation: str.split() A: vdats=vdate.split("") You can't split with an empty separator. This will raise a ValueError exception. A: Clearly vbalance is not a list. Appending to a Decimal is meaningless, so that operation is not supported. Perhaps you meant to add vdats to it instead: vbalance += vdats
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 = list()\nvdate = str(dates.date)\nvdats = vdate.split(\"\")\nvdats = vdats[0]\nl.append(vdats)\n\nor that you have to declare vbalance differently in your previous code.\n\nJust from what you posted I guess you get a ValueError:\n>>> string = \"ab cd asd\"\n>>> print string.split('')\n\nTraceback (most recent call last):\n Line 2, in <module>\n print string.split('')\nValueError: empty separator\n\nAssuming vdate contains a valid string and vbalance contains a list, if you just want to split the string on the whitespaces, use:\nvdats = vdate.split()\n\nOtherwise you have to pass which separator you want to use, but obviously, this string cannot be empty.\nDocumentation: str.split()\n", "vdats=vdate.split(\"\")\n\nYou can't split with an empty separator. This will raise a ValueError exception.\n", "Clearly vbalance is not a list. Appending to a Decimal is meaningless, so that operation is not supported. Perhaps you meant to add vdats to it instead:\nvbalance += vdats\n\n" ]
[ 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, and adds the result to a list. Each point here is an element in a vector of lists, i.e. a data structure that looks like array([[1,2,3], [4,5,6], ...]). Here is the problematic function: def myClass: def my_inefficient_method(self): final_vector = [] # Assume 'my_vector' and 'my_other_vector' are defined numpy arrays for point in all_points: if not self.condition_met: a = self.my_func1(point, my_vector) b = self.my_func2(point, my_other_vector) else: a = self.my_func3(point, my_vector) b = self.my_func4(point, my_other_vector) c = a + b final_vector.append(c) # Choose random element from resulting vector 'final_vector' self.condition_met is set before my_inefficient_method is called, so it seems unnecessary to check it each time, but I am not sure how to better write this. Since there are no destructive operations here it is seems like I could rewrite this entire thing as a vectorized operation -- is that possible? any ideas how to do this? A: 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). import numpy as NP # create two functions fnx1 = lambda x : x**2 fnx2 = lambda x : NP.sum(fnx1(x)) # create some data M = NP.random.randint(10, 99, 40).reshape(8, 5) # creates index array based on condition satisfaction # (is the sum (of that row/data point) even or odd) ndx = NP.where( NP.sum(M, 0) % 2 == 0 ) # only those data points that satisfy the condition (are even) # are passed to one function then another and the result off applying both # functions to each data point is stored in an array res = NP.apply_along_axis( fnx2, 1, M[ndx,] ) print(res) # returns: [[11609 15309 15742 12406 4781]] From your description i abstracted this flow: check for condition (boolean) 'if True' calls pair functions on those data points (rows) that satisfy the condition appends result from each set of calls to a list ('res' below) A: Can you rewrite my_funcx to be vectorized? If so, you can do def myClass: def my_efficient_method(self): # Assume 'all_points', 'my_vector' and 'my_other_vector' are defined numpy arrays if not self.condition_met: a = self.my_func1(all_points, my_vector) b = self.my_func2(all_points, my_other_vector) else: a = self.my_func3(all_points, my_vector) b = self.my_func4(all_points, my_other_vector) final_vector = a + b # Choose random element from resulting vector 'final_vector' A: It's probably best to do what mtrw, but if you're not sure about vectorizing, you can try numpy.vectorize on the my_funcs http://docs.scipy.org/doc/numpy/reference/generated/numpy.vectorize.html
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 here is an element in a vector of lists, i.e. a data structure that looks like array([[1,2,3], [4,5,6], ...]). Here is the problematic function: def myClass: def my_inefficient_method(self): final_vector = [] # Assume 'my_vector' and 'my_other_vector' are defined numpy arrays for point in all_points: if not self.condition_met: a = self.my_func1(point, my_vector) b = self.my_func2(point, my_other_vector) else: a = self.my_func3(point, my_vector) b = self.my_func4(point, my_other_vector) c = a + b final_vector.append(c) # Choose random element from resulting vector 'final_vector' self.condition_met is set before my_inefficient_method is called, so it seems unnecessary to check it each time, but I am not sure how to better write this. Since there are no destructive operations here it is seems like I could rewrite this entire thing as a vectorized operation -- is that possible? any ideas how to do this?
[ "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 index array based on condition satisfaction\n# (is the sum (of that row/data point) even or odd)\nndx = NP.where( NP.sum(M, 0) % 2 == 0 )\n\n# only those data points that satisfy the condition (are even) \n# are passed to one function then another and the result off applying both \n# functions to each data point is stored in an array\nres = NP.apply_along_axis( fnx2, 1, M[ndx,] )\n\nprint(res)\n# returns: [[11609 15309 15742 12406 4781]]\n\nFrom your description i abstracted this flow:\n\ncheck for condition (boolean) 'if\nTrue'\ncalls pair functions on those data\npoints (rows) that satisfy the\ncondition\nappends result from each set of calls\nto a list ('res' below)\n\n", "Can you rewrite my_funcx to be vectorized? If so, you can do\ndef myClass:\n def my_efficient_method(self):\n # Assume 'all_points', 'my_vector' and 'my_other_vector' are defined numpy arrays\n if not self.condition_met:\n a = self.my_func1(all_points, my_vector)\n b = self.my_func2(all_points, my_other_vector)\n else:\n a = self.my_func3(all_points, my_vector)\n b = self.my_func4(all_points, my_other_vector)\n final_vector = a + b\n # Choose random element from resulting vector 'final_vector'\n\n", "It's probably best to do what mtrw, but if you're not sure about vectorizing, you can try numpy.vectorize on the my_funcs\nhttp://docs.scipy.org/doc/numpy/reference/generated/numpy.vectorize.html\n" ]
[ 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 multiple levels of forms, so each client is specifically geared towards a given site. each client app looks something like main: parse initial url call function level1 (data1) function level1 (data) parse the url, for data1 use the required xpath to get the dom elements call the next function call level2 (data) function level2 (data2) parse the url, for data2 use the required xpath to get the dom elements call the next function call level3 function level3 (dat3) parse the url, for data3 use the required xpath to get the dom elements call the next function call level4 function level4 (data) parse the url, for data4 use the required xpath to get the dom elements at the final function.. --all the data output, and eventually returned to the server --at this point the data has elements from each function... my question: given that the number of calls that is made to the child function by the current function varies, i'm trying to figure out the best approach. each function essentialy fetches a page of content, and then parses the page using a number of different XPath expressions, combined with different regex expressions depending on the site/page. if i run a client on a single box, as a sequential process, it'll take awhile, but the load on the box is rather small. i've thought of attempting to implement the child functions as threads from the current function, but that could be a nightmare, as well as quickly bring the "box" to its knees! i've thought of breaking the app up in a manner that would allow the master to essentially pass packets to the client boxes, in a way to allow each client/function to be run directly from the master. this process requires a bit of rewrite, but it has a number of advantages. a bunch of redundancy, and speed. it would detect if a section of the process was crashing and restart from that point. but not sure if it would be any faster... i'm writing the parsing scripts in python.. so... any thoughts/comments would be appreciated... i can get into a great deal more detail, but didn't want to bore anyone!! thanks! tom A: This sounds like a usecase for MapReduce on Hadoop. Hadoop 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, this would be a smaller cluster. A Map/Reduce job usually splits the input data-set into independent chunks which are processed by the map tasks in a completely parallel manner. You mentioned that, i've thought of breaking the app up in a manner that would allow the master to essentially pass packets to the client boxes, in a way to allow each client/function to be run directly from the master. From what I understand, you want a main machine (box) to act as a master, and have client boxes that run other functions. For instance, you could run your main() function and parse the initial URLs on it. The nice thing is that you could parallelize your task for each of these URLs across different machines, since they appear to be independent of each other. Since level4 depends on level3, which depends on level2 .. and so on, you can just pipe the output of each to the next rather than calling one from each. For examples on how to do this, I would recommend checking out, in the given order, the following tutorials, The Hadoop tutorial is a simple introduction and overview to what map-reduce is and how it works. Michael Noll's tutorial on how to utilize Hadoop on top of Python (the basic concepts of Mapper and Reducer) in a simple way And finally, a tutorial for a framework called Dumbo, released by the folks at Last.fm, which automates and builds on Michael Noll's basic example for use in a production system. Hope this helps. A: Take a look at the multiprocessing class. It allows you to set up a work queue and a pool of workers -- as you parse the page, you can spawn off tasks to be done by separate processes. A: Check out the scrapy package. It will allow for easy creation of your "client apps" (a.k.a crawlers, spiders, or scrapers) that go "deep" into a website. brool and viksit both have good suggestions for the distributed part of your project.
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 is specifically geared towards a given site. each client app looks something like main: parse initial url call function level1 (data1) function level1 (data) parse the url, for data1 use the required xpath to get the dom elements call the next function call level2 (data) function level2 (data2) parse the url, for data2 use the required xpath to get the dom elements call the next function call level3 function level3 (dat3) parse the url, for data3 use the required xpath to get the dom elements call the next function call level4 function level4 (data) parse the url, for data4 use the required xpath to get the dom elements at the final function.. --all the data output, and eventually returned to the server --at this point the data has elements from each function... my question: given that the number of calls that is made to the child function by the current function varies, i'm trying to figure out the best approach. each function essentialy fetches a page of content, and then parses the page using a number of different XPath expressions, combined with different regex expressions depending on the site/page. if i run a client on a single box, as a sequential process, it'll take awhile, but the load on the box is rather small. i've thought of attempting to implement the child functions as threads from the current function, but that could be a nightmare, as well as quickly bring the "box" to its knees! i've thought of breaking the app up in a manner that would allow the master to essentially pass packets to the client boxes, in a way to allow each client/function to be run directly from the master. this process requires a bit of rewrite, but it has a number of advantages. a bunch of redundancy, and speed. it would detect if a section of the process was crashing and restart from that point. but not sure if it would be any faster... i'm writing the parsing scripts in python.. so... any thoughts/comments would be appreciated... i can get into a great deal more detail, but didn't want to bore anyone!! thanks! tom
[ "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, this would be a smaller cluster.\nA Map/Reduce job usually splits the input data-set into independent chunks which are processed by the map tasks in a completely parallel manner. \nYou mentioned that,\n\ni've thought of breaking the app up in\n a manner that would allow the master\n to essentially pass packets to the\n client boxes, in a way to allow each\n client/function to be run directly\n from the master.\n\nFrom what I understand, you want a main machine (box) to act as a master, and have client boxes that run other functions. For instance, you could run your main() function and parse the initial URLs on it. The nice thing is that you could parallelize your task for each of these URLs across different machines, since they appear to be independent of each other.\nSince level4 depends on level3, which depends on level2 .. and so on, you can just pipe the output of each to the next rather than calling one from each.\nFor examples on how to do this, I would recommend checking out, in the given order, the following tutorials,\n\nThe Hadoop tutorial is a simple introduction and overview to what map-reduce is and how it works.\nMichael Noll's tutorial on how to utilize Hadoop on top of Python (the basic concepts of Mapper and Reducer) in a simple way\nAnd finally, a tutorial for a framework called Dumbo, released by the folks at Last.fm, which automates and builds on Michael Noll's basic example for use in a production system.\n\nHope this helps.\n", "Take a look at the multiprocessing class. It allows you to set up a work queue and a pool of workers -- as you parse the page, you can spawn off tasks to be done by separate processes.\n", "Check out the scrapy package. It will allow for easy creation of your \"client apps\" (a.k.a crawlers, spiders, or scrapers) that go \"deep\" into a website.\nbrool and viksit both have good suggestions for the distributed part of your project.\n" ]
[ 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 multiline string through tac to reverse the order. filter_through("one\ntwo\nthree\n", "tac") # => returns "three\ntwo\none\n" Note: the example is only that - I realize there are much better ways of reversing lines in python. A: Use the subprocess module. In your case, you could use something like import subprocess proc=subprocess.Popen(['tac','-'], shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, ) output,_=proc.communicate('one\ntwo\nthree\n') print output Note that the command sent is tac - so that tac expects input from stdin. We send to stdin by calling the communicate method. communicate returns a 2-tuple: the output from stdout, and stderr.
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_through("one\ntwo\nthree\n", "tac") # => returns "three\ntwo\none\n" Note: the example is only that - I realize there are much better ways of reversing lines in python.
[ "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 - so that tac expects input from stdin.\nWe send to stdin by calling the communicate method. communicate returns a 2-tuple: the output from stdout, and stderr. \n" ]
[ 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 onto my script to make it more secure? EDIT: To clarify: my website accepts absolutely NO input from users. I'm just designing a back-end admin panel to make it easier to update database entries. A: 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". Checking the ip address will force the attacker to "ride" on the session with XSS+XHR or XSRF. This is because the hijacked token will not work on his box. Unfortunately this also causes problems for corporate networks which use outgoing load balancing between multiple ip addresses. HTTPS is a must be used for the entire session. At no point can your token be sent over HTTP. This is clearly layed out in "Broken Authentication and Session Management" in The OWASP Top 10 for 2010, which you absolutely must read if you are writing a session handler. Session id's must always time out. If they do not then this is called an immortal session, which is a recognized vulnerability. Further more i am concerned about the randomness of your token. Make sure your study how to properly generate a cryptographic nonce. Make sure your random number generator is strong and seeded with information that an attacker cannot know. I also suspect that you haven't taken XSS and XSRF into consideration. It doesn't matter how strong you make your session in other areas if you leave a major vulnerability unchecked. Make sure you scan your application using a free xss scanner or the open source wapiti. Keep in mind that no test will accurately detect XSRF and every single request in your application is vulnerable unless you specifically patch it. A: The proper way to secure admin access is using HTTPS. There are two attacks against HTTPS: Trojan on your machine Man-in-the-middle uses legitimate yet malicious certificates Clearly (1) is the most likely. But on the other hand, your Trojan is likely to be out after your bank details and such, and the attacker is not going to sieve through all your stuff to discover and explore your admin relationship with a website. Clearly if the attacker is sophisticated as to go for (2) you are not in much of a position to prevail. That's as small an attack surface as you can get. A: Https is a must, but you also have to come to terms with the fact that no site can be 100% secure. The only other way for you to get a significant improvement in security is to have very short session timeouts and provide you users with hardware tokens, but even tokens can be stolen. A: THe one thing I miss besides everything that is mentioned is fixing "all other security problems". If you have a SQL injection, you're effort on the cookies is a waste of time. If you have a XSRF vuln, you're effort on the cookies is a waste of time. If you have XSS, .... If you have HPP, ... If you have ...., .... You get the point. If you really want to cover everything, I suggest you get the vulnerability landscape clear and build an attack tree (Bruce Schneier).
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? EDIT: To clarify: my website accepts absolutely NO input from users. I'm just designing a back-end admin panel to make it easier to update database entries.
[ "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 attacker to \"ride\" on the session with XSS+XHR or XSRF. This is because the hijacked token will not work on his box. Unfortunately this also causes problems for corporate networks which use outgoing load balancing between multiple ip addresses. \nHTTPS is a must be used for the entire session. At no point can your token be sent over HTTP. This is clearly layed out in \"Broken Authentication and Session Management\" in The OWASP Top 10 for 2010, which you absolutely must read if you are writing a session handler. \nSession id's must always time out. If they do not then this is called an immortal session, which is a recognized vulnerability. \nFurther more i am concerned about the randomness of your token. Make sure your study how to properly generate a cryptographic nonce. Make sure your random number generator is strong and seeded with information that an attacker cannot know. \nI also suspect that you haven't taken XSS and XSRF into consideration. It doesn't matter how strong you make your session in other areas if you leave a major vulnerability unchecked. Make sure you scan your application using a free xss scanner or the open source wapiti. Keep in mind that no test will accurately detect XSRF and every single request in your application is vulnerable unless you specifically patch it. \n", "The proper way to secure admin access is using HTTPS.\nThere are two attacks against HTTPS:\n\nTrojan on your machine\nMan-in-the-middle uses legitimate yet malicious certificates\n\nClearly (1) is the most likely. But on the other hand, your Trojan is likely to be out after your bank details and such, and the attacker is not going to sieve through all your stuff to discover and explore your admin relationship with a website.\nClearly if the attacker is sophisticated as to go for (2) you are not in much of a position to prevail.\nThat's as small an attack surface as you can get.\n", "Https is a must, but you also have to come to terms with the fact that no site can be 100% secure. The only other way for you to get a significant improvement in security is to have very short session timeouts and provide you users with hardware tokens, but even tokens can be stolen.\n", "THe one thing I miss besides everything that is mentioned is fixing \"all other security problems\". \n\nIf you have a SQL injection, you're effort on the cookies is a waste of time.\nIf you have a XSRF vuln, you're effort on the cookies is a waste of time.\nIf you have XSS, ....\nIf you have HPP, ...\nIf you have ...., ....\n\nYou get the point.\nIf you really want to cover everything, I suggest you get the vulnerability landscape clear and build an attack tree (Bruce Schneier).\n" ]
[ 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 platform is C, gcc under Linux. What is the best solution for this problem? I looked up on google and so XML, phthon and Lua bindings for C. Is using a separate scripting language the best approach? If so, which one would you recommend for my need? Addendum: What if I would like to mirror data structures in script files? If I have an array of structures for example, if there an easy way to store and load it? Thanks A: I recommend Lua. It was designed for configuration. A: The simplest way would be to have a text file containing something like: key = value key2 = anothervalue .... keyn = etc And then you simply open this file and parse it, putting everything in something like a hashmap/dictionary. A quick search on google comes up with a library (libConfuse) that can do this for you. A: Check out CCAN ciniparser. Its a fork of the original iniparser (which is no longer maintained) and makes parsing INI style configuration files easy. Code from the example (almost mirrored by the unit tests): #include <stdio.h> #include <stdbool.h> #include <ccan/ciniparser/ciniparser.h> #define CONFIG_FILE "/etc/config.ini" int main(int argc, char *argv[]) { dictionary *d; char *val1; bool val2; double val3; int val4; d = ciniparser_load(CONFIG_FILE); if (d == NULL) return 1; val1 = ciniparser_getstring(d, "daemon:pidfile", NULL); val2 = ciniparser_getboolean(d, "daemon:debug", false); val3 = ciniparser_getdouble(d, "daemon:maxload", 3.5); val4 = ciniparser_getint(d, "daemon:maxchild", 5); ciniparser_freedict(d); return 0; } Of course, you can just drop the few files needed in your tree and #include "iniparser.h", there are no dependencies on other CCAN modules unless you want to run the unit tests. A sample configuration might look like this: [stooges] larry=larry_stooge curly=curly_stooge moe=moe_stooge shemp=questionable [cartoons] tom_hates=jerry Getting the value of stooges:shemp would yield a statically allocated questionable that you would use as-is (without modifying) or allocate and duplicate (i.e. strdup()). It doesn't get much easier than that. Wrap access to the dictionary with a simple mutex and its thread safe. CCAN is the Comprehensive C Archive network. Think CPAN , just C. Its a project Rusty Russell began a while ago which is finally gaining some traction. Disclaimer: I maintain the module. A: What's wrong with a plain text file? Are these configuration settings read once when the app starts, or continuously throughout the life of the app? When do they get written? It sounds like they only get read once at the begining of the app, because you need to recompile every time they change. If there's only a handful of values, then I'd say keep it simple and stick with a text file formatted as key/value pairs: Config1 = 1 ConfigValue2 = 33.4 ConfigValue3 = ABC If you have more complex settings, maybe some hierarchy of values, XML might make more sense. A: How much configuration do you need that it needs to be a "script file"? I just keep a little chunk of code handy that's a ini format parser. A: You could reread the configuration file when a signal such as SIGUSR1 is received. A: you can just store all configurations values externally and read it with the old plain C you can do something like: param=value param2=value2 and read it normally with fgets and then do a strtok looking for '=' and then you have both params and values. if you want to use XML i recommend you libxml2.
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 best solution for this problem? I looked up on google and so XML, phthon and Lua bindings for C. Is using a separate scripting language the best approach? If so, which one would you recommend for my need? Addendum: What if I would like to mirror data structures in script files? If I have an array of structures for example, if there an easy way to store and load it? Thanks
[ "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 google comes up with a library (libConfuse) that can do this for you.\n", "Check out CCAN ciniparser. Its a fork of the original iniparser (which is no longer maintained) and makes parsing INI style configuration files easy.\nCode from the example (almost mirrored by the unit tests):\n#include <stdio.h>\n#include <stdbool.h>\n#include <ccan/ciniparser/ciniparser.h>\n\n#define CONFIG_FILE \"/etc/config.ini\"\n\nint main(int argc, char *argv[])\n{\n dictionary *d;\n char *val1;\n bool val2;\n double val3;\n int val4;\n\n d = ciniparser_load(CONFIG_FILE);\n if (d == NULL)\n return 1;\n\n val1 = ciniparser_getstring(d, \"daemon:pidfile\", NULL);\n val2 = ciniparser_getboolean(d, \"daemon:debug\", false);\n val3 = ciniparser_getdouble(d, \"daemon:maxload\", 3.5);\n val4 = ciniparser_getint(d, \"daemon:maxchild\", 5);\n\n ciniparser_freedict(d);\n\n return 0;\n}\n\nOf course, you can just drop the few files needed in your tree and #include \"iniparser.h\", there are no dependencies on other CCAN modules unless you want to run the unit tests.\nA sample configuration might look like this:\n[stooges]\nlarry=larry_stooge\ncurly=curly_stooge\nmoe=moe_stooge\nshemp=questionable\n\n[cartoons]\ntom_hates=jerry\n\nGetting the value of stooges:shemp would yield a statically allocated questionable that you would use as-is (without modifying) or allocate and duplicate (i.e. strdup()). It doesn't get much easier than that. Wrap access to the dictionary with a simple mutex and its thread safe.\nCCAN is the Comprehensive C Archive network. Think CPAN , just C. Its a project Rusty Russell began a while ago which is finally gaining some traction.\nDisclaimer: I maintain the module.\n", "What's wrong with a plain text file? Are these configuration settings read once when the app starts, or continuously throughout the life of the app? When do they get written? It sounds like they only get read once at the begining of the app, because you need to recompile every time they change.\nIf there's only a handful of values, then I'd say keep it simple and stick with a text file formatted as key/value pairs:\nConfig1 = 1\nConfigValue2 = 33.4\nConfigValue3 = ABC\n\nIf you have more complex settings, maybe some hierarchy of values, XML might make more sense.\n", "How much configuration do you need that it needs to be a \"script file\"? \nI just keep a little chunk of code handy that's a ini format parser.\n", "You could reread the configuration file when a signal such as SIGUSR1 is received.\n", "you can just store all configurations values externally and read it with the old plain C\nyou can do something like:\nparam=value\nparam2=value2\nand read it normally with fgets and then do a strtok looking for '=' and then you have both params and values.\nif you want to use XML i recommend you libxml2.\n" ]
[ 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 (empty($path)) return '.'; if (strpos($path, '/') === 0) $initial_slashes = true; else $initial_slashes = false; if ( ($initial_slashes) && (strpos($path, '//') === 0) && (strpos($path, '///') === false) ) $initial_slashes = 2; $initial_slashes = (int) $initial_slashes; $comps = explode('/', $path); $new_comps = array(); foreach ($comps as $comp) { if (in_array($comp, array('', '.'))) continue; if ( ($comp != '..') || (!$initial_slashes && !$new_comps) || ($new_comps && (end($new_comps) == '..')) ) array_push($new_comps, $comp); elseif ($new_comps) array_pop($new_comps); } $comps = $new_comps; $path = implode('/', $comps); if ($initial_slashes) $path = str_repeat('/', $initial_slashes) . $path; if ($path) return $path; else return '.'; } This will work exactly the same as os.path.normpath() in Python A: Yes, the realpath command will return a normalized path. It's similar to a combined version of Python's os.path.normpath and os.path.realpath. However, it will also resolve symbolic links. I'm not sure what you'd do if you didn't want that behavior.
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 (strpos($path, '//') === 0) &&\n (strpos($path, '///') === false)\n )\n $initial_slashes = 2;\n $initial_slashes = (int) $initial_slashes;\n\n $comps = explode('/', $path);\n $new_comps = array();\n foreach ($comps as $comp)\n {\n if (in_array($comp, array('', '.')))\n continue;\n if (\n ($comp != '..') ||\n (!$initial_slashes && !$new_comps) ||\n ($new_comps && (end($new_comps) == '..'))\n )\n array_push($new_comps, $comp);\n elseif ($new_comps)\n array_pop($new_comps);\n }\n $comps = $new_comps;\n $path = implode('/', $comps);\n if ($initial_slashes)\n $path = str_repeat('/', $initial_slashes) . $path;\n if ($path)\n return $path;\n else\n return '.';\n}\n\nThis will work exactly the same as os.path.normpath() in Python\n", "Yes, the realpath command will return a normalized path. It's similar to a combined version of Python's os.path.normpath and os.path.realpath.\nHowever, it will also resolve symbolic links. I'm not sure what you'd do if you didn't want that behavior.\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 generated by padlib intersect a line segment. The brute force method would be to just use the set of approximating line segments produced by padlib to find the answer. However, I suspect that a better answer can be found analytically. I only have a few dozen spline segments - searching them should be faster than thousand of line segments. A little search took me down this road: Bezier Curve -> Kochanek-Bartels Spline -> Cubic Hermite spline On the last page, I found this function: p(t) = h00(t)p0 + h10(t)m0 + h01(t)p1 + h11(t)m1 where p(t) is a actually a point (2-dimensional vector), hij(t) functions are cubic polynomials, p0, p1, m0 and m1 are points I can get from padlib code. Now, I can see that the solution to my problem is p(t) = u + v * t1, where u and v are the end of my line segment. However, working out the analytical solution is beyond me. Does anyone here know of an existing solution? Or can help me with solving the equations? A: 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 test against your line segment. A: I've finally got to a working code to illustrate the method suggested by Mark Thornton. Below is the Python code for the intersection routine, together with pygame code to test it visually. The cubic roots solution can be written based on this question. import pygame from pygame.locals import * import sys import random from math import sqrt, fabs, pow from lines import X, Y import itertools import pygame from pygame import draw, Color import padlib from roots_detailed import cubicRoots def add_points(*points): X = 0 Y = 0 for (x,y) in points: X += x Y += y return (X,Y) def diff_points(p2, p1): # p2 - p1 return (X(p2)-X(p1), Y(p2)-Y(p1)); def scale_point(factor, p): return (factor * X(p), factor*Y(p)) def between(v0, v, v1): if v0 > v1: v0, v1 = v1, v0 return v >= v0 and v <= v1 # the point is guaranteed to be on the right line def pointOnLineSegment(l1, l2, point): return between(X(l1), X(point), X(l2)) and between(Y(l1), Y(point), Y(l2)) def rotate(x, y, R1, R2, R3, R4): return (x*R1 + y*R2, x*R3 + y * R4); def findIntersections(p0, p1, m0, m1, l1, l2): # We're solving the equation of one segment of Kochanek-Bartels # spline intersecting with a line segment # The spline is described at http://en.wikipedia.org/wiki/Cubic_Hermite_spline # The discussion on the adopted solution can be found at https://stackoverflow.com/questions/1813719/intersection-between-bezier-curve-and-a-line-segment # # The equation we're solving is # # h00(t) p0 + h10(t) m0 + h01(t) p1 + h11(t) m1 = u + v t1 # # where # # h00(t) = 2t^3 - 3t^2 + 1 # h10(t) = t^3 - 2t^2 + t # h01(t) = -2t^3 + 3t^2 # h11(t) = t^3 - t^2 # u = l1 # v = l2-l1 u = l1 v = diff_points(l2, l1); # The first thing we do is to move u to the other side: # # h00(t) p0 + h10(t) m0 + h01(t) p1 + h11(t) m1 - u = v t1 # # Then we're looking for matrix R that would turn (v t1) into # ({|v|, 0} t1). This is rotation of coordinate system matrix, # described at http://mathworld.wolfram.com/RotationMatrix.html # # R(h00(t) p0 + h10(t) m0 + h01(t) p1 + h11(t) m1 - u) = R(v t1) = {|v|, 0}t1 # # We only care about R[1,0] and R[1,1] because it lets us solve # the equation for y coordinate where y == 0 (intersecting the # spline segment with the x axis of rotated coordinate # system). I'll call R[1,0] = R3 and R[1,1] = R4 . v_abs = sqrt(v[0] ** 2 + v[1] ** 2) R1 = X(v) / v_abs R2 = Y(v) / v_abs R3 = -Y(v) / v_abs R4 = X(v) / v_abs # The letters x and y are denoting x and y components of vectors # p0, p1, m0, m1, and u. p0x = p0[0]; p0y = p0[1] p1x = p1[0]; p1y = p1[1] m0x = m0[0]; m0y = m0[1] m1x = m1[0]; m1y = m1[1] ux = X(u); uy = Y(u) # # # R3(h00(t) p0x + h10(t) m0x + h01(t) p1x + h11(t) m1x - ux) + # + R4(h00(t) p0y + h10(t) m0y + h01(t) p1y + h11(t) m1y - uy) = 0 # # Opening all parentheses and simplifying for hxx we get: # # h00(t) p0x R3 + h10(t) m0x R3 + h01(t) p1x R3 + h11(t) m1x R3 - ux R3 + # + h00(t) p0y R4 + h10(t) m0y R4 + h01(t) p1y R4 + h11(t) m1y R4 - uy R4 = 0 # # h00(t) p0x R3 + h10(t) m0x R3 + h01(t) p1x R3 + h11(t) m1x R3 - ux R3 + # + h00(t) p0y R4 + h10(t) m0y R4 + h01(t) p1y R4 + h11(t) m1y R4 - uy R4 = 0 # # (1) # h00(t) (p0x R3 + p0y R4) + h10(t) (m0x R3 + m0y R4) + # h01(t) (p1x R3 + p1y R4) + h11(t) (m1x R3 + m1y R4) - (ux R3 + uy R4) = 0 # # We now introduce new substitution K00 = p0x * R3 + p0y * R4 K10 = m0x * R3 + m0y * R4 K01 = p1x * R3 + p1y * R4 K11 = m1x * R3 + m1y * R4 U = ux * R3 + uy * R4 # Expressed in those terms, equation (1) above becomes # # h00(t) K00 + h10(t) K10 + h01(t) K01 + h11(t) K11 - U = 0 # # We will now substitute the expressions for hxx(t) functions # # (2t^3 - 3t^2 + 1) K00 + (t^3 - 2t^2 + t) K10 + (-2t^3 + 3t^2) K01 + (t^3 - t^2) K11 - U = 0 # # 2 K00 t^3 - 3 K00 t^2 + K00 + # + K10 t^3 - 2 K10 t^2 + K10 t - # - 2 K01 t^3 + 3 K01 t^2 + # + K11 t^3 - K11 t^2 - U = 0 # # 2 K00 t^3 - 3 K00 t^2 + 0t + K00 # + K10 t^3 - 2 K10 t^2 + K10 t # - 2 K01 t^3 + 3 K01 t^2 # + K11 t^3 - K11 t^2 + 0t - U = 0 # # (2 K00 + K10 - 2K01 + K11) t^3 # +(-3 K00 - 2K10 + 3 K01 - K11) t^2 # + K10 t # + K00 - U = 0 # # # (2 K00 + K10 - 2K01 + K11) t^3 + (-3 K00 - 2K10 + 3 K01 - K11) t^2 + K10 t + K00 - U = 0 # # All we need now is to solwe a cubic equation valuesOfT = cubicRoots((2 * K00 + K10 - 2 * K01 + K11), (-3 * K00 - 2 * K10 + 3 * K01 - K11), (K10), K00 - U) # We can then put the values of it into our original spline segment # formula to find the potential intersection points. Any point # that's on original line segment is an intersection def h00(t): return 2 * t**3 - 3 * t**2 + 1 def h10(t): return t**3 - 2 * t**2 + t def h01(t): return -2 * t**3 + 3 * t**2 def h11(t): return t**3 - t**2 intersections = [] for t in valuesOfT: if t < 0 or t > 1.0: continue # point = h00(t) * p0 + h10(t) * m0 + h01(t) * p1 + h11(t) * m1 point = add_points( scale_point(h00(t), p0), scale_point(h10(t), m0), scale_point(h01(t), p1), scale_point(h11(t), m1) ) if pointOnLineSegment(l1, l2, point): intersections.append(point) return intersections def findIntersectionsManyCurves(p0_array, p1_array, m0_array, m1_array, u, v): result = []; for (p0, p1, m0, m1) in itertools.izip(p0_array, p1_array, m0_array, m1_array): result.extend(findIntersections(p0, p1, m0, m1, u, v)) return result def findIntersectionsManyCurvesManyLines(p0, p1, m0, m1, points): result = []; for (u,v) in itertools.izip(*[iter(points)]*2): result.extend(findIntersectionsManyCurves(p0, p1, m0, m1, u, v)) return result class EventsEmitter(object): def __init__(self): self.consumers = [] def emit(self, eventName, *params): for method in self.consumers: funcName = method.im_func.func_name if hasattr(method, "im_func") else method.func_name if funcName == eventName: method(*params) def register(self, method): self.consumers.append(method) def unregister(self, method): self.consumers.remove(method) class BunchOfPointsModel(EventsEmitter): def __init__(self): EventsEmitter.__init__(self) self.pts = [] def points(self): return self.pts.__iter__() def pointsSequence(self): return tuple(self.pts) def have(self, point): return point in self.pts def addPoint(self,p): self.pts.append(p) self.emit("pointsChanged", p) def replacePoint(self, oldP, newP): idx = self.pts.index(oldP) self.pts[idx] = newP self.emit("pointsChanged", newP) def removePoint(self, p): self.point.remove(p) self.emit("pointsChanged", p) class BunchOfPointsCompositeModel(object): def __init__(self, m1, m2): self.m1 = m1 self.m2 = m2 def points(self): return itertools.chain(self.m1.points(), self.m2.points()) def have(self, point): return self.m1.have(point) or self.m2.have(point) def replacePoint(self, oldP, newP): if self.m1.have(oldP): self.m1.replacePoint(oldP, newP) else: self.m2.replacePoint(oldP, newP) def removePoint(self, p): if self.m1.have(p): self.m1.removePoint(p) else: self.m2.removePoint(p) def register(self, method): self.m1.register(method) self.m2.register(method) def unregister(self, method): self.m1.unregister(method) self.m2.unregister(method) class BunchOfPointsDragController(EventsEmitter): def __init__(self, model): EventsEmitter.__init__(self) self.model = model self.draggedPoint = None def mouseMovedTo(self, x,y): if self.draggedPoint != None: newPoint = (x,y) draggedPoint = self.draggedPoint self.draggedPoint = newPoint self.model.replacePoint(draggedPoint, newPoint) def buttonDown(self, x,y): if self.draggedPoint == None: closePoint = self.getCloseEnoughPoint(x,y) if closePoint != None: self.draggedPoint = closePoint self.emit("dragPointChanged",closePoint) def buttonUp(self, x,y): self.mouseMovedTo(x,y) self.draggedPoint = None self.emit("dragPointChanged", None) def getCloseEnoughPoint(self, x,y): minSquareDistance = 25 closestPoint = None for point in self.model.points(): dx = X(point) - x dy = Y(point) - y distance = dx*dx + dy*dy if minSquareDistance > distance: closestPoint = point minSquareDistance = distance return closestPoint def isDraggedPoint(self, p): return p is self.draggedPoint class CurvesLinesViewPointsView(object): def __init__(self, screen, modelCurves, modelLines, model, controller): self.screen = screen self.modelLines = modelLines self.modelCurves = modelCurves self.controller = controller controller.register(self.dragPointChanged) model.register(self.pointsChanged) def draw(self): self.screen.fill(Color("black")) pygame.draw.lines(self.screen, Color("cyan"), 0, self.modelLines.pointsSequence(), 3) (p0, p1, m0, m1) = padlib.BezierCurve(screen,modelCurves.pointsSequence(),3,100,Color("magenta")) self.drawPointSet(self.modelCurves.points(), lambda(p):self.controller.isDraggedPoint(p), Color("white"), Color("red")) self.drawPointSet(self.modelLines.points(), lambda(p):self.controller.isDraggedPoint(p), Color("lightgray"), Color("red")) self.drawSimplePointSet(findIntersectionsManyCurvesManyLines(p0, p1, m0, m1,self.modelLines.points()), Color("blue")) def drawSimplePointSet(self, points, normalColor): self.drawPointSet(points, lambda(p):True, None, normalColor); def drawPointSet(self, points, specialPoint, normalColor, specialColor): for p in points: if specialPoint(p): draw.circle(self.screen, specialColor, p, 6) else: draw.circle(self.screen, normalColor, p, 2) pygame.display.update() def dragPointChanged(self, p): self.draw() def pointsChanged(self, p): self.draw() class PygameEventsDistributor(EventsEmitter): def __init__(self): EventsEmitter.__init__(self) def processEvent(self, e): if e.type == MOUSEMOTION: self.emit("mouseMovedTo", e.pos[0], e.pos[1]) elif e.type == MOUSEBUTTONDOWN: self.emit("buttonDown", e.pos[0], e.pos[1]) elif e.type == MOUSEBUTTONUP: self.emit("buttonUp", e.pos[0], e.pos[1]) modelLines = BunchOfPointsModel() modelCurves = BunchOfPointsModel() model = BunchOfPointsCompositeModel(modelLines, modelCurves); controller = BunchOfPointsDragController(model) distributor = PygameEventsDistributor() distributor.register(controller.mouseMovedTo) distributor.register(controller.buttonUp) distributor.register(controller.buttonDown) pygame.init() screen = pygame.display.set_mode((640, 480)) modelCurves.addPoint((29,34)) modelCurves.addPoint((98,56)) modelCurves.addPoint((200, 293)) modelCurves.addPoint((350, 293)) modelLines.addPoint((23,123)) modelLines.addPoint((78,212)) view = CurvesLinesViewPointsView(screen, modelCurves, modelLines, model, controller) keepGoing = True try: while (keepGoing): for event in pygame.event.get(): if event.type == QUIT: keepGoing = False break distributor.processEvent(event) pass finally: pygame.quit()
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 force method would be to just use the set of approximating line segments produced by padlib to find the answer. However, I suspect that a better answer can be found analytically. I only have a few dozen spline segments - searching them should be faster than thousand of line segments. A little search took me down this road: Bezier Curve -> Kochanek-Bartels Spline -> Cubic Hermite spline On the last page, I found this function: p(t) = h00(t)p0 + h10(t)m0 + h01(t)p1 + h11(t)m1 where p(t) is a actually a point (2-dimensional vector), hij(t) functions are cubic polynomials, p0, p1, m0 and m1 are points I can get from padlib code. Now, I can see that the solution to my problem is p(t) = u + v * t1, where u and v are the end of my line segment. However, working out the analytical solution is beyond me. Does anyone here know of an existing solution? Or can help me with solving the equations?
[ "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 test against your line segment.\n", "I've finally got to a working code to illustrate the method suggested by Mark Thornton. Below is the Python code for the intersection routine, together with pygame code to test it visually. The cubic roots solution can be written based on this question. \nimport pygame\nfrom pygame.locals import *\nimport sys\nimport random\nfrom math import sqrt, fabs, pow\nfrom lines import X, Y\nimport itertools\nimport pygame\nfrom pygame import draw, Color\nimport padlib\nfrom roots_detailed import cubicRoots\n\n\ndef add_points(*points):\n X = 0\n Y = 0\n for (x,y) in points:\n X += x\n Y += y\n return (X,Y)\n\ndef diff_points(p2, p1):\n # p2 - p1\n return (X(p2)-X(p1), Y(p2)-Y(p1));\n\ndef scale_point(factor, p):\n return (factor * X(p), factor*Y(p))\n\ndef between(v0, v, v1):\n if v0 > v1: v0, v1 = v1, v0\n return v >= v0 and v <= v1\n\n\n# the point is guaranteed to be on the right line\ndef pointOnLineSegment(l1, l2, point):\n return between(X(l1), X(point), X(l2)) and between(Y(l1), Y(point), Y(l2))\n\n\ndef rotate(x, y, R1, R2, R3, R4):\n return (x*R1 + y*R2, x*R3 + y * R4);\n\ndef findIntersections(p0, p1, m0, m1, l1, l2):\n # We're solving the equation of one segment of Kochanek-Bartels\n # spline intersecting with a line segment\n # The spline is described at http://en.wikipedia.org/wiki/Cubic_Hermite_spline \n # The discussion on the adopted solution can be found at https://stackoverflow.com/questions/1813719/intersection-between-bezier-curve-and-a-line-segment\n # \n # The equation we're solving is \n #\n # h00(t) p0 + h10(t) m0 + h01(t) p1 + h11(t) m1 = u + v t1\n #\n # where \n #\n # h00(t) = 2t^3 - 3t^2 + 1\n # h10(t) = t^3 - 2t^2 + t\n # h01(t) = -2t^3 + 3t^2\n # h11(t) = t^3 - t^2\n # u = l1\n # v = l2-l1\n\n u = l1\n v = diff_points(l2, l1);\n\n # The first thing we do is to move u to the other side:\n #\n # h00(t) p0 + h10(t) m0 + h01(t) p1 + h11(t) m1 - u = v t1\n #\n # Then we're looking for matrix R that would turn (v t1) into\n # ({|v|, 0} t1). This is rotation of coordinate system matrix,\n # described at http://mathworld.wolfram.com/RotationMatrix.html\n #\n # R(h00(t) p0 + h10(t) m0 + h01(t) p1 + h11(t) m1 - u) = R(v t1) = {|v|, 0}t1\n #\n # We only care about R[1,0] and R[1,1] because it lets us solve\n # the equation for y coordinate where y == 0 (intersecting the\n # spline segment with the x axis of rotated coordinate\n # system). I'll call R[1,0] = R3 and R[1,1] = R4 . \n\n v_abs = sqrt(v[0] ** 2 + v[1] ** 2)\n R1 = X(v) / v_abs\n R2 = Y(v) / v_abs\n R3 = -Y(v) / v_abs\n R4 = X(v) / v_abs\n\n\n # The letters x and y are denoting x and y components of vectors\n # p0, p1, m0, m1, and u.\n\n p0x = p0[0]; p0y = p0[1]\n p1x = p1[0]; p1y = p1[1]\n m0x = m0[0]; m0y = m0[1]\n m1x = m1[0]; m1y = m1[1]\n ux = X(u); uy = Y(u)\n\n #\n #\n # R3(h00(t) p0x + h10(t) m0x + h01(t) p1x + h11(t) m1x - ux) +\n # + R4(h00(t) p0y + h10(t) m0y + h01(t) p1y + h11(t) m1y - uy) = 0\n #\n # Opening all parentheses and simplifying for hxx we get:\n #\n # h00(t) p0x R3 + h10(t) m0x R3 + h01(t) p1x R3 + h11(t) m1x R3 - ux R3 +\n # + h00(t) p0y R4 + h10(t) m0y R4 + h01(t) p1y R4 + h11(t) m1y R4 - uy R4 = 0\n # \n # h00(t) p0x R3 + h10(t) m0x R3 + h01(t) p1x R3 + h11(t) m1x R3 - ux R3 + \n # + h00(t) p0y R4 + h10(t) m0y R4 + h01(t) p1y R4 + h11(t) m1y R4 - uy R4 = 0\n # \n # (1)\n # h00(t) (p0x R3 + p0y R4) + h10(t) (m0x R3 + m0y R4) + \n # h01(t) (p1x R3 + p1y R4) + h11(t) (m1x R3 + m1y R4) - (ux R3 + uy R4) = 0\n #\n # We now introduce new substitution\n\n K00 = p0x * R3 + p0y * R4\n K10 = m0x * R3 + m0y * R4\n K01 = p1x * R3 + p1y * R4\n K11 = m1x * R3 + m1y * R4\n U = ux * R3 + uy * R4\n\n # Expressed in those terms, equation (1) above becomes\n #\n # h00(t) K00 + h10(t) K10 + h01(t) K01 + h11(t) K11 - U = 0\n #\n # We will now substitute the expressions for hxx(t) functions\n #\n # (2t^3 - 3t^2 + 1) K00 + (t^3 - 2t^2 + t) K10 + (-2t^3 + 3t^2) K01 + (t^3 - t^2) K11 - U = 0\n # \n # 2 K00 t^3 - 3 K00 t^2 + K00 + \n # + K10 t^3 - 2 K10 t^2 + K10 t - \n # - 2 K01 t^3 + 3 K01 t^2 + \n # + K11 t^3 - K11 t^2 - U = 0\n # \n # 2 K00 t^3 - 3 K00 t^2 + 0t + K00 \n # + K10 t^3 - 2 K10 t^2 + K10 t\n # - 2 K01 t^3 + 3 K01 t^2 \n # + K11 t^3 - K11 t^2 + 0t - U = 0\n # \n # (2 K00 + K10 - 2K01 + K11) t^3 \n # +(-3 K00 - 2K10 + 3 K01 - K11) t^2\n # + K10 t\n # + K00 - U = 0\n # \n # \n # (2 K00 + K10 - 2K01 + K11) t^3 + (-3 K00 - 2K10 + 3 K01 - K11) t^2 + K10 t + K00 - U = 0\n #\n # All we need now is to solwe a cubic equation\n valuesOfT = cubicRoots((2 * K00 + K10 - 2 * K01 + K11),\n (-3 * K00 - 2 * K10 + 3 * K01 - K11),\n (K10),\n K00 - U)\n # We can then put the values of it into our original spline segment\n # formula to find the potential intersection points. Any point\n # that's on original line segment is an intersection\n\n def h00(t): return 2 * t**3 - 3 * t**2 + 1\n def h10(t): return t**3 - 2 * t**2 + t\n def h01(t): return -2 * t**3 + 3 * t**2\n def h11(t): return t**3 - t**2\n\n intersections = []\n for t in valuesOfT:\n if t < 0 or t > 1.0: continue\n # point = h00(t) * p0 + h10(t) * m0 + h01(t) * p1 + h11(t) * m1\n point = add_points(\n scale_point(h00(t), p0),\n scale_point(h10(t), m0),\n scale_point(h01(t), p1),\n scale_point(h11(t), m1)\n )\n\n if pointOnLineSegment(l1, l2, point): intersections.append(point)\n\n\n return intersections\n\ndef findIntersectionsManyCurves(p0_array, p1_array, m0_array, m1_array, u, v):\n result = [];\n for (p0, p1, m0, m1) in itertools.izip(p0_array, p1_array, m0_array, m1_array):\n result.extend(findIntersections(p0, p1, m0, m1, u, v))\n return result\n\n\ndef findIntersectionsManyCurvesManyLines(p0, p1, m0, m1, points):\n result = [];\n\n for (u,v) in itertools.izip(*[iter(points)]*2):\n result.extend(findIntersectionsManyCurves(p0, p1, m0, m1, u, v))\n\n return result\n\nclass EventsEmitter(object):\n def __init__(self):\n self.consumers = []\n\n def emit(self, eventName, *params):\n for method in self.consumers:\n funcName = method.im_func.func_name if hasattr(method, \"im_func\") else method.func_name\n if funcName == eventName:\n method(*params)\n def register(self, method):\n self.consumers.append(method)\n\n def unregister(self, method):\n self.consumers.remove(method)\n\n\n\nclass BunchOfPointsModel(EventsEmitter):\n def __init__(self):\n EventsEmitter.__init__(self)\n self.pts = []\n\n\n def points(self):\n return self.pts.__iter__()\n\n def pointsSequence(self):\n return tuple(self.pts)\n\n def have(self, point):\n return point in self.pts\n\n def addPoint(self,p):\n self.pts.append(p)\n self.emit(\"pointsChanged\", p)\n\n def replacePoint(self, oldP, newP):\n idx = self.pts.index(oldP)\n self.pts[idx] = newP\n self.emit(\"pointsChanged\", newP)\n\n\n def removePoint(self, p):\n self.point.remove(p)\n self.emit(\"pointsChanged\", p)\n\n\nclass BunchOfPointsCompositeModel(object):\n def __init__(self, m1, m2):\n self.m1 = m1\n self.m2 = m2\n\n def points(self):\n return itertools.chain(self.m1.points(), self.m2.points())\n\n def have(self, point):\n return self.m1.have(point) or self.m2.have(point)\n\n\n def replacePoint(self, oldP, newP):\n if self.m1.have(oldP):\n self.m1.replacePoint(oldP, newP)\n else:\n self.m2.replacePoint(oldP, newP)\n\n def removePoint(self, p):\n if self.m1.have(p):\n self.m1.removePoint(p)\n else:\n self.m2.removePoint(p)\n\n def register(self, method):\n self.m1.register(method)\n self.m2.register(method)\n\n def unregister(self, method):\n self.m1.unregister(method)\n self.m2.unregister(method)\n\nclass BunchOfPointsDragController(EventsEmitter):\n def __init__(self, model):\n EventsEmitter.__init__(self)\n self.model = model\n self.draggedPoint = None\n\n def mouseMovedTo(self, x,y):\n if self.draggedPoint != None:\n newPoint = (x,y)\n draggedPoint = self.draggedPoint\n self.draggedPoint = newPoint\n self.model.replacePoint(draggedPoint, newPoint)\n def buttonDown(self, x,y):\n if self.draggedPoint == None:\n closePoint = self.getCloseEnoughPoint(x,y)\n if closePoint != None:\n self.draggedPoint = closePoint\n self.emit(\"dragPointChanged\",closePoint)\n\n def buttonUp(self, x,y):\n self.mouseMovedTo(x,y)\n self.draggedPoint = None\n self.emit(\"dragPointChanged\", None)\n\n def getCloseEnoughPoint(self, x,y):\n minSquareDistance = 25\n closestPoint = None\n for point in self.model.points():\n dx = X(point) - x\n dy = Y(point) - y\n distance = dx*dx + dy*dy\n if minSquareDistance > distance:\n closestPoint = point\n minSquareDistance = distance\n return closestPoint\n\n def isDraggedPoint(self, p):\n return p is self.draggedPoint\n\nclass CurvesLinesViewPointsView(object):\n def __init__(self, screen, modelCurves, modelLines, model, controller):\n self.screen = screen\n self.modelLines = modelLines\n self.modelCurves = modelCurves\n self.controller = controller\n controller.register(self.dragPointChanged)\n model.register(self.pointsChanged)\n\n def draw(self):\n self.screen.fill(Color(\"black\"))\n pygame.draw.lines(self.screen, Color(\"cyan\"), 0, self.modelLines.pointsSequence(), 3)\n (p0, p1, m0, m1) = padlib.BezierCurve(screen,modelCurves.pointsSequence(),3,100,Color(\"magenta\"))\n\n self.drawPointSet(self.modelCurves.points(),\n lambda(p):self.controller.isDraggedPoint(p),\n Color(\"white\"), Color(\"red\"))\n self.drawPointSet(self.modelLines.points(),\n lambda(p):self.controller.isDraggedPoint(p),\n Color(\"lightgray\"), Color(\"red\"))\n\n\n self.drawSimplePointSet(findIntersectionsManyCurvesManyLines(p0, p1, m0, m1,self.modelLines.points()),\n Color(\"blue\"))\n\n\n\n\n def drawSimplePointSet(self, points, normalColor):\n self.drawPointSet(points, lambda(p):True, None, normalColor);\n\n def drawPointSet(self, points, specialPoint, normalColor, specialColor):\n for p in points:\n if specialPoint(p):\n draw.circle(self.screen, specialColor, p, 6)\n else:\n draw.circle(self.screen, normalColor, p, 2)\n pygame.display.update()\n\n def dragPointChanged(self, p): self.draw()\n def pointsChanged(self, p): self.draw()\n\n\nclass PygameEventsDistributor(EventsEmitter):\n def __init__(self):\n EventsEmitter.__init__(self)\n def processEvent(self, e):\n if e.type == MOUSEMOTION:\n self.emit(\"mouseMovedTo\", e.pos[0], e.pos[1])\n elif e.type == MOUSEBUTTONDOWN:\n self.emit(\"buttonDown\", e.pos[0], e.pos[1])\n elif e.type == MOUSEBUTTONUP:\n self.emit(\"buttonUp\", e.pos[0], e.pos[1])\n\n\nmodelLines = BunchOfPointsModel()\nmodelCurves = BunchOfPointsModel()\nmodel = BunchOfPointsCompositeModel(modelLines, modelCurves);\ncontroller = BunchOfPointsDragController(model)\n\ndistributor = PygameEventsDistributor()\ndistributor.register(controller.mouseMovedTo)\ndistributor.register(controller.buttonUp)\ndistributor.register(controller.buttonDown)\n\npygame.init()\nscreen = pygame.display.set_mode((640, 480))\n\nmodelCurves.addPoint((29,34))\nmodelCurves.addPoint((98,56))\nmodelCurves.addPoint((200, 293))\nmodelCurves.addPoint((350, 293))\n\nmodelLines.addPoint((23,123))\nmodelLines.addPoint((78,212))\n\nview = CurvesLinesViewPointsView(screen, modelCurves, modelLines, model, controller)\n\n\nkeepGoing = True\n\ntry:\n while (keepGoing):\n for event in pygame.event.get():\n if event.type == QUIT:\n keepGoing = False\n break\n distributor.processEvent(event)\n pass\nfinally:\n pygame.quit()\n\n" ]
[ 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 contains sub-applications to separate out the different parts of the system. The reason I intended to make these "sub" applications is that they would not have any use outside the parent application whatsoever, so there would be little point in distributing them separately. We envisage that the portal will be installed in multiple locations (at different universities, for example) so the main app can be dropped into a number of Django projects to install it. We therefore have a different repository for each location's project, which is really just a settings.py file defining the installed portal applications, and a urls.py routing the urls to it. I have started to write some initial code, though, and I've come up against a problem. Some of the code that handles user authentication and profiles seems to be without a home. It doesn't conceptually belong in the portal application as it doesn't relate to the portal's functionality. It also, however, can't go in the project repository - as I would then be duplicating the code over each location's repository. If I then discovered a bug in this code, for example, I would have to manually replicate the fix over all of the location's project files. My idea for a fix is to make all the project repos a fork of a "master" location project, so that I can pull any changes from that master. I think this is messy though, and it means that I have one more repository to look after. I'm looking for a better way to achieve this project. Can anyone recommend a solution or a similar example I can take a look at? The problem seems to be that I am developing a Django project rather than just a Django application. A: 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: project/ settings.py urls.py views.py ... apps/ emails/ urls.py views.py ... notes/ urls.py views.py ... ... apps: Each of the "apps" stands on its own, and other than a settings.py, does not rely on the project itself (though it can rely on other apps). One of the apps, is the user authentication and management. It has all of the URLs for accomplishing its tasks in apps/auth/urls.py. All of its templates are in apps/auth/templates/auth/. All of its functionality is self-contained, so that when I need to tweak something, I know where to go. project: The project/ contains all of the glue required to put these individual apps together into the final project. In my case, I made use heavy of settings.INSTALLED_APPS in project/ to discern which views from the apps were available to me. This way, if I take apps.notes out of my INSTALLED_APPS, everything still works wonderfully, just with no notes. Maintenance: This layout/methodology/plan also has long-term positive ramifications. You can re-use any of the apps later on, with almost no work. You can test the system from the bottom up, ensuring that each of the apps works as intended before being integrated into the whole, helping you find/fix bugs quicker. You can implement a new feature without rolling it out to existing instances of the application (if it isn't in INSTALLED_APPS, they can't see it). I'm sure there are better documented ways of laying out a project, and more widely used ways, but this is the one which has worked best for me so far. A: You should take a look at : Django generic relations Django reusable apps best practices if you want to re-use GIT or any other CVS (git is great for maintaining + deployment) Fabric if you need automated deployments/updates I usually use this project structure : /djangoproject /apps /main # the main code /static # each sub app can serve statics /app1 /static # each sub app can serve statics /app2... /scripts # manage.py, wsgi, apache.conf, fabfile.py... /core # your libraries ... settings.py local_settings.py Each app in /apps have an urls.py thats autoincluded in the main urls.py. And each app can be a git submodule (or svn external) Also, using git, you can work on different parallels branches (master/dev/customerA/customerB...) and merge updates. Creating real reusable is not so easy with django. A: You can extract the common functionality into a separate module and make your apps depend on it: my_portal auth_module profiles_module application1 (depends on auth_module) application2 (depends on auth_module and profiles_module) I think the fact that a 'classical' Django project appear to 'contain' the apps it's using prevent you from seeing the picture - in fact, it's not necessary. For a project where you're going to have some sort of pluggable modules I'd suggest organizing the apps as eggs and using zc.buildout+djangorecipe to manage everything. This way you'll be able to keep your modules in a flat one-level structure. Eggs have the ability to specify dependencies, so if you install application1 (see above), auth_module will be installed automatically. Also it'll be easy to have different configurations deployed to different servers. Suppose, you have server1 which has application1 installed and server2 which has both application1 and application2 installed - you can just have two configs: server1.cfg: [buildout] extends = base_deployment.cfg eggs += application1 server2.cfg: [buildout] extends = base_seployment.cfg eggs += application1 application2 djangorecipe also allows you to specify different settings files for each buildout config so you'll be able to add the necessary bits to the main project's urls and installed apps settings. Not to mention, you can also have a separate config for development configuration (with debug=True and Django Debug Toolbar installed, for example).
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 different parts of the system. The reason I intended to make these "sub" applications is that they would not have any use outside the parent application whatsoever, so there would be little point in distributing them separately. We envisage that the portal will be installed in multiple locations (at different universities, for example) so the main app can be dropped into a number of Django projects to install it. We therefore have a different repository for each location's project, which is really just a settings.py file defining the installed portal applications, and a urls.py routing the urls to it. I have started to write some initial code, though, and I've come up against a problem. Some of the code that handles user authentication and profiles seems to be without a home. It doesn't conceptually belong in the portal application as it doesn't relate to the portal's functionality. It also, however, can't go in the project repository - as I would then be duplicating the code over each location's repository. If I then discovered a bug in this code, for example, I would have to manually replicate the fix over all of the location's project files. My idea for a fix is to make all the project repos a fork of a "master" location project, so that I can pull any changes from that master. I think this is messy though, and it means that I have one more repository to look after. I'm looking for a better way to achieve this project. Can anyone recommend a solution or a similar example I can take a look at? The problem seems to be that I am developing a Django project rather than just a Django application.
[ "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...\n\napps/\n\n\nemails/\n\n\nurls.py\nviews.py\n...\n\nnotes/\n\n\nurls.py\nviews.py\n...\n\n...\n\n\napps:\nEach of the \"apps\" stands on its own, and other than a settings.py, does not rely on the project itself (though it can rely on other apps). One of the apps, is the user authentication and management. It has all of the URLs for accomplishing its tasks in apps/auth/urls.py. All of its templates are in apps/auth/templates/auth/. All of its functionality is self-contained, so that when I need to tweak something, I know where to go.\nproject:\nThe project/ contains all of the glue required to put these individual apps together into the final project. In my case, I made use heavy of settings.INSTALLED_APPS in project/ to discern which views from the apps were available to me. This way, if I take apps.notes out of my INSTALLED_APPS, everything still works wonderfully, just with no notes. \nMaintenance:\nThis layout/methodology/plan also has long-term positive ramifications. You can re-use any of the apps later on, with almost no work. You can test the system from the bottom up, ensuring that each of the apps works as intended before being integrated into the whole, helping you find/fix bugs quicker. You can implement a new feature without rolling it out to existing instances of the application (if it isn't in INSTALLED_APPS, they can't see it). \nI'm sure there are better documented ways of laying out a project, and more widely used ways, but this is the one which has worked best for me so far.\n", "You should take a look at :\n\nDjango generic relations\nDjango reusable apps best practices if you want to re-use\nGIT or any other CVS (git is great for maintaining + deployment)\nFabric if you need automated deployments/updates\n\nI usually use this project structure :\n\n/djangoproject\n\n\n/apps\n\n\n/main # the main code\n/static # each sub app can serve statics\n/app1\n/static # each sub app can serve statics\n/app2...\n\n/scripts # manage.py, wsgi, apache.conf, fabfile.py...\n/core # your libraries ...\nsettings.py\nlocal_settings.py\n\n\nEach app in /apps have an urls.py thats autoincluded in the main urls.py. And each app can be a git submodule (or svn external)\nAlso, using git, you can work on different parallels branches (master/dev/customerA/customerB...) and merge updates.\nCreating real reusable is not so easy with django.\n", "You can extract the common functionality into a separate module and make your apps depend on it:\n\nmy_portal\nauth_module\nprofiles_module\napplication1 (depends on auth_module)\napplication2 (depends on auth_module and profiles_module)\n\nI think the fact that a 'classical' Django project appear to 'contain' the apps it's using prevent you from seeing the picture - in fact, it's not necessary. For a project where you're going to have some sort of pluggable modules I'd suggest organizing the apps as eggs and using zc.buildout+djangorecipe to manage everything.\nThis way you'll be able to keep your modules in a flat one-level structure. Eggs have the ability to specify dependencies, so if you install application1 (see above), auth_module will be installed automatically.\nAlso it'll be easy to have different configurations deployed to different servers. Suppose, you have server1 which has application1 installed and server2 which has both application1 and application2 installed - you can just have two configs:\nserver1.cfg:\n[buildout]\nextends = base_deployment.cfg\neggs += application1\n\nserver2.cfg:\n[buildout]\nextends = base_seployment.cfg\neggs += application1\n application2\n\ndjangorecipe also allows you to specify different settings files for each buildout config so you'll be able to add the necessary bits to the main project's urls and installed apps settings.\nNot to mention, you can also have a separate config for development configuration (with debug=True and Django Debug Toolbar installed, for example). \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[]) throws ScriptException { ScriptEngineManager mgr = new ScriptEngineManager(); ScriptEngine pyEngine = mgr.getEngineByName("python"); try { pyEngine.eval("print \"Python - Hello, world!\""); } catch (Exception ex) { ex.printStackTrace(); } } } This is causing a NullPointerException: java.lang.NullPointerException at jythonEx.main(jythonEx.java:12) Does anyone have any idea what I'm doing wrong here? Edit: Thanks for the responses! I added jython.jar to the classpath and it runs properly: java -cp "./;jython.jar" jythonEx A: You have to register your engine first. From: ScriptEngineManager.getEngineByName: [...] first searches for a ScriptEngineFactory that has been registered as a handle [...] Returns null if no such factory was found The user guide says to use it with JSR-223 you have to: As of Jython 2.5.1 an implementation of JSR 223 is bundled in jython.jar. Simply add jython to your CLASSPATH and ask for the python script engine. Did you do that already? EDIT About your comment: I think you should open a new question, you'll get better answers. A: You'd probably have to register a ScriptEngineFactory for'python'
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 ScriptEngineManager(); ScriptEngine pyEngine = mgr.getEngineByName("python"); try { pyEngine.eval("print \"Python - Hello, world!\""); } catch (Exception ex) { ex.printStackTrace(); } } } This is causing a NullPointerException: java.lang.NullPointerException at jythonEx.main(jythonEx.java:12) Does anyone have any idea what I'm doing wrong here? Edit: Thanks for the responses! I added jython.jar to the classpath and it runs properly: java -cp "./;jython.jar" jythonEx
[ "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 implementation of JSR 223 is bundled in jython.jar. Simply add jython to your CLASSPATH and ask for the python script engine.\n\nDid you do that already?\nEDIT\nAbout your comment: I think you should open a new question, you'll get better answers.\n", "You'd probably have to register a ScriptEngineFactory for'python' \n" ]
[ 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, page): self.page = page def start(self, *args): if args == (): # We apparently don't need authentication for this d1 = getPage(self.page) else: if len(args) == 2: # We have our login information d1 = getPage(self.page, headers={"Authorization": " ".join(args)}) else: raise Exception('Missing parameters') d1.addCallback(self.pageCallback) dl = DeferredList([d1]) d1.addErrback(self.errorHandler) dl.addCallback(self.listCallback) def errorHandler(self,result): # Bad thingy! pass def pageCallback(self, result): return result def listCallback(self, result): print result a = GrabPage('http://www.google.com') data = a.start() # Not the HTML I wish to get the HTML out which is given to pageCallback when start() is called. This has been a pita for me. Ty! And sorry for my sucky coding. A: 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: (source: krondo.com) Until you start the reactor, by setting up deferreds all you're doing is chaining them with no events from which to fire. I recommend you give the Twisted Intro by Dave Peticolas a read. It's quick and it really gives you all the missing information that the Twisted documentation doesn't. Anyways, here is the most basic usage example of getPage as possible: from twisted.web.client import getPage from twisted.internet import reactor url = 'http://aol.com' def print_and_stop(output): print output if reactor.running: reactor.stop() if __name__ == '__main__': print 'fetching', url d = getPage(url) d.addCallback(print_and_stop) reactor.run() Since getPage returns a deferred, I'm adding the callback print_and_stop to the deferred chain. After that, I start the reactor. The reactor fires getPage, which then fires print_and_stop which prints the data from aol.com and then stops the reactor. Edit to show a working example of OP's code: class GrabPage: def __init__(self, page): self.page = page ########### I added this: self.data = None def start(self, *args): if args == (): # We apparently don't need authentication for this d1 = getPage(self.page) else: if len(args) == 2: # We have our login information d1 = getPage(self.page, headers={"Authorization": " ".join(args)}) else: raise Exception('Missing parameters') d1.addCallback(self.pageCallback) dl = DeferredList([d1]) d1.addErrback(self.errorHandler) dl.addCallback(self.listCallback) def errorHandler(self,result): # Bad thingy! pass def pageCallback(self, result): ########### I added this, to hold the data: self.data = result return result def listCallback(self, result): print result # Added for effect: if reactor.running: reactor.stop() a = GrabPage('http://google.com') ########### Just call it without assigning to data #data = a.start() # Not the HTML a.start() ########### I added this: if not reactor.running: reactor.run() ########### Reference the data attribute from the class data = a.data print '------REACTOR STOPPED------' print ########### First 100 characters of a.data: print '------a.data[:100]------' print data[:100]
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 def start(self, *args): if args == (): # We apparently don't need authentication for this d1 = getPage(self.page) else: if len(args) == 2: # We have our login information d1 = getPage(self.page, headers={"Authorization": " ".join(args)}) else: raise Exception('Missing parameters') d1.addCallback(self.pageCallback) dl = DeferredList([d1]) d1.addErrback(self.errorHandler) dl.addCallback(self.listCallback) def errorHandler(self,result): # Bad thingy! pass def pageCallback(self, result): return result def listCallback(self, result): print result a = GrabPage('http://www.google.com') data = a.start() # Not the HTML I wish to get the HTML out which is given to pageCallback when start() is called. This has been a pita for me. Ty! And sorry for my sucky coding.
[ "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 you give the Twisted Intro by Dave Peticolas a read. It's quick and it really gives you all the missing information that the Twisted documentation doesn't.\nAnyways, here is the most basic usage example of getPage as possible:\nfrom twisted.web.client import getPage\nfrom twisted.internet import reactor\n\nurl = 'http://aol.com'\n\ndef print_and_stop(output):\n print output\n if reactor.running:\n reactor.stop()\n\nif __name__ == '__main__':\n print 'fetching', url\n d = getPage(url)\n d.addCallback(print_and_stop)\n reactor.run()\n\nSince getPage returns a deferred, I'm adding the callback print_and_stop to the deferred chain. After that, I start the reactor. The reactor fires getPage, which then fires print_and_stop which prints the data from aol.com and then stops the reactor. \nEdit to show a working example of OP's code:\nclass GrabPage:\n def __init__(self, page):\n self.page = page\n ########### I added this:\n self.data = None\n\n def start(self, *args):\n if args == ():\n # We apparently don't need authentication for this\n d1 = getPage(self.page)\n else:\n if len(args) == 2:\n # We have our login information\n d1 = getPage(self.page, headers={\"Authorization\": \" \".join(args)})\n else:\n raise Exception('Missing parameters')\n\n d1.addCallback(self.pageCallback)\n dl = DeferredList([d1])\n d1.addErrback(self.errorHandler)\n dl.addCallback(self.listCallback)\n\n def errorHandler(self,result):\n # Bad thingy!\n pass\n\n def pageCallback(self, result):\n ########### I added this, to hold the data:\n self.data = result\n return result\n\n def listCallback(self, result):\n print result\n # Added for effect:\n if reactor.running:\n reactor.stop()\n\na = GrabPage('http://google.com')\n########### Just call it without assigning to data\n#data = a.start() # Not the HTML\na.start()\n\n########### I added this:\nif not reactor.running:\n reactor.run()\n\n########### Reference the data attribute from the class\ndata = a.data\nprint '------REACTOR STOPPED------'\nprint\n########### First 100 characters of a.data:\nprint '------a.data[:100]------'\nprint data[:100] \n\n" ]
[ 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? If so, does the problem go away with a nested directory structure? Thanks. A: See: How many files can I put in a directory? A: 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 structure can ameliorate this problem by creating a tree structure (or even a Trie, if it makes sense) of names which can reduce the time it takes to retrieve file stats. A: My suggestion is to use nested directory structure (ie categorization). You can name them using timestamps, special prefixes for each application etc. This gives you a sense of order when you need to search for specific files and for easier management of your files.
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 structure can ameliorate this problem by creating a tree structure (or even a Trie, if it makes sense) of names which can reduce the time it takes to retrieve file stats.\n", "My suggestion is to use nested directory structure (ie categorization). You can name them using timestamps, special prefixes for each application etc. This gives you a sense of order when you need to search for specific files and for easier management of your files.\n" ]
[ 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 VALUES part but when I try to get the list as a whole it does not work. Here is the code. I couldn't figure it out. Any ideas? lines=open(path, "r").readlines() for line in lines[1:]: linex=line.strip().split("\t") linex.insert(0,'sometextindex') try: cursor.execute('INSERT INTO variants VALUES(%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) except: print 'line number=',a,linex A: Why not just use LOAD DATA INFILE from mysql? A: 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], ........ ) .... cursor.execute(stmt) ....
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 is the code. I couldn't figure it out. Any ideas? lines=open(path, "r").readlines() for line in lines[1:]: linex=line.strip().split("\t") linex.insert(0,'sometextindex') try: cursor.execute('INSERT INTO variants VALUES(%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) except: print 'line number=',a,linex
[ "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 date. In fact as of this question (I just checked), twisted.web.soap itself hasn't even been updated in 21 months! I would like to ask if anyone has any experience they would be willing to share with utilizing Twisted's superb asynchronous transport functionality with SUDS. It seems like plugging in a custom Twisted transport would be a natural fit in SUDS' Client.options.transport, I'm just having a hard time wrapping my head around it. I did come up with a way to call the SOAP method with SUDS asynchronously by utilizing twisted.internet.threads.deferToThread(), but this feels like a hack to me. Here is an example of what I've done, to give you an idea: # netscaler is a module I wrote using suds to interface with NetScaler SOAP # Source: http://bitbucket.org/jathanism/netscaler-api/src import netscaler import os import sys from twisted.internet import reactor, defer, threads # netscaler.API is the class that sets up the suds.client.Client object host = 'netscaler.local' username = password = 'nsroot' wsdl_url = 'file://' + os.path.join(os.getcwd(), 'NSUserAdmin.wsdl') api = netscaler.API(host, username=username, password=password, wsdl_url=wsdl_url) results = [] errors = [] def handleResult(result): print '\tgot result: %s' % (result,) results.append(result) def handleError(err): sys.stderr.write('\tgot failure: %s' % (err,)) errors.append(err) # this converts the api.login() call to a Twisted thread. # api.login() should return True and is is equivalent to: # api.service.login(username=self.username, password=self.password) deferred = threads.deferToThread(api.login) deferred.addCallbacks(handleResult, handleError) reactor.run() This works as expected and defers return of the api.login() call until it is complete, instead of blocking. But as I said, it doesn't feel right. Thanks in advance for any help, guidance, feedback, criticism, insults, or total solutions. Update: The only solution I've found is twisted-suds, which is a fork of Suds modified to work with Twisted. A: 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 really what a SUDS/Twisted integration library is interested in. Instead, what you want is an HTTP client which SUDS can use to make the necessary requests and which presents all of the response data so that SUDS can determine what the result was. That is to say, SUDS doesn't really care about the raw bytes on the network. What it cares about is the HTTP requests and responses. If you examine the implementation of twisted.web.soap.Proxy (the client part of the Twisted Web SOAP API), you'll see that it doesn't really do much. It's about 20 lines of code that glues SOAPpy to twisted.web.client.getPage. That is, it's hooking SOAPpy in to Twisted in just the way I described above. Ideally, SUDS would provide some kind of API along the lines of SOAPpy.buildSOAP and SOAPpy.parseSOAPRPC (perhaps the APIs would be a bit more complicated, or accept a few more parameters - I'm not a SOAP expert, so I don't know if SOAPpy's particular APIs are missing something important - but the basic idea should be the same). Then you could write something like twisted.web.soap.Proxy based on SUDS instead. If twisted.web.client.getPage doesn't offer enough control over the requests or enough information about the responses, you could also use twisted.web.client.Agent instead, which is more recently introduced and offers much more control over the whole request/response process. But again, that's really the same idea as the current getPage-based code, just a more flexible/expressive implementation. Having just looked at the API documentation for Client.options.transport, it sounds like a SUDS transport is basically an HTTP client. The problem with this kind of integration is that SUDS wants to send a request and then be able to immediately get the response. Since Twisted is largely based on callbacks, a Twisted-based HTTP client API can't immediately return a response to SUDS. It can only return a Deferred (or equivalent). This is why things work better if the relationship is inverted. Instead of giving SUDS an HTTP client to play with, give SUDS and an HTTP client to a third piece of code and let it orchestrate the interactions. It may not be impossible to have things work by creating a Twisted-based SUDS transport (aka HTTP client), though. The fact that Twisted primarily uses Deferred (aka callbacks) to expose events doesn't mean that this is the only way it can work. By using a third-party library such as greenlet, it's possible to provide a coroutine-based API, where a request for an asynchronous operation involves switching execution from one coroutine to another, and events are delivered by switching back to the original coroutine. There is a project called corotwine which can do just this. It may be possible to use this to provide SUDS with the kind of HTTP client API it wants; however, it's not guaranteed. It depends on SUDS not breaking when a context switch is suddenly inserted where previously there was none. This is a very subtle and fragile property of SUDS and can easily be changed (unintentionally, even) by the SUDS developers in a future release, so it's probably not the ideal solution, even if you can get it to work now (unless you can get cooperation from the SUDS maintainers in the form of a promise to test their code in this kind of configuration to ensure it continues to work). As an aside, the reason Twisted Web's SOAP support is still based on SOAPpy and hasn't been modified for nearly two years is that no clear replacement for SOAPpy has ever shown up. There have been many contenders (What SOAP client libraries exist for Python, and where is the documentation for them? covers several of them). If things ever settle down, it may make sense to try to update Twisted's built-in SOAP support. Until then, I think it makes more sense to do these integration libraries separately, so they can be updated more easily and so Twisted itself doesn't end up with a big pile of different SOAP integration that no one wants (which would be worse than the current situation, where there's just one SOAP integration module that no one wants).
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.soap itself hasn't even been updated in 21 months! I would like to ask if anyone has any experience they would be willing to share with utilizing Twisted's superb asynchronous transport functionality with SUDS. It seems like plugging in a custom Twisted transport would be a natural fit in SUDS' Client.options.transport, I'm just having a hard time wrapping my head around it. I did come up with a way to call the SOAP method with SUDS asynchronously by utilizing twisted.internet.threads.deferToThread(), but this feels like a hack to me. Here is an example of what I've done, to give you an idea: # netscaler is a module I wrote using suds to interface with NetScaler SOAP # Source: http://bitbucket.org/jathanism/netscaler-api/src import netscaler import os import sys from twisted.internet import reactor, defer, threads # netscaler.API is the class that sets up the suds.client.Client object host = 'netscaler.local' username = password = 'nsroot' wsdl_url = 'file://' + os.path.join(os.getcwd(), 'NSUserAdmin.wsdl') api = netscaler.API(host, username=username, password=password, wsdl_url=wsdl_url) results = [] errors = [] def handleResult(result): print '\tgot result: %s' % (result,) results.append(result) def handleError(err): sys.stderr.write('\tgot failure: %s' % (err,)) errors.append(err) # this converts the api.login() call to a Twisted thread. # api.login() should return True and is is equivalent to: # api.service.login(username=self.username, password=self.password) deferred = threads.deferToThread(api.login) deferred.addCallbacks(handleResult, handleError) reactor.run() This works as expected and defers return of the api.login() call until it is complete, instead of blocking. But as I said, it doesn't feel right. Thanks in advance for any help, guidance, feedback, criticism, insults, or total solutions. Update: The only solution I've found is twisted-suds, which is a fork of Suds modified to work with Twisted.
[ "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 really what a SUDS/Twisted integration library is interested in. Instead, what you want is an HTTP client which SUDS can use to make the necessary requests and which presents all of the response data so that SUDS can determine what the result was. That is to say, SUDS doesn't really care about the raw bytes on the network. What it cares about is the HTTP requests and responses.\nIf you examine the implementation of twisted.web.soap.Proxy (the client part of the Twisted Web SOAP API), you'll see that it doesn't really do much. It's about 20 lines of code that glues SOAPpy to twisted.web.client.getPage. That is, it's hooking SOAPpy in to Twisted in just the way I described above.\nIdeally, SUDS would provide some kind of API along the lines of SOAPpy.buildSOAP and SOAPpy.parseSOAPRPC (perhaps the APIs would be a bit more complicated, or accept a few more parameters - I'm not a SOAP expert, so I don't know if SOAPpy's particular APIs are missing something important - but the basic idea should be the same). Then you could write something like twisted.web.soap.Proxy based on SUDS instead. If twisted.web.client.getPage doesn't offer enough control over the requests or enough information about the responses, you could also use twisted.web.client.Agent instead, which is more recently introduced and offers much more control over the whole request/response process. But again, that's really the same idea as the current getPage-based code, just a more flexible/expressive implementation.\nHaving just looked at the API documentation for Client.options.transport, it sounds like a SUDS transport is basically an HTTP client. The problem with this kind of integration is that SUDS wants to send a request and then be able to immediately get the response. Since Twisted is largely based on callbacks, a Twisted-based HTTP client API can't immediately return a response to SUDS. It can only return a Deferred (or equivalent).\nThis is why things work better if the relationship is inverted. Instead of giving SUDS an HTTP client to play with, give SUDS and an HTTP client to a third piece of code and let it orchestrate the interactions.\nIt may not be impossible to have things work by creating a Twisted-based SUDS transport (aka HTTP client), though. The fact that Twisted primarily uses Deferred (aka callbacks) to expose events doesn't mean that this is the only way it can work. By using a third-party library such as greenlet, it's possible to provide a coroutine-based API, where a request for an asynchronous operation involves switching execution from one coroutine to another, and events are delivered by switching back to the original coroutine. There is a project called corotwine which can do just this. It may be possible to use this to provide SUDS with the kind of HTTP client API it wants; however, it's not guaranteed. It depends on SUDS not breaking when a context switch is suddenly inserted where previously there was none. This is a very subtle and fragile property of SUDS and can easily be changed (unintentionally, even) by the SUDS developers in a future release, so it's probably not the ideal solution, even if you can get it to work now (unless you can get cooperation from the SUDS maintainers in the form of a promise to test their code in this kind of configuration to ensure it continues to work).\nAs an aside, the reason Twisted Web's SOAP support is still based on SOAPpy and hasn't been modified for nearly two years is that no clear replacement for SOAPpy has ever shown up. There have been many contenders (What SOAP client libraries exist for Python, and where is the documentation for them? covers several of them). If things ever settle down, it may make sense to try to update Twisted's built-in SOAP support. Until then, I think it makes more sense to do these integration libraries separately, so they can be updated more easily and so Twisted itself doesn't end up with a big pile of different SOAP integration that no one wants (which would be worse than the current situation, where there's just one SOAP integration module that no one wants).\n" ]
[ 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 Twisted factory to handle a protocol object for each port, I am trying to use a separate factory for each port. The reason for this is to force a separation among the groups of clients connecting to the different ports. Unfortunately, it appears that this architecture isn't quite working: clients that connect to one port appear to be available among all the factories (e.g., the protocol class used by each factory includes a 'self.factory.clients.append (self)' statement...instead of adding a given client to just the factory for a particular port, the client is added to all factories), and whenever I shutdown service on one port the listeners on all ports also stop. I've been working with Twisted for a short while, and fear I simply don't fully understand how its factory classes are managed. My question is: is it simply not possible to have multiple, simultaneous instances of the same factory and same protocol in use across different ports (without these instances stepping on each other's toes)? A: 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 self.clients = [] in your factory class's __init__ method.
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 for each port. The reason for this is to force a separation among the groups of clients connecting to the different ports. Unfortunately, it appears that this architecture isn't quite working: clients that connect to one port appear to be available among all the factories (e.g., the protocol class used by each factory includes a 'self.factory.clients.append (self)' statement...instead of adding a given client to just the factory for a particular port, the client is added to all factories), and whenever I shutdown service on one port the listeners on all ports also stop. I've been working with Twisted for a short while, and fear I simply don't fully understand how its factory classes are managed. My question is: is it simply not possible to have multiple, simultaneous instances of the same factory and same protocol in use across different ports (without these instances stepping on each other's toes)?
[ "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 wrapper simply calls a script that takes a data point's name and a file describing all the data points. That script then accesses the data point from the file and performs the computation. Since each job has to load the set of all points only to retrieve the point to be run, I wanted to optimize this step by serializing the file describing the set of points into an easily retrievable format. I tried using JSONpickle, using the following method, to serialize a dictionary describing all the data points to file: def json_serialize(obj, filename, use_jsonpickle=True): f = open(filename, 'w') if use_jsonpickle: import jsonpickle json_obj = jsonpickle.encode(obj) f.write(json_obj) else: simplejson.dump(obj, f, indent=1) f.close() The dictionary contains very simple objects (lists, strings, floats, etc.) and has a total of 54,000 keys. The json file is ~20 Megabytes in size. It takes ~20 seconds to load this file into memory, which seems very slow to me. I switched to using pickle with the same exact object, and found that it generates a file that's about 7.8 megabytes in size, and can be loaded in ~1-2 seconds. This is a significant improvement, but it still seems like loading of a small object (less than 100,000 entries) should be faster. Aside from that, pickle is not human readable, which was the big advantage of JSON for me. Is there a way to use JSON to get similar or better speed ups? If not, do you have other ideas on structuring this? (Is the right solution to simply "slice" the file describing each event into a separate file and pass that on to the script that runs a data point in a cluster job? It seems like that could lead to a proliferation of files). thanks. A: 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: import pickle import cPickle import marshal import json def maked(N=5400): d = {} for x in range(N): k = 'key%d' % x v = [x] * 5 d[k] = v return d d = maked() def marsh(): return marshal.dumps(d) def pick(): return pickle.dumps(d) def pick1(): return pickle.dumps(d, -1) def cpick(): return cPickle.dumps(d) def cpick1(): return cPickle.dumps(d, -1) def jso(): return json.dumps(d) def rep(): return repr(d) and here are their speeds on my laptop: $ py26 -mtimeit -s'import pik' 'pik.marsh()' 1000 loops, best of 3: 1.56 msec per loop $ py26 -mtimeit -s'import pik' 'pik.pick()' 10 loops, best of 3: 173 msec per loop $ py26 -mtimeit -s'import pik' 'pik.pick1()' 10 loops, best of 3: 241 msec per loop $ py26 -mtimeit -s'import pik' 'pik.cpick()' 10 loops, best of 3: 21.8 msec per loop $ py26 -mtimeit -s'import pik' 'pik.cpick1()' 100 loops, best of 3: 10 msec per loop $ py26 -mtimeit -s'import pik' 'pik.jso()' 10 loops, best of 3: 138 msec per loop $ py26 -mtimeit -s'import pik' 'pik.rep()' 100 loops, best of 3: 13.1 msec per loop so, you can have readability and ten times the speed of json.dumps with repr (you sacrifice the ease of parsing from Javascript and other languages); you can have the absolute maximum speed with marshal, almost 90 times faster than json; cPickle offers way more generality (in terms of what you can serialize) than either json or marshal, but if you're never going to use that generality then you might as well go for marshal (or repr if human readability trumps speed). As for your "slicing" idea, in lieu of a multitude of files, you might want to consider a database (a multitude of records) -- you might even get away without actual serialization if you're running with data that has some recognizable "schema" to it. A: I think you are facing a trade-off here: human-readability comes at the cost of performance and large file size. Thus, of all the serialization methods available in Python, JSON is not only the most readable, it is also the slowest. If I had to pursue performance (and file compactness), I'd go for marshall. You can either marshal the whole set with dump() and load() or, building on your idea of slicing things up, marshal separate parts of the data set into separate files. This way you open the door for parallelization of the data processing -- if you feel so inclined. Of course, there are all kinds of restrictions and warnings in the documentation, so if you decide to play it safe, go for pickle.
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 data points. That script then accesses the data point from the file and performs the computation. Since each job has to load the set of all points only to retrieve the point to be run, I wanted to optimize this step by serializing the file describing the set of points into an easily retrievable format. I tried using JSONpickle, using the following method, to serialize a dictionary describing all the data points to file: def json_serialize(obj, filename, use_jsonpickle=True): f = open(filename, 'w') if use_jsonpickle: import jsonpickle json_obj = jsonpickle.encode(obj) f.write(json_obj) else: simplejson.dump(obj, f, indent=1) f.close() The dictionary contains very simple objects (lists, strings, floats, etc.) and has a total of 54,000 keys. The json file is ~20 Megabytes in size. It takes ~20 seconds to load this file into memory, which seems very slow to me. I switched to using pickle with the same exact object, and found that it generates a file that's about 7.8 megabytes in size, and can be loaded in ~1-2 seconds. This is a significant improvement, but it still seems like loading of a small object (less than 100,000 entries) should be faster. Aside from that, pickle is not human readable, which was the big advantage of JSON for me. Is there a way to use JSON to get similar or better speed ups? If not, do you have other ideas on structuring this? (Is the right solution to simply "slice" the file describing each event into a separate file and pass that on to the script that runs a data point in a cluster job? It seems like that could lead to a proliferation of files). thanks.
[ "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):\n k = 'key%d' % x\n v = [x] * 5\n d[k] = v\n return d\nd = maked()\n\ndef marsh():\n return marshal.dumps(d)\n\ndef pick():\n return pickle.dumps(d)\n\ndef pick1():\n return pickle.dumps(d, -1)\n\ndef cpick():\n return cPickle.dumps(d)\n\ndef cpick1():\n return cPickle.dumps(d, -1)\n\ndef jso():\n return json.dumps(d)\n\ndef rep():\n return repr(d)\n\nand here are their speeds on my laptop:\n$ py26 -mtimeit -s'import pik' 'pik.marsh()'\n1000 loops, best of 3: 1.56 msec per loop\n$ py26 -mtimeit -s'import pik' 'pik.pick()'\n10 loops, best of 3: 173 msec per loop\n$ py26 -mtimeit -s'import pik' 'pik.pick1()'\n10 loops, best of 3: 241 msec per loop\n$ py26 -mtimeit -s'import pik' 'pik.cpick()'\n10 loops, best of 3: 21.8 msec per loop\n$ py26 -mtimeit -s'import pik' 'pik.cpick1()'\n100 loops, best of 3: 10 msec per loop\n$ py26 -mtimeit -s'import pik' 'pik.jso()'\n10 loops, best of 3: 138 msec per loop\n$ py26 -mtimeit -s'import pik' 'pik.rep()'\n100 loops, best of 3: 13.1 msec per loop\n\nso, you can have readability and ten times the speed of json.dumps with repr (you sacrifice the ease of parsing from Javascript and other languages); you can have the absolute maximum speed with marshal, almost 90 times faster than json; cPickle offers way more generality (in terms of what you can serialize) than either json or marshal, but if you're never going to use that generality then you might as well go for marshal (or repr if human readability trumps speed).\nAs for your \"slicing\" idea, in lieu of a multitude of files, you might want to consider a database (a multitude of records) -- you might even get away without actual serialization if you're running with data that has some recognizable \"schema\" to it.\n", "I think you are facing a trade-off here: human-readability comes at the cost of performance and large file size. Thus, of all the serialization methods available in Python, JSON is not only the most readable, it is also the slowest. \nIf I had to pursue performance (and file compactness), I'd go for marshall. You can either marshal the whole set with dump() and load() or, building on your idea of slicing things up, marshal separate parts of the data set into separate files. This way you open the door for parallelization of the data processing -- if you feel so inclined.\nOf course, there are all kinds of restrictions and warnings in the documentation, so if you decide to play it safe, go for pickle.\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 operation on a database. So, for instance, I might have a create function: def create(self, opts, args): #I've left out the error handling. strtime = datetime.datetime.now().strftime("%D %H:%M") vals = (strtime, opts.message, opts.keywords, False) self.execute("insert into mytable values (?, ?, ?, ?)", vals) self.commit() Should my test case call this function, then execute the select sql to check that the row was entered? That sounds reasonable, but also makes the tests more difficult to maintain. Would you rewrite the function to return something and check for the return value? Thanks A: 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 1 is your work: constructing a SQL statement. So you can re-organize the code so that you can test just phase 1: def create_sql(self, opts, args): #I've left out the error handling. strtime = datetime.datetime.now().strftime("%D %H:%M") vals = (strtime, opts.message, opts.keywords, False) return "insert into mytable values (?, ?, ?, ?)", vals def create(self, opts, args): self.execute(*self.create_sql(opts, args)) self.commit() The create_sql function is phase 1, and now it's expressed in a way that lets you write tests directly against it: it takes values and returns values, so you can write unit tests that cover its functionality. The create function itself is now simpler, and need not be tested so exhaustively: you could have a few tests that show that it really does execute SQL properly, but you don't have to cover all the edge cases in create. BTW: This video from Pycon (Tests and Testability) might be interesting. A: I would definitely refactor this method for ease of testing -- for example, dependency injection might help: def create(self, opts, args, strtime=None, exec_and_commit=None): #I've left out the error handling. if strtime is None: strtime = datetime.datetime.now().strftime("%D %H:%M") vals = (strtime, opts.message, opts.keywords, False) if exec_and_commit is None: exec_and_commit = self.execute_and_commit exec_and_commit("insert into mytable values (?, ?, ?, ?)", vals) this of course assumes you have an execute_and_commit method that calls execute and then commit methods. This way, the testing code can inject a known value for strtime, and inject its own callable as exec_and_commit to verify that it gets called with the expected arguments. A: Generally, you like to have unit tests in place before refactoring, to ensure no breaking changes are made. And yet some refactoring may be needed to enable testability...an unfortunate paradox, one which has bit me before. That said, there are some small refactorings that may be done safely, without changing behaviour. Rename and extract are two. I recommend you take a look at Michael Feathers' book, Working with Legacy Code. It focuses on refactoring code for testability. The examples are in Java, but the concepts would apply just as well to Python. A: Not familiar with python syntax but if you are new to unit testing, the easiest way to start could be to extract a method that you pass in the command line args and get back the sql command. On this method you can test the part of your code where the real logic lies. Pass in different types of args and check the results against what the sql command should be. Once you start to get the taste of unit testing you can learn a bit about mocking and dependency injection to test if you correctly call the functions that updates the db. Hopefully you are more familiar with java c# syntax than i am with python syntax:) public string GetSqlCommand(string[] commandLineArgs) { //do your parsing here return sqlCommand; } [Test] public void emptyArgs_returnsEmptySqlCommand() { string expectedSqlCommand=""; assert.AreEqual(expectedSqlCommand, GetSqlCommand(new string[]) }
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, opts, args): #I've left out the error handling. strtime = datetime.datetime.now().strftime("%D %H:%M") vals = (strtime, opts.message, opts.keywords, False) self.execute("insert into mytable values (?, ?, ?, ?)", vals) self.commit() Should my test case call this function, then execute the select sql to check that the row was entered? That sounds reasonable, but also makes the tests more difficult to maintain. Would you rewrite the function to return something and check for the return value? Thanks
[ "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 1 is your work: constructing a SQL statement. So you can re-organize the code so that you can test just phase 1:\ndef create_sql(self, opts, args):\n #I've left out the error handling.\n strtime = datetime.datetime.now().strftime(\"%D %H:%M\")\n vals = (strtime, opts.message, opts.keywords, False)\n return \"insert into mytable values (?, ?, ?, ?)\", vals\n\ndef create(self, opts, args):\n self.execute(*self.create_sql(opts, args))\n self.commit()\n\nThe create_sql function is phase 1, and now it's expressed in a way that lets you write tests directly against it: it takes values and returns values, so you can write unit tests that cover its functionality. The create function itself is now simpler, and need not be tested so exhaustively: you could have a few tests that show that it really does execute SQL properly, but you don't have to cover all the edge cases in create. \nBTW: This video from Pycon (Tests and Testability) might be interesting.\n", "I would definitely refactor this method for ease of testing -- for example, dependency injection might help:\ndef create(self, opts, args, strtime=None, exec_and_commit=None):\n #I've left out the error handling.\n if strtime is None:\n strtime = datetime.datetime.now().strftime(\"%D %H:%M\")\n vals = (strtime, opts.message, opts.keywords, False)\n if exec_and_commit is None:\n exec_and_commit = self.execute_and_commit\n exec_and_commit(\"insert into mytable values (?, ?, ?, ?)\", vals)\n\nthis of course assumes you have an execute_and_commit method that calls execute and then commit methods.\nThis way, the testing code can inject a known value for strtime, and inject its own callable as exec_and_commit to verify that it gets called with the expected arguments.\n", "Generally, you like to have unit tests in place before refactoring, to ensure no breaking changes are made. And yet some refactoring may be needed to enable testability...an unfortunate paradox, one which has bit me before.\nThat said, there are some small refactorings that may be done safely, without changing behaviour. Rename and extract are two.\nI recommend you take a look at Michael Feathers' book, Working with Legacy Code. It focuses on refactoring code for testability. The examples are in Java, but the concepts would apply just as well to Python.\n", "Not familiar with python syntax but if you are new to unit testing, the easiest way to start could be to extract a method that you pass in the command line args and get back the sql command. On this method you can test the part of your code where the real logic lies.\nPass in different types of args and check the results against what the sql command should be. Once you start to get the taste of unit testing you can learn a bit about mocking and dependency injection to test if you correctly call the functions that updates the db.\nHopefully you are more familiar with java c# syntax than i am with python syntax:) \npublic string GetSqlCommand(string[] commandLineArgs)\n{\n //do your parsing here\n return sqlCommand;\n}\n[Test]\npublic void emptyArgs_returnsEmptySqlCommand()\n{\n string expectedSqlCommand=\"\";\n assert.AreEqual(expectedSqlCommand, GetSqlCommand(new string[])\n}\n\n" ]
[ 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.Checked and Qt.Unchecked are toggled on edit. class cboxModel(QtCore.QAbstractListModel): def __init__(self, parent=None): super(cboxModel, self).__init__(parent) self.cboxes = [ ['a',0], ['b',1], ['c',2], ['d',0] ] def rowCount(self,index=QtCore.QModelIndex()): return len(self.cboxes) def data(self,index,role): if not index.isValid: return QtCore.QVariant() myname,mystate = self.cboxes[index.row()] if role == QtCore.Qt.DisplayRole: return QtCore.QVariant(myname) if role == QtCore.Qt.CheckStateRole: if mystate == 0: return QtCore.QVariant(QtCore.Qt.Unchecked) elif mystate == 1: return QtCore.QVariant(QtCore.Qt.PartiallyChecked) elif mystate == 2: return QtCore.QVariant(QtCore.Qt.Checked) return QtCore.QVariant() def setData(self,index,value,role=QtCore.Qt.EditRole): if index.isValid(): self.cboxes[index.row()][1] = value.toInt()[0] self.emit(QtCore.SIGNAL("dataChanged(QModelIndex,QModelIndex)"), index, index) print self.cboxes return True return False def flags(self,index): if not index.isValid(): return QtCore.Qt.ItemIsEditable return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsTristate You can test it with this, class MainForm(QtGui.QMainWindow): def __init__(self, parent=None): super(MainForm, self).__init__(parent) model = cboxModel(self) self.view = QtGui.QListView() self.view.setModel(model) self.setCentralWidget(self.view) app = QtGui.QApplication(sys.argv) form = MainForm() form.show() app.exec_() and see that only 2 states are available. I'm assuming there's something simple I'm missing. Any ideas? Thanks! A: 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. A: Looks like it's a known issue, check here: 108755 - Qt::ItemIsTristate fails to set checkboxs within a model view to being Tristate
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(QtCore.QAbstractListModel): def __init__(self, parent=None): super(cboxModel, self).__init__(parent) self.cboxes = [ ['a',0], ['b',1], ['c',2], ['d',0] ] def rowCount(self,index=QtCore.QModelIndex()): return len(self.cboxes) def data(self,index,role): if not index.isValid: return QtCore.QVariant() myname,mystate = self.cboxes[index.row()] if role == QtCore.Qt.DisplayRole: return QtCore.QVariant(myname) if role == QtCore.Qt.CheckStateRole: if mystate == 0: return QtCore.QVariant(QtCore.Qt.Unchecked) elif mystate == 1: return QtCore.QVariant(QtCore.Qt.PartiallyChecked) elif mystate == 2: return QtCore.QVariant(QtCore.Qt.Checked) return QtCore.QVariant() def setData(self,index,value,role=QtCore.Qt.EditRole): if index.isValid(): self.cboxes[index.row()][1] = value.toInt()[0] self.emit(QtCore.SIGNAL("dataChanged(QModelIndex,QModelIndex)"), index, index) print self.cboxes return True return False def flags(self,index): if not index.isValid(): return QtCore.Qt.ItemIsEditable return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsTristate You can test it with this, class MainForm(QtGui.QMainWindow): def __init__(self, parent=None): super(MainForm, self).__init__(parent) model = cboxModel(self) self.view = QtGui.QListView() self.view.setModel(model) self.setCentralWidget(self.view) app = QtGui.QApplication(sys.argv) form = MainForm() form.show() app.exec_() and see that only 2 states are available. I'm assuming there's something simple I'm missing. Any ideas? Thanks!
[ "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:\n108755 - Qt::ItemIsTristate fails to set checkboxs within a model view to being Tristate\n" ]
[ 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 float: 10 <= number < 20 print random.uniform(10, 20), # random integer: 100 <= number <= 1000 print random.randint(100, 1000), # random integer: even numbers in 100 <= number < 1000 print random.randrange(100, 1000, 2) I'm now receiving the following error: C:\Users\Developer\Documents\PythonDemo>python random.py Traceback (most recent call last): File "random.py", line 3, in <module> import random File "C:\Users\Developer\Documents\PythonDemo\random.py", line 8, in <module> print random.random(), TypeError: 'module' object is not callable C:\Users\Developer\Documents\PythonDemo> I've looked at the Python docs and this version of Python supports random. Is there something else I'm missing? A: 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. A: Rename your sample program file to myrandom.py or something. You are confusing import I would bet. A: Edit: Looks like you have same name with built-in random module, so you should change filename to something else as others suggested but after that, you still need to change your codes to initiate Random class rand=random.Random() rand.uniform(10, 20) and also for others because you are calling module itself, instead of Random class >>> for i in range(5): ... # random float: 0.0 <= number < 1.0 ... print rand.random(), ... ... # random float: 10 <= number < 20 ... print rand.uniform(10, 20), ... ... # random integer: 100 <= number <= 1000 ... print rand.randint(100, 1000), ... ... # random integer: even numbers in 100 <= number < 1000 ... print rand.randrange(100, 1000, 2) ... 0.024357795662 12.3296648076 886 478 0.698607283236 16.7373296747 245 638 0.69796131038 14.739388574 888 482 0.543171786714 11.3463795339 106 744 0.752849564435 19.4115177118 998 780 >>> A: You script is importing itself since it is named random.py and then trying to call itself as a method. Rename your script to something else (like test.py) and it will work.
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 print random.randint(100, 1000), # random integer: even numbers in 100 <= number < 1000 print random.randrange(100, 1000, 2) I'm now receiving the following error: C:\Users\Developer\Documents\PythonDemo>python random.py Traceback (most recent call last): File "random.py", line 3, in <module> import random File "C:\Users\Developer\Documents\PythonDemo\random.py", line 8, in <module> print random.random(), TypeError: 'module' object is not callable C:\Users\Developer\Documents\PythonDemo> I've looked at the Python docs and this version of Python supports random. Is there something else I'm missing?
[ "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 would bet.\n", "Edit: Looks like you have same name with built-in random module, so you should change filename to something else as others suggested\nbut after that, you still need to change your codes to initiate Random class\nrand=random.Random()\n\nrand.uniform(10, 20)\n\nand also for others because you are calling module itself, instead of Random class\n>>> for i in range(5):\n... # random float: 0.0 <= number < 1.0\n... print rand.random(),\n...\n... # random float: 10 <= number < 20\n... print rand.uniform(10, 20),\n...\n... # random integer: 100 <= number <= 1000\n... print rand.randint(100, 1000),\n...\n... # random integer: even numbers in 100 <= number < 1000\n... print rand.randrange(100, 1000, 2)\n...\n0.024357795662 12.3296648076 886 478\n0.698607283236 16.7373296747 245 638\n0.69796131038 14.739388574 888 482\n0.543171786714 11.3463795339 106 744\n0.752849564435 19.4115177118 998 780\n>>>\n\n", "You script is importing itself since it is named random.py and then trying to call itself as a method. Rename your script to something else (like test.py) and it will work.\n" ]
[ 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 \xaa equals chr(0xaa), i.e., chr(16 * 10 + 10) -- a small raised lowercase 'a' character. Escape sequences are documented in a short table here in the Python docs.
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 system-wide site-packages, no problem. I have installed Django into the project's virtualenv and I am able to use all the "> python manage.py" commands easily when I activate the virtualenv with the "VIRTUALENV\Scripts\activate.bat" script. I have a fabric tasks file (fabfile.py) in my project that provides tasks for setup, test, deploy, etc. Some of the tasks in my fabfile need to access the settings of my django project through "from django.conf import settings". Since the only usable Fabric install I have is in my system-wide site-packages, I need to activate the virtualenv within my fabfile so django becomes available. To do this, I use the "activate_this" module of the project's virtualenv in order to have access to the project settings and such. Using "print sys.path" before and after I execute activate_this.py, I can tell the python path changes to point to the virtualenv for the project. However, I still cannot import django.conf.settings. I have been able to successfully do this on *nix (Ubuntu and CentOS) and in Cygwin. Do you use this setup/workflow on Windows? If so Can you help me figure out why this wont work on Windows or provide any tips and tricks to get around this issue? Thanks and Cheers. REF: http://virtualenv.openplans.org/#id9 | Using Virtualenv without bin/python Local development environment: Python 2.5.4 Virtualenv 1.4.6 Fabric 0.9.0 Pip 0.6.1 Django 1.1.1 Windows XP (SP3) A: 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 Windows. In this case the activate_this.py script adds the *nix style path: VIRTUALENV_BASE/lib/python2.5/site-packages/ to the python path instead of the Windows specific path: VIRTUALENV_BASE\Lib\site-packages\ I have created an issue in the virtualenv issue tracker which outlines the problem and the solution. If you are interested, you may check on the issue here: http://bitbucket.org/ianb/virtualenv/issue/31/windows-activate_this-assumes-nix-path-to-site Hopefully the fix will be made available in an upcomming release of virtualenv. If you need a fix for this problem right now, and the virtualenv package has not yet been patched, you may "fix" your own activate_this.py as shown below. Edit your VIRTUALENV\Scripts\activate_this.py file. Change the line (17 ?): site_packages = os.path.join(base, 'lib', 'python%s' % sys.version[:3], 'site-packages') to if sys.platform == 'win32': site_packages = os.path.join(base, 'Lib', 'site-packages') else: site_packages = os.path.join(base, 'lib', 'python%s' % sys.version[:3], 'site-packages') With this in place, your activate_this.py script would first check which platform it is running on and then tailor the path to the site-packages directory to fit. Enjoy! A: You will have to execute the activate this, from within the fab file. Altho' I have not tested it, I believe following should work: activate_this = '/path/to/env/bin/activate_this.py' execfile(activate_this, dict(__file__=activate_this))
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 virtualenv and I am able to use all the "> python manage.py" commands easily when I activate the virtualenv with the "VIRTUALENV\Scripts\activate.bat" script. I have a fabric tasks file (fabfile.py) in my project that provides tasks for setup, test, deploy, etc. Some of the tasks in my fabfile need to access the settings of my django project through "from django.conf import settings". Since the only usable Fabric install I have is in my system-wide site-packages, I need to activate the virtualenv within my fabfile so django becomes available. To do this, I use the "activate_this" module of the project's virtualenv in order to have access to the project settings and such. Using "print sys.path" before and after I execute activate_this.py, I can tell the python path changes to point to the virtualenv for the project. However, I still cannot import django.conf.settings. I have been able to successfully do this on *nix (Ubuntu and CentOS) and in Cygwin. Do you use this setup/workflow on Windows? If so Can you help me figure out why this wont work on Windows or provide any tips and tricks to get around this issue? Thanks and Cheers. REF: http://virtualenv.openplans.org/#id9 | Using Virtualenv without bin/python Local development environment: Python 2.5.4 Virtualenv 1.4.6 Fabric 0.9.0 Pip 0.6.1 Django 1.1.1 Windows XP (SP3)
[ "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 Windows.\nIn this case the activate_this.py script adds the *nix style path:\nVIRTUALENV_BASE/lib/python2.5/site-packages/\nto the python path instead of the Windows specific path:\nVIRTUALENV_BASE\\Lib\\site-packages\\\nI have created an issue in the virtualenv issue tracker which outlines the problem and the solution. If you are interested, you may check on the issue here: http://bitbucket.org/ianb/virtualenv/issue/31/windows-activate_this-assumes-nix-path-to-site\nHopefully the fix will be made available in an upcomming release of virtualenv.\n\nIf you need a fix for this problem right now, and the virtualenv package has not yet been patched, you may \"fix\" your own activate_this.py as shown below.\nEdit your VIRTUALENV\\Scripts\\activate_this.py file. Change the line (17 ?):\nsite_packages = os.path.join(base, 'lib', 'python%s' % sys.version[:3], 'site-packages')\n\nto\nif sys.platform == 'win32':\n site_packages = os.path.join(base, 'Lib', 'site-packages')\nelse:\n site_packages = os.path.join(base, 'lib', 'python%s' % sys.version[:3], 'site-packages')\n\nWith this in place, your activate_this.py script would first check which platform it is running on and then tailor the path to the site-packages directory to fit.\nEnjoy!\n", "You will have to execute the activate this, from within the fab file. Altho' I have not tested it, I believe following should work:\nactivate_this = '/path/to/env/bin/activate_this.py'\nexecfile(activate_this, dict(__file__=activate_this))\n\n" ]
[ 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 runs in a distributed process, across a testbed of multiple servers. I'm trying to understand scrapy, to see if it provides benefits over what I'm doing. So, if possible, I'd really like to talk with a few people who are grounded in/or who use scrapy. A: A good place to send an email would be their Google Group. There will likely be many users to help answer your general questions. They also have an IRC channel for more rapid and direct interaction.
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, across a testbed of multiple servers. I'm trying to understand scrapy, to see if it provides benefits over what I'm doing. So, if possible, I'd really like to talk with a few people who are grounded in/or who use scrapy.
[ "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 a particular element i could refer to a field that doesn't exist at that index (referring to appearance when an instance of temp is stored in that index). i have come up with a method of testing this, but it is long winded and requires a second matrix. Is there a function to test for the existence of a field in a class? class temp(): name = "default" class temp1(): appearance = "@" A: 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 seems strange. However, this does answer your question as asked. A: Are you looking for: isinstance(object, classinfo) Return true if the object argument is an instance of the classinfo argument, or of a (direct or indirect) subclass thereof. Also return true if classinfo is a type object (new-style class) and object is an object of that type or of a (direct or indirect) subclass thereof. If object is not a class instance or an object of the given type, the function always returns false. If classinfo is neither a class object nor a type object, it may be a tuple of class or type objects, or may recursively contain other such tuples (other sequence types are not accepted). If classinfo is not a class, type, or tuple of classes, types, and such tuples, a TypeError exception is raised. Whatever you're trying to do doesn't seem like a good idea. Please describe your original need in more detail, and we'll help you come up with a better design. A: You could use exception handling to do this as well. try: val = x.name except AttributeError: val = x.appearance
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 doesn't exist at that index (referring to appearance when an instance of temp is stored in that index). i have come up with a method of testing this, but it is long winded and requires a second matrix. Is there a function to test for the existence of a field in a class? class temp(): name = "default" class temp1(): appearance = "@"
[ "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 seems strange. However, this does answer your question as asked.\n", "Are you looking for:\n\nisinstance(object, classinfo)\nReturn\ntrue if the object argument is an\ninstance of the classinfo argument, or\nof a (direct or indirect) subclass\nthereof. Also return true if classinfo\nis a type object (new-style class) and\nobject is an object of that type or of\na (direct or indirect) subclass\nthereof. If object is not a class\ninstance or an object of the given\ntype, the function always returns\nfalse. If classinfo is neither a class\nobject nor a type object, it may be a\ntuple of class or type objects, or may\nrecursively contain other such tuples\n(other sequence types are not\naccepted). If classinfo is not a\nclass, type, or tuple of classes,\ntypes, and such tuples, a TypeError\nexception is raised.\n\nWhatever you're trying to do doesn't seem like a good idea. Please describe your original need in more detail, and we'll help you come up with a better design.\n", "You could use exception handling to do this as well.\ntry:\n val = x.name\nexcept AttributeError:\n val = x.appearance\n\n" ]
[ 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? A: 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: for j, i in enumerate(x): Note that this gives the index of x first, so I've reversed j, i. A: You might want to use zip for i,j in zip(x,range(0,len(x))): Example, >>> x = [1, 2, 3] >>> y = [4, 5, 6] >>> zipped = zip(x, y) >>> print zipped [(1, 4), (2, 5), (3, 6)] >>> for a,b in zipped: ... print a,b ... 1 4 2 5 3 6 >>> Note: The correct answer for this question is enumerate as other mentioned, zip is general option to have multiple items in a single loop A: for i,j in enumerate(x)
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 in zip(x,range(0,len(x))):\n\nExample,\n>>> x = [1, 2, 3]\n>>> y = [4, 5, 6]\n>>> zipped = zip(x, y)\n>>> print zipped\n[(1, 4), (2, 5), (3, 6)]\n>>> for a,b in zipped:\n... print a,b\n...\n1 4\n2 5\n3 6\n>>>\n\nNote: The correct answer for this question is enumerate as other mentioned, zip is general option to have multiple items in a single loop\n", "for i,j in enumerate(x)\n\n" ]
[ 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. However, this particular binding is fairly new, and doesn't seem to have a real home page. A: You might want to check out this Qt Quarterly post - Poppler: Displaying PDF Files with Qt that explains how to do this in Qt. It's in C++ but I see poppler has Python bindings so it shouldn't be a problem to port the example code in the post to Python. A: Reportlab - http://www.reportlab.com/software/opensource/
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 explains how to do this in Qt. It's in C++ but I see poppler has Python bindings so it shouldn't be a problem to port the example code in the post to Python.\n", "Reportlab - http://www.reportlab.com/software/opensource/\n" ]
[ 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('<label>My name is Jim</label><em>Hi</em>') True >> verify_target('<em>Hi<label>My name is Jim</label></em>') False A: I would get rid of Regex and look at Beautiful Soup. findAll(True) lists all the tags found in your source. from BeautifulSoup import BeautifulSoup soup = BeautifulSoup(source) allTags = soup.findAll(True) [tag.name for tag in allTags ] [u'em', u'label'] then you just need to remove possible duplicates and confront your tags lists. This snippet verifies that ALL of source's tags are present in target's tags. from BeautifulSoup import BeautifulSoup def get_tags_set(source): soup = BeautifulSoup(source) all_tags = soup.findAll(True) return set([tag.name for tag in all_tags]) def verify(tags_source_orig, tags_source_to_verify): return tags_source_orig == set.intersection(tags_source_orig, tags_source_to_verify) source= '<label>What\'s your name</label><label>What\'s your name</label><em>Hello</em>' source_to_verify= '<em>Hello</em><label>What\'s your name</label><label>What\'s your name</label>' print verify(get_tags_set(source),get_tags_set(source_to_verify)) A: I don't think that regex is the right way here, basically because html is not always just a string, but it's a bit more complex, with nested tags. I suggest you to use HTMLParser, create a class with parses the original source and builds a structure on it. Then verify that the same data structure is valid for the targets to be verified.
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_target('<em>Hi<label>My name is Jim</label></em>') False
[ "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 and confront your tags lists.\nThis snippet verifies that ALL of source's tags are present in target's tags.\nfrom BeautifulSoup import BeautifulSoup\ndef get_tags_set(source):\n soup = BeautifulSoup(source)\n all_tags = soup.findAll(True)\n return set([tag.name for tag in all_tags])\n\ndef verify(tags_source_orig, tags_source_to_verify):\n return tags_source_orig == set.intersection(tags_source_orig, tags_source_to_verify)\n\nsource= '<label>What\\'s your name</label><label>What\\'s your name</label><em>Hello</em>'\nsource_to_verify= '<em>Hello</em><label>What\\'s your name</label><label>What\\'s your name</label>'\nprint verify(get_tags_set(source),get_tags_set(source_to_verify))\n\n", "I don't think that regex is the right way here, basically because html is not always just a string, but it's a bit more complex, with nested tags.\nI suggest you to use HTMLParser, create a class with parses the original source and builds a structure on it. Then verify that the same data structure is valid for the targets to be verified.\n" ]
[ 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 have vendor specific types for some database drivers. And sure, you can use Integer. Initializing different classes based based on column value is easy. What you need for this particular case is single table inheritance.
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 looking into the official launchpadlib, instead of rolling your own solution. A: You could check bzrlib it has some integration with launchpad.
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 understand this code, know that the variable path contains the full path to my data set which, when loaded, gives me a variable called immgen. Know that immgen is an object (a Bioconductor ExpressionSet object) and that exprs(immgen) returns a data frame with 125 columns (experiments) and tens of thousands of rows (named genes). (Just in case it's not clear, this is Python code, using robjects.r to call R code) import numpy as np import rpy2.robjects as robjects # ... some code to build path robjects.r("load('%s')"%path) # loads immgen e = robjects.r['data.frame']("exprs(immgen)") expression_data = np.array(e) This code runs, but expression_data is simply array([[1]]). I'm pretty sure that e doesn't represent the data frame generated by exprs() due to things like: In [40]: e._get_ncol() Out[40]: 1 In [41]: e._get_nrow() Out[41]: 1 But then again who knows? Even if e did represent my data.frame, that it doesn't convert straight to an array would be fair enough - a data frame has more in it than an array (rownames and colnames) and so maybe life shouldn't be this easy. However I still can't work out how to perform the conversion. The documentation is a bit too terse for me, though my limited understanding of the headings in the docs implies that this should be possible. Anyone any thoughts? A: This is the most straightforward and reliable way i've found to to transfer a data frame from R to Python. To 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 format is the only common interface required here. data(iris) iris$Species = unclass(iris$Species) write.table(iris, file="/path/to/my/file/np_iris.txt", row.names=F, sep=",") # now start a python session import numpy as NP fpath = "/path/to/my/file/np_iris.txt" A = NP.loadtxt(fpath, comments="#", delimiter=",", skiprows=1) # print(type(A)) # returns: <type 'numpy.ndarray'> print(A.shape) # returns: (150, 5) print(A[1:5,]) # returns: [[ 4.9  3.   1.4  0.2  1. ] [ 4.7  3.2  1.3  0.2  1. ] [ 4.6  3.1  1.5  0.2  1. ] [ 5.   3.6  1.4  0.2  1. ]] According to the Documentation (and my own experience for what it's worth) loadtxt is the preferred method for conventional data import. You can also pass in to loadtxt a tuple of data types (the argument is dtypes), one item in the tuple for each column. Notice 'skiprows=1' to step over the column headers (for loadtxt rows are indexed from 1, columns from 0). Finally, i converted the dataframe factor to integer (which is actually the underlying data type for factor) prior to exporting--'unclass' is probably the easiest way to do this. If you have big data (ie, don't want to load the entire data file into memory but still need to access it) NumPy's memory-mapped data structure ('memmap') is a good choice: from tempfile import mkdtemp import os.path as path filename = path.join(mkdtemp(), 'tempfile.dat') # now create a memory-mapped file with shape and data type # based on original R data frame: A = NP.memmap(fpath, dtype="float32", mode="w+", shape=(150, 5)) # methods are ' flush' (writes to disk any changes you make to the array), and 'close' # to write data to the memmap array (acdtually an array-like memory-map to # the data stored on disk) A[:] = somedata[:] A: Why going through a data.frame when 'exprs(immgen)' returns a /matrix/ and your end goal is to have your data in a matrix ? Passing the matrix to numpy is straightforward (and can even be made without making a copy): http://rpy.sourceforge.net/rpy2/doc-2.1/html/numpy.html#from-rpy2-to-numpy This should beat in both simplicity and efficiency the suggestion of going through text representation of numerical data in flat files as a way to exchange data. You seem to be working with bioconductor classes, and might be interested in the following: http://pypi.python.org/pypi/rpy2-bioconductor-extensions/
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 contains the full path to my data set which, when loaded, gives me a variable called immgen. Know that immgen is an object (a Bioconductor ExpressionSet object) and that exprs(immgen) returns a data frame with 125 columns (experiments) and tens of thousands of rows (named genes). (Just in case it's not clear, this is Python code, using robjects.r to call R code) import numpy as np import rpy2.robjects as robjects # ... some code to build path robjects.r("load('%s')"%path) # loads immgen e = robjects.r['data.frame']("exprs(immgen)") expression_data = np.array(e) This code runs, but expression_data is simply array([[1]]). I'm pretty sure that e doesn't represent the data frame generated by exprs() due to things like: In [40]: e._get_ncol() Out[40]: 1 In [41]: e._get_nrow() Out[41]: 1 But then again who knows? Even if e did represent my data.frame, that it doesn't convert straight to an array would be fair enough - a data frame has more in it than an array (rownames and colnames) and so maybe life shouldn't be this easy. However I still can't work out how to perform the conversion. The documentation is a bit too terse for me, though my limited understanding of the headings in the docs implies that this should be possible. Anyone any thoughts?
[ "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 format is the only common interface required here.\ndata(iris)\niris$Species = unclass(iris$Species)\n\nwrite.table(iris, file=\"/path/to/my/file/np_iris.txt\", row.names=F, sep=\",\")\n\n# now start a python session\nimport numpy as NP\n\nfpath = \"/path/to/my/file/np_iris.txt\"\n\nA = NP.loadtxt(fpath, comments=\"#\", delimiter=\",\", skiprows=1)\n\n# print(type(A))\n# returns: <type 'numpy.ndarray'>\n\nprint(A.shape)\n# returns: (150, 5)\n\nprint(A[1:5,])\n# returns: \n [[ 4.9  3.   1.4  0.2  1. ]\n [ 4.7  3.2  1.3  0.2  1. ]\n [ 4.6  3.1  1.5  0.2  1. ]\n [ 5.   3.6  1.4  0.2  1. ]]\n\nAccording to the Documentation (and my own experience for what it's worth) loadtxt is the preferred method for conventional data import.\nYou can also pass in to loadtxt a tuple of data types (the argument is dtypes), one item in the tuple for each column. Notice 'skiprows=1' to step over the column headers (for loadtxt rows are indexed from 1, columns from 0).\nFinally, i converted the dataframe factor to integer (which is actually the underlying data type for factor) prior to exporting--'unclass' is probably the easiest way to do this.\nIf you have big data (ie, don't want to load the entire data file into memory but still need to access it) NumPy's memory-mapped data structure ('memmap') is a good choice:\nfrom tempfile import mkdtemp\nimport os.path as path\n\nfilename = path.join(mkdtemp(), 'tempfile.dat')\n\n# now create a memory-mapped file with shape and data type \n# based on original R data frame:\nA = NP.memmap(fpath, dtype=\"float32\", mode=\"w+\", shape=(150, 5))\n\n# methods are ' flush' (writes to disk any changes you make to the array), and 'close'\n# to write data to the memmap array (acdtually an array-like memory-map to \n# the data stored on disk)\nA[:] = somedata[:]\n\n", "Why going through a data.frame when 'exprs(immgen)' returns a /matrix/ and your end goal is to have your data in a matrix ?\nPassing the matrix to numpy is straightforward (and can even be made without making a copy):\nhttp://rpy.sourceforge.net/rpy2/doc-2.1/html/numpy.html#from-rpy2-to-numpy\nThis should beat in both simplicity and efficiency the suggestion of going through text representation of numerical data in flat files as a way to exchange data.\nYou seem to be working with bioconductor classes, and might be interested in the following:\nhttp://pypi.python.org/pypi/rpy2-bioconductor-extensions/\n" ]
[ 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 however, shows a new python process running after I do this. Running scripts works fine, though. Do I need to use another Python shell, some other ssh server, some different configs? Thanks A: 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. However, try running "python -i" to overcome it. A: The problem is probably that you're running the Windows Python executable, which expects a Windows console environment to run in, over a channel which doesn't support the features of Windows console. You might find Andy Koppe's conin to be useful.
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 running after I do this. Running scripts works fine, though. Do I need to use another Python shell, some other ssh server, some different configs? Thanks
[ "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 channel which doesn't support the features of Windows console. You might find Andy Koppe's conin to be useful.\n" ]
[ 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 Django? A: 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: def my_custom_sql(self): from django.db import connection cursor = connection.cursor() cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz]) row = cursor.fetchone() return row For something more generic, create an abstract base model that defines a function like that with an "sql" parameter. A: The newest development version (future 1.2) has .raw() method to help you with that: Person.objects.raw('SELECT * FROM myapp_person') More information can be found under http://docs.djangoproject.com/en/dev/topics/db/sql/. A: Since the issue is "manually converting query results into objects," the simplest solution is often to see if your custom SQL can fit into an ORM .extra() call rather than being a pure-SQL query. Often it can, and then you let the ORM do all the work of building up objects as usual.
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 return row\n\nFor something more generic, create an abstract base model that defines a function like that with an \"sql\" parameter.\n", "The newest development version (future 1.2) has .raw() method to help you with that:\nPerson.objects.raw('SELECT * FROM myapp_person')\n\nMore information can be found under http://docs.djangoproject.com/en/dev/topics/db/sql/.\n", "Since the issue is \"manually converting query results into objects,\" the simplest solution is often to see if your custom SQL can fit into an ORM .extra() call rather than being a pure-SQL query. Often it can, and then you let the ORM do all the work of building up objects as usual.\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 commonPackage. I want to install the commonPackage into lib/site-packages, but I don't want it copys the source code. Instead, I want it creates a commonPackage.pth in lib/site-packages with the path of where the commonPackage at. So that when I modify commonPackage or update it from SVN, I don't need to install it again. Here comes the problem, how can I write the setup.py or use the options of python setup.py install so that it would do what I want? A: Oops, I just find exactly what I want here. The develop command of setuptools do what I said. Here you type python setup.py develop It creates .pth rather than copying everything into site-packages. A: You can always take a look at virtualenv which will allow you to create a python environment for each of your projects - this is the ideal way to develop/build/deploy your app without having load up your site-packages directory with all and sundry. There's a good tutorial here: http://iamzed.com/2009/05/07/a-primer-on-virtualenv/ Good luck !
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 want it copys the source code. Instead, I want it creates a commonPackage.pth in lib/site-packages with the path of where the commonPackage at. So that when I modify commonPackage or update it from SVN, I don't need to install it again. Here comes the problem, how can I write the setup.py or use the options of python setup.py install so that it would do what I want?
[ "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 of your projects - this is the ideal way to develop/build/deploy your app without having load up your site-packages directory with all and sundry.\nThere's a good tutorial here:\nhttp://iamzed.com/2009/05/07/a-primer-on-virtualenv/\nGood luck !\n" ]
[ 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# I would make this a static method. What's the most pythonic thing to do here? A: Moving it to a function is common, if it doesn't touch the class at all. If it manipulates class attributes, use the classmethod decorator: @classmethod def spam(cls, ...): # cls is the class, you can use it to get class attributes classmethod and staticmethod (which is the same as the former, except that the method doesn't get a reference to the class from its first parameter) have been introduced quite recently. It means that some Python programmers are used to avoid static and class methods. Some hardcore Python programmers will tell you that these decorators just complicate things; some other people (usually former C# or Java programmers) will tell you that using a function isn't object-oriented enough. I think it's just a matter of preference.
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 here?
[ "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 that the method doesn't get a reference to the class from its first parameter) have been introduced quite recently.\nIt means that some Python programmers are used to avoid static and class methods.\nSome hardcore Python programmers will tell you that these decorators just complicate things; some other people (usually former C# or Java programmers) will tell you that using a function isn't object-oriented enough.\nI think it's just a matter of preference.\n" ]
[ 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 _ImageCrop I've printed out.. : print x0, y0, x1, y1 self.__crop = x0, y0, x1, y1 Values seem to be correct. Input is a JPEG image of size 1600x2390. Python version: 2.5, PIL version: 1.1.6 Any suggestions? Thanks A: Works For Me: Python 2.6.1, PIL 1.1.6, JPEG of size 2020x1338 pixels. Are 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. A: I`m do next: cover=Image.open(path_to_cover+"/shablon1.jpg") .... def generit_nomer_proekt(self,nomer): size_box=(160,40) font=ImageFont.truetype('/home/vintello/workspace/mpg_to_dvd/src/cover/ttf/aricyr.ttf',int(30)) im = Image.new ( "RGB", size_box , "white" ) draw = ImageDraw.Draw ( im ) draw.text ( (20,0), unicode(nomer,"utf-8"), fill="#74716f", font=font ) return im ..... nazv_vert=self.generit_nomer_proekt(nomer) coo=nazv_vert.size left_x=1575 left_y=383 box_vert_nazv=(left_x,left_y,left_x+coo[0],left_y+coo[1]) cover.paste(nazv_vert,box_vert_nazv) or if you wont as PNG past use: cover.paste(nazv_vert,box_vert_nazv,nazv_vert)
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.. : print x0, y0, x1, y1 self.__crop = x0, y0, x1, y1 Values seem to be correct. Input is a JPEG image of size 1600x2390. Python version: 2.5, PIL version: 1.1.6 Any suggestions? Thanks
[ "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(path_to_cover+\"/shablon1.jpg\")\n\n....\ndef generit_nomer_proekt(self,nomer):\n size_box=(160,40)\n font=ImageFont.truetype('/home/vintello/workspace/mpg_to_dvd/src/cover/ttf/aricyr.ttf',int(30))\n im = Image.new ( \"RGB\", size_box , \"white\" )\n draw = ImageDraw.Draw ( im )\n draw.text ( (20,0), unicode(nomer,\"utf-8\"), fill=\"#74716f\", font=font )\n return im\n\n.....\nnazv_vert=self.generit_nomer_proekt(nomer)\ncoo=nazv_vert.size\nleft_x=1575\nleft_y=383\nbox_vert_nazv=(left_x,left_y,left_x+coo[0],left_y+coo[1])\ncover.paste(nazv_vert,box_vert_nazv)\n\nor if you wont as PNG past use:\ncover.paste(nazv_vert,box_vert_nazv,nazv_vert)\n\n" ]
[ 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 agent is simply a program that runs, and takes a file name as parameter. As far as I know, "send as attachment" is using some DLL/API called MAPI. I would need to change my app so that it does not simply accept file name arguments, but can receive MAPI(?) calls MS Word uses when "sending as attachment". Further, I need to change the default mail agent by creating my own MAPI32.dll stub which simply redirects to my app. I'd appreciate if anyone had more info on how this could be achieved! A: 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 __stdcall calling convention. Also critical is setting the right registry keys in order for you mapi dll to be chosen by the system stub, it looks like you've already found the right one in order to specify a particular mapi dll be used when your applicaion makes mapi calls. I did this exact thing just recently: wrote my own skeleton mapi dll, and had a lot of trouble getting the system stub to call my extended mapi functions. The key was that mapi32.dll calls GetProcAddress on the "foo@x" entry point, not the "foo" entrypoint in the mapi interface in order to test whether or not your dll is "compliant" with extended mapi (I think for simple mapi calls it does not use the "foo@x" but the plain "foo" entrypoint name). I also had to compile my skeleton library interface file in my project "As C" and not "As C++" in order to get all the symbol names right. For example, MAPIInitialize should be declared like this in your source code: HRESULT __stdcall MAPIInitialize( LPVOID lpMapiInit ) ... and you'll need to specify a .def file with entries like this: EXPORTS MAPIInitialize@4=_MAPIInitialize@4 MAPIInitialize=_MAPIInitialize@4 For simple mapi calls (as opposed to extended mapi calls), you may not need the "double export". In order to see what the exports look like for a working mapi implementation, you can do this (if you have outlook installed on your system): c:\> dumpbin /exports c:\Program Files\Common Files\SYSTEM\MSMAPI\1033\msmapi32.dll (or substitute the path you find in the registry in HKLM\Software\Clients\Mail\Microsoft Outlook\DLLPathEx) A: OK, to answer my own question. I need to build a DLL with "MAPISendDocuments" and/or "MAPISendMail" functions defined. This DLL can have any name, and is referenced in the registry at HKLM/Software/Clients/Mail/MyMailApp/DLLPath. Found examples using Delphi...
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 know, "send as attachment" is using some DLL/API called MAPI. I would need to change my app so that it does not simply accept file name arguments, but can receive MAPI(?) calls MS Word uses when "sending as attachment". Further, I need to change the default mail agent by creating my own MAPI32.dll stub which simply redirects to my app. I'd appreciate if anyone had more info on how this could be achieved!
[ "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 __stdcall calling convention. Also critical is setting the right registry keys in order for you mapi dll to be chosen by the system stub, it looks like you've already found the right one in order to specify a particular mapi dll be used when your applicaion makes mapi calls.\nI did this exact thing just recently: wrote my own skeleton mapi dll, and had a lot of trouble getting the system stub to call my extended mapi functions. The key was that mapi32.dll calls GetProcAddress on the \"foo@x\" entry point, not the \"foo\" entrypoint in the mapi interface in order to test whether or not your dll is \"compliant\" with extended mapi (I think for simple mapi calls it does not use the \"foo@x\" but the plain \"foo\" entrypoint name). I also had to compile my skeleton library interface file in my project \"As C\" and not \"As C++\" in order to get all the symbol names right. \nFor example, MAPIInitialize should be declared like this in your source code:\nHRESULT __stdcall MAPIInitialize( LPVOID lpMapiInit )\n...\n\nand you'll need to specify a .def file with entries like this:\nEXPORTS\n MAPIInitialize@4=_MAPIInitialize@4\n MAPIInitialize=_MAPIInitialize@4\n\nFor simple mapi calls (as opposed to extended mapi calls), you may not need the \"double export\". In order to see what the exports look like for a working mapi implementation, you can do this (if you have outlook installed on your system):\n\nc:\\> dumpbin /exports c:\\Program Files\\Common Files\\SYSTEM\\MSMAPI\\1033\\msmapi32.dll\n\n(or substitute the path you find in the registry in HKLM\\Software\\Clients\\Mail\\Microsoft Outlook\\DLLPathEx)\n", "OK, to answer my own question. I need to build a DLL with \"MAPISendDocuments\" and/or \"MAPISendMail\" functions defined.\nThis DLL can have any name, and is referenced in the registry at HKLM/Software/Clients/Mail/MyMailApp/DLLPath.\nFound examples using Delphi...\n" ]
[ 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 more rocks fall, until you lose. What I have so far is the chef and 1 rock falling. However, for some reason if the sprites collide, or if the rock touches the bottom of the screen, the game ends, without giving a game over message like I told it to. I'm very confused, and can't see what I did. I know that I did not code it correctly for the 2 rocks part, but I can't even get it to slightly run. Help! Here's what I have now: from livewires import games, color import random games.init(screen_width = 640, screen_height = 480, fps = 50) class Chef(games.Sprite): image = games.load_image("chef.bmp") def __init__(self): super(Chef, self).__init__(image = Chef.image, x = games.mouse.x, bottom = games.screen.height) def update(self): self.x = games.mouse.x if self.left < 0: self.left = 0 if self.right > games.screen.width: self.right = games.screen.width self.check_catch() def check_catch(self): for pizza in self.overlapping_sprites: if not self.bottom>games.screen.height: self.end_game() class Rock(games.Sprite): def update(self): if self.bottom > games.screen.height: new_rock=Rock(x=random.randrange(games.screen.width), y=10, dy=1) games.screen.add(new_rock) def end_game(self): end_message = games.Message(value = "Game Over", size = 90, color = color.red, x = games.screen.width/2, y = games.screen.height/2, lifetime = 5 * games.screen.fps, after_death = games.screen.quit) games.screen.add(end_message) def main(): wall_image = games.load_image("wall.jpg", transparent = False) games.screen.background = wall_image the_chef = Chef() games.screen.add(the_chef) rock_image=games.load_image("rock.bmp") the_rock=Rock(image=rock_image, x=random.randrange(games.screen.width), y=10, dy=1) games.screen.add(the_rock) games.mouse.is_visible = False games.screen.event_grab = True games.screen.mainloop() main() A: You have declared end_game method in Rock class but you are calling it from check_catch method of Chef class.
'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 you lose. What I have so far is the chef and 1 rock falling. However, for some reason if the sprites collide, or if the rock touches the bottom of the screen, the game ends, without giving a game over message like I told it to. I'm very confused, and can't see what I did. I know that I did not code it correctly for the 2 rocks part, but I can't even get it to slightly run. Help! Here's what I have now: from livewires import games, color import random games.init(screen_width = 640, screen_height = 480, fps = 50) class Chef(games.Sprite): image = games.load_image("chef.bmp") def __init__(self): super(Chef, self).__init__(image = Chef.image, x = games.mouse.x, bottom = games.screen.height) def update(self): self.x = games.mouse.x if self.left < 0: self.left = 0 if self.right > games.screen.width: self.right = games.screen.width self.check_catch() def check_catch(self): for pizza in self.overlapping_sprites: if not self.bottom>games.screen.height: self.end_game() class Rock(games.Sprite): def update(self): if self.bottom > games.screen.height: new_rock=Rock(x=random.randrange(games.screen.width), y=10, dy=1) games.screen.add(new_rock) def end_game(self): end_message = games.Message(value = "Game Over", size = 90, color = color.red, x = games.screen.width/2, y = games.screen.height/2, lifetime = 5 * games.screen.fps, after_death = games.screen.quit) games.screen.add(end_message) def main(): wall_image = games.load_image("wall.jpg", transparent = False) games.screen.background = wall_image the_chef = Chef() games.screen.add(the_chef) rock_image=games.load_image("rock.bmp") the_rock=Rock(image=rock_image, x=random.randrange(games.screen.width), y=10, dy=1) games.screen.add(the_rock) games.mouse.is_visible = False games.screen.event_grab = True games.screen.mainloop() main()
[ "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, 'CurrentDimensionUnits': App.Constants.UnitsOfMeasure.Pixels, 'CurrentResolutionUnits': App.Constants.ResolutionUnits.PixelsPerIn, 'Height': 1440, 'MaintainAspectRatio': True, 'Resample': True, 'ResampleType': App.Constants.ResampleType.SmartSize, 'ResizeAllLayers': True, 'Resolution': 72, 'Width': 1920, }) Using this code works perfectly if the aspect ratio of an image is the same as the one defined in the code - i.e. 1.33333. But how should I make it work with images that do not have this ratio? For me, what is important is that the new Width is 1920; Height has to be able to adjust automatically. Any ideas which part of my code should be altered and how? A: According to this forum post, the magic word is None – i.e. change 'Height': 1440, to 'Height': None, As we found out in the comments below, you also have to set AspectRatio to None.
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.UnitsOfMeasure.Pixels, 'CurrentResolutionUnits': App.Constants.ResolutionUnits.PixelsPerIn, 'Height': 1440, 'MaintainAspectRatio': True, 'Resample': True, 'ResampleType': App.Constants.ResampleType.SmartSize, 'ResizeAllLayers': True, 'Resolution': 72, 'Width': 1920, }) Using this code works perfectly if the aspect ratio of an image is the same as the one defined in the code - i.e. 1.33333. But how should I make it work with images that do not have this ratio? For me, what is important is that the new Width is 1920; Height has to be able to adjust automatically. Any ideas which part of my code should be altered and how?
[ "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 does not (unresolved externals on link). ############################## ifdef PYTHON DEFINES += -DFEAT_PYTHON INCLUDES += -I$(PYTHON)/include EXTRA_OBJS += $(OUTDIR)/if_python.o ifndef DYNAMIC_PYTHON DYNAMIC_PYTHON = yes endif ifndef PYTHON_VER PYTHON_VER = 30 endif ifeq (yes, $(DYNAMIC_PYTHON)) DEFINES += -DDYNAMIC_PYTHON -DDYNAMIC_PYTHON_DLL=\"python$(PYTHON_VER).dll\" else EXTRA_LIBS += $(PYTHON)/libs/python$(PYTHON_VER).lib endif endif However when running: $ make -f Make_cyg.mak OLE=Yes PYTHON=/cygdrive/p/Applications/PortablePython_1.1_py3.0.1/App/ RUBY=/cygdrive/c/Programme/Ruby/ this results in the following errors: In file included from /cygdrive/p/Applications/PortablePython_1.1_py3.0.1/App//i nclude/Python.h:70, from if_python.c:43: /cygdrive/p/Applications/PortablePython_1.1_py3.0.1/App//include/bytesobject.h:1 04:1: warning: "F_BLANK" redefined In file included from globals.h:1554, from vim.h:1831, from if_python.c:20: farsi.h:74:1: warning: this is the location of the previous definition if_python.c:729: warning: initialization makes integer from pointer without a ca st if_python.c:733: warning: initialization from incompatible pointer type if_python.c:734: warning: initialization from incompatible pointer type if_python.c:735: warning: initialization from incompatible pointer type if_python.c:737: error: `cmpfunc' undeclared here (not in a function) if_python.c:737: error: initializer element is not constant if_python.c:737: error: (near initialization for `OutputType.tp_repr') if_python.c:737: error: parse error before numeric constant /** more errors **/ if_python.c:2256: warning: initialization from incompatible pointer type if_python.c:2257: warning: initialization from incompatible pointer type if_python.c: In function `PythonMod_Init': if_python.c:2351: error: structure has no member named `ob_type' if_python.c:2352: error: structure has no member named `ob_type' if_python.c:2353: error: structure has no member named `ob_type' if_python.c:2354: error: structure has no member named `ob_type' if_python.c:2355: error: structure has no member named `ob_type' if_python.c:2356: error: structure has no member named `ob_type' make: *** [gobj/if_python.o] Error 1 I am using a portable python install from Portable Python. I don't know if that may be the source of the error. I am hoping someone knows how to compile vim with python 3 support (if I only compile it with ruby support it compiles nicely). Thanks in advance, Gjallar A: I have compiled vim with python3 support. Here is the Patch updated for vim 7.2.411. For compilation instruction check out my 2009 September 22 mail on groups.google.com/group/vim_dev/browse_frm/month/2009-09 (adding a second hyperlink didn't work) A: There is a lot of things going on at once here. First of all, why do you want Python 3.0? If you really want Python 3, then you should use Python 3.1. Second of all, what does "Python 3 support" mean in the case of gVim? Is it to make extensions with Python? Then you don't want Python 3 support, as any extension that exists for gVim is going to be written for Python 2. And yeah, it seems very strange to use portable python. Since you are compiling gVim with cygwin, you should reasonably use a Python compiled with the same Cygwin. Doesn't the normal gvim for Windows have Python support?
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). ############################## ifdef PYTHON DEFINES += -DFEAT_PYTHON INCLUDES += -I$(PYTHON)/include EXTRA_OBJS += $(OUTDIR)/if_python.o ifndef DYNAMIC_PYTHON DYNAMIC_PYTHON = yes endif ifndef PYTHON_VER PYTHON_VER = 30 endif ifeq (yes, $(DYNAMIC_PYTHON)) DEFINES += -DDYNAMIC_PYTHON -DDYNAMIC_PYTHON_DLL=\"python$(PYTHON_VER).dll\" else EXTRA_LIBS += $(PYTHON)/libs/python$(PYTHON_VER).lib endif endif However when running: $ make -f Make_cyg.mak OLE=Yes PYTHON=/cygdrive/p/Applications/PortablePython_1.1_py3.0.1/App/ RUBY=/cygdrive/c/Programme/Ruby/ this results in the following errors: In file included from /cygdrive/p/Applications/PortablePython_1.1_py3.0.1/App//i nclude/Python.h:70, from if_python.c:43: /cygdrive/p/Applications/PortablePython_1.1_py3.0.1/App//include/bytesobject.h:1 04:1: warning: "F_BLANK" redefined In file included from globals.h:1554, from vim.h:1831, from if_python.c:20: farsi.h:74:1: warning: this is the location of the previous definition if_python.c:729: warning: initialization makes integer from pointer without a ca st if_python.c:733: warning: initialization from incompatible pointer type if_python.c:734: warning: initialization from incompatible pointer type if_python.c:735: warning: initialization from incompatible pointer type if_python.c:737: error: `cmpfunc' undeclared here (not in a function) if_python.c:737: error: initializer element is not constant if_python.c:737: error: (near initialization for `OutputType.tp_repr') if_python.c:737: error: parse error before numeric constant /** more errors **/ if_python.c:2256: warning: initialization from incompatible pointer type if_python.c:2257: warning: initialization from incompatible pointer type if_python.c: In function `PythonMod_Init': if_python.c:2351: error: structure has no member named `ob_type' if_python.c:2352: error: structure has no member named `ob_type' if_python.c:2353: error: structure has no member named `ob_type' if_python.c:2354: error: structure has no member named `ob_type' if_python.c:2355: error: structure has no member named `ob_type' if_python.c:2356: error: structure has no member named `ob_type' make: *** [gobj/if_python.o] Error 1 I am using a portable python install from Portable Python. I don't know if that may be the source of the error. I am hoping someone knows how to compile vim with python 3 support (if I only compile it with ruby support it compiles nicely). Thanks in advance, Gjallar
[ "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. First of all, why do you want Python 3.0? If you really want Python 3, then you should use Python 3.1. \nSecond of all, what does \"Python 3 support\" mean in the case of gVim? Is it to make extensions with Python? Then you don't want Python 3 support, as any extension that exists for gVim is going to be written for Python 2.\nAnd yeah, it seems very strange to use portable python. Since you are compiling gVim with cygwin, you should reasonably use a Python compiled with the same Cygwin.\nDoesn't the normal gvim for Windows have Python support?\n" ]
[ 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 python codes and c/c++ dll under a sub folder, I prefer to name the sub folder like XXX-1.0, the number is the version of my python codes. The entry python module is just simple call a python module under the sub-folder. By this way different version python codes can be deployed together without collision. May I know it is possible or not? Thanks. A: If you created a .pth file, eg., X.pth and put XXX-1.0 inside as content XXX-1.0\ - xxx.py X.pth Then, you could import xxx Note: only tested on site-packages folder, I am not sure you could put your sub folder anywhere. Edit: For example, wxPython do that way, since it can have multiple version on same machine. wx-2.8-msw-unicode \ wx \ more stuff wx.pth (wx-2.8-msw-unicode) A: I am not sure that I understand your question correctly, but here is a simple way to have several package versions without collisions. A directory structure: C:\tmp\eggs>dir /B /S C:\tmp\eggs\libs C:\tmp\eggs\test.py C:\tmp\eggs\libs\foo-1.0.egg C:\tmp\eggs\libs\foo-2.0.egg C:\tmp\eggs\libs\foo-1.0.egg\foo.py C:\tmp\eggs\libs\foo-2.0.egg\foo.py Now the contents of files: # contents of C:\tmp\eggs\libs\foo-1.0.egg\foo.py version=(1,0) # contents of C:\tmp\eggs\libs\foo-2.0.egg\foo.py version=(2,0) #contents of C:\tmp\eggs\test.py: import sys sys.path.insert(1, 'libs') from pkg_resources import require require('foo<1.5') import foo print foo.version # will output (1,0) If you change 'foo<1.5' to 'foo>1.5', or 'foo' output will change to (2,0) Details you will find in setuptools documentation. A: Here's how I've done it: tools |-- packageA |-- packageA-1.0 |-- packageA |-- modules |-- packageA-2.0 |-- packageA |-- modules |-- packageB ... This way, when you want to upgrade, just add /packageA/packageA-2.0 to the PYTHONPATH and you can still do import packageA.
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 folder like XXX-1.0, the number is the version of my python codes. The entry python module is just simple call a python module under the sub-folder. By this way different version python codes can be deployed together without collision. May I know it is possible or not? Thanks.
[ "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 on same machine.\nwx-2.8-msw-unicode \\\n wx\n \\\n more stuff\nwx.pth (wx-2.8-msw-unicode)\n\n", "I am not sure that I understand your question correctly, but here is a simple way to have several package versions without collisions.\nA directory structure:\nC:\\tmp\\eggs>dir /B /S\nC:\\tmp\\eggs\\libs\nC:\\tmp\\eggs\\test.py\nC:\\tmp\\eggs\\libs\\foo-1.0.egg\nC:\\tmp\\eggs\\libs\\foo-2.0.egg\nC:\\tmp\\eggs\\libs\\foo-1.0.egg\\foo.py\nC:\\tmp\\eggs\\libs\\foo-2.0.egg\\foo.py\n\nNow the contents of files:\n# contents of C:\\tmp\\eggs\\libs\\foo-1.0.egg\\foo.py\nversion=(1,0)\n\n\n# contents of C:\\tmp\\eggs\\libs\\foo-2.0.egg\\foo.py\nversion=(2,0)\n\n\n#contents of C:\\tmp\\eggs\\test.py:\n\nimport sys\nsys.path.insert(1, 'libs')\nfrom pkg_resources import require\n\nrequire('foo<1.5')\nimport foo\nprint foo.version\n# will output (1,0)\n\nIf you change 'foo<1.5' to 'foo>1.5', or 'foo' output will change to (2,0)\nDetails you will find in setuptools documentation.\n", "Here's how I've done it:\ntools\n |-- packageA\n |-- packageA-1.0\n |-- packageA\n |-- modules\n |-- packageA-2.0\n |-- packageA\n |-- modules\n |-- packageB\n ...\n\nThis way, when you want to upgrade, just add /packageA/packageA-2.0 to the PYTHONPATH and you can still do import packageA. \n" ]
[ 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. Are there any straightforward ways for two Python servers to talk to one another, or does the task processor have to have web-hooks or something? It feels there ought to be a blessed way to do this... A: Look toward message brokers like ActiveMQ, RabbitMQ, ZeroMQ. They are designed to solve problems similar to what you've described. I'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. On low level message brokers keep socket connections to consumers, so it is more efficient than periodical polling. A: SimpleXMLRPCServer. See my answer here: Network programming in Python You could also use periodic polling (in case stuff gets lots) but xmlrpcserver should be fine for most of the work. A: I tend to use polling. If the task table isn't that large it doesn't really involve that much overhead. Otherwise you can implement a web service, or socket type connections. You can use SOAPpy to start writing web service stuff, or just extends BaseHTTPServer or something like that to accept messages (HTTP requests) from Django. I do feel that might be more programming than it's worth, but then again, if the tasks only come infrequently it might be the neatest solution. I would however run my home-build mini-server in some protected environment; only Django should be able to do HTTP requests on there, as it's not easy to build a secure web server. EDIT I just thought about Twisted. This may be the perfect network part for your server if you decide not to use a messaging queue (some twisted examples)
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 servers to talk to one another, or does the task processor have to have web-hooks or something? It feels there ought to be a blessed way to do this...
[ "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 brokers keep socket connections to consumers, so it is more efficient than periodical polling.\n", "SimpleXMLRPCServer.\nSee my answer here: Network programming in Python\nYou could also use periodic polling (in case stuff gets lots) but xmlrpcserver should be fine for most of the work.\n", "I tend to use polling. If the task table isn't that large it doesn't really involve that much overhead.\nOtherwise you can implement a web service, or socket type connections. \nYou can use SOAPpy to start writing web service stuff, or just extends BaseHTTPServer or something like that to accept messages (HTTP requests) from Django. I do feel that might be more programming than it's worth, but then again, if the tasks only come infrequently it might be the neatest solution.\nI would however run my home-build mini-server in some protected environment; only Django should be able to do HTTP requests on there, as it's not easy to build a secure web server.\nEDIT\nI just thought about Twisted. This may be the perfect network part for your server if you decide not to use a messaging queue (some twisted examples)\n" ]
[ 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 provided by James Tauber here, which for example sorts all the "a"'s close together whether they have accents on them or not. Other examples of why this might be useful is for different alphabet orders (languages other than English) and sorting numeric values (sorting 10 after 9 rather than codepoint order.) Is this possible in SQLAlchemy? If not, is it supported by the pysqlite3 or MySQLdb modules, or for any other SQL database modules supported by python for that matter? Any information would be greatly appreciated. A: Below is an example demonstrating unicode collation algorithm for sqlite: from sqlalchemy import * from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker from pyuca import Collator metadata = MetaData() Base = declarative_base(metadata=metadata) class Item(Base): __tablename__ = 'Item' id = Column(Integer, primary_key=True) value = Column(String, nullable=False) collator = Collator('allkeys.txt') def collate_unicode(value1, value2): return cmp(collator.sort_key(value1), collator.sort_key(value2)) engine = create_engine('sqlite://') engine.raw_connection().create_collation('unicode', collate_unicode) metadata.create_all(engine) session = sessionmaker(engine)() for word in [u"ĉambr", u"ĉar", u"car'", u"carin'", u"ĉe", u"ĉef'", u"centjar'", u"centr'", u"cerb'", u"cert'", u"ĉes'", u"ceter'"]: item = Item(value=word) session.add(item) session.commit() for item in session.query(Item).order_by(collate(Item.value, 'unicode')): print item.value A: I modified Denis Otkidach's answer a little bit so I'll add my changes as community wiki in case anyone else is interested: # -*- coding: utf-8 -*- from sqlalchemy import * from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker from sqlalchemy import types from pyuca import Collator class MyUnicode(types.TypeDecorator): impl = types.Unicode def get_col_spec(self): # Return a new Unicode type sorted with # the `mycollation` function return 'Unicode COLLATE mycollation' # Create the collator (sorting) function/instance collator = Collator('allkeys.txt') def mycollation(value1, value2): if False: # Use pyuca for sorting return cmp(collator.sort_key(value1), collator.sort_key(value2)) else: # Normalize to lowercased combining characters for sorting import unicodedata return cmp(unicodedata.normalize('NFD', unicode(value1)).lower(), unicodedata.normalize('NFD', unicode(value2)).lower()) # Create a new metadata/base/table metadata = MetaData() Base = declarative_base(metadata=metadata) class Item(Base): __tablename__ = 'CollatedTable' id = Column(Integer, primary_key=True) # (Note the `unique=True` in the next line so that an index # is created, therefore stored in collated order for faster SELECTs) value = Column(MyUnicode(), nullable=False, unique=True) # Create a new database connection engine = create_engine('sqlite://') engine.echo = True # Print the SQL engine.raw_connection().create_collation('mycollation', mycollation) metadata.create_all(engine) session = sessionmaker(engine)() # Add some test data for word in [u"ĉambr", u"ĉar", u"car'", u"carin'", u"ĉe", u"ĉef'", u"centjar'", u"centr'", u"cerb'", u"cert'", u"ĉes'", u"ceter'", u"zimble", u'bumble', u'apple', u'ápple', u'ãpple', u'đjango', u'django']: item = Item(value=word) session.add(item) session.commit() for item in session.query(Item).order_by(Item.value): # collate(Item.value, 'mycollation') print item.value
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 close together whether they have accents on them or not. Other examples of why this might be useful is for different alphabet orders (languages other than English) and sorting numeric values (sorting 10 after 9 rather than codepoint order.) Is this possible in SQLAlchemy? If not, is it supported by the pysqlite3 or MySQLdb modules, or for any other SQL database modules supported by python for that matter? Any information would be greatly appreciated.
[ "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):\n __tablename__ = 'Item'\n id = Column(Integer, primary_key=True)\n value = Column(String, nullable=False)\n\ncollator = Collator('allkeys.txt')\n\ndef collate_unicode(value1, value2):\n return cmp(collator.sort_key(value1), collator.sort_key(value2))\n\nengine = create_engine('sqlite://')\nengine.raw_connection().create_collation('unicode', collate_unicode)\nmetadata.create_all(engine)\nsession = sessionmaker(engine)()\n\nfor word in [u\"ĉambr\", u\"ĉar\", u\"car'\", u\"carin'\", u\"ĉe\", u\"ĉef'\",\n u\"centjar'\", u\"centr'\", u\"cerb'\", u\"cert'\", u\"ĉes'\", u\"ceter'\"]:\n item = Item(value=word)\n session.add(item)\n session.commit()\n\nfor item in session.query(Item).order_by(collate(Item.value, 'unicode')):\n print item.value\n\n", "I modified Denis Otkidach's answer a little bit so I'll add my changes as community wiki in case anyone else is interested:\n# -*- coding: utf-8 -*-\nfrom sqlalchemy import *\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy import types\nfrom pyuca import Collator\n\nclass MyUnicode(types.TypeDecorator):\n impl = types.Unicode\n def get_col_spec(self):\n # Return a new Unicode type sorted with \n # the `mycollation` function\n return 'Unicode COLLATE mycollation'\n\n# Create the collator (sorting) function/instance\ncollator = Collator('allkeys.txt')\ndef mycollation(value1, value2):\n if False:\n # Use pyuca for sorting\n return cmp(collator.sort_key(value1), \n collator.sort_key(value2))\n else:\n # Normalize to lowercased combining characters for sorting\n import unicodedata\n return cmp(unicodedata.normalize('NFD', unicode(value1)).lower(),\n unicodedata.normalize('NFD', unicode(value2)).lower())\n\n# Create a new metadata/base/table\nmetadata = MetaData()\nBase = declarative_base(metadata=metadata)\nclass Item(Base):\n __tablename__ = 'CollatedTable'\n id = Column(Integer, primary_key=True)\n # (Note the `unique=True` in the next line so that an index \n # is created, therefore stored in collated order for faster SELECTs)\n value = Column(MyUnicode(), nullable=False, unique=True)\n\n# Create a new database connection\nengine = create_engine('sqlite://')\nengine.echo = True # Print the SQL\nengine.raw_connection().create_collation('mycollation', mycollation)\nmetadata.create_all(engine)\nsession = sessionmaker(engine)()\n\n# Add some test data\nfor word in [u\"ĉambr\", u\"ĉar\", u\"car'\", u\"carin'\", u\"ĉe\", u\"ĉef'\",\n u\"centjar'\", u\"centr'\", u\"cerb'\", u\"cert'\", u\"ĉes'\", u\"ceter'\",\n\n u\"zimble\", u'bumble', \n u'apple', u'ápple', u'ãpple',\n u'đjango', u'django']:\n item = Item(value=word)\n session.add(item)\nsession.commit()\n\nfor item in session.query(Item).order_by(Item.value): # collate(Item.value, 'mycollation')\n print item.value\n\n" ]
[ 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 called show_employees and I can delete and update employees by passing an an post request to the views delete_employee and update_employee. I've put @login_required decorators before each of these views since I don't want anyone accessing them without being authenticated. Is this okay? In the delete_employee and update_employee views, I only respond to request if it is an AJAX POST request (uisng is_ajax()). Is this okay? I return a 'success' when the view succeeds in doing what is needed and an error when there is a Validation error in my form but I'm still not handling other exceptions. How should I do this? Should i return standard 500 page through an AJAX response like this by wrapping the view with a try-except block to handle all exceptions? Is there anything else I can do secure my view? Here's a sample view of mine: @login_required def add_site(request): data = {} if request.method == 'POST': if request.is_ajax(): form = AddSiteForm(request.user, request.POST) if form.is_valid(): site = form.save(commit=False) site.user = request.user site.save() data['status'] = 'success' data['html'] = render_to_string('site.html', locals(), context_instance=RequestContext(request)) return HttpResponse(simplejson.dumps(data), mimetype='application/json') else: data['status'] = 'error' data['errors'] = {} for field, error in form.errors.iteritems(): data['errors']['id_'+field] = strip_tags(unicode(error)) return HttpResponse(simplejson.dumps(data), mimetype='application/json') Thank you. A: 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 just a login_required decorator. Suppose now you have only admins, but later you want to add other kinds of users, it's easy then to miss a login_required decorator then and granting those users access to admin views. You won't have this problem with properly defined permissions. Next, is_ajax just checks for the HTTP_X_REQUESTED_WITH header. This has not really to do with security, but with user friendly behavior. This way you prevent a normal user from accidentally opening that page in the browser and getting some weird data. It does not help anything in security, every decent hacker can set an additional HTTP header :). Not handling exceptions can be potentially dangerous, if you accidentally leave on the DEBUG=True, in which case django will provide pieces of code and backtraces, potentially giving away weaknesses. But, if this option is off django will show it's own 500 error page. My suggestion is: look for all expected django exceptions (aren't that many) and make sure you catch those properly. Further I'd say, let the other exception be handled by django, django will still provide possibilities to generate backtraces and other debugging info and send these to the admins instead of displaying them on-site. If you catch all unexpected errors this behavior will not be directly available, maybe leaving you unknown about failing code. Finally, as you are working with user input data, I'd suggest you take a look at the security chapter in the django book, it explains the most important threats and how to handle them in the django framework.
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 update employees by passing an an post request to the views delete_employee and update_employee. I've put @login_required decorators before each of these views since I don't want anyone accessing them without being authenticated. Is this okay? In the delete_employee and update_employee views, I only respond to request if it is an AJAX POST request (uisng is_ajax()). Is this okay? I return a 'success' when the view succeeds in doing what is needed and an error when there is a Validation error in my form but I'm still not handling other exceptions. How should I do this? Should i return standard 500 page through an AJAX response like this by wrapping the view with a try-except block to handle all exceptions? Is there anything else I can do secure my view? Here's a sample view of mine: @login_required def add_site(request): data = {} if request.method == 'POST': if request.is_ajax(): form = AddSiteForm(request.user, request.POST) if form.is_valid(): site = form.save(commit=False) site.user = request.user site.save() data['status'] = 'success' data['html'] = render_to_string('site.html', locals(), context_instance=RequestContext(request)) return HttpResponse(simplejson.dumps(data), mimetype='application/json') else: data['status'] = 'error' data['errors'] = {} for field, error in form.errors.iteritems(): data['errors']['id_'+field] = strip_tags(unicode(error)) return HttpResponse(simplejson.dumps(data), mimetype='application/json') Thank you.
[ "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 just a login_required decorator. Suppose now you have only admins, but later you want to add other kinds of users, it's easy then to miss a login_required decorator then and granting those users access to admin views. You won't have this problem with properly defined permissions.\nNext, is_ajax just checks for the HTTP_X_REQUESTED_WITH header. This has not really to do with security, but with user friendly behavior. This way you prevent a normal user from accidentally opening that page in the browser and getting some weird data. It does not help anything in security, every decent hacker can set an additional HTTP header :).\nNot handling exceptions can be potentially dangerous, if you accidentally leave on the DEBUG=True, in which case django will provide pieces of code and backtraces, potentially giving away weaknesses. But, if this option is off django will show it's own 500 error page. My suggestion is: look for all expected django exceptions (aren't that many) and make sure you catch those properly. Further I'd say, let the other exception be handled by django, django will still provide possibilities to generate backtraces and other debugging info and send these to the admins instead of displaying them on-site. If you catch all unexpected errors this behavior will not be directly available, maybe leaving you unknown about failing code.\nFinally, as you are working with user input data, I'd suggest you take a look at the security chapter in the django book, it explains the most important threats and how to handle them in the django framework.\n" ]
[ 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 to be store as either a list of lists, or a list of objects, both of which can't really be done without pickling as far as I know. Can anyone help? Even storing it as a text file may work :S Edit: I was a litle vague on details it seems. I am sampling some data from an external source (scraping via BeautifulSoup/http2lib if it matters). This data then needs to be stored, as a whole, since it will be plotted on a graph. The data changes (but not often - perhaps once a week). Since the dataset is so simple (literally what you see above, 1 string field, and 1 integer) I figured it's easier to store them as a list of lists, then actually store them in a model. I have a feeling I have skipped over an even easier solution by concentrating too much on the fact the data needs to be stored together as one large lump. I will be storing 500+ of these bits of data as a group, at once. A: You could just store them as two separate lists and only worry about combing them when you actually access them. Something like this: class MyModel(db.Model): my_strings = db.StringListProperty() my_ints = db.ListProperty(int) def get_data(self): return zip(self.my_strings, self.my_ints) def set_data(self, data): self.my_strings = [element[0] for element in data] self.my_ints = [element[1] for element in data] data = property(get_data, set_data) That way, you can just do something like entity = MyModel() entity.data = [("xyz", 123), ("abc", 456), ("hij", 678)] entity.put() # ... for string_value, int_value in entity.data: # do something A: If it's really just a list of tuples / two "columns", could you just use an alternating list and a ListProperty? This would be fine if the data had a consistent dimension, was small, and didn't require indexing. e.g. To encode the example you gave in a list do: # i forget if mixed types are allowed, but you get the idea. ["xyz", 123, "abc", 456, "hij", 678, "rer", 838]
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, or a list of objects, both of which can't really be done without pickling as far as I know. Can anyone help? Even storing it as a text file may work :S Edit: I was a litle vague on details it seems. I am sampling some data from an external source (scraping via BeautifulSoup/http2lib if it matters). This data then needs to be stored, as a whole, since it will be plotted on a graph. The data changes (but not often - perhaps once a week). Since the dataset is so simple (literally what you see above, 1 string field, and 1 integer) I figured it's easier to store them as a list of lists, then actually store them in a model. I have a feeling I have skipped over an even easier solution by concentrating too much on the fact the data needs to be stored together as one large lump. I will be storing 500+ of these bits of data as a group, at once.
[ "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)\n\n def set_data(self, data):\n self.my_strings = [element[0] for element in data]\n self.my_ints = [element[1] for element in data]\n\n data = property(get_data, set_data)\n\nThat way, you can just do something like\nentity = MyModel()\nentity.data = [(\"xyz\", 123), (\"abc\", 456), (\"hij\", 678)]\nentity.put()\n\n# ...\n\nfor string_value, int_value in entity.data:\n # do something\n\n", "If it's really just a list of tuples / two \"columns\", could you just use an alternating list and a ListProperty? This would be fine if the data had a consistent dimension, was small, and didn't require indexing.\ne.g. To encode the example you gave in a list do:\n\n# i forget if mixed types are allowed, but you get the idea.\n[\"xyz\", 123, \"abc\", 456, \"hij\", 678, \"rer\", 838]\n\n" ]
[ 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 listen to a certain IP address, say 10.0.0.78. How-to manage that? This is a snippet of my code: application = service.Application('SMS_Inbound') smsInbound = resource.Resource() smsInbound.putChild('75sms_inbound',ReceiveSMS(application)) smsInboundServer = internet.TCPServer(8001, webserver.Site(smsInbound)) smsInboundServer.setName("SMS Handling") smsInboundServer.setServiceParent(application) A: What you're looking for is the interface argument to twisted.application.internet.TCPServer: smsInboundServer = internet.TCPServer(8001, webserver.Site(smsInbound), interface='10.0.0.78') (Which it inherits from reactor.listenTCP(), since all the t.a.i.*Server classes really just forward to reactor.listenXXX for the appropriate protocol.)
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? This is a snippet of my code: application = service.Application('SMS_Inbound') smsInbound = resource.Resource() smsInbound.putChild('75sms_inbound',ReceiveSMS(application)) smsInboundServer = internet.TCPServer(8001, webserver.Site(smsInbound)) smsInboundServer.setName("SMS Handling") smsInboundServer.setServiceParent(application)
[ "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.listenXXX for the appropriate protocol.)\n" ]
[ 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, self).__init__(*args, **kwargs) self.fields['opening_challenge'].label = "lame translation" def clean_opening_challenge(self): challenge = self.cleaned_data['opening_challenge'] if challenge is None: raise forms.ValidationError('Укажите шаг, открывающий данную доп. возможность') return challenge class HiddenExtraForm(forms.ModelForm): class Meta: model = Extra exclude = ('opening_challenge') def __init__(self, *args, **kwargs): super(HiddenExtraForm, self).__init__(*args, **kwargs) The view code goes like that: @login_required def manage_extra(request, extra_id=None, hidden=False): if not_admin(request.user): raise Http404 if extra_id is None: # Adding a new extra extra = Extra() if hidden: FormClass = HiddenExtraForm else: FormClass = OpenExtraForm else: # Editing an extra extra = get_object_or_404(Extra, pk=extra_id) if extra.is_hidden(): FromClass = HiddenExtraForm else: FormClass = OpenExtraForm if request.POST: form = FormClass(request.POST, instance=extra) if form.is_valid(): form.save() return HttpResponseRedirect(reverse(view_extra, args=[extra.id])) else: form = FormClass(instance=extra) return render_to_response('form.html', { 'form' : form, }, context_instance=RequestContext(request) ) The problem is somehow if extra.is_hidden() returns True, the statement FromClass = HiddenExtraForm doesn't work. I mean, in all other conditions that are used in the code it works fine: the correct Form classes are intantiated and it all works. But if extra.is_hidden(), the debugger shows that the condition is passed and it goes to the next line and does nothing! As a result I get a UnboundLocalVar error which says FormClass hasn't been asssigned at all. Any ideas on what's happening? A: You need to decide between FromClass and FormClass. You use FormClass everywhere except: if extra.is_hidden(): FromClass = HiddenExtraForm
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.fields['opening_challenge'].label = "lame translation" def clean_opening_challenge(self): challenge = self.cleaned_data['opening_challenge'] if challenge is None: raise forms.ValidationError('Укажите шаг, открывающий данную доп. возможность') return challenge class HiddenExtraForm(forms.ModelForm): class Meta: model = Extra exclude = ('opening_challenge') def __init__(self, *args, **kwargs): super(HiddenExtraForm, self).__init__(*args, **kwargs) The view code goes like that: @login_required def manage_extra(request, extra_id=None, hidden=False): if not_admin(request.user): raise Http404 if extra_id is None: # Adding a new extra extra = Extra() if hidden: FormClass = HiddenExtraForm else: FormClass = OpenExtraForm else: # Editing an extra extra = get_object_or_404(Extra, pk=extra_id) if extra.is_hidden(): FromClass = HiddenExtraForm else: FormClass = OpenExtraForm if request.POST: form = FormClass(request.POST, instance=extra) if form.is_valid(): form.save() return HttpResponseRedirect(reverse(view_extra, args=[extra.id])) else: form = FormClass(instance=extra) return render_to_response('form.html', { 'form' : form, }, context_instance=RequestContext(request) ) The problem is somehow if extra.is_hidden() returns True, the statement FromClass = HiddenExtraForm doesn't work. I mean, in all other conditions that are used in the code it works fine: the correct Form classes are intantiated and it all works. But if extra.is_hidden(), the debugger shows that the condition is passed and it goes to the next line and does nothing! As a result I get a UnboundLocalVar error which says FormClass hasn't been asssigned at all. Any ideas on what's happening?
[ "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 = models.ForeignKey(User, unique=True) birthday = models.DateField() class Media(models.Model): title = models.CharField(max_length=200) description = models.TextField(max_length=2000) class Role(models.Model): name = models.CharField(max_length=50) What I want is a junction table that looks something like this: CREATE TABLE `media_roles` ( `media_id` bigint(20) unsigned NOT NULL, `profile_id` bigint(20) unsigned NOT NULL, `role_id` bigint(20) unsigned NOT NULL ) John Doe - Director, Writer, Producer Jane Doe - Executive Producer ... This is what I've used so far: class MediaRole(models.Model): media = models.ForeignKey(Media) user = models.ForeignKey(Profile) role = models.ForeignKey(Role) But isn't there any better way of doing this, not involving the creation of a separate class in the model? A: What about separating the two m2m relationships? class Profile(models.Model): ... medias = models.ManyToManyField(Media, related_name='profiles') roles = models.ManyToManyField(Role, related_name='profiles') In this way Django create two association tables for you, and you can utilize the convenient related fields like this: profile = Profile.objects.get(user=someone) print profile.medias.all() print profile.roles.all()
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.DateField() class Media(models.Model): title = models.CharField(max_length=200) description = models.TextField(max_length=2000) class Role(models.Model): name = models.CharField(max_length=50) What I want is a junction table that looks something like this: CREATE TABLE `media_roles` ( `media_id` bigint(20) unsigned NOT NULL, `profile_id` bigint(20) unsigned NOT NULL, `role_id` bigint(20) unsigned NOT NULL ) John Doe - Director, Writer, Producer Jane Doe - Executive Producer ... This is what I've used so far: class MediaRole(models.Model): media = models.ForeignKey(Media) user = models.ForeignKey(Profile) role = models.ForeignKey(Role) But isn't there any better way of doing this, not involving the creation of a separate class in the model?
[ "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 convenient related fields like this:\nprofile = Profile.objects.get(user=someone)\nprint profile.medias.all()\nprint profile.roles.all()\n\n" ]
[ 0 ]
[]
[]
[ "django", "many_to_many", "model", "model_view_controller", "python" ]
stackoverflow_0002674752_django_many_to_many_model_model_view_controller_python.txt