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: wxPython: Threading GUI --> Using Custom Event Handler I am trying to learn how to run a thread off the main GUI app to do my serial port sending/receiving while keeping my GUI alive. My best Googling attempts have landed me at the wxpython wiki on: http://wiki.wxpython.org/LongRunningTasks which provides several examples. I have settled on learning the first example, involving starting a worker thread when the particular button is selected. I am having trouble understanding the custom-event-definition: def EVT_RESULT(win, func): """Define Result Event.""" win.Connect(-1, -1, EVT_RESULT_ID, func) class ResultEvent(wx.PyEvent): """Simple event to carry arbitrary result data.""" def __init__(self, data): """Init Result Event.""" wx.PyEvent.__init__(self) self.SetEventType(EVT_RESULT_ID) self.data = data Primarily the def EVT_RESULT(win, func): """Define Result Event.""" win.Connect(-1, -1, EVT_RESULT_ID, func) I think EVT_RESULT is placed outside the classes so as to make it call-able by both classes (making it global?) And.. the main GUI app monitors the thread's progress via: # Set up event handler for any worker thread results EVT_RESULT(self,self.OnResult) I also notice that in a lot of examples, when the writer uses from wx import * they simply bind things by EVT_SOME_NEW_EVENT(self, self.handler) as opposed to wx.Bind(EVT_SOME_NEW_EVENT, self.handler) Which doesn't help me understand it any faster. Thanks, A: That's the old style of defining custom events. See the migration guide for more information. Taken from the migration guide: If you create your own custom event types and EVT_* functions, and you want to be able to use them with the Bind method above then you should change your EVT_* to be an instance of wx.PyEventBinder instead of a function. For example, if you used to have something like this: myCustomEventType = wxNewEventType() def EVT_MY_CUSTOM_EVENT(win, id, func): win.Connect(id, -1, myCustomEventType, func) Change it like so: myCustomEventType = wx.NewEventType() EVT_MY_CUSTOM_EVENT = wx.PyEventBinder(myCustomEventType, 1) Here is another post that I made with a couple of example programs that do exactly what you are looking for. A: You can define events like this: from wx.lib.newevent import NewEvent ResultEvent, EVT_RESULT = NewEvent() You post the event like this: wx.PostEvent(handler, ResultEvent(data=data)) Bind it like this: def OnResult(event): event.data handler.Bind(EVT_RESULT, OnResult) But if you just need to make a call from a non-main thread in the main thread you can use wx.CallAfter, here is an example. Custom events are useful when you don't want to hard code who is responsible for what (see the observer design pattern). For example, lets say you have a main window and a couple of child windows. Suppose that some of the child windows need to be refreshed when a certain change occurs in the main window. The main window could directly refresh those child windows in such a case but a more elegant approach would be to define a custom event and have the main window post it to itself (and not bother who needs to react to it). Then the children that need to react to that event can do it them selves by binding to it (and if there is more than one it is important that they call event.Skip() so that all of the bound methods get called). A: You may want to use Python threads and queues and not custom events. I have a wxPython program (OpenSTV) that loads large files that caused the gui to freeze during the loading. To prevent the freezing, I dispatch a thread to load the file and use a queue to communicate between the gui and the thread (e.g., to communicate an exception to the GUI). def loadBallots(self): self.dirtyBallots = Ballots() self.dirtyBallots.exceptionQueue = Queue(1) loadThread = Thread(target=self.dirtyBallots.loadUnknown, args=(self.filename,)) loadThread.start() # Display a progress dialog dlg = wx.ProgressDialog(\ "Loading ballots", "Loading ballots from %s\nNumber of ballots: %d" % (os.path.basename(self.filename), self.dirtyBallots.numBallots), parent=self.frame, style = wx.PD_APP_MODAL | wx.PD_ELAPSED_TIME ) while loadThread.isAlive(): sleep(0.1) dlg.Pulse("Loading ballots from %s\nNumber of ballots: %d" % (os.path.basename(self.filename), self.dirtyBallots.numBallots)) dlg.Destroy() if not self.dirtyBallots.exceptionQueue.empty(): raise RuntimeError(self.dirtyBallots.exceptionQueue.get())
wxPython: Threading GUI --> Using Custom Event Handler
I am trying to learn how to run a thread off the main GUI app to do my serial port sending/receiving while keeping my GUI alive. My best Googling attempts have landed me at the wxpython wiki on: http://wiki.wxpython.org/LongRunningTasks which provides several examples. I have settled on learning the first example, involving starting a worker thread when the particular button is selected. I am having trouble understanding the custom-event-definition: def EVT_RESULT(win, func): """Define Result Event.""" win.Connect(-1, -1, EVT_RESULT_ID, func) class ResultEvent(wx.PyEvent): """Simple event to carry arbitrary result data.""" def __init__(self, data): """Init Result Event.""" wx.PyEvent.__init__(self) self.SetEventType(EVT_RESULT_ID) self.data = data Primarily the def EVT_RESULT(win, func): """Define Result Event.""" win.Connect(-1, -1, EVT_RESULT_ID, func) I think EVT_RESULT is placed outside the classes so as to make it call-able by both classes (making it global?) And.. the main GUI app monitors the thread's progress via: # Set up event handler for any worker thread results EVT_RESULT(self,self.OnResult) I also notice that in a lot of examples, when the writer uses from wx import * they simply bind things by EVT_SOME_NEW_EVENT(self, self.handler) as opposed to wx.Bind(EVT_SOME_NEW_EVENT, self.handler) Which doesn't help me understand it any faster. Thanks,
[ "That's the old style of defining custom events. See the migration guide for more information.\nTaken from the migration guide:\n\nIf you create your own custom event\n types and EVT_* functions, and you\n want to be able to use them with the\n Bind method above then you should\n change your EVT_* to be an instance of wx.PyEventBinder instead of a\n function. For example, if you used to\n have something like this:\nmyCustomEventType = wxNewEventType()\ndef EVT_MY_CUSTOM_EVENT(win, id, func):\n win.Connect(id, -1, myCustomEventType, func)\n\nChange it like so:\nmyCustomEventType = wx.NewEventType()\nEVT_MY_CUSTOM_EVENT = wx.PyEventBinder(myCustomEventType, 1)\n\n\nHere is another post that I made with a couple of example programs that do exactly what you are looking for.\n", "You can define events like this:\nfrom wx.lib.newevent import NewEvent\n\nResultEvent, EVT_RESULT = NewEvent()\n\nYou post the event like this:\nwx.PostEvent(handler, ResultEvent(data=data))\n\nBind it like this:\ndef OnResult(event):\n event.data\n\nhandler.Bind(EVT_RESULT, OnResult)\n\nBut if you just need to make a call from a non-main thread in the main thread you can use wx.CallAfter, here is an example.\nCustom events are useful when you don't want to hard code who is responsible for what (see the observer design pattern). For example, lets say you have a main window and a couple of child windows. Suppose that some of the child windows need to be refreshed when a certain change occurs in the main window. The main window could directly refresh those child windows in such a case but a more elegant approach would be to define a custom event and have the main window post it to itself (and not bother who needs to react to it). Then the children that need to react to that event can do it them selves by binding to it (and if there is more than one it is important that they call event.Skip() so that all of the bound methods get called).\n", "You may want to use Python threads and queues and not custom events. I have a wxPython program (OpenSTV) that loads large files that caused the gui to freeze during the loading. To prevent the freezing, I dispatch a thread to load the file and use a queue to communicate between the gui and the thread (e.g., to communicate an exception to the GUI).\n def loadBallots(self):\n self.dirtyBallots = Ballots()\n self.dirtyBallots.exceptionQueue = Queue(1)\n loadThread = Thread(target=self.dirtyBallots.loadUnknown, args=(self.filename,))\n loadThread.start()\n\n # Display a progress dialog\n dlg = wx.ProgressDialog(\\\n \"Loading ballots\",\n \"Loading ballots from %s\\nNumber of ballots: %d\" % \n (os.path.basename(self.filename), self.dirtyBallots.numBallots),\n parent=self.frame, style = wx.PD_APP_MODAL | wx.PD_ELAPSED_TIME\n )\n while loadThread.isAlive():\n sleep(0.1)\n dlg.Pulse(\"Loading ballots from %s\\nNumber of ballots: %d\" %\n (os.path.basename(self.filename), self.dirtyBallots.numBallots))\n dlg.Destroy()\n\nif not self.dirtyBallots.exceptionQueue.empty():\n raise RuntimeError(self.dirtyBallots.exceptionQueue.get())\n\n" ]
[ 4, 2, 0 ]
[]
[]
[ "custom_events", "multithreading", "python", "wxpython" ]
stackoverflow_0002345608_custom_events_multithreading_python_wxpython.txt
Q: Python's subprocessing with pipes and large files I'm trying to use python + ffmpeg + oggenc to convert any audiofile to ogg. The program works, almost. But for big files (i think > ~6mb) the ffmpeg process starts to sleep at pipe_wait. I don't know which pipe it waits for. If I kill the ffmpeg process, the oggenc process continues and I get a resulting ogg-file with about ~2:40 of all the sound. #!/usr/bin/env python # -*- coding: utf-8 -*- from subprocess import Popen, PIPE from sys import argv ffmpeg = Popen([ "ffmpeg", "-i", argv[1], "-vcodec", "null", "-acodec", "pcm_s16le", "-ac", "2", "-ab", "44100", "-f", "wav", "-" ],stdout = PIPE,stderr = PIPE) oggenc = Popen([ "oggenc", "-", "--raw", "-q", "4", "-o", argv[2] ],stdin = ffmpeg.stdout,stderr = PIPE) oggenc.communicate() ffmpeg.communicate() EDIT: Thought I might add that this works perfectly: #!/bin/bash ffmpeg -i "$1" -vcodec null -acodec pcm_s16le -ac 2 -ab 44100 -f wav - | oggenc - --raw -q 4 -o "$2" A: What exactly do you do with the stderr channels of the two pipes? Encoders/decoders typically produce lots of stderr output, as status updates; this output is piped to your process, and buffers will become full. Perhaps you should add some dummy ffmpeg.stderr.read() call before the (useless, I think) .communicate calls, or even better, drop the stderr=PIPE arguments completely. UPDATE For the >/dev/null equivalent, do the following: nulfp = open(os.devnull, "w") … … = subprocess.Popen(…, stderr=nulfp.fileno()) Obviously, you can re-use the same nulfp for all stderrs you want to ignore. A: Its tricky to see who needs to pass the pipe, eer I mean you should use a debugger like the one in NetBeans to help gather more clues. Pipe's may not be the best approach, perhaps using a temporary file would simplify things.
Python's subprocessing with pipes and large files
I'm trying to use python + ffmpeg + oggenc to convert any audiofile to ogg. The program works, almost. But for big files (i think > ~6mb) the ffmpeg process starts to sleep at pipe_wait. I don't know which pipe it waits for. If I kill the ffmpeg process, the oggenc process continues and I get a resulting ogg-file with about ~2:40 of all the sound. #!/usr/bin/env python # -*- coding: utf-8 -*- from subprocess import Popen, PIPE from sys import argv ffmpeg = Popen([ "ffmpeg", "-i", argv[1], "-vcodec", "null", "-acodec", "pcm_s16le", "-ac", "2", "-ab", "44100", "-f", "wav", "-" ],stdout = PIPE,stderr = PIPE) oggenc = Popen([ "oggenc", "-", "--raw", "-q", "4", "-o", argv[2] ],stdin = ffmpeg.stdout,stderr = PIPE) oggenc.communicate() ffmpeg.communicate() EDIT: Thought I might add that this works perfectly: #!/bin/bash ffmpeg -i "$1" -vcodec null -acodec pcm_s16le -ac 2 -ab 44100 -f wav - | oggenc - --raw -q 4 -o "$2"
[ "What exactly do you do with the stderr channels of the two pipes?\nEncoders/decoders typically produce lots of stderr output, as status updates; this output is piped to your process, and buffers will become full. Perhaps you should add some dummy ffmpeg.stderr.read() call before the (useless, I think) .communicate calls, or even better, drop the stderr=PIPE arguments completely.\nUPDATE\nFor the >/dev/null equivalent, do the following:\nnulfp = open(os.devnull, \"w\")\n…\n… = subprocess.Popen(…, stderr=nulfp.fileno())\n\nObviously, you can re-use the same nulfp for all stderrs you want to ignore.\n", "Its tricky to see who needs to pass the pipe, eer I mean you should use a debugger like the one in NetBeans to help gather more clues. Pipe's may not be the best approach, perhaps using a temporary file would simplify things. \n" ]
[ 5, 0 ]
[]
[]
[ "ffmpeg", "python", "subprocess" ]
stackoverflow_0002358936_ffmpeg_python_subprocess.txt
Q: positioning sound with pygame? Is there a way to do panning or 3d sound in Pygame? The only way I've found to control sound playback is to set the volume for both the left and right channels. A: http://pysonic.sourceforge.net/ Try this out, it's a wrapper over the FMOD sound library, it won't disappoint :) A: You are correct - Pygame itself doesn't have any high-level way to position sound other than manually adjusting channel volumes (and it looks like it only supports stereo). The best way, to do 3D-audio, especially for games, is to use OpenAL. Unfortunately, there's no way to this in Pygame (note that there is an OpenAL library in "pgreloaded," the next version of Pygame). Pyglet, however, does use OpenAL. I've never tried mixing Pygame and pyglet, though - I wonder if it would work? A: I think setting the separate channel volume is the only way. Pygame doesn't seem to have any notion of world space or positioning for sounds.
positioning sound with pygame?
Is there a way to do panning or 3d sound in Pygame? The only way I've found to control sound playback is to set the volume for both the left and right channels.
[ "http://pysonic.sourceforge.net/\nTry this out, it's a wrapper over the FMOD sound library, it won't disappoint :)\n", "You are correct - Pygame itself doesn't have any high-level way to position sound other than manually adjusting channel volumes (and it looks like it only supports stereo).\nThe best way, to do 3D-audio, especially for games, is to use OpenAL. Unfortunately, there's no way to this in Pygame (note that there is an OpenAL library in \"pgreloaded,\" the next version of Pygame). Pyglet, however, does use OpenAL. I've never tried mixing Pygame and pyglet, though - I wonder if it would work?\n", "I think setting the separate channel volume is the only way. Pygame doesn't seem to have any notion of world space or positioning for sounds.\n" ]
[ 1, 1, 0 ]
[]
[]
[ "audio", "pygame", "python" ]
stackoverflow_0001583284_audio_pygame_python.txt
Q: OpenID or Auth in Django? What are the pros and cons of using open id vs auth? Shoud I do both? A: That depends whether you want to support Open ID. As to the reasons behind Open ID, in my view the most compelling one is that it avoids requiring your users to have an account just for your site, with all the hassle that involves (yet another username and password to remember). If you decide you want to use Open ID, there's not need to choose between that and auth - use django-openid-auth, which adds Open ID support to the auth framework. Definitely try and avoid using an Open ID implementation that doesn't plug into Django's auth framework - you'll lose a lot of the baked-in goodness of Django (model-level permissions etc). A: OpenID and OAuth do different things. OpenID lets users log into your site. OAuth lets people give your site access to their data elsewhere. On the other side of the coin, OAuth gives you a secure way to let users access their data in your service from elsewhere. If you implement OpenID, don't implement an OpenID producer. Everyone's already got an OpenID, whether they know it or not. Just consume openids from elsewhere. Migrating OpenIDs shouldn't be hard. Just make sure that a user account can connect via multiple OIDs, then they can add new ones as needed, and remove when they're done with them. Edit: Just saw that you were talking about django auth, not oauth. Oops. The second paragraph still stands.
OpenID or Auth in Django?
What are the pros and cons of using open id vs auth? Shoud I do both?
[ "That depends whether you want to support Open ID. As to the reasons behind Open ID, in my view the most compelling one is that it avoids requiring your users to have an account just for your site, with all the hassle that involves (yet another username and password to remember).\nIf you decide you want to use Open ID, there's not need to choose between that and auth - use django-openid-auth, which adds Open ID support to the auth framework.\nDefinitely try and avoid using an Open ID implementation that doesn't plug into Django's auth framework - you'll lose a lot of the baked-in goodness of Django (model-level permissions etc).\n", "OpenID and OAuth do different things. OpenID lets users log into your site. OAuth lets people give your site access to their data elsewhere. On the other side of the coin, OAuth gives you a secure way to let users access their data in your service from elsewhere.\nIf you implement OpenID, don't implement an OpenID producer. Everyone's already got an OpenID, whether they know it or not. Just consume openids from elsewhere. Migrating OpenIDs shouldn't be hard. Just make sure that a user account can connect via multiple OIDs, then they can add new ones as needed, and remove when they're done with them.\nEdit: Just saw that you were talking about django auth, not oauth. Oops. The second paragraph still stands.\n" ]
[ 5, 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002359272_django_python.txt
Q: Compatibility with IIS and Apache -- PHP, Python, etc? I'm currently planning out a web app that I want to host for people and allow them to host themselves on either Linux/Apache of IIS6 or IIS7 (for the benefits of bandwidth, directory services [login, etc.]). I see that PHP is supported on both platforms. I've heard people serving Django and Python in IIS using PyISAPIe. I'm not sure about Ruby/Rails on IIS until IronRuby ships. I don't have much Perl experience but understand it would run in IIS as well. Anyone have input for me? Thanks in advance. A: I have several production php5/6 applications that run on either windows/iis and apache/linux. switching between platforms has not been an issue for me. i test on a windows server talking to a mysql db on a linux machine. i deploy to a linux web server without issue. i cannot speak for rails or pytong as i'm not a ruby or python guy. however, they should work fine from what i understand of them. if i were you i'd pick the language you have the most experience with. A: Your lowest common denominator for building apps to seemlessly run on both the LAMP and Microsoft stacks is PHP. Perl is another option, it's well supported on both Windows and Linux/Apache. But I think I'd be choosing PHP over Perl because of support for FastCGI which improves reliability and performance on the Windows stack. Microsoft and Zend have been doing a lot of work on PHP for Windows so that you can write PHP apps and confidently expect them to run well on both platforms. The proof of the pudding of this is that Joomla, WordPress, phpBBS and many other of the well known open source PHP applications run straight out of the box on Windows. Also as a developer and third line support engineer for a shared web hosting company, with a fair bit of experience in this area, I'd say that PHP on Windows is every bit as flexible, performant and reliable as PHP on the LAMP stack. Finally, Ruby on Rails and Python/DJango aren't well supported options on IIS and will be non-existant on shared hosting platforms. This is mostly due to the amount of console access you'd need to knock things into shape to be able to run Rails/DJango.
Compatibility with IIS and Apache -- PHP, Python, etc?
I'm currently planning out a web app that I want to host for people and allow them to host themselves on either Linux/Apache of IIS6 or IIS7 (for the benefits of bandwidth, directory services [login, etc.]). I see that PHP is supported on both platforms. I've heard people serving Django and Python in IIS using PyISAPIe. I'm not sure about Ruby/Rails on IIS until IronRuby ships. I don't have much Perl experience but understand it would run in IIS as well. Anyone have input for me? Thanks in advance.
[ "I have several production php5/6 applications that run on either windows/iis and apache/linux. switching between platforms has not been an issue for me. i test on a windows server talking to a mysql db on a linux machine. i deploy to a linux web server without issue. i cannot speak for rails or pytong as i'm not a ruby or python guy. however, they should work fine from what i understand of them. if i were you i'd pick the language you have the most experience with.\n", "Your lowest common denominator for building apps to seemlessly run on both the LAMP and Microsoft stacks is PHP.\nPerl is another option, it's well supported on both Windows and Linux/Apache. But I think I'd be choosing PHP over Perl because of support for FastCGI which improves reliability and performance on the Windows stack. Microsoft and Zend have been doing a lot of work on PHP for Windows so that you can write PHP apps and confidently expect them to run well on both platforms. The proof of the pudding of this is that Joomla, WordPress, phpBBS and many other of the well known open source PHP applications run straight out of the box on Windows. \nAlso as a developer and third line support engineer for a shared web hosting company, with a fair bit of experience in this area, I'd say that PHP on Windows is every bit as flexible, performant and reliable as PHP on the LAMP stack.\nFinally, Ruby on Rails and Python/DJango aren't well supported options on IIS and will be non-existant on shared hosting platforms. This is mostly due to the amount of console access you'd need to knock things into shape to be able to run Rails/DJango.\n" ]
[ 0, 0 ]
[]
[]
[ "apache", "iis", "php", "python" ]
stackoverflow_0002359314_apache_iis_php_python.txt
Q: Python - lexical analysis and tokenization I'm looking to speed along my discovery process here quite a bit, as this is my first venture into the world of lexical analysis. Maybe this is even the wrong path. First, I'll describe my problem: I've got very large properties files (in the order of 1,000 properties), which when distilled, are really just about 15 important properties and the rest can be generated or rarely ever change. So, for example: general { name = myname ip = 127.0.0.1 } component1 { key = value foo = bar } This is the type of format I want to create to tokenize something like: property.${general.name}blah.home.directory = /blah property.${general.name}.ip = ${general.ip} property.${component1}.ip = ${general.ip} property.${component1}.foo = ${component1.foo} into property.mynameblah.home.directory = /blah property.myname.ip = 127.0.0.1 property.component1.ip = 127.0.0.1 property.component1.foo = bar Lexical analysis and tokenization sounds like my best route, but this is a very simple form of it. It's a simple grammar, a simple substitution and I'd like to make sure that I'm not bringing a sledgehammer to knock in a nail. I could create my own lexer and tokenizer, or ANTlr is a possibility, but I don't like re-inventing the wheel and ANTlr sounds like overkill. I'm not familiar with compiler techniques, so pointers in the right direction & code would be most appreciated. Note: I can change the input format. A: There's an excellent article on Using Regular Expressions for Lexical Analysis at effbot.org. Adapting the tokenizer to your problem: import re token_pattern = r""" (?P<identifier>[a-zA-Z_][a-zA-Z0-9_]*) |(?P<integer>[0-9]+) |(?P<dot>\.) |(?P<open_variable>[$][{]) |(?P<open_curly>[{]) |(?P<close_curly>[}]) |(?P<newline>\n) |(?P<whitespace>\s+) |(?P<equals>[=]) |(?P<slash>[/]) """ token_re = re.compile(token_pattern, re.VERBOSE) class TokenizerException(Exception): pass def tokenize(text): pos = 0 while True: m = token_re.match(text, pos) if not m: break pos = m.end() tokname = m.lastgroup tokvalue = m.group(tokname) yield tokname, tokvalue if pos != len(text): raise TokenizerException('tokenizer stopped at pos %r of %r' % ( pos, len(text))) To test it, we do: stuff = r'property.${general.name}.ip = ${general.ip}' stuff2 = r''' general { name = myname ip = 127.0.0.1 } ''' print ' stuff '.center(60, '=') for tok in tokenize(stuff): print tok print ' stuff2 '.center(60, '=') for tok in tokenize(stuff2): print tok for: ========================== stuff =========================== ('identifier', 'property') ('dot', '.') ('open_variable', '${') ('identifier', 'general') ('dot', '.') ('identifier', 'name') ('close_curly', '}') ('dot', '.') ('identifier', 'ip') ('whitespace', ' ') ('equals', '=') ('whitespace', ' ') ('open_variable', '${') ('identifier', 'general') ('dot', '.') ('identifier', 'ip') ('close_curly', '}') ========================== stuff2 ========================== ('newline', '\n') ('identifier', 'general') ('whitespace', ' ') ('open_curly', '{') ('newline', '\n') ('whitespace', ' ') ('identifier', 'name') ('whitespace', ' ') ('equals', '=') ('whitespace', ' ') ('identifier', 'myname') ('newline', '\n') ('whitespace', ' ') ('identifier', 'ip') ('whitespace', ' ') ('equals', '=') ('whitespace', ' ') ('integer', '127') ('dot', '.') ('integer', '0') ('dot', '.') ('integer', '0') ('dot', '.') ('integer', '1') ('newline', '\n') ('close_curly', '}') ('newline', '\n') A: A simple DFA works well for this. You only need a few states: Looking for ${ Seen ${ looking for at least one valid character forming the name Seen at least one valid name character, looking for more name characters or }. If the properties file is order agnostic, you might want a two pass processor to verify that each name resolves correctly. Of course, you then need to write the substitution code, but once you have a list of all the names used, the simplest possible implementation is a find/replace on ${name} with its corresponding value. A: For as simple as your format seems to be, I think a full-on parser/lexer would be way overkill. Seems like a combination of regexes and string manipulation would do the trick. Another idea is to change the file to something like json or xml and use an existing package. A: If you can change the format of the input files, then you could use a parser for an existing format, such as JSON. However, from your problem statement it sounds like that isn't the case. So if you want to create a custom lexer and parser, use PLY (Python Lex/Yacc). It is easy to use and works the same as lex/yacc. Here is a link to an example of a calculator built using PLY. Note that everything starting with t_ is a lexer rule - defining a valid token - and everything starting with p_ is a parser rule that defines a production of the grammar. A: The syntax you provide seems similar to Mako templates engine. I think you could give it a try, it's rather simple API.
Python - lexical analysis and tokenization
I'm looking to speed along my discovery process here quite a bit, as this is my first venture into the world of lexical analysis. Maybe this is even the wrong path. First, I'll describe my problem: I've got very large properties files (in the order of 1,000 properties), which when distilled, are really just about 15 important properties and the rest can be generated or rarely ever change. So, for example: general { name = myname ip = 127.0.0.1 } component1 { key = value foo = bar } This is the type of format I want to create to tokenize something like: property.${general.name}blah.home.directory = /blah property.${general.name}.ip = ${general.ip} property.${component1}.ip = ${general.ip} property.${component1}.foo = ${component1.foo} into property.mynameblah.home.directory = /blah property.myname.ip = 127.0.0.1 property.component1.ip = 127.0.0.1 property.component1.foo = bar Lexical analysis and tokenization sounds like my best route, but this is a very simple form of it. It's a simple grammar, a simple substitution and I'd like to make sure that I'm not bringing a sledgehammer to knock in a nail. I could create my own lexer and tokenizer, or ANTlr is a possibility, but I don't like re-inventing the wheel and ANTlr sounds like overkill. I'm not familiar with compiler techniques, so pointers in the right direction & code would be most appreciated. Note: I can change the input format.
[ "There's an excellent article on Using Regular Expressions for Lexical Analysis at effbot.org.\nAdapting the tokenizer to your problem:\nimport re\n\ntoken_pattern = r\"\"\"\n(?P<identifier>[a-zA-Z_][a-zA-Z0-9_]*)\n|(?P<integer>[0-9]+)\n|(?P<dot>\\.)\n|(?P<open_variable>[$][{])\n|(?P<open_curly>[{])\n|(?P<close_curly>[}])\n|(?P<newline>\\n)\n|(?P<whitespace>\\s+)\n|(?P<equals>[=])\n|(?P<slash>[/])\n\"\"\"\n\ntoken_re = re.compile(token_pattern, re.VERBOSE)\n\nclass TokenizerException(Exception): pass\n\ndef tokenize(text):\n pos = 0\n while True:\n m = token_re.match(text, pos)\n if not m: break\n pos = m.end()\n tokname = m.lastgroup\n tokvalue = m.group(tokname)\n yield tokname, tokvalue\n if pos != len(text):\n raise TokenizerException('tokenizer stopped at pos %r of %r' % (\n pos, len(text)))\n\nTo test it, we do:\nstuff = r'property.${general.name}.ip = ${general.ip}'\nstuff2 = r'''\ngeneral {\n name = myname\n ip = 127.0.0.1\n}\n'''\n\nprint ' stuff '.center(60, '=')\nfor tok in tokenize(stuff):\n print tok\n\nprint ' stuff2 '.center(60, '=')\nfor tok in tokenize(stuff2):\n print tok\n\nfor:\n========================== stuff ===========================\n('identifier', 'property')\n('dot', '.')\n('open_variable', '${')\n('identifier', 'general')\n('dot', '.')\n('identifier', 'name')\n('close_curly', '}')\n('dot', '.')\n('identifier', 'ip')\n('whitespace', ' ')\n('equals', '=')\n('whitespace', ' ')\n('open_variable', '${')\n('identifier', 'general')\n('dot', '.')\n('identifier', 'ip')\n('close_curly', '}')\n========================== stuff2 ==========================\n('newline', '\\n')\n('identifier', 'general')\n('whitespace', ' ')\n('open_curly', '{')\n('newline', '\\n')\n('whitespace', ' ')\n('identifier', 'name')\n('whitespace', ' ')\n('equals', '=')\n('whitespace', ' ')\n('identifier', 'myname')\n('newline', '\\n')\n('whitespace', ' ')\n('identifier', 'ip')\n('whitespace', ' ')\n('equals', '=')\n('whitespace', ' ')\n('integer', '127')\n('dot', '.')\n('integer', '0')\n('dot', '.')\n('integer', '0')\n('dot', '.')\n('integer', '1')\n('newline', '\\n')\n('close_curly', '}')\n('newline', '\\n')\n\n", "A simple DFA works well for this. You only need a few states:\n\nLooking for ${\nSeen ${ looking for at least one valid character forming the name\nSeen at least one valid name character, looking for more name characters or }.\n\nIf the properties file is order agnostic, you might want a two pass processor to verify that each name resolves correctly.\nOf course, you then need to write the substitution code, but once you have a list of all the names used, the simplest possible implementation is a find/replace on ${name} with its corresponding value.\n", "For as simple as your format seems to be, I think a full-on parser/lexer would be way overkill. Seems like a combination of regexes and string manipulation would do the trick. \nAnother idea is to change the file to something like json or xml and use an existing package.\n", "If you can change the format of the input files, then you could use a parser for an existing format, such as JSON.\nHowever, from your problem statement it sounds like that isn't the case. So if you want to create a custom lexer and parser, use PLY (Python Lex/Yacc). It is easy to use and works the same as lex/yacc.\nHere is a link to an example of a calculator built using PLY. Note that everything starting with t_ is a lexer rule - defining a valid token - and everything starting with p_ is a parser rule that defines a production of the grammar.\n", "The syntax you provide seems similar to Mako templates engine. I think you could give it a try, it's rather simple API.\n" ]
[ 14, 4, 2, 1, 1 ]
[]
[]
[ "lexical_analysis", "python", "transform" ]
stackoverflow_0002358890_lexical_analysis_python_transform.txt
Q: If I'm only planning to use MySQL, and if speed is a priority, is there any convincing reason to use SQLAlchemy? SQLAlchemy seems really heavyweight if all I use is MySQL. Why are convincing reasons for/against the use of SQLAlchemy in an application that only uses MySQL. A: ORM means that your OO application actually makes sense when interpreted as the interaction of objects. No ORM means that you must wallow in the impedance mismatch between SQL and Objects. Working without an ORM means lots of redundant code to map between SQL query result sets, individual SQL statements and objects. SQLAchemy partitions your application cleanly into objects that interact and a persistence mechanism that (today) happens to be a relational database. With SQLAlchemy you stand a fighting chance of separating the core model and processing from the odd limitations and quirks of a SQL RDBMS. A: I don't think performance should be much of a factor in your choice. The layer that an ORM adds will be insignificant compared to the speed of the database. Databases always end up being a bottleneck. Using an ORM may allow you to develop faster with less bugs. You can still access the DB directly if you have a query that doesn't work well with the ORM layer. A: sqlalchemy provides more than just an orm, you can select/insert/update/delete from table objects, join them etc.... the benefit of using those things over building strings with sql in them is guarding against sql injection attacks for one. You also get some decent connection management that you don't have to write yourself. The orm part may not be appropriate for your application, but rolling your own sql handling and connection handling would be really really stupid in my opinion.
If I'm only planning to use MySQL, and if speed is a priority, is there any convincing reason to use SQLAlchemy?
SQLAlchemy seems really heavyweight if all I use is MySQL. Why are convincing reasons for/against the use of SQLAlchemy in an application that only uses MySQL.
[ "ORM means that your OO application actually makes sense when interpreted as the interaction of objects.\nNo ORM means that you must wallow in the impedance mismatch between SQL and Objects. Working without an ORM means lots of redundant code to map between SQL query result sets, individual SQL statements and objects. \nSQLAchemy partitions your application cleanly into objects that interact and a persistence mechanism that (today) happens to be a relational database. \nWith SQLAlchemy you stand a fighting chance of separating the core model and processing from the odd limitations and quirks of a SQL RDBMS.\n", "I don't think performance should be much of a factor in your choice. The layer that an ORM adds will be insignificant compared to the speed of the database. Databases always end up being a bottleneck.\nUsing an ORM may allow you to develop faster with less bugs. You can still access the DB directly if you have a query that doesn't work well with the ORM layer.\n", "sqlalchemy provides more than just an orm, you can select/insert/update/delete from table objects, join them etc.... the benefit of using those things over building strings with sql in them is guarding against sql injection attacks for one. You also get some decent connection management that you don't have to write yourself. \nThe orm part may not be appropriate for your application, but rolling your own sql handling and connection handling would be really really stupid in my opinion.\n" ]
[ 7, 4, 0 ]
[]
[]
[ "mysql", "pylons", "python", "sqlalchemy" ]
stackoverflow_0002358822_mysql_pylons_python_sqlalchemy.txt
Q: Correctness about variable scope I'm currently developing some things in Python and I have a question about variables scope. This is the code: a = None anything = False if anything: a = 1 else: a = 2 print a # prints 2 If I remove the first line (a = None) the code still works as before. However in this case I'd be declaring the variable inside an "if" block, and regarding other languages like Java, that variable would only be visible inside the "if". How exactly variable scoping works in Python and what's the good way to program in cases like this? Thanks! A: As a rule of thumb, scopes are created in three places: File-scope - otherwise known as module scope Class-scope - created inside class blocks Function-scope - created inside def blocks (There are a few exceptions to these.) Assigning to a name reserves it in the scope namespace, marked as unbound until reaching the first assignment. So for a mental model, you are assigning values to names in a scope. A: I believe that Python uses function scope for local variables. That is, in any given function, if you assign a value to a local variable, it will be available from that moment onwards within that function until it returns. Therefore, since both branches of your code are guaranteed to assign to a, there is no need to assign None to a initially. Note that when you can also access variables declared in outer functions -- in other words, Python has closures. def adder(first): def add(second): return first + second return add This defines a function called adder. When called with an argument first, it will return a function that adds whatever argument it receives to first and return that value. For instance: add_two = adder(2) add_three = adder(3) add_two(4) # = 6 add_three(4) # = 7 However, although you can read the value from the outer function, you can't change it (unlike in many other languages). For instance, imagine trying to implement an accumulator. You might write code like so: def accumulator(): total = 0 def add(number): total += number return total return add Unfortunately, trying to use this code results in an error message: UnboundLocalError: local variable 'total' referenced before assignment This is because the line total += number tries to change the value of total, which cannot be done in this way in Python. A: There is no problem assigning the variable in the if block. In this case it is being assigned on both branches, so you can see it will definitely be defined when you come to print it. If one of the branches did not assign to a then a NameError exception would be raise when you try to print it after that branch A: Python doesn't need variables to be declared initially, so you can declare and define at arbitrary points. And yes, the scope is function scope, so it will be visible outside the if. A: i'm quite a beginner programmer, but for what i know, in python private variables don't exist. see private variables in the python documentation for a detailed discussion. useful informations can also be found in the section "scopes and namespaces" on the same page. personally, i write code like the one you posted pretty much every day, especially when the condition relies in getting input from the user, for example if len(sys.argv)==2: f = open(sys.argv[1], 'r') else: print ('provide input file') i do declare variables before using them for structured types, for example i declare an empty list before appending its items within a loop. hope it helps.
Correctness about variable scope
I'm currently developing some things in Python and I have a question about variables scope. This is the code: a = None anything = False if anything: a = 1 else: a = 2 print a # prints 2 If I remove the first line (a = None) the code still works as before. However in this case I'd be declaring the variable inside an "if" block, and regarding other languages like Java, that variable would only be visible inside the "if". How exactly variable scoping works in Python and what's the good way to program in cases like this? Thanks!
[ "As a rule of thumb, scopes are created in three places:\n\nFile-scope - otherwise known as module scope\nClass-scope - created inside class blocks\nFunction-scope - created inside def blocks\n\n(There are a few exceptions to these.)\nAssigning to a name reserves it in the scope namespace, marked as unbound until reaching the first assignment. So for a mental model, you are assigning values to names in a scope.\n", "I believe that Python uses function scope for local variables. That is, in any given function, if you assign a value to a local variable, it will be available from that moment onwards within that function until it returns. Therefore, since both branches of your code are guaranteed to assign to a, there is no need to assign None to a initially.\nNote that when you can also access variables declared in outer functions -- in other words, Python has closures.\ndef adder(first):\n def add(second):\n return first + second\n\n return add\n\nThis defines a function called adder. When called with an argument first, it will return a function that adds whatever argument it receives to first and return that value. For instance:\nadd_two = adder(2)\nadd_three = adder(3)\nadd_two(4) # = 6\nadd_three(4) # = 7\n\nHowever, although you can read the value from the outer function, you can't change it (unlike in many other languages). For instance, imagine trying to implement an accumulator. You might write code like so:\ndef accumulator():\n total = 0\n def add(number):\n total += number\n return total\n return add\n\nUnfortunately, trying to use this code results in an error message:\nUnboundLocalError: local variable 'total' referenced before assignment\n\nThis is because the line total += number tries to change the value of total, which cannot be done in this way in Python.\n", "There is no problem assigning the variable in the if block.\nIn this case it is being assigned on both branches, so you can see it will definitely be defined when you come to print it.\nIf one of the branches did not assign to a then a NameError exception would be raise when you try to print it after that branch\n", "Python doesn't need variables to be declared initially, so you can declare and define at arbitrary points. And yes, the scope is function scope, so it will be visible outside the if.\n", "i'm quite a beginner programmer, but for what i know, in python private variables don't exist. see private variables in the python documentation for a detailed discussion.\nuseful informations can also be found in the section \"scopes and namespaces\" on the same page.\npersonally, i write code like the one you posted pretty much every day, especially when the condition relies in getting input from the user, for example\nif len(sys.argv)==2:\n f = open(sys.argv[1], 'r')\nelse:\n print ('provide input file')\n\ni do declare variables before using them for structured types, for example i declare an empty list before appending its items within a loop.\nhope it helps.\n" ]
[ 8, 2, 1, 0, 0 ]
[]
[]
[ "python", "scope" ]
stackoverflow_0002359726_python_scope.txt
Q: Python try/except ... function always returns false I'm trying to figure out the problem in this short paragraph of code. Any help would be appreciated. Regardless of what I specify User.email to be, it always returns false. def add(self): #1 -- VALIDATE EMAIL ADDRESS #Check that e-mail has been completed try: #Validate if e-mail address is in correct format if (isAddressValid(self.email) == 0): self.errors['email'] = 'You have entered an invalid e-mail address'; return 0 except NameError: self.errors['email'] = 'Please enter your e-mail' return 0 >>> u = User() >>> u.email = 'test@example.com' >>> u.add() 0 >>> print u.errors {'email': 'Please enter your e-mail'} I have confirmed that the false being returned is coming from except NameError. Also, isAddressValid() is just a method to check the structure of an e-mail address. Thanks. A: You haven't included a return statement for the positive case... Also, when a function doesn't include a return statement, the caller receives None instead... def add(self): #1 -- VALIDATE EMAIL ADDRESS #Check that e-mail has been completed try: #Validate if e-mail address is in correct format if (isAddressValid(self.email) == 0): self.errors['email'] = 'You have entered an invalid e-mail address'; return False except NameError: self.errors['email'] = 'Please enter your e-mail' return False return True A: Actually you have two values. 0 None If you print the value instead of using it in an if-statement, you'll see the two conditions. Consider adding print statements to see what the value actually is. if (isAddressValid(self.email) == 0): If this is True, you get 0. If this is False, you'll get None. And the exception give 0. A: If I were re-writing this code, I would go for something like this: def add(self): try: if not isAddressValid(self.email): self.errors['email'] = 'You have entered an invalid e-mail address'; except NameError: self.errors['email'] = 'Please enter your e-mail' return 'email' not in self.errors A: Im not sure what problem you are talking about , but you are always returning 0 Try adding an else clause for the case of the Valid Email (which you are currently not considering) def add(self): #1 -- VALIDATE EMAIL ADDRESS #Check that e-mail has been completed try: #Validate if e-mail address is in correct format if (isAddressValid(self.email) == 0): self.errors['email'] = 'You have entered an invalid e-mail address'; return 0 else return 1 except NameError: self.errors['email'] = 'Please enter your e-mail' return 0 A: You said isAddressValid is a method, right? Since add is also a method, perhaps you have to prepend a self.: if (self.isAddressValid(self.email) == 0): This most probably will deal with your NameError. After that, add an else clause when the check succeeds: … self.errors['email'] = 'You have entered an invalid e-mail address' return 0 else: return 1
Python try/except ... function always returns false
I'm trying to figure out the problem in this short paragraph of code. Any help would be appreciated. Regardless of what I specify User.email to be, it always returns false. def add(self): #1 -- VALIDATE EMAIL ADDRESS #Check that e-mail has been completed try: #Validate if e-mail address is in correct format if (isAddressValid(self.email) == 0): self.errors['email'] = 'You have entered an invalid e-mail address'; return 0 except NameError: self.errors['email'] = 'Please enter your e-mail' return 0 >>> u = User() >>> u.email = 'test@example.com' >>> u.add() 0 >>> print u.errors {'email': 'Please enter your e-mail'} I have confirmed that the false being returned is coming from except NameError. Also, isAddressValid() is just a method to check the structure of an e-mail address. Thanks.
[ "You haven't included a return statement for the positive case... Also, when a function doesn't include a return statement, the caller receives None instead... \ndef add(self):\n\n #1 -- VALIDATE EMAIL ADDRESS\n #Check that e-mail has been completed\n try:\n #Validate if e-mail address is in correct format\n if (isAddressValid(self.email) == 0):\n self.errors['email'] = 'You have entered an invalid e-mail address';\n return False\n\n except NameError:\n self.errors['email'] = 'Please enter your e-mail'\n return False\n\n return True\n\n", "Actually you have two values.\n\n0\nNone\n\nIf you print the value instead of using it in an if-statement, you'll see the two conditions. Consider adding print statements to see what the value actually is.\nif (isAddressValid(self.email) == 0):\n\nIf this is True, you get 0.\nIf this is False, you'll get None.\nAnd the exception give 0.\n", "If I were re-writing this code, I would go for something like this:\ndef add(self):\n try:\n if not isAddressValid(self.email):\n self.errors['email'] = 'You have entered an invalid e-mail address';\n except NameError:\n self.errors['email'] = 'Please enter your e-mail'\n return 'email' not in self.errors\n\n", "Im not sure what problem you are talking about , but you are always returning 0\nTry adding an else clause for the case of the Valid Email (which you are currently not considering)\ndef add(self):\n\n#1 -- VALIDATE EMAIL ADDRESS\n#Check that e-mail has been completed\ntry:\n #Validate if e-mail address is in correct format\n if (isAddressValid(self.email) == 0):\n self.errors['email'] = 'You have entered an invalid e-mail address';\n return 0\n else\n return 1\n\nexcept NameError:\n self.errors['email'] = 'Please enter your e-mail'\n return 0\n\n", "You said isAddressValid is a method, right? Since add is also a method, perhaps you have to prepend a self.:\nif (self.isAddressValid(self.email) == 0):\n\nThis most probably will deal with your NameError.\nAfter that, add an else clause when the check succeeds:\n …\n self.errors['email'] = 'You have entered an invalid e-mail address'\n return 0\nelse:\n return 1\n\n" ]
[ 5, 1, 1, 0, 0 ]
[]
[]
[ "pylons", "python" ]
stackoverflow_0002356573_pylons_python.txt
Q: Tips on how to parse custom file format Sorry about the vague title, but I really don't know how to describe this problem concisely. I've created a (more or less) simple domain-specific language that I will to use to specify what validation rules to apply to different entities (generally forms submitted from a web page). I've included a sample at the bottom of this post of what the language looks like. My problem is that I have no idea how to begin parsing this language into a form I can use (I will be using Python to do the parsing). My goal is to end up with a list of rules/filters (as strings, including arguments, e.g. 'cocoa(99)') that should be applied (in order) to each object/entity (also a string, e.g. 'chocolate', 'chocolate.lindt', etc.). I'm not sure what technique to use to start with, or even what techniques exist for problems like this. What do you think is the best way of going about this? I'm not looking for a complete solution, just a general nudge in the right direction. Thanks. Sample file of language: # Comments start with the '#' character and last until the end of the line # Indentation is significant (as in Python) constant NINETY_NINE = 99 # Defines the constant `NINETY_NINE` to have the value `99` *: # Applies to all data isYummy # Everything must be yummy chocolate: # To validate, say `validate("chocolate", object)` sweet # chocolate must be sweet (but not necessarily chocolate.*) lindt: # To validate, say `validate("chocolate.lindt", object)` tasty # Applies only to chocolate.lindt (and not to chocolate.lindt.dark, for e.g.) *: # Applies to all data under chocolate.lindt smooth # Could also be written smooth() creamy(1) # Level 1 creamy dark: # dark has no special validation rules extraDark: melt # Filter that modifies the object being examined c:bitter # Must be bitter, but only validated on client s:cocoa(NINETY_NINE) # Must contain 99% cocoa, but only validated on server. Note constant milk: creamy(2) # Level 2 creamy, overrides creamy(1) of chocolate.lindt.* for chocolate.lindt.milk creamy(3) # Overrides creamy(2) of previous line (all but the last specification of a given rule are ignored) ruleset food: # To define a chunk of validation rules that can be expanded from the placeholder `food` (think macro) caloriesWithin(10, 2000) # Unlimited parameters allowed edible leftovers: # Nested rules allowed in rulesets stale # Rulesets may be nested and/or include other rulesets in their definition chocolate: # Previously defined groups can be re-opened and expanded later ferrero: hasHazelnut cake: tasty # Same rule used for different data (see chocolate.lindt) isLie ruleset food # Substitutes with rules defined for food; cake.leftovers must now be stale pasta: ruleset food # pasta.leftovers must also be stale # Sample use (in JavaScript): # var choc = { # lindt: { # cocoa: { # percent: 67, # mass: '27g' # } # } # // Objects/groups that are ommitted (e.g. ferrro in this example) are not validated and raise no errors # // Objects that are not defined in the validation rules do not raise any errors (e.g. cocoa in this example) # }; # validate('chocolate', choc); # `validate` called isYummy(choc), sweet(choc), isYummy(choc.lindt), smooth(choc.lindt), creamy(choc.lindt, 1), and tasty(choc.lindt) in that order # `validate` returned an array of any validation errors that were found # Order of rule validation for objects: # The current object is initially the object passed in to the validation function (second argument). # The entry point in the rule group hierarchy is given by the first argument to the validation function. # 1. First all rules that apply to all objects (defined using '*') are applied to the current object, # starting with the most global rules and ending with the most local ones. # 2. Then all specific rules for the current object are applied. # 3. Then a depth-first traversal of the current object is done, repeating steps 1 and 2 with each object found as the current object # When two rules have equal priority, they are applied in the order they were defined in the file. # No need to end on blank line A: First off, if you want to learn about parsing, then write your own recursive descent parser. The language you've defined only requires a handful of productions. I suggest using Python's tokenize library to spare yourself the boring task of converting a stream of bytes into a stream of tokens. For practical parsing options, read on... A quick and dirty solution is to use python itself: NINETY_NINE = 99 # Defines the constant `NINETY_NINE` to have the value `99` rules = { '*': { # Applies to all data 'isYummy': {}, # Everything must be yummy 'chocolate': { # To validate, say `validate("chocolate", object)` 'sweet': {}, # chocolate must be sweet (but not necessarily chocolate.*) 'lindt': { # To validate, say `validate("chocolate.lindt", object)` 'tasty':{} # Applies only to chocolate.lindt (and not to chocolate.lindt.dark, for e.g.) '*': { # Applies to all data under chocolate.lindt 'smooth': {} # Could also be written smooth() 'creamy': 1 # Level 1 creamy }, # ... } } } There are several ways to pull off this trick, e.g., here's a cleaner (albeit somewhat unusual) approach using classes: class _: class isYummy: pass class chocolate: class sweet: pass class lindt: class tasty: pass class _: class smooth: pass class creamy: level = 1 # ... As an intermediate step to a full parser, you can use the "batteries-included" Python parser, which parses Python syntax and returns an AST. The AST is very deep with lots of (IMO) unnecessary levels. You can filter these down to a much simpler structure by culling any nodes that have only one child. With this approach you can do something like this: import parser, token, symbol, pprint _map = dict(token.tok_name.items() + symbol.sym_name.items()) def clean_ast(ast): if not isinstance(ast, list): return ast elif len(ast) == 2: # Elide single-child nodes. return clean_ast(ast[1]) else: return [_map[ast[0]]] + [clean_ast(a) for a in ast[1:]] ast = parser.expr('''{ '*': { # Applies to all data isYummy: _, # Everything must be yummy chocolate: { # To validate, say `validate("chocolate", object)` sweet: _, # chocolate must be sweet (but not necessarily chocolate.*) lindt: { # To validate, say `validate("chocolate.lindt", object)` tasty: _, # Applies only to chocolate.lindt (and not to chocolate.lindt.dark, for e.g.) '*': { # Applies to all data under chocolate.lindt smooth: _, # Could also be written smooth() creamy: 1 # Level 1 creamy } # ... } } } }''').tolist() pprint.pprint(clean_ast(ast)) This approach does have its limitations. The final AST is still a bit noisy, and the language you define has to be interpretable as valid python code. For instance, you couldn't support this... *: isYummy ...because this syntax doesn't parse as python code. Its big advantage, however, is that you control the AST conversion, so it is impossible to inject arbitrary Python code. A: Again not teaching you about parsing, but your format is so close to legal YAML that you might want to just redefine your language as a subset of YAML and use a standard YAML parser. A: If your goal is to learn about parsing, I'd highly recommend an OO style library like PyParsing. They are not as fast as the more sophisticated antler, lex, yac options, but you get started with the parsing right away. A: As 'Marcelo Cantos' suggested you can use python dict, benefit is that you do not have to parse any thing, you can use same rules on server side as python dict and on client side using javascript objects, and can pass them from server to client or viceversa as JSON. If you really want to do parsing yourself see this http://nedbatchelder.com/text/python-parsers.html but I am not sure you will be easily able to parse a indented language. A: The language you've shown an example for is probably too complex to write a simple (and bug-free) parsing function for. I'd suggest reading up on parsing techniques such as recursive-descent or table-driven parsing such as LL(1), LL(k), etc. But that may be too general and/or complicated. It might be easier to simplify your rules language to something simple like delimited text. For example, something like chocolate:sweet chocolate.lindt:tasty chocolate.lindt.*:smooth,creamy(1) This would be easier to parse and could be done without formal parsers. A: There are libraries and tools to make parsing easier. One of the more well known is lex / yacc. There's a python library called 'lex' and a tutorial on using it. A: what is the motivation for the customized file structure? Would it be possible to remodel your data into a better known structure like XML? If so you could use one of a multitude to parse your file. Using an accepted parsing tool may save you a lot of time debugging, and it may make your file more readable if that is a consideration
Tips on how to parse custom file format
Sorry about the vague title, but I really don't know how to describe this problem concisely. I've created a (more or less) simple domain-specific language that I will to use to specify what validation rules to apply to different entities (generally forms submitted from a web page). I've included a sample at the bottom of this post of what the language looks like. My problem is that I have no idea how to begin parsing this language into a form I can use (I will be using Python to do the parsing). My goal is to end up with a list of rules/filters (as strings, including arguments, e.g. 'cocoa(99)') that should be applied (in order) to each object/entity (also a string, e.g. 'chocolate', 'chocolate.lindt', etc.). I'm not sure what technique to use to start with, or even what techniques exist for problems like this. What do you think is the best way of going about this? I'm not looking for a complete solution, just a general nudge in the right direction. Thanks. Sample file of language: # Comments start with the '#' character and last until the end of the line # Indentation is significant (as in Python) constant NINETY_NINE = 99 # Defines the constant `NINETY_NINE` to have the value `99` *: # Applies to all data isYummy # Everything must be yummy chocolate: # To validate, say `validate("chocolate", object)` sweet # chocolate must be sweet (but not necessarily chocolate.*) lindt: # To validate, say `validate("chocolate.lindt", object)` tasty # Applies only to chocolate.lindt (and not to chocolate.lindt.dark, for e.g.) *: # Applies to all data under chocolate.lindt smooth # Could also be written smooth() creamy(1) # Level 1 creamy dark: # dark has no special validation rules extraDark: melt # Filter that modifies the object being examined c:bitter # Must be bitter, but only validated on client s:cocoa(NINETY_NINE) # Must contain 99% cocoa, but only validated on server. Note constant milk: creamy(2) # Level 2 creamy, overrides creamy(1) of chocolate.lindt.* for chocolate.lindt.milk creamy(3) # Overrides creamy(2) of previous line (all but the last specification of a given rule are ignored) ruleset food: # To define a chunk of validation rules that can be expanded from the placeholder `food` (think macro) caloriesWithin(10, 2000) # Unlimited parameters allowed edible leftovers: # Nested rules allowed in rulesets stale # Rulesets may be nested and/or include other rulesets in their definition chocolate: # Previously defined groups can be re-opened and expanded later ferrero: hasHazelnut cake: tasty # Same rule used for different data (see chocolate.lindt) isLie ruleset food # Substitutes with rules defined for food; cake.leftovers must now be stale pasta: ruleset food # pasta.leftovers must also be stale # Sample use (in JavaScript): # var choc = { # lindt: { # cocoa: { # percent: 67, # mass: '27g' # } # } # // Objects/groups that are ommitted (e.g. ferrro in this example) are not validated and raise no errors # // Objects that are not defined in the validation rules do not raise any errors (e.g. cocoa in this example) # }; # validate('chocolate', choc); # `validate` called isYummy(choc), sweet(choc), isYummy(choc.lindt), smooth(choc.lindt), creamy(choc.lindt, 1), and tasty(choc.lindt) in that order # `validate` returned an array of any validation errors that were found # Order of rule validation for objects: # The current object is initially the object passed in to the validation function (second argument). # The entry point in the rule group hierarchy is given by the first argument to the validation function. # 1. First all rules that apply to all objects (defined using '*') are applied to the current object, # starting with the most global rules and ending with the most local ones. # 2. Then all specific rules for the current object are applied. # 3. Then a depth-first traversal of the current object is done, repeating steps 1 and 2 with each object found as the current object # When two rules have equal priority, they are applied in the order they were defined in the file. # No need to end on blank line
[ "First off, if you want to learn about parsing, then write your own recursive descent parser. The language you've defined only requires a handful of productions. I suggest using Python's tokenize library to spare yourself the boring task of converting a stream of bytes into a stream of tokens.\nFor practical parsing options, read on...\nA quick and dirty solution is to use python itself:\nNINETY_NINE = 99 # Defines the constant `NINETY_NINE` to have the value `99`\n\nrules = {\n '*': { # Applies to all data\n 'isYummy': {}, # Everything must be yummy\n\n 'chocolate': { # To validate, say `validate(\"chocolate\", object)`\n 'sweet': {}, # chocolate must be sweet (but not necessarily chocolate.*)\n\n 'lindt': { # To validate, say `validate(\"chocolate.lindt\", object)`\n 'tasty':{} # Applies only to chocolate.lindt (and not to chocolate.lindt.dark, for e.g.)\n\n '*': { # Applies to all data under chocolate.lindt\n 'smooth': {} # Could also be written smooth()\n 'creamy': 1 # Level 1 creamy\n },\n# ...\n }\n }\n}\n\nThere are several ways to pull off this trick, e.g., here's a cleaner (albeit somewhat unusual) approach using classes:\nclass _:\n class isYummy: pass\n\n class chocolate:\n class sweet: pass\n\n class lindt:\n class tasty: pass\n\n class _:\n class smooth: pass\n class creamy: level = 1\n# ...\n\nAs an intermediate step to a full parser, you can use the \"batteries-included\" Python parser, which parses Python syntax and returns an AST. The AST is very deep with lots of (IMO) unnecessary levels. You can filter these down to a much simpler structure by culling any nodes that have only one child. With this approach you can do something like this:\nimport parser, token, symbol, pprint\n\n_map = dict(token.tok_name.items() + symbol.sym_name.items())\n\ndef clean_ast(ast):\n if not isinstance(ast, list):\n return ast\n elif len(ast) == 2: # Elide single-child nodes.\n return clean_ast(ast[1])\n else:\n return [_map[ast[0]]] + [clean_ast(a) for a in ast[1:]]\n\nast = parser.expr('''{\n\n'*': { # Applies to all data\n isYummy: _, # Everything must be yummy\n\n chocolate: { # To validate, say `validate(\"chocolate\", object)`\n sweet: _, # chocolate must be sweet (but not necessarily chocolate.*)\n\n lindt: { # To validate, say `validate(\"chocolate.lindt\", object)`\n tasty: _, # Applies only to chocolate.lindt (and not to chocolate.lindt.dark, for e.g.)\n\n '*': { # Applies to all data under chocolate.lindt\n smooth: _, # Could also be written smooth()\n creamy: 1 # Level 1 creamy\n }\n# ...\n }\n }\n}\n\n}''').tolist()\npprint.pprint(clean_ast(ast))\n\nThis approach does have its limitations. The final AST is still a bit noisy, and the language you define has to be interpretable as valid python code. For instance, you couldn't support this...\n*:\n isYummy\n\n...because this syntax doesn't parse as python code. Its big advantage, however, is that you control the AST conversion, so it is impossible to inject arbitrary Python code.\n", "Again not teaching you about parsing, but your format is so close to legal YAML that you might want to just redefine your language as a subset of YAML and use a standard YAML parser.\n", "If your goal is to learn about parsing, I'd highly recommend an OO style library like PyParsing. They are not as fast as the more sophisticated antler, lex, yac options, but you get started with the parsing right away. \n", "As 'Marcelo Cantos' suggested you can use python dict, benefit is that you do not have to parse any thing, you can use same rules on server side as python dict and on client side using javascript objects, and can pass them from server to client or viceversa as JSON.\nIf you really want to do parsing yourself see this\nhttp://nedbatchelder.com/text/python-parsers.html\nbut I am not sure you will be easily able to parse a indented language.\n", "The language you've shown an example for is probably too complex to write a simple (and bug-free) parsing function for. I'd suggest reading up on parsing techniques such as recursive-descent or table-driven parsing such as LL(1), LL(k), etc.\nBut that may be too general and/or complicated. It might be easier to simplify your rules language to something simple like delimited text.\nFor example, something like\nchocolate:sweet\nchocolate.lindt:tasty\nchocolate.lindt.*:smooth,creamy(1)\nThis would be easier to parse and could be done without formal parsers.\n", "There are libraries and tools to make parsing easier. One of the more well known is lex / yacc. There's a python library called 'lex' and a tutorial on using it.\n", "what is the motivation for the customized file structure? Would it be possible to remodel your data into a better known structure like XML? If so you could use one of a multitude to parse your file. Using an accepted parsing tool may save you a lot of time debugging, and it may make your file more readable if that is a consideration\n" ]
[ 9, 5, 3, 2, 1, 0, 0 ]
[]
[]
[ "file_format", "parsing", "python" ]
stackoverflow_0002036236_file_format_parsing_python.txt
Q: Bash while loop calling a Python script I would like to call a Python script from within a Bash while loop. However, I do not understand very well how to use appropriately the while loop (and maybe variable) syntax of the Bash. The behaviour I am looking for is that, while a file still contains lines (DNA sequences), I am calling a Python script to extract groups of sequences so that another program (dialign2) can align them. Finally, I add the alignments to a result file. Note: I am not trying to iterate over the file. What should I change in order for the Bash while loop to work? I also want to be sure that the while loop will re-check the changing file.txt on each loop. Here is my attempt: #!/bin/bash # Call a python script as many times as needed to treat a text file c=1 while [ `wc -l file.txt` > 0 ] ; # Stop when file.txt has no more lines do echo "Python script called $c times" python script.py # Uses file.txt and removes lines from it # The Python script also returns a temp.txt file containing DNA sequences c=$c + 1 dialign -f temp.txt # aligns DNA sequences cat temp.fa >>results.txt # append DNA alignements to result file done Thanks! A: No idea why you want to do this. c=1 while [[ -s file.txt ]] ; # Stop when file.txt has no more lines do echo "Python script called $c times" python script.py # Uses file.txt and removes lines from it c=$(($c + 1)) done A: try -gt to eliminate the shell metacharacter > while [ `wc -l file.txt` -gt 0 ] do ... c=$[c + 1] done A: The following should do what you say you want: #!/bin/bash c=1 while read line; do echo "Python script called $c times" # $line contains a line of text from file.txt python script.py c=$((c + 1)) done < file.txt However, there is no need to use bash, to iterate over the lines in a file. You can do that quite easily without ever leaving python: myfile = open('file.txt', 'r') for count, line in enumerate(myfile): print '%i lines in file' % (count + 1,) # the variable "line" contains the line of text from the file.txt # Do your thing here. A: @OP if you want to loop through a file , just use while read loop. Also, you are not using the variables $c as well as the line. Are you passing each line to your Python script? Or you just calling your Python script whenever a line is encountered? (your script going to be slow if you do that) while true do while read -r line do # if you are taking STDIN in myscript.py, then something must be passed to # myscript.py, if not i really don't understand what you are doing. echo "$line" | python myscript.py > temp.txt dialign -f temp.txt # aligns DNA sequences cat temp.txt >>results.txt done <"file.txt" if [ ! -s "file.txt" ]; break ;fi done Lastly, you could have done everything in Python. the way to iterate "file.txt" in Python is simply f=open("file.txt"): for line in f: print "do something with line" print "or bring what you have in myscript.py here" f.close()
Bash while loop calling a Python script
I would like to call a Python script from within a Bash while loop. However, I do not understand very well how to use appropriately the while loop (and maybe variable) syntax of the Bash. The behaviour I am looking for is that, while a file still contains lines (DNA sequences), I am calling a Python script to extract groups of sequences so that another program (dialign2) can align them. Finally, I add the alignments to a result file. Note: I am not trying to iterate over the file. What should I change in order for the Bash while loop to work? I also want to be sure that the while loop will re-check the changing file.txt on each loop. Here is my attempt: #!/bin/bash # Call a python script as many times as needed to treat a text file c=1 while [ `wc -l file.txt` > 0 ] ; # Stop when file.txt has no more lines do echo "Python script called $c times" python script.py # Uses file.txt and removes lines from it # The Python script also returns a temp.txt file containing DNA sequences c=$c + 1 dialign -f temp.txt # aligns DNA sequences cat temp.fa >>results.txt # append DNA alignements to result file done Thanks!
[ "No idea why you want to do this.\nc=1\nwhile [[ -s file.txt ]] ; # Stop when file.txt has no more lines\ndo\n echo \"Python script called $c times\"\n python script.py # Uses file.txt and removes lines from it\n c=$(($c + 1))\ndone\n\n", "try -gt to eliminate the shell metacharacter >\nwhile [ `wc -l file.txt` -gt 0 ]\ndo\n ...\n c=$[c + 1]\ndone\n\n", "The following should do what you say you want:\n#!/bin/bash\n\nc=1\nwhile read line; \ndo\n echo \"Python script called $c times\"\n # $line contains a line of text from file.txt\n python script.py \n c=$((c + 1))\ndone < file.txt\n\nHowever, there is no need to use bash, to iterate over the lines in a file. You can do that quite easily without ever leaving python:\nmyfile = open('file.txt', 'r')\n\nfor count, line in enumerate(myfile):\n print '%i lines in file' % (count + 1,)\n # the variable \"line\" contains the line of text from the file.txt \n\n # Do your thing here.\n\n", "@OP if you want to loop through a file , just use while read loop. Also, you are not using the variables $c as well as the line. Are you passing each line to your Python script? Or you just calling your Python script whenever a line is encountered? (your script going to be slow if you do that)\nwhile true\ndo\n while read -r line\n do\n # if you are taking STDIN in myscript.py, then something must be passed to\n # myscript.py, if not i really don't understand what you are doing.\n\n echo \"$line\" | python myscript.py > temp.txt\n dialign -f temp.txt # aligns DNA sequences\n cat temp.txt >>results.txt\n done <\"file.txt\"\n if [ ! -s \"file.txt\" ]; break ;fi\ndone \n\nLastly, you could have done everything in Python. the way to iterate \"file.txt\" in Python is simply\nf=open(\"file.txt\"):\nfor line in f:\n print \"do something with line\"\n print \"or bring what you have in myscript.py here\"\nf.close()\n\n" ]
[ 3, 1, 0, 0 ]
[]
[]
[ "bash", "python", "while_loop" ]
stackoverflow_0002359896_bash_python_while_loop.txt
Q: How to import constants from .h file into python module What is a recommended way to import a bunch of constants defined in a c-style (not c++, just plain old c) .h file into python module so that it can be used in python's part of a project. In the project we use a mix of languages and in perl I can do this importing by using h2xs utility to generate .pm module. Constants definition looks like #define FOO 1 enum { BAR, BAZ }; etc. C-style comments are also presented an have to be properly handled. A: I recently used the pyparsing library to scan for enum constants. Here it is, along with a sample string and the resulting output. Notice it also handles comments and commented out sections. With a little modification it could stuff the constants in a dictionary. from pyparsing import * sample = ''' stuff before enum hello { Zero, One, Two, Three, Five=5, Six, Ten=10 } in the middle enum blah { alpha, // blah beta, /* blah blah gamma = 10 , */ zeta = 50 } at the end ''' # syntax we don't want to see in the final parse tree _lcurl = Suppress('{') _rcurl = Suppress('}') _equal = Suppress('=') _comma = Suppress(',') _enum = Suppress('enum') identifier = Word(alphas,alphanums+'_') integer = Word(nums) enumValue = Group(identifier('name') + Optional(_equal + integer('value'))) enumList = Group(enumValue + ZeroOrMore(_comma + enumValue)) enum = _enum + identifier('enum') + _lcurl + enumList('list') + _rcurl enum.ignore(cppStyleComment) for item,start,stop in enum.scanString(sample): id = 0 for entry in item.list: if entry.value != '': id = int(entry.value) print '%s_%s = %d' % (item.enum.upper(),entry.name.upper(),id) id += 1 OUTPUT: HELLO_ZERO = 0 HELLO_ONE = 1 HELLO_TWO = 2 HELLO_THREE = 3 HELLO_FIVE = 5 HELLO_SIX = 6 HELLO_TEN = 10 BLAH_ALPHA = 0 BLAH_BETA = 1 BLAH_ZETA = 50 A: I once had to do something similar, and in the end I did something strange but highly reliable. Dealing with all the possibilities for how values might be defined is tricky... for instance, you have to handle #include "someotherfile.h" enum NewEnum { A = -5, B = SOME_OTHER_ENUM, C, D = 3 }; (which is really nasty and no one should ever do...) In the end, part of my build process was a perl script that parsed the header file for all enums and defines, and then produced a .c file that included the header and was nothing more then a bunch of print statements, printing the actual value for each define. This file was compiled and executed, and the output of that was used to produce the next source file ( Java, in my case ). This ensured that I got the right values, as I was using the C preprocessor and compiler to produce the answers. A: I'd suggest the other way round, if possible: define all your constants in a Python dict or module and auto-generate the .h in Python. It will be much, much easier. A: Create a script/program that is called from make and creates the necessary python file. If you only need #define and enum it shouldn't be too hard to write. Then remember NOT to check this python file into source control as you want the build process to force the regeneration of the file every time.
How to import constants from .h file into python module
What is a recommended way to import a bunch of constants defined in a c-style (not c++, just plain old c) .h file into python module so that it can be used in python's part of a project. In the project we use a mix of languages and in perl I can do this importing by using h2xs utility to generate .pm module. Constants definition looks like #define FOO 1 enum { BAR, BAZ }; etc. C-style comments are also presented an have to be properly handled.
[ "I recently used the pyparsing library to scan for enum constants. Here it is, along with a sample string and the resulting output. Notice it also handles comments and commented out sections. With a little modification it could stuff the constants in a dictionary.\nfrom pyparsing import *\n\nsample = '''\n stuff before\n\n enum hello {\n Zero,\n One,\n Two,\n Three,\n Five=5,\n Six,\n Ten=10\n }\n\n in the middle\n\n enum blah\n {\n alpha, // blah\n beta, /* blah blah\n gamma = 10 , */\n zeta = 50\n }\n\n at the end\n '''\n\n# syntax we don't want to see in the final parse tree\n_lcurl = Suppress('{')\n_rcurl = Suppress('}')\n_equal = Suppress('=')\n_comma = Suppress(',')\n_enum = Suppress('enum')\n\nidentifier = Word(alphas,alphanums+'_')\ninteger = Word(nums)\n\nenumValue = Group(identifier('name') + Optional(_equal + integer('value')))\nenumList = Group(enumValue + ZeroOrMore(_comma + enumValue))\nenum = _enum + identifier('enum') + _lcurl + enumList('list') + _rcurl\n\nenum.ignore(cppStyleComment)\n\nfor item,start,stop in enum.scanString(sample):\n id = 0\n for entry in item.list:\n if entry.value != '':\n id = int(entry.value)\n print '%s_%s = %d' % (item.enum.upper(),entry.name.upper(),id)\n id += 1\n\nOUTPUT:\nHELLO_ZERO = 0\nHELLO_ONE = 1\nHELLO_TWO = 2\nHELLO_THREE = 3\nHELLO_FIVE = 5\nHELLO_SIX = 6\nHELLO_TEN = 10\nBLAH_ALPHA = 0\nBLAH_BETA = 1\nBLAH_ZETA = 50\n\n", "I once had to do something similar, and in the end I did something strange but highly reliable. Dealing with all the possibilities for how values might be defined is tricky... for instance, you have to handle\n#include \"someotherfile.h\"\nenum NewEnum {\n A = -5,\n B = SOME_OTHER_ENUM, \n C,\n D = 3\n};\n\n(which is really nasty and no one should ever do...)\nIn the end, part of my build process was a perl script that parsed the header file for all enums and defines, and then produced a .c file that included the header and was nothing more then a bunch of print statements, printing the actual value for each define. This file was compiled and executed, and the output of that was used to produce the next source file ( Java, in my case ).\nThis ensured that I got the right values, as I was using the C preprocessor and compiler to produce the answers.\n", "I'd suggest the other way round, if possible: define all your constants in a Python dict or module and auto-generate the .h in Python. It will be much, much easier.\n", "Create a script/program that is called from make and creates the necessary python file. If you only need #define and enum it shouldn't be too hard to write. Then remember NOT to check this python file into source control as you want the build process to force the regeneration of the file every time.\n" ]
[ 6, 1, 0, 0 ]
[]
[]
[ "c", "python" ]
stackoverflow_0001942020_c_python.txt
Q: Dealing with UTF-8 numbers in Python Suppose I am reading a file containing 3 comma separated numbers. The file was saved with with an unknown encoding, so far I am dealing with ANSI and UTF-8. If the file was in UTF-8 and it had 1 row with values 115,113,12 then: with open(file) as f: a,b,c=map(int,f.readline().split(',')) would throw this: invalid literal for int() with base 10: '\xef\xbb\xbf115' The first number is always mangled with these '\xef\xbb\xbf' characters. For the rest 2 numbers the conversion works fine. If I manually replace '\xef\xbb\xbf' with '' and then do the int conversion it will work. Is there a better way of doing this for any type of encoded file? A: import codecs with codecs.open(file, "r", "utf-8-sig") as f: a, b, c= map(int, f.readline().split(",")) This works in Python 2.6.4. The codecs.open call opens the file and returns data as unicode, decoding from UTF-8 and ignoring the initial BOM. A: What you're seeing is a UTF-8 encoded BOM, or "Byte Order Mark". The BOM is not usually used for UTF-8 files, so the best way to handle it might be to open the file with a UTF-8 codec, and skip over the U+FEFF character if present.
Dealing with UTF-8 numbers in Python
Suppose I am reading a file containing 3 comma separated numbers. The file was saved with with an unknown encoding, so far I am dealing with ANSI and UTF-8. If the file was in UTF-8 and it had 1 row with values 115,113,12 then: with open(file) as f: a,b,c=map(int,f.readline().split(',')) would throw this: invalid literal for int() with base 10: '\xef\xbb\xbf115' The first number is always mangled with these '\xef\xbb\xbf' characters. For the rest 2 numbers the conversion works fine. If I manually replace '\xef\xbb\xbf' with '' and then do the int conversion it will work. Is there a better way of doing this for any type of encoded file?
[ "import codecs\n\nwith codecs.open(file, \"r\", \"utf-8-sig\") as f:\n a, b, c= map(int, f.readline().split(\",\"))\n\nThis works in Python 2.6.4. The codecs.open call opens the file and returns data as unicode, decoding from UTF-8 and ignoring the initial BOM.\n", "What you're seeing is a UTF-8 encoded BOM, or \"Byte Order Mark\". The BOM is not usually used for UTF-8 files, so the best way to handle it might be to open the file with a UTF-8 codec, and skip over the U+FEFF character if present.\n" ]
[ 17, 13 ]
[]
[]
[ "byte_order_mark", "character_encoding", "python", "utf_8" ]
stackoverflow_0002359832_byte_order_mark_character_encoding_python_utf_8.txt
Q: how to read an excel file on google app engine Generally I work with CSV files but for this project I need to support XLS too. Does anyone have experience reading XLS files on GAE with Python? 2 possible alternatives I am considering: xlrd Google Docs API A: xlrd saves you the network round-trip implied by the use of Google Docs; if you don't need to keep the document stored (which would be a substantial plus for Google Docs), this might incline you towards xlrd. I believe they're both high-quality. However, for both speed and accuracy of "translation", there's really no alternative to benchmarking them both on a range of files reflecting your specific needs and interests.
how to read an excel file on google app engine
Generally I work with CSV files but for this project I need to support XLS too. Does anyone have experience reading XLS files on GAE with Python? 2 possible alternatives I am considering: xlrd Google Docs API
[ "xlrd saves you the network round-trip implied by the use of Google Docs; if you don't need to keep the document stored (which would be a substantial plus for Google Docs), this might incline you towards xlrd. I believe they're both high-quality.\nHowever, for both speed and accuracy of \"translation\", there's really no alternative to benchmarking them both on a range of files reflecting your specific needs and interests.\n" ]
[ 3 ]
[]
[]
[ "csv", "excel", "google_app_engine", "python" ]
stackoverflow_0002360010_csv_excel_google_app_engine_python.txt
Q: Python directory list returned to Django template Total Python newb here. I have a images directory and I need to return the names and urls of those files to a django template that I can loop through for links. I know it will be the server path, but I can modify it via JS. I've tried os.walk, but I keep getting empty results. A: If your images are in one directory import os root="/my" Path=os.path.join(root,"path","images") os.chdir(Path) for files in os.listdir("."): if files[-3:].lower() in ["gif","png","jpg","bmp"] : print "image file: ",files A: If it's a single directory, os.listdir('thedirectory') will give you a list of filename strings that seem to be suitable for your purposes (though it won't make "the urls" -- not sure how you want to make them?). If you need a whole tree of directories (recursively including subdirectories) then it's worth debugging your failed attempts at using os.walk, but it's hard for us to spot the bugs in code that we're not shown;-).
Python directory list returned to Django template
Total Python newb here. I have a images directory and I need to return the names and urls of those files to a django template that I can loop through for links. I know it will be the server path, but I can modify it via JS. I've tried os.walk, but I keep getting empty results.
[ "If your images are in one directory\nimport os\nroot=\"/my\"\nPath=os.path.join(root,\"path\",\"images\")\nos.chdir(Path)\nfor files in os.listdir(\".\"):\n if files[-3:].lower() in [\"gif\",\"png\",\"jpg\",\"bmp\"] :\n print \"image file: \",files\n\n", "If it's a single directory, os.listdir('thedirectory') will give you a list of filename strings that seem to be suitable for your purposes (though it won't make \"the urls\" -- not sure how you want to make them?). If you need a whole tree of directories (recursively including subdirectories) then it's worth debugging your failed attempts at using os.walk, but it's hard for us to spot the bugs in code that we're not shown;-).\n" ]
[ 2, 1 ]
[]
[]
[ "directory_structure", "list", "python" ]
stackoverflow_0002360205_directory_structure_list_python.txt
Q: wxPython change field on tab I apologize for a simple question, but I did not see this in the tutorials. I have a very simple gui, but I would like the user to be able to press the TAB key and have it move from one input field to another. I am using wxPython with Python 2.6. A: It should just work in the general case; what specific controls are you having issues with? You may need to pass wx.TAB_TRAVERSAL as a style, or if you need to manipulate the order, you can use the Move(After|Before)InTabOrder(otherControl) methods on the control. See http://wiki.wxpython.org/Getting%20Started#How_to_get_tabs_to_work for examples of both of these techniques!
wxPython change field on tab
I apologize for a simple question, but I did not see this in the tutorials. I have a very simple gui, but I would like the user to be able to press the TAB key and have it move from one input field to another. I am using wxPython with Python 2.6.
[ "It should just work in the general case; what specific controls are you having issues with? You may need to pass wx.TAB_TRAVERSAL as a style, or if you need to manipulate the order, you can use the Move(After|Before)InTabOrder(otherControl) methods on the control.\nSee http://wiki.wxpython.org/Getting%20Started#How_to_get_tabs_to_work for examples of both of these techniques!\n" ]
[ 6 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0002359300_python_wxpython.txt
Q: Google App Engine with Eclipse? I'm trying to use Google App Engine with Eclipse but it's not working. I downloaded PyDev, and made a Hello World Python app, so that's working fine. Then I created a new project, with the "Google App Engine" template. I was following these instructions. I used the "Hello Webapp World" as a template, and didn't change any of the Python code. I added the GAE directory to my external libraries. I then made a run configuration for my project, with the "Main Module" as the "HelloWorld.py" file I had created. I had one "Program Argument": "${project_loc}/src" Running this returns the following: Status: 404 Not Found Content-Type: text/html; charset=utf-8 Cache-Control: no-cache Expires: Fri, 01 Jan 1990 00:00:00 GMT Content-Length: 0 However, if I launch this same app using the Google App Engine Launcher, it works fine. So what am I doing wrong in Eclipse? A: I've dealt with this same problem myself. The Main Module needs to be set to the following: ${GOOGLE_APP_ENGINE}/dev_appserver.py It does cover it in the instructions, step 3 under Starting Your First Project. I must have glazed over it myself the first time as well. Hope this helps!
Google App Engine with Eclipse?
I'm trying to use Google App Engine with Eclipse but it's not working. I downloaded PyDev, and made a Hello World Python app, so that's working fine. Then I created a new project, with the "Google App Engine" template. I was following these instructions. I used the "Hello Webapp World" as a template, and didn't change any of the Python code. I added the GAE directory to my external libraries. I then made a run configuration for my project, with the "Main Module" as the "HelloWorld.py" file I had created. I had one "Program Argument": "${project_loc}/src" Running this returns the following: Status: 404 Not Found Content-Type: text/html; charset=utf-8 Cache-Control: no-cache Expires: Fri, 01 Jan 1990 00:00:00 GMT Content-Length: 0 However, if I launch this same app using the Google App Engine Launcher, it works fine. So what am I doing wrong in Eclipse?
[ "I've dealt with this same problem myself. \nThe Main Module needs to be set to the following:\n${GOOGLE_APP_ENGINE}/dev_appserver.py\n\nIt does cover it in the instructions, step 3 under Starting Your First Project. I must have glazed over it myself the first time as well. Hope this helps!\n" ]
[ 6 ]
[]
[]
[ "eclipse", "google_app_engine", "pydev", "python" ]
stackoverflow_0002359550_eclipse_google_app_engine_pydev_python.txt
Q: Python: Misunderstanding about how imports work Here is my loader class, ItemLoader.py: from google.appengine.ext import db from google.appengine.tools import bulkloader import models class ItemLoader(bulkloader.Loader): def __init__(self): bulkloader.Loader.__init__(self, 'Item', [('CSIN', int), # not too DRY... ('name', str), ('price', int), ('quantity', int) ] ) loaders = [ItemLoader] Here is my kind implementation, models.py: from google.appengine.ext import db class Item(db.Model): CSIN = db.IntegerProperty() name = db.StringProperty() price = db.IntegerProperty() # OK that it's an int? quantity = db.IntegerProperty() These are essentially copied from GAE instructions. When I run appcfg.py, I get this error: ImportError: No module named models What am I doing wrong? If I take out that import statement, I get a different error: ... No implementation for kind 'Item' UPDATE 1: I tried copy/pasting directly from Google's instructions, and I get that same import error. UPDATE 2: Changed the name of the kind implementation to models.py. Still doesn't work. Both ItemLoader.py and models.py are in the same directory. UPDATE 3: hacky solution: put them both in the same file! It works, but what am I not understanding about imports? A: You must add models directory to the PYTHONPATH. From docs: (which is in your PYTHONPATH, such as the directory where you'll run the tool) If you don't do that, python can't find your module.
Python: Misunderstanding about how imports work
Here is my loader class, ItemLoader.py: from google.appengine.ext import db from google.appengine.tools import bulkloader import models class ItemLoader(bulkloader.Loader): def __init__(self): bulkloader.Loader.__init__(self, 'Item', [('CSIN', int), # not too DRY... ('name', str), ('price', int), ('quantity', int) ] ) loaders = [ItemLoader] Here is my kind implementation, models.py: from google.appengine.ext import db class Item(db.Model): CSIN = db.IntegerProperty() name = db.StringProperty() price = db.IntegerProperty() # OK that it's an int? quantity = db.IntegerProperty() These are essentially copied from GAE instructions. When I run appcfg.py, I get this error: ImportError: No module named models What am I doing wrong? If I take out that import statement, I get a different error: ... No implementation for kind 'Item' UPDATE 1: I tried copy/pasting directly from Google's instructions, and I get that same import error. UPDATE 2: Changed the name of the kind implementation to models.py. Still doesn't work. Both ItemLoader.py and models.py are in the same directory. UPDATE 3: hacky solution: put them both in the same file! It works, but what am I not understanding about imports?
[ "You must add models directory to the PYTHONPATH. From docs:\n(which is in your PYTHONPATH, such as the directory where you'll run the tool)\n\nIf you don't do that, python can't find your module.\n" ]
[ 1 ]
[]
[]
[ "google_app_engine", "import", "python" ]
stackoverflow_0002360399_google_app_engine_import_python.txt
Q: Python and Memory Consumption I am searching for a way to be able to handle overloading the RAM and CPU using a high memory program... I would like to process a LARGE amount of data contained in files. I then read the files and process the data therein. The problem is there are many nested for loops and a root XML file is being created from all the data processed. The program easily consumes a couple gigs of RAM after half hour or so of run-time. Is there something I can do to not let RAM get so big and/or work around it.. ? A: Do you really need to keep the whole data from the XML file on memory at once? Most (all?) XML libraries out there allow you to do iterative parsing, meaning that you keep in memory just a few nodes of the XML file, not the whole file. That is unless you are making a string containing the XML file yourself without any library, but that is a bit insane. If that is the case, use a library ASAP. The specific code samples presented here might not apply to your project, but consider a few principles—borne out by testing and the lxml documentation—when faced with XML data measured in gigabytes or more: Use an iterative parsing strategy to incrementally process large documents. If searching the entire document in random order is required, move to an indexed XML database. Be extremely conservative in the data that you select. If you are only interested in particular nodes, use methods that select by those names. If you require predicate syntax, try one of the XPath classes and methods available. Consider the task at hand and the comfort level of the developer. Object models such as lxml's objectify or Amara might be more natural for Python developers when speed is not a consideration. cElementTree is faster when only parsing is required. Take the time to do even simple benchmarking. When processing millions of records, small differences add up, and it is not always obvious which methods are the most efficient. If you need to do complex operations on the data, why don't you just put it on a relational database and operate on the data from there? That will have better performance.
Python and Memory Consumption
I am searching for a way to be able to handle overloading the RAM and CPU using a high memory program... I would like to process a LARGE amount of data contained in files. I then read the files and process the data therein. The problem is there are many nested for loops and a root XML file is being created from all the data processed. The program easily consumes a couple gigs of RAM after half hour or so of run-time. Is there something I can do to not let RAM get so big and/or work around it.. ?
[ "Do you really need to keep the whole data from the XML file on memory at once?\nMost (all?) XML libraries out there allow you to do iterative parsing, meaning that you keep in memory just a few nodes of the XML file, not the whole file. That is unless you are making a string containing the XML file yourself without any library, but that is a bit insane. If that is the case, use a library ASAP.\n\nThe specific code samples presented here might not apply to your project, but consider a few principles—borne out by testing and the lxml documentation—when faced with XML data measured in gigabytes or more:\n\nUse an iterative parsing strategy to incrementally process large documents.\nIf searching the entire document in random order is required, move to an indexed XML database.\nBe extremely conservative in the data that you select. If you are only interested in particular nodes, use methods that select by those names. If you require predicate syntax, try one of the XPath classes and methods available.\nConsider the task at hand and the comfort level of the developer. Object models such as lxml's objectify or Amara might be more natural for Python developers when speed is not a consideration. cElementTree is faster when only parsing is required.\nTake the time to do even simple benchmarking. When processing millions of records, small differences add up, and it is not always obvious which methods are the most efficient.\n\n\nIf you need to do complex operations on the data, why don't you just put it on a relational database and operate on the data from there? That will have better performance.\n" ]
[ 3 ]
[]
[]
[ "memory_management", "python" ]
stackoverflow_0002360483_memory_management_python.txt
Q: Recommended ways to split some functionality into functions, modules and packages? There comes a point where, in a relatively large sized project, one need to think about splitting the functionality into various functions, and then various modules, and then various packages. Sometimes across different source distributions (eg: extracting a common utility, such as optparser, into a separate project). The question - how does one decide the parts to put in the same module, and the parts to put in a separate module? Same question for packages. A: There's a classic paper by David Parnas called "On the criteria to be used in decomposing systems into modules". It's a classic (and has a certain age, so can be a little outdated). Maybe you can start from there, a PDF is available here http://www.cs.umd.edu/class/spring2003/cmsc838p/Design/criteria.pdf A: Take out a pen and piece of paper. Try to draw how your software interacts on a high level. Draw the different layers of the software etc. Group items by functionality and purpose, maybe even by what sort of technology they use. If your software has multiple abstraction layers, I would say to group them by that. On a high level, the elements of a specific layer all share the same general purpose. Now that you have your software in layers, you can divide these layers into different projects based on specific functionality or specialization. As for a certain stage that you reach in which you should do this? I'd say when you have multiple people working on the code base or if you want to keep your project as modular as possible. Hopefully your code is modular enough to do this with. If you are unable to break apart your software on a high level, then your software is probably spaghetti code and you should look at refactoring it. Hopefully that will give you something to work with. A: See How many Python classes should I put in one file? Sketch your overall set of class definitions. Partition these class definitions into "modules". Implement and test the modules separately from each other. Knit the modules together to create your final application. Note. It's almost impossible to decompose a working application that evolved organically. So don't do that. Decompose your design early and often. Build separate modules. Integrate to build an application. A: IMHO this should probably one of the things you do earlier in the development process. I have never worked on a large-scale project, but it would make sense that you make a roadmap of what's going to be done and where. (Not trying to rib you for asking about it like you made a mistake :D ) Modules are generally grouped somehow, by purpose or functionality. You could try each implementation of an interface, or other connections. A: I sympathize with you. You are suffering from self-doubt. Don't worry. If you can speak any language, including your mother tongue, you are qualified to do modularization on your own. For evidence, you may read "The Language Instinct," or "The Math Instinct." Look around, but not too much. You can learn a lot from them, but you can learn many bad things from them too. Some projects/framework get a lot fo hype. Yet, some of their groupings of functionality, even names given to modules are misleading. They don't "reveal intention" of the programmers. They fail the "high cohesiveness" test. Books are no better. Please apply 80/20 rule in your book selection. Even a good, very complete, well-researched book like Capers Jones' 2010 "Software Engineering Best Practices" is clueless. It says 10-man Agile/XP team would take 12 years to do Windows Vista or 25 years to do an ERP package! It says there is no method till 2009 for segmentation, its term for modularization. I don't think it will help you. My point is: You must pick your model/reference/source of examples very carefully. Don't over-estimate famous names and under-estimate yourself. Here is my help, proven in my experience. It is a lot like deciding what attributes go to which DB table, what properties/methods go to which class/object etc? On a deeper level, it is a lot like arranging furniture at home, or books in a shelf. You have done such things already. Software is the same, no big deal! Worry about "cohesion" first. e.g. Books (Leo Tolstoy, James Joyce, DE Lawrence) is choesive .(HTML, CSS, John Keats. jQuery, tinymce) is not. And there are many ways to arrange things. Even taxonomists are still in serious feuds over this. Then worry about "coupling." Be "shy". "Don't talk to strangers." Don't be over-friendly. Try to make your package/DB table/class/object/module/bookshelf as self-contained, as independent as possible. Joel has talked about his admiration for the Excel team that abhor all external dependencies and that even built their own compiler. A: Actually it varies for each project you create but here is an example: core package contains modules that are your project cant live without. this may contain the main functionality of your application. ui package contains modules that deals with the user interface. that is if you split the UI from your console. This is just an example. and it would really you that would be deciding which and what to go where.
Recommended ways to split some functionality into functions, modules and packages?
There comes a point where, in a relatively large sized project, one need to think about splitting the functionality into various functions, and then various modules, and then various packages. Sometimes across different source distributions (eg: extracting a common utility, such as optparser, into a separate project). The question - how does one decide the parts to put in the same module, and the parts to put in a separate module? Same question for packages.
[ "There's a classic paper by David Parnas called \"On the criteria to be used in decomposing systems into modules\". It's a classic (and has a certain age, so can be a little outdated).\nMaybe you can start from there, a PDF is available here\nhttp://www.cs.umd.edu/class/spring2003/cmsc838p/Design/criteria.pdf\n", "Take out a pen and piece of paper. Try to draw how your software interacts on a high level. Draw the different layers of the software etc. Group items by functionality and purpose, maybe even by what sort of technology they use. If your software has multiple abstraction layers, I would say to group them by that. On a high level, the elements of a specific layer all share the same general purpose. Now that you have your software in layers, you can divide these layers into different projects based on specific functionality or specialization. \nAs for a certain stage that you reach in which you should do this? I'd say when you have multiple people working on the code base or if you want to keep your project as modular as possible. Hopefully your code is modular enough to do this with. If you are unable to break apart your software on a high level, then your software is probably spaghetti code and you should look at refactoring it. \nHopefully that will give you something to work with.\n", "See How many Python classes should I put in one file?\nSketch your overall set of class definitions.\nPartition these class definitions into \"modules\".\nImplement and test the modules separately from each other.\nKnit the modules together to create your final application.\nNote. It's almost impossible to decompose a working application that evolved organically. So don't do that. \nDecompose your design early and often. Build separate modules. Integrate to build an application.\n", "IMHO this should probably one of the things you do earlier in the development process. I have never worked on a large-scale project, but it would make sense that you make a roadmap of what's going to be done and where. (Not trying to rib you for asking about it like you made a mistake :D )\nModules are generally grouped somehow, by purpose or functionality. You could try each implementation of an interface, or other connections.\n", "I sympathize with you. You are suffering from self-doubt. Don't worry. If you can speak any language, including your mother tongue, you are qualified to do modularization on your own. For evidence, you may read \"The Language Instinct,\" or \"The Math Instinct.\"\nLook around, but not too much. You can learn a lot from them, but you can learn many bad things from them too. \n\nSome projects/framework get a lot fo hype. Yet, some of their groupings of functionality, even names given to modules are misleading. They don't \"reveal intention\" of the programmers. They fail the \"high cohesiveness\" test.\nBooks are no better. Please apply 80/20 rule in your book selection. Even a good, very complete, well-researched book like Capers Jones' 2010 \"Software Engineering Best Practices\" is clueless. It says 10-man Agile/XP team would take 12 years to do Windows Vista or 25 years to do an ERP package! It says there is no method till 2009 for segmentation, its term for modularization. I don't think it will help you.\n\nMy point is: You must pick your model/reference/source of examples very carefully. Don't over-estimate famous names and under-estimate yourself.\nHere is my help, proven in my experience.\n\nIt is a lot like deciding what attributes go to which DB table, what properties/methods go to which class/object etc? On a deeper level, it is a lot like arranging furniture at home, or books in a shelf. You have done such things already. Software is the same, no big deal!\nWorry about \"cohesion\" first. e.g. Books (Leo Tolstoy, James Joyce, DE Lawrence) is choesive .(HTML, CSS, John Keats. jQuery, tinymce) is not. And there are many ways to arrange things. Even taxonomists are still in serious feuds over this.\nThen worry about \"coupling.\" Be \"shy\". \"Don't talk to strangers.\" Don't be over-friendly. Try to make your package/DB table/class/object/module/bookshelf as self-contained, as independent as possible. Joel has talked about his admiration for the Excel team that abhor all external dependencies and that even built their own compiler.\n\n", "Actually it varies for each project you create but here is an example:\n\ncore package contains modules that are your project cant live without. this may contain the main functionality of your application.\nui package contains modules that deals with the user interface. that is if you split the UI from your console.\n\nThis is just an example. and it would really you that would be deciding which and what to go where.\n" ]
[ 7, 4, 2, 1, 1, 0 ]
[]
[]
[ "module", "package", "python" ]
stackoverflow_0001168565_module_package_python.txt
Q: Google App Engine: Give arguments to a script from URL handler? Here is a portion of my app.yaml file: handlers: - url: /remote_api script: $PYTHON_LIB/google/appengine/ext/remote_api/handler.py login: admin - url: /detail/(\d)+ script: Detail.py - url: /.* script: Index.py I want that capture group (the one signified by (\d)) to be available to the script Detail.py. How can I do this? Do I need to figure out a way to access GET data from Detail.py? Also, when I navigate to a URL like /fff, which should match the Index.py handler, I just get a blank response. A: I see two questions, how to pass elements of the url path as variables in the handler, and how to get the catch-all to render properly. Both of these have more to do with the main() method in the handler than the app.yaml 1) to pass the id in the /detail/(\d) url, you want something like this: class DetailHandler(webapp.RequestHandler): def get(self, detail_id): # put your code here, detail_id contains the passed variable def main(): # Note the wildcard placeholder in the url matcher application = webapp.WSGIApplication([('/details/(.*)', DetailHandler)] wsgiref.handlers.CGIHandler().run(application) 2) to ensure your Index.py catches everything, you want something like this: class IndexHandler(webapp.RequestHandler): def get(self): # put your handler code here def main(): # Note the wildcard without parens application = webapp.WSGIApplication([('/.*', IndexHandler)] wsgiref.handlers.CGIHandler().run(application) Hope that helps.
Google App Engine: Give arguments to a script from URL handler?
Here is a portion of my app.yaml file: handlers: - url: /remote_api script: $PYTHON_LIB/google/appengine/ext/remote_api/handler.py login: admin - url: /detail/(\d)+ script: Detail.py - url: /.* script: Index.py I want that capture group (the one signified by (\d)) to be available to the script Detail.py. How can I do this? Do I need to figure out a way to access GET data from Detail.py? Also, when I navigate to a URL like /fff, which should match the Index.py handler, I just get a blank response.
[ "I see two questions, how to pass elements of the url path as variables in the handler, and how to get the catch-all to render properly.\nBoth of these have more to do with the main() method in the handler than the app.yaml\n1) to pass the id in the /detail/(\\d) url, you want something like this:\nclass DetailHandler(webapp.RequestHandler):\n def get(self, detail_id):\n # put your code here, detail_id contains the passed variable\n\ndef main():\n # Note the wildcard placeholder in the url matcher\n application = webapp.WSGIApplication([('/details/(.*)', DetailHandler)]\n wsgiref.handlers.CGIHandler().run(application)\n\n2) to ensure your Index.py catches everything, you want something like this:\nclass IndexHandler(webapp.RequestHandler):\n def get(self):\n # put your handler code here\n\ndef main():\n # Note the wildcard without parens\n application = webapp.WSGIApplication([('/.*', IndexHandler)]\n wsgiref.handlers.CGIHandler().run(application)\n\nHope that helps.\n" ]
[ 12 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002360638_google_app_engine_python.txt
Q: What should people new to Python know about its community and ecosystem? I'm cobbling together some sort of an introduction to Python, but one that focuses on the community and the ecosystem around Python rather than just the language. With How to Think Like a Computer Scientist and other great tutorials, it's easy to get familiar with the language, but it took me a fair while before I knew what The Cheese Shop, or, err, PyPi is about, how pip and virtualenv work and why you should use them, where you should go for help, the interesting blogs that you should follow, how your code should look (PEP 8, writing pythonic code) and so on. The 'soft stuff'. What confused you the most when you just started out with Python? Are there certain things that you would've wanted to know about, or resources you wish you would have stumbled upon earlier than you did? People to know about? I found a few similar questions on StackOverflow (e.g. here) but nothing really close to what I'd like to hear from you guys. Hope this question doesn't feel too subjective to your tastes :-) (And, if you'd like to help out, feel free to send a message.) A: I think one of the most important thing a beginner need to know about Python ecosystem is that it's a general purpose language surrounded by specialized libs. Experienced pythonistas know them, but a newbie can't: Don't stop to tkinter : go wx, gtk or qt. Don't dev web code by hands : use TurboGears, Pylons, Web.py or Django. Don't parse HTML / XML with hard tools : use lxml or beautifulsoup. Don't make syscall to imagemagik : use PIL. Don't make advanced maths manually : use NumPy and SciPy. Don't access simple databases by hand : use ORM like SQLAlchemy. Don't reinvent sysadmin wheels : use Fabric. etc. The main ones should be listed in a book with guidances to choose among them. A: "What confused you the most when you just started out with Python?" Rule 2 of learning Python: Any general-purpose module or framework you think you want has already been written. Several times. The hard part is realizing that your idea is Not unique. Been already improved upon before you even starting thinking about it. Already posted somewhere. So, code less and search more. Search widely and flexibly until you find things that are similar to what you want to do. Realize that you might have a name you think is descriptive. But other folks may call it something different. Join the community, adopt their naming. You may not like the phrase "ORM", but that's what it's called. Realize that your idea, no matter how sound it seems, may be really poor. When you find a framework that seems to have "needless extra features", you may be missing something from your idea. Realize that your idea, no matter how "intuitive" it seems, may be really poor. When you find a framework that seems "counter-intuitive", the problem could be yours. Learn theirs first, then compare and contrast after you've mastered theirs. Until you've mastered theirs, keep searching and learning. A: A few points related to the ecosystem and indirectly the community: I wished I had been reminded more about the Batteries included. I think people should be told to print-out the Table of Contents of the Standard Library and keep it under their pillow, for frequent reviews (that advice, I finally took, several years into it, from an online intro/beginner's video presentation!). The [relative] stability, extensive but relevant content of the Std Lib speaks to the thoughtful governance of the community leaders and its beloved BDFL. I think newcomers can also be "warned" (the word is maybe too strong, too unfair) about the extreme variety of PiPy. This reflects the vibrant, smart and diverse (in terms of background, domain of application, interests...) collective of users and contributors. This however can be overwhelming and possibly risky as all packages in there are not "prime time ready" (But many are and "saved my life" many times over). Even if you feel too new to Python, don't only use the libraries, do peek under the hood! This is true of many languages, but maybe particularly of Python, there's much to be learned from perusing various source code. The reasons this may be particular true for Python are intrinsic to the language itself (multi-paradigms, hi level of abstraction...) but also because of the relative uniformity of coding (and architecting) style and because of the general level of collaboration within the community. A: "What confused you the most when you just started out with Python?" Rule 1 of learning Python: Use the Source, Luke. There are question on SO asking for "good" source from which to learn Python. The best answers amount to "read the libraries that came with Python." One can say that the libraries that come with Python are quirky. In places. Which makes them all the better for learning from. There's a community of like-minded people who are not clones. Open source software is the highest-quality software you'll ever get to work with, but it's not created by paid developers who will rigidly enforce standards. A: explaining what a PEP is, how it is written and who wrote them, where we can find them. PEPs give a lot of background informations about a specific feature of the language. they also are the tool which shows how fast evolving python is. (i wish i had read some PEPs earlier, but i was not really aware of them, although they are frequently linked in the manual) A: From PEP 20: import this (aka, the Zen of Python) A: developing a python package that can be installed with easy_install etc... I consider it equivalent to developing a jar or dll etc.... on the same token, developing said package(s) with virtualenv or buildout If I would have known those things sooner, I would have probably used python for more than just scripting way back when I first started using it.
What should people new to Python know about its community and ecosystem?
I'm cobbling together some sort of an introduction to Python, but one that focuses on the community and the ecosystem around Python rather than just the language. With How to Think Like a Computer Scientist and other great tutorials, it's easy to get familiar with the language, but it took me a fair while before I knew what The Cheese Shop, or, err, PyPi is about, how pip and virtualenv work and why you should use them, where you should go for help, the interesting blogs that you should follow, how your code should look (PEP 8, writing pythonic code) and so on. The 'soft stuff'. What confused you the most when you just started out with Python? Are there certain things that you would've wanted to know about, or resources you wish you would have stumbled upon earlier than you did? People to know about? I found a few similar questions on StackOverflow (e.g. here) but nothing really close to what I'd like to hear from you guys. Hope this question doesn't feel too subjective to your tastes :-) (And, if you'd like to help out, feel free to send a message.)
[ "I think one of the most important thing a beginner need to know about Python ecosystem is that it's a general purpose language surrounded by specialized libs. Experienced pythonistas know them, but a newbie can't:\n\nDon't stop to tkinter : go wx, gtk or qt.\nDon't dev web code by hands : use TurboGears, Pylons, Web.py or Django.\nDon't parse HTML / XML with hard tools : use lxml or beautifulsoup.\nDon't make syscall to imagemagik : use PIL.\nDon't make advanced maths manually : use NumPy and SciPy.\nDon't access simple databases by hand : use ORM like SQLAlchemy.\nDon't reinvent sysadmin wheels : use Fabric.\netc.\n\nThe main ones should be listed in a book with guidances to choose among them.\n", "\"What confused you the most when you just started out with Python?\"\nRule 2 of learning Python: Any general-purpose module or framework you think you want has already been written. Several times.\nThe hard part is realizing that your idea is\n\nNot unique.\nBeen already improved upon before you even starting thinking about it.\nAlready posted somewhere.\n\nSo, code less and search more. Search widely and flexibly until you find things that are similar to what you want to do.\n\nRealize that you might have a name you think is descriptive. But other folks may call it something different. Join the community, adopt their naming. You may not like the phrase \"ORM\", but that's what it's called. \nRealize that your idea, no matter how sound it seems, may be really poor. When you find a framework that seems to have \"needless extra features\", you may be missing something from your idea. \nRealize that your idea, no matter how \"intuitive\" it seems, may be really poor. When you find a framework that seems \"counter-intuitive\", the problem could be yours. Learn theirs first, then compare and contrast after you've mastered theirs. Until you've mastered theirs, keep searching and learning.\n\n", "A few points related to the ecosystem and indirectly the community: \n\nI wished I had been reminded more about the Batteries included. I think people should be told to print-out the Table of Contents of the Standard Library and keep it under their pillow, for frequent reviews (that advice, I finally took, several years into it, from an online intro/beginner's video presentation!). The [relative] stability, extensive but relevant content of the Std Lib speaks to the thoughtful governance of the community leaders and its beloved BDFL.\nI think newcomers can also be \"warned\" (the word is maybe too strong, too unfair) about the extreme variety of PiPy. This reflects the vibrant, smart and diverse (in terms of background, domain of application, interests...) collective of users and contributors. This however can be overwhelming and possibly risky as all packages in there are not \"prime time ready\" (But many are and \"saved my life\" many times over).\nEven if you feel too new to Python, don't only use the libraries, do peek under the hood! This is true of many languages, but maybe particularly of Python, there's much to be learned from perusing various source code. The reasons this may be particular true for Python are intrinsic to the language itself (multi-paradigms, hi level of abstraction...) but also because of the relative uniformity of coding (and architecting) style and because of the general level of collaboration within the community.\n\n", "\"What confused you the most when you just started out with Python?\"\nRule 1 of learning Python: Use the Source, Luke.\nThere are question on SO asking for \"good\" source from which to learn Python. The best answers amount to \"read the libraries that came with Python.\"\nOne can say that the libraries that come with Python are quirky. In places. Which makes them all the better for learning from.\n\nThere's a community of like-minded people who are not clones.\nOpen source software is the highest-quality software you'll ever get to work with, but it's not created by paid developers who will rigidly enforce standards.\n\n", "explaining what a PEP is, how it is written and who wrote them, where we can find them. PEPs give a lot of background informations about a specific feature of the language. they also are the tool which shows how fast evolving python is.\n(i wish i had read some PEPs earlier, but i was not really aware of them, although they are frequently linked in the manual)\n", "From PEP 20: \nimport this\n\n(aka, the Zen of Python)\n", "developing a python package that can be installed with easy_install etc... I consider it equivalent to developing a jar or dll etc.... \non the same token, developing said package(s) with virtualenv or buildout\nIf I would have known those things sooner, I would have probably used python for more than just scripting way back when I first started using it.\n" ]
[ 18, 9, 7, 5, 4, 4, 1 ]
[]
[]
[ "documentation", "python" ]
stackoverflow_0002351793_documentation_python.txt
Q: Global function in __init__.py not accessible using Pylons + Python I'm having trouble creating a global function accessible from within all classes. I receive an error from within user.py that says: NameError: global name 'connectCentral' is not defined Here is my current code. project/model/__ init __.py: """The application's model objects""" import sqlalchemy as sa from sqlalchemy import orm from sqlalchemy import engine_from_config from pylons import config import central #Establish an on-demand connection to the central database def connectCentral(): engine = engine_from_config(config, 'sqlalchemy.central.') central.engine = engine central.Session.configure(bind=engine) project/model/user.py import project.model class User(object): def emailExists(self): try: connectCentral() emails = central.Session.query(User).filter_by(email=self.email).count() if (emails > 0): return False else: return True except NameError: self.errors['email'] = 'E-Mail not set' return False Am I missing an import? Is there a better way to do this? Thanks. A: You need to qualify the name with the module (or package) it's in, so: try: project.model.connectCentral() etc.
Global function in __init__.py not accessible using Pylons + Python
I'm having trouble creating a global function accessible from within all classes. I receive an error from within user.py that says: NameError: global name 'connectCentral' is not defined Here is my current code. project/model/__ init __.py: """The application's model objects""" import sqlalchemy as sa from sqlalchemy import orm from sqlalchemy import engine_from_config from pylons import config import central #Establish an on-demand connection to the central database def connectCentral(): engine = engine_from_config(config, 'sqlalchemy.central.') central.engine = engine central.Session.configure(bind=engine) project/model/user.py import project.model class User(object): def emailExists(self): try: connectCentral() emails = central.Session.query(User).filter_by(email=self.email).count() if (emails > 0): return False else: return True except NameError: self.errors['email'] = 'E-Mail not set' return False Am I missing an import? Is there a better way to do this? Thanks.
[ "You need to qualify the name with the module (or package) it's in, so:\n try:\n project.model.connectCentral()\n\netc.\n" ]
[ 2 ]
[]
[]
[ "pylons", "python" ]
stackoverflow_0002360846_pylons_python.txt
Q: Building an interleaved buffer for pyopengl and numpy I'm trying to batch up a bunch of vertices and texture coords in an interleaved array before sending it to pyOpengl's glInterleavedArrays/glDrawArrays. The only problem is that I'm unable to find a suitably fast enough way to append data into a numpy array. Is there a better way to do this? I would have thought it would be quicker to preallocate the array and then fill it with data but instead, generating a python list and converting it to a numpy array is "faster". Although 15ms for 4096 quads seems slow. I have included some example code and their timings. #!/usr/bin/python import timeit import numpy import ctypes import random USE_RANDOM=True USE_STATIC_BUFFER=True STATIC_BUFFER = numpy.empty(4096*20, dtype=numpy.float32) def render(i): # pretend these are different each time if USE_RANDOM: tex_left, tex_right, tex_top, tex_bottom = random.random(), random.random(), random.random(), random.random() left, right, top, bottom = random.random(), random.random(), random.random(), random.random() else: tex_left, tex_right, tex_top, tex_bottom = 0.0, 1.0, 1.0, 0.0 left, right, top, bottom = -1.0, 1.0, 1.0, -1.0 ibuffer = ( tex_left, tex_bottom, left, bottom, 0.0, # Lower left corner tex_right, tex_bottom, right, bottom, 0.0, # Lower right corner tex_right, tex_top, right, top, 0.0, # Upper right corner tex_left, tex_top, left, top, 0.0, # upper left ) return ibuffer # create python list.. convert to numpy array at end def create_array_1(): ibuffer = [] for x in xrange(4096): data = render(x) ibuffer += data ibuffer = numpy.array(ibuffer, dtype=numpy.float32) return ibuffer # numpy.array, placing individually by index def create_array_2(): if USE_STATIC_BUFFER: ibuffer = STATIC_BUFFER else: ibuffer = numpy.empty(4096*20, dtype=numpy.float32) index = 0 for x in xrange(4096): data = render(x) for v in data: ibuffer[index] = v index += 1 return ibuffer # using slicing def create_array_3(): if USE_STATIC_BUFFER: ibuffer = STATIC_BUFFER else: ibuffer = numpy.empty(4096*20, dtype=numpy.float32) index = 0 for x in xrange(4096): data = render(x) ibuffer[index:index+20] = data index += 20 return ibuffer # using numpy.concat on a list of ibuffers def create_array_4(): ibuffer_concat = [] for x in xrange(4096): data = render(x) # converting makes a diff! data = numpy.array(data, dtype=numpy.float32) ibuffer_concat.append(data) return numpy.concatenate(ibuffer_concat) # using numpy array.put def create_array_5(): if USE_STATIC_BUFFER: ibuffer = STATIC_BUFFER else: ibuffer = numpy.empty(4096*20, dtype=numpy.float32) index = 0 for x in xrange(4096): data = render(x) ibuffer.put( xrange(index, index+20), data) index += 20 return ibuffer # using ctype array CTYPES_ARRAY = ctypes.c_float*(4096*20) def create_array_6(): ibuffer = [] for x in xrange(4096): data = render(x) ibuffer += data ibuffer = CTYPES_ARRAY(*ibuffer) return ibuffer def equals(a, b): for i,v in enumerate(a): if b[i] != v: return False return True if __name__ == "__main__": number = 100 # if random, don't try and compare arrays if not USE_RANDOM and not USE_STATIC_BUFFER: a = create_array_1() assert equals( a, create_array_2() ) assert equals( a, create_array_3() ) assert equals( a, create_array_4() ) assert equals( a, create_array_5() ) assert equals( a, create_array_6() ) t = timeit.Timer( "testing2.create_array_1()", "import testing2" ) print 'from list:', t.timeit(number)/number*1000.0, 'ms' t = timeit.Timer( "testing2.create_array_2()", "import testing2" ) print 'array: indexed:', t.timeit(number)/number*1000.0, 'ms' t = timeit.Timer( "testing2.create_array_3()", "import testing2" ) print 'array: slicing:', t.timeit(number)/number*1000.0, 'ms' t = timeit.Timer( "testing2.create_array_4()", "import testing2" ) print 'array: concat:', t.timeit(number)/number*1000.0, 'ms' t = timeit.Timer( "testing2.create_array_5()", "import testing2" ) print 'array: put:', t.timeit(number)/number*1000.0, 'ms' t = timeit.Timer( "testing2.create_array_6()", "import testing2" ) print 'ctypes float array:', t.timeit(number)/number*1000.0, 'ms' Timings using random numbers: $ python testing2.py from list: 15.0486779213 ms array: indexed: 24.8184704781 ms array: slicing: 50.2214789391 ms array: concat: 44.1691994667 ms array: put: 73.5879898071 ms ctypes float array: 20.6674289703 ms edit note: changed code to produce random numbers for each render to reduce object reuse and to simulate different vertices each time. edit note2: added static buffer and force all numpy.empty() to use dtype=float32 note 1/Apr/2010: still no progress and I don't really feel that any of the answers have solved the problem yet. A: The reason that create_array_1 is so much faster seems to be that the items in the (python) list all point to the same object. You can see this if you test: print (ibuffer[0] is ibuffer[1]) inside the subroutines. In create_array_1 this is true (before you create the numpy array), while in create_array_2 this is always going to be false. I guess this means that data conversion step in the array conversion only has to happen once in create_array_1, while it happens 4096 times in create_array_2. If this is the reason, I guess the timings will be different if you make render generate random data. Create_array_5 is slowest as it makes a new array each time you add data to the end. A: The benefit of numpy is not realized by simply storing the data in an array, it is achieved by performing operations across many elements in an array instead of one by one. Your example can be boiled down and optimized to this trivial solution with orders of magnitude speedup: numpy.random.standard_normal(4096*20) ...that's not very helpful, but it does kind of hint at where the costs are. Here is an incremental improvement that beats the list append solution (but only slightly) by eliminating the iteration over 4096 elements. xs = numpy.arange(4096) render2 = numpy.vectorize(render) def create_array_7(): ibuffer = STATIC_BUFFER for i, a in enumerate(render2(xs)): ibuffer[i::20] = a return ibuffer ... but not the speedup we are looking for. The real savings will be realized by a recasting of the render routine so that you don't have to create a python object for every value that ends up being placed in the buffer. Where does tex_left, tex_right...etc. come from? Are they calculated or read? A: I know it seems strange, but have you tried fromfile?
Building an interleaved buffer for pyopengl and numpy
I'm trying to batch up a bunch of vertices and texture coords in an interleaved array before sending it to pyOpengl's glInterleavedArrays/glDrawArrays. The only problem is that I'm unable to find a suitably fast enough way to append data into a numpy array. Is there a better way to do this? I would have thought it would be quicker to preallocate the array and then fill it with data but instead, generating a python list and converting it to a numpy array is "faster". Although 15ms for 4096 quads seems slow. I have included some example code and their timings. #!/usr/bin/python import timeit import numpy import ctypes import random USE_RANDOM=True USE_STATIC_BUFFER=True STATIC_BUFFER = numpy.empty(4096*20, dtype=numpy.float32) def render(i): # pretend these are different each time if USE_RANDOM: tex_left, tex_right, tex_top, tex_bottom = random.random(), random.random(), random.random(), random.random() left, right, top, bottom = random.random(), random.random(), random.random(), random.random() else: tex_left, tex_right, tex_top, tex_bottom = 0.0, 1.0, 1.0, 0.0 left, right, top, bottom = -1.0, 1.0, 1.0, -1.0 ibuffer = ( tex_left, tex_bottom, left, bottom, 0.0, # Lower left corner tex_right, tex_bottom, right, bottom, 0.0, # Lower right corner tex_right, tex_top, right, top, 0.0, # Upper right corner tex_left, tex_top, left, top, 0.0, # upper left ) return ibuffer # create python list.. convert to numpy array at end def create_array_1(): ibuffer = [] for x in xrange(4096): data = render(x) ibuffer += data ibuffer = numpy.array(ibuffer, dtype=numpy.float32) return ibuffer # numpy.array, placing individually by index def create_array_2(): if USE_STATIC_BUFFER: ibuffer = STATIC_BUFFER else: ibuffer = numpy.empty(4096*20, dtype=numpy.float32) index = 0 for x in xrange(4096): data = render(x) for v in data: ibuffer[index] = v index += 1 return ibuffer # using slicing def create_array_3(): if USE_STATIC_BUFFER: ibuffer = STATIC_BUFFER else: ibuffer = numpy.empty(4096*20, dtype=numpy.float32) index = 0 for x in xrange(4096): data = render(x) ibuffer[index:index+20] = data index += 20 return ibuffer # using numpy.concat on a list of ibuffers def create_array_4(): ibuffer_concat = [] for x in xrange(4096): data = render(x) # converting makes a diff! data = numpy.array(data, dtype=numpy.float32) ibuffer_concat.append(data) return numpy.concatenate(ibuffer_concat) # using numpy array.put def create_array_5(): if USE_STATIC_BUFFER: ibuffer = STATIC_BUFFER else: ibuffer = numpy.empty(4096*20, dtype=numpy.float32) index = 0 for x in xrange(4096): data = render(x) ibuffer.put( xrange(index, index+20), data) index += 20 return ibuffer # using ctype array CTYPES_ARRAY = ctypes.c_float*(4096*20) def create_array_6(): ibuffer = [] for x in xrange(4096): data = render(x) ibuffer += data ibuffer = CTYPES_ARRAY(*ibuffer) return ibuffer def equals(a, b): for i,v in enumerate(a): if b[i] != v: return False return True if __name__ == "__main__": number = 100 # if random, don't try and compare arrays if not USE_RANDOM and not USE_STATIC_BUFFER: a = create_array_1() assert equals( a, create_array_2() ) assert equals( a, create_array_3() ) assert equals( a, create_array_4() ) assert equals( a, create_array_5() ) assert equals( a, create_array_6() ) t = timeit.Timer( "testing2.create_array_1()", "import testing2" ) print 'from list:', t.timeit(number)/number*1000.0, 'ms' t = timeit.Timer( "testing2.create_array_2()", "import testing2" ) print 'array: indexed:', t.timeit(number)/number*1000.0, 'ms' t = timeit.Timer( "testing2.create_array_3()", "import testing2" ) print 'array: slicing:', t.timeit(number)/number*1000.0, 'ms' t = timeit.Timer( "testing2.create_array_4()", "import testing2" ) print 'array: concat:', t.timeit(number)/number*1000.0, 'ms' t = timeit.Timer( "testing2.create_array_5()", "import testing2" ) print 'array: put:', t.timeit(number)/number*1000.0, 'ms' t = timeit.Timer( "testing2.create_array_6()", "import testing2" ) print 'ctypes float array:', t.timeit(number)/number*1000.0, 'ms' Timings using random numbers: $ python testing2.py from list: 15.0486779213 ms array: indexed: 24.8184704781 ms array: slicing: 50.2214789391 ms array: concat: 44.1691994667 ms array: put: 73.5879898071 ms ctypes float array: 20.6674289703 ms edit note: changed code to produce random numbers for each render to reduce object reuse and to simulate different vertices each time. edit note2: added static buffer and force all numpy.empty() to use dtype=float32 note 1/Apr/2010: still no progress and I don't really feel that any of the answers have solved the problem yet.
[ "The reason that create_array_1 is so much faster seems to be that the items in the (python) list all point to the same object. You can see this if you test:\nprint (ibuffer[0] is ibuffer[1])\n\ninside the subroutines. In create_array_1 this is true (before you create the numpy array), while in create_array_2 this is always going to be false. I guess this means that data conversion step in the array conversion only has to happen once in create_array_1, while it happens 4096 times in create_array_2.\nIf this is the reason, I guess the timings will be different if you make render generate random data. Create_array_5 is slowest as it makes a new array each time you add data to the end.\n", "The benefit of numpy is not realized by simply storing the data in an array, it is achieved by performing operations across many elements in an array instead of one by one. Your example can be boiled down and optimized to this trivial solution with orders of magnitude speedup:\nnumpy.random.standard_normal(4096*20)\n\n...that's not very helpful, but it does kind of hint at where the costs are.\nHere is an incremental improvement that beats the list append solution (but only slightly) by eliminating the iteration over 4096 elements.\nxs = numpy.arange(4096)\nrender2 = numpy.vectorize(render)\n\ndef create_array_7():\n ibuffer = STATIC_BUFFER\n for i, a in enumerate(render2(xs)):\n ibuffer[i::20] = a\n return ibuffer\n\n... but not the speedup we are looking for.\nThe real savings will be realized by a recasting of the render routine so that you don't have to create a python object for every value that ends up being placed in the buffer. Where does tex_left, tex_right...etc. come from? Are they calculated or read?\n", "I know it seems strange, but have you tried fromfile?\n" ]
[ 1, 1, 0 ]
[]
[]
[ "2d", "numpy", "opengl", "pyopengl", "python" ]
stackoverflow_0002350110_2d_numpy_opengl_pyopengl_python.txt
Q: Solving Sparse Linear Problem With Some Known Boundary Values I'm trying to solve a Poisson equation on a rectangular domain which ends up being a linear problem like Ax=b but since I know the boundary conditions, there are nodes where I have the solution values. I guess my question is... How can I solve the sparse system Ax=b if I know what some of the coordinates of x are and the undetermined values depend on these as well? It's the same as a normal solve except I know some of the solution to begin with. Thanks! A: If I understand correctly, some elements of x are known, and some are not, and you want to solve Ax = b for the unknown values of x, correct? Let Ax = [A1 A2][x1; x2] = b, where the vector x = [x1; x2], the vector x1 has the unknown values of x, and vector x2 have the known values of x. Then, A1x1 = b - A2x2. Therefore, solve for x1 using scipy.linalg.solve or any other desired solver.
Solving Sparse Linear Problem With Some Known Boundary Values
I'm trying to solve a Poisson equation on a rectangular domain which ends up being a linear problem like Ax=b but since I know the boundary conditions, there are nodes where I have the solution values. I guess my question is... How can I solve the sparse system Ax=b if I know what some of the coordinates of x are and the undetermined values depend on these as well? It's the same as a normal solve except I know some of the solution to begin with. Thanks!
[ "If I understand correctly, some elements of x are known, and some are not, and you want to solve Ax = b for the unknown values of x, correct?\nLet Ax = [A1 A2][x1; x2] = b, where the vector x = [x1; x2], the vector x1 has the unknown values of x, and vector x2 have the known values of x. Then, A1x1 = b - A2x2. Therefore, solve for x1 using scipy.linalg.solve or any other desired solver.\n" ]
[ 1 ]
[]
[]
[ "numpy", "poisson", "python", "sparse_matrix" ]
stackoverflow_0002361176_numpy_poisson_python_sparse_matrix.txt
Q: datetime rendering in the admin forms I have the following Model and ModelAdmin classes. However when I view the posts in the admin list page, the created fields are rendered as 2010-03-01 22:15:18.494594. I've tried setting the DATETIME_FORMAT variable in settings.py, but that didn't help. Any ideas how to control the formatting of datetime fields in the admin forms. PS. I know I could write a method in the Post model, that does calls strftime on the created field, and render that method instead of created, but I'm sure there is a better way to handle this. #models.py class Post(models.Model): title = models.CharField(max_length=255) price = models.DecimalField(max_digits=11, decimal_places=2) description = models.TextField(blank=True) category = models.ForeignKey("Category") created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) #admin.py class PostAdmin(admin.ModelAdmin): list_display = ("title", "category", "price", "created",) list_filter = ("category",) search_fields = ("title", "category__name",) admin.site.register(Post, PostAdmin) A: I am not aware of a way to simply specify a date format for use in the admin interface. You do have other options though. Take a look here. According to the documentation the list of columns on the list page can include the name of a field (or simply property if I remember correctly), a callable (taking the model object as an argument), the name of a callable on the class itself that takes a model object as an argument, or the name of an instance method on the class. http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display A: Odd, on my admin lists the dates are displayed like this by default: Feb. 28, 2010, 12:25 p.m. Have you set your locale information in settings.py? TIME_ZONE = 'America/Los_Angeles' LANGUAGE_CODE = 'en-us' USE_I18N = True
datetime rendering in the admin forms
I have the following Model and ModelAdmin classes. However when I view the posts in the admin list page, the created fields are rendered as 2010-03-01 22:15:18.494594. I've tried setting the DATETIME_FORMAT variable in settings.py, but that didn't help. Any ideas how to control the formatting of datetime fields in the admin forms. PS. I know I could write a method in the Post model, that does calls strftime on the created field, and render that method instead of created, but I'm sure there is a better way to handle this. #models.py class Post(models.Model): title = models.CharField(max_length=255) price = models.DecimalField(max_digits=11, decimal_places=2) description = models.TextField(blank=True) category = models.ForeignKey("Category") created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) #admin.py class PostAdmin(admin.ModelAdmin): list_display = ("title", "category", "price", "created",) list_filter = ("category",) search_fields = ("title", "category__name",) admin.site.register(Post, PostAdmin)
[ "I am not aware of a way to simply specify a date format for use in the admin interface. You do have other options though. Take a look here. According to the documentation the list of columns on the list page can include the name of a field (or simply property if I remember correctly), a callable (taking the model object as an argument), the name of a callable on the class itself that takes a model object as an argument, or the name of an instance method on the class.\nhttp://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display\n", "Odd, on my admin lists the dates are displayed like this by default:\n\nFeb. 28, 2010, 12:25 p.m.\n\nHave you set your locale information in settings.py?\nTIME_ZONE = 'America/Los_Angeles'\nLANGUAGE_CODE = 'en-us'\nUSE_I18N = True\n\n" ]
[ 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002360699_django_python.txt
Q: using __init__.py I am having difficulty understanding the usage scenarios or design goals of python's __init__.py files in my projects. Assume that I have 'model' directory (refers as a package) which contains the following files __init__.py meta.py solrmodel.py mongomodel.py samodel.py I found two ways of using __init__.py: I have common a definition which needs to be used in solrmodel.py, mongomodel.py, samodel.py. Can I use __init__.py as a base/common definition for all the *model.py classes? This means that I have to import model/__init__.py. Or, the __init__.py shall have imported definitions of solrmodel.py, mongomodel.py, samodel.py in its own and it allows the easy import of classes or function like this: # file: __init__.py from mongomodel import * from solrmodel import * from samodel import * (I am aware that import * is not recommended and I just used it as a convention) I could not decide between above two scenarios. Are there more usage scenarios for __init__.py and can you explain the usage? A: The vast majority of the __init__.py files I write are empty, because many packages don't have anything to initialize. One example in which I may want initialization is when at package-load time I want to read in a bunch of data once and for all (from files, a DB, or the web, say) -- in which case it's much nicer to put that reading in a private function in the package's __init__.py rather than have a separate "initialization module" and redundantly import that module from every single real module in the package (uselessly repetitive and error-prone: that's obviously a case in which relying on the language's guarantee that the package's __init__.py is loaded once before any module in the package is obviously much more Pythonic!). For other concrete and authoritative expressions of opinion, look at the different approaches taken in the various packages that are part of Python's standard library. A: The contents of __init__.py are imported when you import a module within the package. You're overlooking a third scenario, which is to put the common parts in a separate module and then have the other modules import that, leaving __init__.py for things that will be used outside the package. This is the practice I usually follow.
using __init__.py
I am having difficulty understanding the usage scenarios or design goals of python's __init__.py files in my projects. Assume that I have 'model' directory (refers as a package) which contains the following files __init__.py meta.py solrmodel.py mongomodel.py samodel.py I found two ways of using __init__.py: I have common a definition which needs to be used in solrmodel.py, mongomodel.py, samodel.py. Can I use __init__.py as a base/common definition for all the *model.py classes? This means that I have to import model/__init__.py. Or, the __init__.py shall have imported definitions of solrmodel.py, mongomodel.py, samodel.py in its own and it allows the easy import of classes or function like this: # file: __init__.py from mongomodel import * from solrmodel import * from samodel import * (I am aware that import * is not recommended and I just used it as a convention) I could not decide between above two scenarios. Are there more usage scenarios for __init__.py and can you explain the usage?
[ "The vast majority of the __init__.py files I write are empty, because many packages don't have anything to initialize.\nOne example in which I may want initialization is when at package-load time I want to read in a bunch of data once and for all (from files, a DB, or the web, say) -- in which case it's much nicer to put that reading in a private function in the package's __init__.py rather than have a separate \"initialization module\" and redundantly import that module from every single real module in the package (uselessly repetitive and error-prone: that's obviously a case in which relying on the language's guarantee that the package's __init__.py is loaded once before any module in the package is obviously much more Pythonic!).\nFor other concrete and authoritative expressions of opinion, look at the different approaches taken in the various packages that are part of Python's standard library.\n", "The contents of __init__.py are imported when you import a module within the package.\nYou're overlooking a third scenario, which is to put the common parts in a separate module and then have the other modules import that, leaving __init__.py for things that will be used outside the package. This is the practice I usually follow.\n" ]
[ 52, 23 ]
[]
[]
[ "initialization", "module", "package", "python" ]
stackoverflow_0002361124_initialization_module_package_python.txt
Q: django error :1146, "Table 'basic_project.topics_topic' doesn't exist" TemplateSyntaxError at /tribes/ Caught an exception while rendering: (1146, "Table 'basic_project.topics_topic' doesn't exist") Why? A: Because. You have to run syncdb everytime you add a new app or model.
django error :1146, "Table 'basic_project.topics_topic' doesn't exist"
TemplateSyntaxError at /tribes/ Caught an exception while rendering: (1146, "Table 'basic_project.topics_topic' doesn't exist") Why?
[ "Because.\nYou have to run syncdb everytime you add a new app or model.\n" ]
[ 2 ]
[]
[]
[ "django", "pinax", "python" ]
stackoverflow_0002361451_django_pinax_python.txt
Q: Pure Python in Xcode? Could anyone tell me how to use pure Python without Cocoa support in Xcode? I can only find the Cocoa-Python template on the Internet. Thanks in advance. A: If you are just trying to write pure Python command line tools, using Xcode is like using a big sledge hammer to hit a tiny nail, in other words, probably not the best tool for the job. There are some old posts out there about how to set up a pure Python Xcode project, like this one, but, in the end, you might be better off using an editor you're already familiar with, like emacs, or, if you don't mind spending a little bit of money, TextMate, all along with a free vcs like mercurial or git. Or take a look in MacPorts for those and other options. A: Just about the best IDE for editing and running Python code is actually still emacs. The python-mode for emacs does a wonderful job of maintaining whitespace and, with a bit of configuration, emacs is truly a powerful editor. Pretty radically different than your typical GUI editor, certainly, and some find it quite distasteful. I've personally used emacs, mostly, for editing Python since 1992 or so. Google will reveal all, including a native version of Emacs for Mac OS X. A: A lot of people like eclipse with PyDev for python, although I don't know how wel it works on OS X with apple's mishandling of java. A: Even though I am using BBEdit, I found Wingware Python editor did a good job in exploiting the introspected data of Python modules. Purely designed for Python. Give it a try. http://www.wingide.com/
Pure Python in Xcode?
Could anyone tell me how to use pure Python without Cocoa support in Xcode? I can only find the Cocoa-Python template on the Internet. Thanks in advance.
[ "If you are just trying to write pure Python command line tools, using Xcode is like using a big sledge hammer to hit a tiny nail, in other words, probably not the best tool for the job. There are some old posts out there about how to set up a pure Python Xcode project, like this one, but, in the end, you might be better off using an editor you're already familiar with, like emacs, or, if you don't mind spending a little bit of money, TextMate, all along with a free vcs like mercurial or git. Or take a look in MacPorts for those and other options.\n", "Just about the best IDE for editing and running Python code is actually still emacs. The python-mode for emacs does a wonderful job of maintaining whitespace and, with a bit of configuration, emacs is truly a powerful editor.\nPretty radically different than your typical GUI editor, certainly, and some find it quite distasteful. I've personally used emacs, mostly, for editing Python since 1992 or so.\nGoogle will reveal all, including a native version of Emacs for Mac OS X.\n", "A lot of people like eclipse with PyDev for python, although I don't know how wel it works on OS X with apple's mishandling of java.\n", "Even though I am using BBEdit, I found Wingware Python editor did a good job in exploiting the introspected data of Python modules. Purely designed for Python. Give it a try.\nhttp://www.wingide.com/\n" ]
[ 7, 0, 0, 0 ]
[]
[]
[ "python", "xcode" ]
stackoverflow_0002359994_python_xcode.txt
Q: Modifying the `clear` attribute of an image with TinyMCE I'm using TinyMCE with the tinymce-django app in my Django website. I am using it in the admin interface to edit HTML fields. (Something like a flatpage.) When adding images with TinyMCE, how can I change their clear style attribute? A: First go to the image popup. After selecting image, navigate to Appearance tab. If you don't see this popup, make sure that the editor mode is advanced and the plugin advimage is included. Now, you have two options to do so: CSS class. You have to define, for example, .clear { clear: both; } in your CSS stylesheet. In TinyMCE you will see the class, select clear. If you don't see your class that's probably because you didn't include the stylesheet in content_css, but you can still select (value) and type it yourself. CSS style. Add clear: both; (or right/left, whatever you need), in the style row. I've made an screenshot of both options, you need only one of them: It is possible to edit the style manually, in HTML popup. If the editor is intended for developers, then this is the easist approach, and probably also the fastest one. A: You need to have clear included in the valid elements rules (or the extended valid elements), or TinyMCE will strip it out.
Modifying the `clear` attribute of an image with TinyMCE
I'm using TinyMCE with the tinymce-django app in my Django website. I am using it in the admin interface to edit HTML fields. (Something like a flatpage.) When adding images with TinyMCE, how can I change their clear style attribute?
[ "First go to the image popup. After selecting image, navigate to Appearance tab.\nIf you don't see this popup, make sure that the editor mode is advanced and the plugin advimage is included.\nNow, you have two options to do so:\n\nCSS class. You have to define, for example, .clear { clear: both; }\n in your CSS stylesheet. In TinyMCE you will see the class, select clear.\n If you don't see your class that's probably because you didn't include the stylesheet in content_css, but you can still select (value) and type it yourself.\nCSS style. Add clear: both; (or right/left, whatever you need), in the style row.\n\nI've made an screenshot of both options, you need only one of them:\n\n\nIt is possible to edit the style manually, in HTML popup. If the editor is intended for developers, then this is the easist approach, and probably also the fastest one.\n", "You need to have clear included in the valid elements rules (or the extended valid elements), or TinyMCE will strip it out.\n" ]
[ 2, 0 ]
[]
[]
[ "django", "django_tinymce", "python" ]
stackoverflow_0002309894_django_django_tinymce_python.txt
Q: RSS screen scraper Can anyone point me towards a ready made RSS screen scraper, preferably in Python in order to get full text RSS feeds? A: There's a good list of them here, which mentions Feed Parser, which you use like this: import feedparser python_wiki_rss_url = "http://www.python.org/cgi-bin/moinmoin/" \ "RecentChanges?action=rss_rc" feed = feedparser.parse( python_wiki_rss_url ) You can then do things like: for item in feed["items"]: print item["title"] A: feedparser.org is great A: Sorry but it doesn't exist in python, though they do in php. You are more then welcome to use and improve the one I made named scraped. Though it does not do all sites, it is a recipe based system that currently only handles the NYT, WSJ and the Economist. I am working on an all inclusive algorithm, but its a major undertaking. It includes a ton of analysis to the different types of html and xml. Even the 3 sites mentioned above, have vastly different algorithms on how to scrape their sites WSJ being the most complex by far. They screw their HTML up with so much useless crap, mainly to just stop you. Here is the program I was talking about, it requires lxml but it explains everything in the readme. It reads the config files, parses partial rss feeds, takes links and then scrapes those links, formulating in the end a RSS 2.0 xml file. Which I mainly convert into a ebook for my kindle. I utilize lxml, BeautifulSoup and feedparser. http://tinyurl.com/yh3s9pa You can also look at the calibre project, which uses a similar method to the way I do it, on recipes.
RSS screen scraper
Can anyone point me towards a ready made RSS screen scraper, preferably in Python in order to get full text RSS feeds?
[ "There's a good list of them here, which mentions Feed Parser, which you use like this:\nimport feedparser\n\npython_wiki_rss_url = \"http://www.python.org/cgi-bin/moinmoin/\" \\\n \"RecentChanges?action=rss_rc\"\n\nfeed = feedparser.parse( python_wiki_rss_url )\n\nYou can then do things like:\nfor item in feed[\"items\"]:\n print item[\"title\"]\n\n", "feedparser.org is great\n", "Sorry but it doesn't exist in python, though they do in php. You are more then welcome to use and improve the one I made named scraped. Though it does not do all sites, it is a recipe based system that currently only handles the NYT, WSJ and the Economist. I am working on an all inclusive algorithm, but its a major undertaking. It includes a ton of analysis to the different types of html and xml. Even the 3 sites mentioned above, have vastly different algorithms on how to scrape their sites WSJ being the most complex by far. They screw their HTML up with so much useless crap, mainly to just stop you. \nHere is the program I was talking about, it requires lxml but it explains everything in the readme. It reads the config files, parses partial rss feeds, takes links and then scrapes those links, formulating in the end a RSS 2.0 xml file. Which I mainly convert into a ebook for my kindle. I utilize lxml, BeautifulSoup and feedparser.\nhttp://tinyurl.com/yh3s9pa\nYou can also look at the calibre project, which uses a similar method to the way I do it, on recipes. \n" ]
[ 3, 1, 0 ]
[]
[]
[ "python", "rss" ]
stackoverflow_0002362066_python_rss.txt
Q: Is Tkinter worth learning? I generally make my desktop interfaces with Qt, but some recent TK screenshots convince me Tk isn't just ugly motif any more. Additionally Tkinter comes bundled with Python, which makes distribution easier. So is it worth learning or should I stick with Qt? (source: kb-creative.net) A: The answer to your question is a resounding yes. Qt is good, I have nothing against it. But Tk is better and far easier to use and quite well documented - not just on the Python webspace, but there are also many third-party tutorials out there. This particular one is where I learned it from and it has been quite infallible in serving me. A: As a step up to other GUI toolkits, sure. If you know other toolkits then you already understand TkInter and can leave it until you actually need it. A: You might want to take a look at this(wxPython). wxPython is the best and most mature cross-platform GUI toolkit, given a number of constraints. The only reason wxPython isn't the standard Python GUI toolkit is that Tkinter was there first. -- Guido van Rossum A: Why not go for PyQT? You apparently are already familiar with Qt, so it should be relatively easy to learn. In my opinion it looks better than Tkinter, and it sure is better documented. A: I used Qt with C++, but decided to have a go with Tkinter with Python. I had a bit of trouble installing the latest version of Tcl/Tk, but got there eventually. I did it all with the help of this tkdocs.com tutorial, which is great.
Is Tkinter worth learning?
I generally make my desktop interfaces with Qt, but some recent TK screenshots convince me Tk isn't just ugly motif any more. Additionally Tkinter comes bundled with Python, which makes distribution easier. So is it worth learning or should I stick with Qt? (source: kb-creative.net)
[ "The answer to your question is a resounding yes.\nQt is good, I have nothing against it. But Tk is better and far easier to use and quite well documented - not just on the Python webspace, but there are also many third-party tutorials out there. This particular one is where I learned it from and it has been quite infallible in serving me. \n", "As a step up to other GUI toolkits, sure. If you know other toolkits then you already understand TkInter and can leave it until you actually need it.\n", "You might want to take a look at this(wxPython).\n\nwxPython is the best and most mature cross-platform GUI toolkit, given a number of constraints. The only reason wxPython isn't the standard Python GUI toolkit is that Tkinter was there first.\n -- Guido van Rossum\n\n", "Why not go for PyQT? You apparently are already familiar with Qt, so it should be relatively easy to learn. In my opinion it looks better than Tkinter, and it sure is better documented.\n", "I used Qt with C++, but decided to have a go with Tkinter with Python. I had a bit of trouble installing the latest version of Tcl/Tk, but got there eventually. I did it all with the help of this tkdocs.com tutorial, which is great.\n" ]
[ 24, 4, 4, 2, 0 ]
[]
[]
[ "python", "qt", "tk_toolkit", "tkinter", "user_interface" ]
stackoverflow_0002361328_python_qt_tk_toolkit_tkinter_user_interface.txt
Q: Database-Independent MAX() Function in SQLAlchemy I'd like to calculate a MAX() value for a column. What's the proper way to do this in sqlalchemy while preserving database independence? A: You can find aggregate functions in: from sqlalchemy import func func.avg(...) func.sum(...) func.max(...) In 0.5 you can use an ORM query like a select: session.query(func.max(Table.column))
Database-Independent MAX() Function in SQLAlchemy
I'd like to calculate a MAX() value for a column. What's the proper way to do this in sqlalchemy while preserving database independence?
[ "You can find aggregate functions in: \nfrom sqlalchemy import func \nfunc.avg(...) \nfunc.sum(...) \nfunc.max(...) \n\nIn 0.5 you can use an ORM query like a select:\nsession.query(func.max(Table.column)) \n\n" ]
[ 6 ]
[]
[]
[ "mysql", "pylons", "python", "sqlalchemy" ]
stackoverflow_0002358634_mysql_pylons_python_sqlalchemy.txt
Q: PyQt4: Adding QtMessageBox.information functionality to custom window what I need is something very alike QtMessageBox.information method, but I need it form my custom window. I need a one window with few labels, one QtTreeViewWidget, one QButtonGroup … This window will be called from main window. If we call class that implements called window as SelectionWindow, than what I need is: class MainWindow(QtGui.QMainWindow): ... def method2(self): selWin = SelectionWindow() tempSelectionValue = selWin.getSelection() # Blocked until return from getSelection self.method1(tempSelectionValue) ... class SelectionWindow(QtGui.QMainWindow): ... def getSelection(self): ... return selectedRow ... Method getSelection from SelectionWindow should pop up selection window and at the end return row selected in QTreeViewWidget. I want that main window remains blocked until user selects one row in selection window and confirms it by button. I hope that you will understand what I need. I will appreciate any help! Thanks, Tiho A: I would do something like this: dialog window with buttonbox -> events connected to accept() and reject() slots of the dialog itself set the dialog modality to something like application modal call the exec_() method of the dialog to keep it blocking until the user chooses ok/cancel after the execution of the exec_() method terminates, you can read what you need from the dialog widgets. Something like this should fit your needs: class SelectionWindow(QtGui.QMainWindow): ... def getSelection(self): result = self.exec_() if result: # User clicked Ok - read currentRow selectedRow = self.ui.myQtTreeViewWidget.currentIndex() else: # User clicked Cancel selectedRow = None return selectedRow ...
PyQt4: Adding QtMessageBox.information functionality to custom window
what I need is something very alike QtMessageBox.information method, but I need it form my custom window. I need a one window with few labels, one QtTreeViewWidget, one QButtonGroup … This window will be called from main window. If we call class that implements called window as SelectionWindow, than what I need is: class MainWindow(QtGui.QMainWindow): ... def method2(self): selWin = SelectionWindow() tempSelectionValue = selWin.getSelection() # Blocked until return from getSelection self.method1(tempSelectionValue) ... class SelectionWindow(QtGui.QMainWindow): ... def getSelection(self): ... return selectedRow ... Method getSelection from SelectionWindow should pop up selection window and at the end return row selected in QTreeViewWidget. I want that main window remains blocked until user selects one row in selection window and confirms it by button. I hope that you will understand what I need. I will appreciate any help! Thanks, Tiho
[ "I would do something like this:\n\ndialog window with buttonbox ->\nevents connected to accept() and\nreject() slots of the dialog itself\nset the dialog modality to something like application modal\ncall the exec_() method of the dialog to keep it blocking until the user chooses ok/cancel\nafter the execution of the exec_() method terminates, you can read what you need from the dialog widgets. \n\nSomething like this should fit your needs:\nclass SelectionWindow(QtGui.QMainWindow):\n ...\n def getSelection(self):\n result = self.exec_()\n if result:\n # User clicked Ok - read currentRow\n selectedRow = self.ui.myQtTreeViewWidget.currentIndex()\n else:\n # User clicked Cancel\n selectedRow = None\n return selectedRow\n ...\n\n" ]
[ 0 ]
[]
[]
[ "pyqt4", "python" ]
stackoverflow_0002335104_pyqt4_python.txt
Q: Python: Access Posix' locale database without setlocale() The setup is a Django based website on an Ubuntu server system with lots of useful information in /usr/share/i18n/locales. The question: Can I access this pool of wisdom without using Python's locale.setlocale() afore? The reason: The docs say, that it is very expensive to call setlocale(), and affects the whole application. But in my case I have a, say, French site (Django handles setting the locale automatically), and I just want to display the name of January in the de_AT locale, or format a number like they do in Russia. A: The magic library to achieve this is called Babel. Does what I want: Before import locale setlocale(LC_ALL, 'de') x = locale.format('%.2f', 123) setlocale(LC_ALL, '') After from babel.numbers import format_decimal x = format_decimal(123, format='#0.00', locale='de') ...and has a good Djang integration gratis.
Python: Access Posix' locale database without setlocale()
The setup is a Django based website on an Ubuntu server system with lots of useful information in /usr/share/i18n/locales. The question: Can I access this pool of wisdom without using Python's locale.setlocale() afore? The reason: The docs say, that it is very expensive to call setlocale(), and affects the whole application. But in my case I have a, say, French site (Django handles setting the locale automatically), and I just want to display the name of January in the de_AT locale, or format a number like they do in Russia.
[ "The magic library to achieve this is called Babel. Does what I want:\nBefore\nimport locale\nsetlocale(LC_ALL, 'de')\nx = locale.format('%.2f', 123)\nsetlocale(LC_ALL, '')\n\nAfter\nfrom babel.numbers import format_decimal\nx = format_decimal(123, format='#0.00', locale='de')\n\n...and has a good Djang integration gratis.\n" ]
[ 3 ]
[]
[]
[ "django", "internationalization", "locale", "posix", "python" ]
stackoverflow_0002361764_django_internationalization_locale_posix_python.txt
Q: At what point does importing become the correct solution? This weekend I was working on a project and I needed to use a binomial distribution to test the probability of an event (the probability that x of y characters would be alphanumeric given random bytes). My first solution was to write the test myself since it is rather simple. def factorial(n): if n == 0: return 1 else: return n * factorial(n-1) def binomial_prob(n,k,p): bin_coeff = (factorial(n))/(factorial(k)*factorial(n-k)) return = bin_coeff * pow(p,k) * pow((1 - p),(n-k)) And I used that. However, SciPy includes a binom_test method that does exactly this. But, for distribution this probably increases the size significantly (both SciPy and NumPy would be required) and it is for a relatively simple test. I suppose an auxiliary question is how intelligent is py2exe. Does it just import the modules I use from SciPy and NumPy, or the whole libraries. I expect just the modules that I reference, but I guess the next question is on how many modules does SciPy.stats depend on. But I digress... So my question is this, when should I use code already written at the cost of including far more than I need, and when should I just write my own implementation? (I tagged this as python, but I suppose it could be a more general question) A: "when should I use code already written at the cost of including far more than I need" Always. When should I just write my own implementation? Never. The "including far more than I need" question is generally quite silly. What do you care how much is "included"? The only time this can ever matter is when you're writing embedded software and are severely memory-constrained. For all other programming -- All other programming -- don't think twice. Include pre-written code early and often. Write less. Solve problems more quickly. The operating system will swap the unused pages out of memory. You can safely ignore them. Programming is about solving problems, not producing code. Less code is better. No code is best. A: The answer depends on who will use your application and how widely it will be distributed. The Unix/Linux folks tend to heavily favour use of existing libraries, because they are used to every machine being a development machine that can rebuild its own software from source. Partly this is because of necessity, as native code libraries typically need to be compiled and linked against the local environment. But on Windows it's a different proposition entirely, since most users can't, won't, and indeed shouldn't do that, so you have to consider how the use of these 3rd party libraries will affect your distribution plans - in terms of the license, in terms of the download size, the usability, etc. You're talking about py2exe which suggests to me that you're making a single-file executable for distribution to Windows users. This means that your main concerns will be compatibility (since libraries containing native code can only run on one type of platform - Win32 code should be fine though) and size, since py2exe will not do anything cunning with the dependencies; expect the whole thing to be bundled into your executable. The best approach is to package it up and see what happens. It's a simple and non-destructive step, so you should try it for yourself as soon as possible. You also need to consider the licenses of any libraries you distribute. Again the 're-use everything' crowd sometimes forget this because they often work on software that they don't have to redistribute and so this isn't an issue. For you, it might be, especially if you have code that is owned by your employer or institution, although it's important to realise that when you distribute Python apps, you essentially distribute source code for anybody to look at anyway.
At what point does importing become the correct solution?
This weekend I was working on a project and I needed to use a binomial distribution to test the probability of an event (the probability that x of y characters would be alphanumeric given random bytes). My first solution was to write the test myself since it is rather simple. def factorial(n): if n == 0: return 1 else: return n * factorial(n-1) def binomial_prob(n,k,p): bin_coeff = (factorial(n))/(factorial(k)*factorial(n-k)) return = bin_coeff * pow(p,k) * pow((1 - p),(n-k)) And I used that. However, SciPy includes a binom_test method that does exactly this. But, for distribution this probably increases the size significantly (both SciPy and NumPy would be required) and it is for a relatively simple test. I suppose an auxiliary question is how intelligent is py2exe. Does it just import the modules I use from SciPy and NumPy, or the whole libraries. I expect just the modules that I reference, but I guess the next question is on how many modules does SciPy.stats depend on. But I digress... So my question is this, when should I use code already written at the cost of including far more than I need, and when should I just write my own implementation? (I tagged this as python, but I suppose it could be a more general question)
[ "\"when should I use code already written at the cost of including far more than I need\"\nAlways.\nWhen should I just write my own implementation?\nNever.\nThe \"including far more than I need\" question is generally quite silly. What do you care how much is \"included\"?\nThe only time this can ever matter is when you're writing embedded software and are severely memory-constrained.\nFor all other programming -- All other programming -- don't think twice. Include pre-written code early and often. Write less. Solve problems more quickly. The operating system will swap the unused pages out of memory. You can safely ignore them.\nProgramming is about solving problems, not producing code. Less code is better. No code is best.\n", "The answer depends on who will use your application and how widely it will be distributed. The Unix/Linux folks tend to heavily favour use of existing libraries, because they are used to every machine being a development machine that can rebuild its own software from source. Partly this is because of necessity, as native code libraries typically need to be compiled and linked against the local environment. But on Windows it's a different proposition entirely, since most users can't, won't, and indeed shouldn't do that, so you have to consider how the use of these 3rd party libraries will affect your distribution plans - in terms of the license, in terms of the download size, the usability, etc.\nYou're talking about py2exe which suggests to me that you're making a single-file executable for distribution to Windows users. This means that your main concerns will be compatibility (since libraries containing native code can only run on one type of platform - Win32 code should be fine though) and size, since py2exe will not do anything cunning with the dependencies; expect the whole thing to be bundled into your executable. The best approach is to package it up and see what happens. It's a simple and non-destructive step, so you should try it for yourself as soon as possible.\nYou also need to consider the licenses of any libraries you distribute. Again the 're-use everything' crowd sometimes forget this because they often work on software that they don't have to redistribute and so this isn't an issue. For you, it might be, especially if you have code that is owned by your employer or institution, although it's important to realise that when you distribute Python apps, you essentially distribute source code for anybody to look at anyway.\n" ]
[ 5, 0 ]
[]
[]
[ "import", "python" ]
stackoverflow_0002356036_import_python.txt
Q: How can i capture the UDP packet and find the TTL Values from the packet using python HI I want to capture the UDP packets by joining to the Multicast group. after the receving the packet i want to check for the TTL value from that UDP packet. How can i achieve this by using python ? The Sammple code as mentioned below: here rec_port is any port which i had used to bind; eg: 9180 rec_hostname is any multicast group which i had joined;eg:239.2.2.2 #! /usr/bin/env python ......... ............ sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(("", rec_port)) mreq = struct.pack("4sl", socket.inet_aton(rec_hostname), socket.INADDR_ANY) sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) total_length = 0 while True: print "Waiting for the packets, if no packets recevied by 10 seconds, than i will exit" sock.settimeout(10) data , address = sock.recvfrom(2048) if len(data) > 1: total_length=total_length + len(data) print "Data is:", data print "Length of data received is:", len(data) print "Packet recevied from :", address[0] print "Total Packet size:", total_length else: break sock.close() print "Total Packet size:", total_length A: You probably want to use this python wrapper. If it doesn't satisfy you can wrap libpcap yourself. In response to unwind: You don't have to act "promiscious" with libpcap, you can inject and snoop valid traffic -- i.e., meant for your NIC. Edit: Read this tutorial on pcap to figure out how to isolate the ttl field. A: in a comment, you told us that you are able to join the multicast group. now you can use getsockopt(), specify IPPROTO_IP for the level parameter and IP_MULTICAST_TTL for the option, to get the TTL value which is written to outgoing packets.
How can i capture the UDP packet and find the TTL Values from the packet using python
HI I want to capture the UDP packets by joining to the Multicast group. after the receving the packet i want to check for the TTL value from that UDP packet. How can i achieve this by using python ? The Sammple code as mentioned below: here rec_port is any port which i had used to bind; eg: 9180 rec_hostname is any multicast group which i had joined;eg:239.2.2.2 #! /usr/bin/env python ......... ............ sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(("", rec_port)) mreq = struct.pack("4sl", socket.inet_aton(rec_hostname), socket.INADDR_ANY) sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) total_length = 0 while True: print "Waiting for the packets, if no packets recevied by 10 seconds, than i will exit" sock.settimeout(10) data , address = sock.recvfrom(2048) if len(data) > 1: total_length=total_length + len(data) print "Data is:", data print "Length of data received is:", len(data) print "Packet recevied from :", address[0] print "Total Packet size:", total_length else: break sock.close() print "Total Packet size:", total_length
[ "You probably want to use this python wrapper. If it doesn't satisfy you can wrap libpcap yourself.\nIn response to unwind: You don't have to act \"promiscious\" with libpcap, you can inject and snoop valid traffic -- i.e., meant for your NIC.\nEdit: Read this tutorial on pcap to figure out how to isolate the ttl field.\n", "in a comment, you told us that you are able to join the multicast group.\nnow you can use getsockopt(), specify IPPROTO_IP for the level parameter and IP_MULTICAST_TTL for the option, to get the TTL value which is written to outgoing packets.\n" ]
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002362541_python.txt
Q: Delete() views and template code Template: <form method="POST" action="/customer/delete/"> <div style="float: right; margin: 0px; padding: 05px; "> Name:<select name="customer"> {% for customer in customer %} <option value="{{ customer.name|escape }}" ></option><br /> {% endfor %} </select> <input type=submit value="delete"> </div> </form> Views: def delete(request, name): Customer.objects.get(name=name).delete() return HttpResponse('deleted') Urls.py (r'^customer/delete/', 'quote.excel.views.delete'), This isnt working,plz correct the code. A: Your URLConf isn't catching any data to pass on to the variable name. You need to either catch it as a part of the URL, or leave it to catch in a POSTed argument. As part of the URL: (r'^customer/(?P<name>[a-z]*)/delete/', 'quote.excel.views.delete') def delete(request, name): if request.method == "POST": # GET requests should NEVER delete anything, # or the google bot will wreck your data. Customer.objects.get(name=name).delete() As a post variable: (r'^customer/delete/', 'quote.excel.views.delete') def delete(request): # No arguments passed in if request.method == "POST": name = request.POST['name'] Customer.objects.get(name=name).delete() A: Customer.objects.get(name = request.POST['name']).delete() By the way, are you sure that the action variable in the template is indeed 'delete'? If it isn't, the url called (and hence the method) will be different. <form method="POST" action="/customer/{{ action }}/">
Delete() views and template code
Template: <form method="POST" action="/customer/delete/"> <div style="float: right; margin: 0px; padding: 05px; "> Name:<select name="customer"> {% for customer in customer %} <option value="{{ customer.name|escape }}" ></option><br /> {% endfor %} </select> <input type=submit value="delete"> </div> </form> Views: def delete(request, name): Customer.objects.get(name=name).delete() return HttpResponse('deleted') Urls.py (r'^customer/delete/', 'quote.excel.views.delete'), This isnt working,plz correct the code.
[ "Your URLConf isn't catching any data to pass on to the variable name. You need to either catch it as a part of the URL, or leave it to catch in a POSTed argument.\nAs part of the URL:\n(r'^customer/(?P<name>[a-z]*)/delete/', 'quote.excel.views.delete')\n\ndef delete(request, name):\n if request.method == \"POST\": \n # GET requests should NEVER delete anything, \n # or the google bot will wreck your data.\n Customer.objects.get(name=name).delete()\n\nAs a post variable:\n(r'^customer/delete/', 'quote.excel.views.delete')\n\ndef delete(request): # No arguments passed in\n if request.method == \"POST\":\n name = request.POST['name']\n Customer.objects.get(name=name).delete()\n\n", "Customer.objects.get(name = request.POST['name']).delete()\n\nBy the way, are you sure that the action variable in the template is indeed 'delete'? If it isn't, the url called (and hence the method) will be different.\n<form method=\"POST\" action=\"/customer/{{ action }}/\">\n\n" ]
[ 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002361074_django_python.txt
Q: Match start and end of file in python with regex I'm having a hard time finding the regex for the start and end of a file in python. How would I accomplish this ? A: Read the whole file into a string, then \A matches only the beginning of a string, and \Z matches only the end of a string. With re.MULTILINE, '^' matches the beginning of the string and the just after a newline, and '$' matches the end of the string and just before a newline. See the Python documentation for re syntax. import re data = '''sentence one. sentence two. a bad sentence sentence three. sentence four.''' # find lines ending in a period print re.findall(r'^.*\.$',data,re.MULTILINE) # match if the first line ends in a period print re.findall(r'\A^.*\.$',data,re.MULTILINE) # match if the last line ends in a period. print re.findall(r'^.*\.$\Z',data,re.MULTILINE) Output: ['sentence one.', 'sentence two.', 'sentence three.', 'sentence four.'] ['sentence one.'] ['sentence four.'] A: Maybe you should pose your question more clearly, like what you trying to do. That said, you can slurp the file into one whole string, and match your pattern using re. import re data=open("file").read() pat=re.compile("^.*pattern.*$",re.M|re.DOTALL) print pat.findall(data) There are better ways to do what you want, whatever it is, without re. A: regex $ is NOT your friend; see this SO answer
Match start and end of file in python with regex
I'm having a hard time finding the regex for the start and end of a file in python. How would I accomplish this ?
[ "Read the whole file into a string, then \\A matches only the beginning of a string, and \\Z matches only the end of a string. With re.MULTILINE, '^' matches the beginning of the string and the just after a newline, and '$' matches the end of the string and just before a newline. See the Python documentation for re syntax.\nimport re\n\ndata = '''sentence one.\nsentence two.\na bad sentence\nsentence three.\nsentence four.'''\n\n# find lines ending in a period\nprint re.findall(r'^.*\\.$',data,re.MULTILINE)\n# match if the first line ends in a period\nprint re.findall(r'\\A^.*\\.$',data,re.MULTILINE)\n# match if the last line ends in a period.\nprint re.findall(r'^.*\\.$\\Z',data,re.MULTILINE)\n\nOutput:\n['sentence one.', 'sentence two.', 'sentence three.', 'sentence four.']\n['sentence one.']\n['sentence four.']\n\n", "Maybe you should pose your question more clearly, like what you trying to do. That said, you can slurp the file into one whole string, and match your pattern using re.\nimport re\ndata=open(\"file\").read()\npat=re.compile(\"^.*pattern.*$\",re.M|re.DOTALL)\nprint pat.findall(data)\n\nThere are better ways to do what you want, whatever it is, without re.\n", "regex $ is NOT your friend; see this SO answer \n" ]
[ 20, 2, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002362471_python_regex.txt
Q: Nested functions scope in Python I have the following function that walks a nested tree and prints the result def walk_tree(tree): def read_node(node): print node for n in node['subnodes']: read_node(n) read_node(tree) If I want to return a txt with the data collected from walking the tree, thought that the following would have worked: def walk_tree(tree): txt = '' def read_node(node): txt += node for n in node['subnodes']: read_node(n) read_node(tree) But txt doesn't seem to be in read_node's scope. Any suggestion? Thanks A: txt is accessible in read_node, I think it's just some problem with += and that txt is not in local scope in read_node. >>> def a(): ... x = "" ... def b(): ... x += "X" ... b() ... print x ... >>> a() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 5, in a File "<stdin>", line 4, in b UnboundLocalError: local variable 'x' referenced before assignment >>> >>> >>> def a(): ... x = [] ... def b(): ... x.append("X") ... b() ... print "".join(x) ... >>> a() X You should use list and "".join(...) instead of str += ... anyways. A: In Python you cannot rebind variables of an outer scope (of walk_tree in your example). So this will fail: def a(): def b(): txt += "b" # !!! print txt txt = "mytext" b() a() but this will work: def a(): def b(): # removed assignment: txt += "b" print txt txt = "mytext" b() a() So you may want to avoid rebinding: def a(): def b(): obj["key"] = "newtext" obj = {"key" : "mytext"} b() a() A: You could try: def walk_tree(tree): txt = '' # (1) def read_node(node, txt=txt): txt += node # (2) for n in node['subnodes']: read_node(n, txt) read_node(tree) This binds walk_trees value of txt to the default value in read_node, which should persist (if my grasp of Python theory is correct).
Nested functions scope in Python
I have the following function that walks a nested tree and prints the result def walk_tree(tree): def read_node(node): print node for n in node['subnodes']: read_node(n) read_node(tree) If I want to return a txt with the data collected from walking the tree, thought that the following would have worked: def walk_tree(tree): txt = '' def read_node(node): txt += node for n in node['subnodes']: read_node(n) read_node(tree) But txt doesn't seem to be in read_node's scope. Any suggestion? Thanks
[ "txt is accessible in read_node, I think it's just some problem with += and that txt is not in local scope in read_node.\n>>> def a():\n... x = \"\"\n... def b():\n... x += \"X\"\n... b()\n... print x\n... \n>>> a()\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"<stdin>\", line 5, in a\n File \"<stdin>\", line 4, in b\nUnboundLocalError: local variable 'x' referenced before assignment\n>>> \n>>> \n>>> def a():\n... x = []\n... def b():\n... x.append(\"X\")\n... b()\n... print \"\".join(x)\n... \n>>> a()\nX\n\nYou should use list and \"\".join(...) instead of str += ... anyways.\n", "In Python you cannot rebind variables of an outer scope (of walk_tree in your example).\nSo this will fail:\ndef a():\n def b():\n txt += \"b\" # !!!\n\n print txt\n\n txt = \"mytext\"\n b()\n\na()\n\nbut this will work:\ndef a():\n def b():\n # removed assignment: txt += \"b\"\n\n print txt\n\n txt = \"mytext\"\n b()\n\na()\n\nSo you may want to avoid rebinding:\ndef a():\n def b():\n obj[\"key\"] = \"newtext\"\n\n obj = {\"key\" : \"mytext\"}\n b()\n\na()\n\n", "You could try:\ndef walk_tree(tree):\n txt = '' # (1)\n def read_node(node, txt=txt):\n txt += node # (2)\n for n in node['subnodes']:\n read_node(n, txt)\n read_node(tree)\n\nThis binds walk_trees value of txt to the default value in read_node, which should persist (if my grasp of Python theory is correct).\n" ]
[ 6, 5, 0 ]
[]
[]
[ "python", "tree" ]
stackoverflow_0002363266_python_tree.txt
Q: python os.utime doesn't update the access time I'm trying to modify the access timestamp and modify timestamp of a remote file I'm using the following line: os.utime(filePath, (1267533581,1267090862)) the modify timestamp get updated but the access timestamp doesn't I have tried to use this on a local file on a local file and everything is working well I'm working on windows. the file system is NTFS A: Perhaps the last access time is disabled on your system. This could have been done for performance purposes. It's controlled by a registry setting. See: http://www.pctools.com/guides/registry/detail/50
python os.utime doesn't update the access time
I'm trying to modify the access timestamp and modify timestamp of a remote file I'm using the following line: os.utime(filePath, (1267533581,1267090862)) the modify timestamp get updated but the access timestamp doesn't I have tried to use this on a local file on a local file and everything is working well I'm working on windows. the file system is NTFS
[ "Perhaps the last access time is disabled on your system. This could have been done for performance purposes. It's controlled by a registry setting. See:\nhttp://www.pctools.com/guides/registry/detail/50\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0002363497_python.txt
Q: Splitting list in python I have a list which I have obtained from a python script. the content of the list goes something like: The content below is in a file but I loaded it into a list for comparing it to something else. But now I have to split this list such that each new list created contains the complex name with the corresponding number. Hope it is clear now :) d.complex.1 24 25 67 123 764 d.complex.200 23 54 35 64 d.complex.302 . . . I want to split this list such that, a new list is created from d.complex.1 to d.complex.2 (excluding d.complex.2) i.e.: d.complex.1 24 25 67 123 764 end of list >newlist d.complex.200 23 54 35 64 endoflist Can anyone help me out? Cheers, Chavanak A: without more detailed info and assuming your "list" is in a file. f=0 for line in open("file"): if "d.complex.2" in line: break # or exit if "d.complex.1" in line: f=1 if f: print line.rstrip() output $ ./python.py d.complex.1 24 25 67 123 764 A: >>> mylist='d.complex.1\n24\n25\n67\n123\n764\nd.complex.200\n23\n54\n35\n64\nd.complex.302'.split("\n") >>> res=[] >>> for line in mylist: ... if line.startswith("d.complex"): ... res.append([]) ... res[-1].append(line) ... >>> res [['d.complex.1', '24', '25', '67', '123', '764'], ['d.complex.200', '23', '54', '35', '64'], ['d.complex.302']]
Splitting list in python
I have a list which I have obtained from a python script. the content of the list goes something like: The content below is in a file but I loaded it into a list for comparing it to something else. But now I have to split this list such that each new list created contains the complex name with the corresponding number. Hope it is clear now :) d.complex.1 24 25 67 123 764 d.complex.200 23 54 35 64 d.complex.302 . . . I want to split this list such that, a new list is created from d.complex.1 to d.complex.2 (excluding d.complex.2) i.e.: d.complex.1 24 25 67 123 764 end of list >newlist d.complex.200 23 54 35 64 endoflist Can anyone help me out? Cheers, Chavanak
[ "without more detailed info and assuming your \"list\" is in a file.\nf=0\nfor line in open(\"file\"):\n if \"d.complex.2\" in line: break # or exit\n if \"d.complex.1\" in line:\n f=1\n if f:\n print line.rstrip()\n\noutput\n$ ./python.py\nd.complex.1\n24\n25\n67\n123\n764\n\n", ">>> mylist='d.complex.1\\n24\\n25\\n67\\n123\\n764\\nd.complex.200\\n23\\n54\\n35\\n64\\nd.complex.302'.split(\"\\n\")\n>>> res=[]\n>>> for line in mylist:\n... if line.startswith(\"d.complex\"):\n... res.append([])\n... res[-1].append(line)\n... \n>>> res\n[['d.complex.1', '24', '25', '67', '123', '764'], ['d.complex.200', '23', '54', '35', '64'], ['d.complex.302']]\n\n" ]
[ 0, 0 ]
[]
[]
[ "list", "python", "split" ]
stackoverflow_0002363417_list_python_split.txt
Q: Embedding Python code as a preprocessor PHP style I'm going back over an old project where I added preprocessor functionality to Essence' and I realised that my previous solution of writing a domain specific language and associated lexer/parser was overkill. Instead I just need to be able to embed dynamic language code into the file, isolate it at runtime, eval and insert the results. In other words very similar to the PHP model of inserting dynamic code into HTML. I'd rather not use PHP as Python is much easier to distribute as part of a larger project (IronPython or Jython) So the question goes, how best to implement something like the following: <code>Python goes here</code> Lots of essence <code>Python</code> prime code goes here I don't want to have to alter the structure of the Essence' file (if I remove all the code blocks everything left should be able to be syntactically correct. It needs to be able to insert text in place of a code block like PHP. Finally security wise I'm not bothered about code injection, as it would be the user themselves choosing the file to execute although if there were security benefits to one model over another with no extra costs that would obviously be good. Cheers in advance A: Your best bet is to use one of the already made (and battle tested) Templating Engines. The two big ones that I've used are Mako, and Cheetah. They allow you to embed code right in the page, and are mostly used as the View in an MVC architecture. If you feel that using one of those engines is overkill for your project, here is a small tutorial on how to implement basic templates yourself. Keep in mind that the example will need to be modified to suit your particular project/needs.
Embedding Python code as a preprocessor PHP style
I'm going back over an old project where I added preprocessor functionality to Essence' and I realised that my previous solution of writing a domain specific language and associated lexer/parser was overkill. Instead I just need to be able to embed dynamic language code into the file, isolate it at runtime, eval and insert the results. In other words very similar to the PHP model of inserting dynamic code into HTML. I'd rather not use PHP as Python is much easier to distribute as part of a larger project (IronPython or Jython) So the question goes, how best to implement something like the following: <code>Python goes here</code> Lots of essence <code>Python</code> prime code goes here I don't want to have to alter the structure of the Essence' file (if I remove all the code blocks everything left should be able to be syntactically correct. It needs to be able to insert text in place of a code block like PHP. Finally security wise I'm not bothered about code injection, as it would be the user themselves choosing the file to execute although if there were security benefits to one model over another with no extra costs that would obviously be good. Cheers in advance
[ "Your best bet is to use one of the already made (and battle tested) Templating Engines. The two big ones that I've used are Mako, and Cheetah. They allow you to embed code right in the page, and are mostly used as the View in an MVC architecture.\nIf you feel that using one of those engines is overkill for your project, here is a small tutorial on how to implement basic templates yourself. Keep in mind that the example will need to be modified to suit your particular project/needs.\n" ]
[ 6 ]
[]
[]
[ "python" ]
stackoverflow_0002363609_python.txt
Q: Teaching Python to a Law Student Im trying to teach python to a Law student (happens to be my fiancee).She has been insisting on me teaching her about it. One problem: She doesn't know anything about programming. I was thinking on starting with dive into python, but i'm worried most not about the python part, but the "she does not know anything about programming" problem. How can I keep her interested? I'm worried because she will have to learn if/else - oop - functions and stuff as she learns the python syntax, and she might get bored. Maybe a project we can work together? Some simple django app? Any ideas will be appreciated. Related? :https://stackoverflow.com/questions/111857/what-did-you-use-to-teach-yourself-python A: Nothing is better for learning to program than a real project (by real I mean of use for somebody besides the author), internet connection and an expert friend. As long as she is willing to learn. Screencasts are a great way to learn new stuff fast and not-so-boring. Try http://showmedo.com for example A: Scott Hanselman recently podcasted about a book called "Hello World : Computer Programming for Kids and Other Beginners". It's written using Python and sounds like a good introduction to programming for beginners of all ages - I'm thinking about getting it for my nephew's birthday. Might be worth a look? A: Try this: http://homepage.mac.com/s_lott/books/nonprogrammer.html#book-nonprogrammer Non-programmers are my target market. A: The only way to learn is to automate some everyday tasks for her, for example fetching her online news or something, or something like a basic password manager. The possibilities are endless ! :P A: Tom, my experience has not been positive about it. My wife "wanted" to learn python but never went beyond a few chapters of "Dive into Python". I vaguely infer that she had a few doubts on the way, and never got interested in solving them. I have little doubt that an adult seldom does something new unless he/she needs to do it. I do not want to discourage you but I'd leave it up to her (my wife) to decide whether to learn programming or not -- I would not try to teach her if she does not ask for that. My wife is quite interested in photography instead. On the positive side, we might have new ways of learning programming invented only recently like Scratch, which probably have a better chance of conversions. A: A more "fun" approach to try is to give examples of everyday things that your wife will understand. Say if you are teaching her about if/else control flow, then give examples like "if time is 8am, wake up to go to work, else continue sleeping". In pseudocode, if time == 8am: do wake up else: do continue sleeping. Other examples, learning about functions. So you can tell her, that functions let her do things over and over. eg def go_toilet(): open door close door lift toilet seat do stuff flush wash hands exit door A: I have heard good things about the book Learn to Program from the Pragmatic Programmers. It uses Ruby instead of Python, and is geared toward teaching basic programming concepts to complete beginners. It seems to have examples and exercises geared toward stuff your average person can relate to.
Teaching Python to a Law Student
Im trying to teach python to a Law student (happens to be my fiancee).She has been insisting on me teaching her about it. One problem: She doesn't know anything about programming. I was thinking on starting with dive into python, but i'm worried most not about the python part, but the "she does not know anything about programming" problem. How can I keep her interested? I'm worried because she will have to learn if/else - oop - functions and stuff as she learns the python syntax, and she might get bored. Maybe a project we can work together? Some simple django app? Any ideas will be appreciated. Related? :https://stackoverflow.com/questions/111857/what-did-you-use-to-teach-yourself-python
[ "Nothing is better for learning to program than a real project (by real I mean of use for somebody besides the author), internet connection and an expert friend. As long as she is willing to learn.\nScreencasts are a great way to learn new stuff fast and not-so-boring. Try http://showmedo.com for example\n", "Scott Hanselman recently podcasted about a book called \"Hello World : Computer Programming for Kids and Other Beginners\".\nIt's written using Python and sounds like a good introduction to programming for beginners of all ages - I'm thinking about getting it for my nephew's birthday.\nMight be worth a look?\n", "Try this: http://homepage.mac.com/s_lott/books/nonprogrammer.html#book-nonprogrammer\nNon-programmers are my target market.\n", "The only way to learn is to automate some everyday tasks for her, for example fetching her online news or something, or something like a basic password manager. \nThe possibilities are endless ! :P\n", "Tom, my experience has not been positive about it. My wife \"wanted\" to learn python but never went beyond a few chapters of \"Dive into Python\". I vaguely infer that she had a few doubts on the way, and never got interested in solving them. I have little doubt that an adult seldom does something new unless he/she needs to do it. \nI do not want to discourage you but I'd leave it up to her (my wife) to decide whether to learn programming or not -- I would not try to teach her if she does not ask for that. My wife is quite interested in photography instead. \nOn the positive side, we might have new ways of learning programming invented only recently like Scratch, which probably have a better chance of conversions. \n", "A more \"fun\" approach to try is to give examples of everyday things that your wife will understand. Say if you are teaching her about if/else control flow, then give examples like \"if time is 8am, wake up to go to work, else continue sleeping\". In pseudocode, \nif time == 8am:\n do wake up\nelse:\n do continue sleeping.\n\nOther examples, learning about functions. So you can tell her, that functions let her do things over and over. eg\ndef go_toilet():\n open door\n close door\n lift toilet seat\n do stuff\n flush\n wash hands\n exit door\n\n", "I have heard good things about the book Learn to Program from the Pragmatic Programmers. It uses Ruby instead of Python, and is geared toward teaching basic programming concepts to complete beginners.\nIt seems to have examples and exercises geared toward stuff your average person can relate to.\n" ]
[ 5, 3, 3, 2, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002363116_python.txt
Q: Python PIL: color index to RGB following this link i was able to load and read pixels from a .gif. That question specifically askes for a RGB value, but the accepted (and most voted answer) that I used as reference gets me to get an int as value. What is it? I guess some sort of index, but how to convert it to a proper rgb value? Thanks [..] img = Image.open(GIF_FILENAME) pix = img.load() for i in range(5): print img.getpixel((i, 0)) # this returns me like 78, 65.. how to get RGB? [..] A: img = Image.open(GIF_FILENAME) rgbimg = img.convert('RGB') for i in range(5): print rgbimg.getpixel((i, 0))
Python PIL: color index to RGB
following this link i was able to load and read pixels from a .gif. That question specifically askes for a RGB value, but the accepted (and most voted answer) that I used as reference gets me to get an int as value. What is it? I guess some sort of index, but how to convert it to a proper rgb value? Thanks [..] img = Image.open(GIF_FILENAME) pix = img.load() for i in range(5): print img.getpixel((i, 0)) # this returns me like 78, 65.. how to get RGB? [..]
[ "img = Image.open(GIF_FILENAME)\nrgbimg = img.convert('RGB')\nfor i in range(5):\n print rgbimg.getpixel((i, 0))\n\n" ]
[ 7 ]
[]
[]
[ "image", "python" ]
stackoverflow_0002363583_image_python.txt
Q: Comparing two lists items in python I have two files which I loaded into lists. The content of the first file is something like this: d.complex.1 23 34 56 58 68 76 . . . etc d.complex.179 43 34 59 69 76 . . . etc The content of the second file is also the same but with different numerical values. Please consider from one d.complex.* to another d.complex.* as one set. Now I am interested in comparing each numerical value from one set of first file with each numerical value of the sets in the second file. I would like to record the number of times each numerical has appeared in the second file overall. For example, the number 23 from d.complex.1 could have appeared 5 times in file 2 under different sets. All I want to do is record the number of occurrences of number 23 in file 2 including all sets of file 2. My initial approach was to load them into a list and compare but I am not able to achieve this. I searched in google and came across sets but being a python noob, I need some guidance. Can anyone help me? If you feel the question is not clear,please let me know. I have also pasted the complete file 1 and file 2 here: http://pastebin.com/mwAWEcTa http://pastebin.com/DuXDDRYT A: Open the file using Python's open function, then iterate over all its lines. Check whether the line contains a number, if so, increase its count in a defaultdict instance as described here. Repeat this for the other file and compare the resulting dicts. A: First create a function which can load a given file, as you may want to maintain individual sets and also want to count occurrence of each number, best would be to have a dict for whole file where keys are set names e.g. complex.1 etc, for each such set keep another dict for numbers in set, below code explains it better def file_loader(f): file_dict = {} current_set = None for line in f: if line.startswith('d.complex'): file_dict[line] = current_set = {} continue if current_set is not None: current_set[line] = current_set.get(line, 0) return file_dict Now you can easily write a function which will count a number in given file_dict def count_number(file_dict, num): count = 0 for set_name, number_set in file_dict.iteritems(): count += number_set.get(num, 0) return count e.g here is a usage example s = """d.complex.1 10 11 12 10 11 12""" file_dict = file_loader(s.split("\n")) print file_dict print count_number(file_dict, '10') output is: {'d.complex.1': {'11': 2, '10': 2, '12': 2}} 2 You may have to improve file loader, e.g. skip empty lines, convert to int etc
Comparing two lists items in python
I have two files which I loaded into lists. The content of the first file is something like this: d.complex.1 23 34 56 58 68 76 . . . etc d.complex.179 43 34 59 69 76 . . . etc The content of the second file is also the same but with different numerical values. Please consider from one d.complex.* to another d.complex.* as one set. Now I am interested in comparing each numerical value from one set of first file with each numerical value of the sets in the second file. I would like to record the number of times each numerical has appeared in the second file overall. For example, the number 23 from d.complex.1 could have appeared 5 times in file 2 under different sets. All I want to do is record the number of occurrences of number 23 in file 2 including all sets of file 2. My initial approach was to load them into a list and compare but I am not able to achieve this. I searched in google and came across sets but being a python noob, I need some guidance. Can anyone help me? If you feel the question is not clear,please let me know. I have also pasted the complete file 1 and file 2 here: http://pastebin.com/mwAWEcTa http://pastebin.com/DuXDDRYT
[ "Open the file using Python's open function, then iterate over all its lines. Check whether the line contains a number, if so, increase its count in a defaultdict instance as described here.\nRepeat this for the other file and compare the resulting dicts.\n", "First create a function which can load a given file, as you may want to maintain individual sets and also want to count occurrence of each number, best would be to have a dict for whole file where keys are set names e.g. complex.1 etc, for each such set keep another dict for numbers in set, below code explains it better\ndef file_loader(f):\n file_dict = {}\n current_set = None\n for line in f:\n if line.startswith('d.complex'):\n file_dict[line] = current_set = {}\n continue\n\n if current_set is not None:\n current_set[line] = current_set.get(line, 0)\n\n return file_dict\n\nNow you can easily write a function which will count a number in given file_dict\ndef count_number(file_dict, num):\n count = 0\n for set_name, number_set in file_dict.iteritems():\n count += number_set.get(num, 0)\n\n return count\n\ne.g here is a usage example\ns = \"\"\"d.complex.1\n10\n11\n12\n10\n11\n12\"\"\"\n\nfile_dict = file_loader(s.split(\"\\n\"))\nprint file_dict\nprint count_number(file_dict, '10')\n\noutput is:\n{'d.complex.1': {'11': 2, '10': 2, '12': 2}}\n2\n\nYou may have to improve file loader, e.g. skip empty lines, convert to int etc\n" ]
[ 2, 1 ]
[]
[]
[ "compare", "file", "python" ]
stackoverflow_0002363954_compare_file_python.txt
Q: returning out of for-loop I'm pretty new at python and I was wondering if this: def func(self, foo): for foo in self.list: if foo.boolfunc(): return True return False is good practice. Can I return out of a loop like the above or should i use a while-loop, like so? def func(self, foo): found = false while(not found & i < len(self.list)): found = foo.boolfunc() ++i return found My java-professor warns us never to use breaks in our loops, but this technically isn't a break and it's more concise, so... yeah thanks A: There's nothing wrong with your example, but it's better to write def func(self, foo): return any(foo.boolfunc() for foo in self.list) A: It should be mentioned that in Python, for loops can have an else clause. The else clause is only executed when the loop terminates through exhaustion of the list. So you could write: def func(self): for foo in self.list: if foo.boolfunc(): return True else: return False A: Your professor is advocating a practice called "Single point of Return", which basically states that any block of code should only have one point of exit. Breaks in loops are somewhat distinct from this, but usually lumped together. It's a controversial opinion, to say the least, and certainly not as hard and fast a rule as "never use goto". It's probably worth doing it his way - you can appease him and also see the benefit of both approaches, but most people probably aren't too strict on single point of return if violating it makes their code more readable. A: "Early exit" is a perfectly Pythonic style (when warranted: gnibbler's answer correctly points out that for your specific use case there's a built-in [[in Python 2.5 and better]] that's preferable) and often helps realize the Pythonic goal of "flat is better than nested". And for is usually the right way to do looping in Python, at application-level: if there's any complicated loop logic (as might warrant a while), it's often better to push it down to an auxiliary generator anyway. Advantages sometimes claimed for the alternative "single point of exit" include the existence of a single "exit bottleneck" at which clean-up can be performed. But since exceptions are always possible, you don't know that your single return is a unique exit bottleneck, even if you have it: the proper way to ensure good cleanup is, instead, the with statement (in 2.6, or 2.5 with an "import from the future"; for older versions of Python, the clunkier but still useful try/finally instead). Knuth's article "Structured Programming With Goto Statements" (pdf) -- an incredible, visionary article from 1974 by the man that many consider a living legend of computer science, both theoretical and practical -- is well worth reading. Anybody who doubts the article's applicability to Python should consider the following short quote from it: devices like indentation, rather than delimiters, might become feasible for expressing local structure in the source language. twenty years before Python 1.0 was published, Knuth already foresaw the key syntax aspect that was to become such a hallmark of Python (and, independently, Haskell, released a bit earlier than Python -- from personal discussion with Knuth, Peyton Jones, and van Rossum, I can attest they all claim that these three inventions of "indentation for grouping" were entirely independent from each other, just a case of "great minds think alike" -- or, in Charles Fort's words, "it was just steam engine time";-). Formal proofs of code including early exit are of course not a jot harder than for equivalent code with single point of exit, if nothing else because the famous proof by Corrado Böhm and Giuseppe Jacopini shows how to perform a mechanical transformation from any flowchart to one containing only sequence, selection and repetition (but of course the transformed program -- just like any other program trying to avoid the early-exit style -- is prone to having more nesting than needed, and extra boolean "status" variable, which interfere with readability, directness, and efficiency -- making early-exit much superior in languages that support it well). A: It is good practice. My java-professor warns us never to use breaks in our loops Why is that? “never” is a strong word in computer science and should never (…) be used.1) 1) Except for “goto” … we all have our pet peeves. ;-)
returning out of for-loop
I'm pretty new at python and I was wondering if this: def func(self, foo): for foo in self.list: if foo.boolfunc(): return True return False is good practice. Can I return out of a loop like the above or should i use a while-loop, like so? def func(self, foo): found = false while(not found & i < len(self.list)): found = foo.boolfunc() ++i return found My java-professor warns us never to use breaks in our loops, but this technically isn't a break and it's more concise, so... yeah thanks
[ "There's nothing wrong with your example, but it's better to write\ndef func(self, foo):\n return any(foo.boolfunc() for foo in self.list)\n\n", "It should be mentioned that in Python, for loops can have an else clause. The else clause is only executed when the loop terminates through exhaustion of the list.\nSo you could write:\ndef func(self):\n for foo in self.list:\n if foo.boolfunc():\n return True\n else:\n return False\n\n", "Your professor is advocating a practice called \"Single point of Return\", which basically states that any block of code should only have one point of exit. Breaks in loops are somewhat distinct from this, but usually lumped together.\nIt's a controversial opinion, to say the least, and certainly not as hard and fast a rule as \"never use goto\". It's probably worth doing it his way - you can appease him and also see the benefit of both approaches, but most people probably aren't too strict on single point of return if violating it makes their code more readable.\n", "\"Early exit\" is a perfectly Pythonic style (when warranted: gnibbler's answer correctly points out that for your specific use case there's a built-in [[in Python 2.5 and better]] that's preferable) and often helps realize the Pythonic goal of \"flat is better than nested\". And for is usually the right way to do looping in Python, at application-level: if there's any complicated loop logic (as might warrant a while), it's often better to push it down to an auxiliary generator anyway.\nAdvantages sometimes claimed for the alternative \"single point of exit\" include the existence of a single \"exit bottleneck\" at which clean-up can be performed. But since exceptions are always possible, you don't know that your single return is a unique exit bottleneck, even if you have it: the proper way to ensure good cleanup is, instead, the with statement (in 2.6, or 2.5 with an \"import from the future\"; for older versions of Python, the clunkier but still useful try/finally instead).\nKnuth's article \"Structured Programming With Goto Statements\" (pdf) -- an incredible, visionary article from 1974 by the man that many consider a living legend of computer science, both theoretical and practical -- is well worth reading. Anybody who doubts the article's applicability to Python should consider the following short quote from it:\n\ndevices like indentation, rather than\n delimiters, might become feasible for\n expressing local structure in the\n source language.\n\ntwenty years before Python 1.0 was published, Knuth already foresaw the key syntax aspect that was to become such a hallmark of Python (and, independently, Haskell, released a bit earlier than Python -- from personal discussion with Knuth, Peyton Jones, and van Rossum, I can attest they all claim that these three inventions of \"indentation for grouping\" were entirely independent from each other, just a case of \"great minds think alike\" -- or, in Charles Fort's words, \"it was just steam engine time\";-).\nFormal proofs of code including early exit are of course not a jot harder than for equivalent code with single point of exit, if nothing else because the famous proof by Corrado Böhm and Giuseppe Jacopini shows how to perform a mechanical transformation from any flowchart to one containing only sequence, selection and repetition (but of course the transformed program -- just like any other program trying to avoid the early-exit style -- is prone to having more nesting than needed, and extra boolean \"status\" variable, which interfere with readability, directness, and efficiency -- making early-exit much superior in languages that support it well).\n", "It is good practice.\n\nMy java-professor warns us never to use breaks in our loops\n\nWhy is that? “never” is a strong word in computer science and should never (…) be used.1)\n\n1) Except for “goto” … we all have our pet peeves. ;-)\n" ]
[ 14, 9, 6, 5, 2 ]
[ "\"Breaking out of a loop\" can easily devolve to bad practice because it conceals the terminating condition of the loop.\nIf your if statement is of moderate complexity, then it can become unclear what post-condition the loop establishes.\nIf your exit condition is obvious, then an early exit is a common syntactic optimization. \nIf your exit condition is not obvious, then a convoluted, nested, hard-to-follow set of if statements is doing you more harm than good. \nIndeed, this SO question shows that the presence of a simple try block can lead to conditions so baffling that a clearly incorrect piece of code was produced and could not easily be debugged.\nGenerally, all \"early-exit\" things (the break statement, in particular) lead to problems creating a formal proof. (The else statement has similar problems.)\nIf you develop your program by reasoning out the statements required to create the necessary post-condition, you'll never need break or an early return because you can't easily create these statements using formal methods.\nAlso, note that any advice to avoid break or else will lead to hate mail and downvoting. For inexplicable reasons, looking closely at some programming constructs is a bad thing. \n\"else\" considered harmful in Python?\nIf the exit condition of a loop with a break (or early return) is not obvious, you need to rework things to make it obvious.\nIn this example, they're obvious, so there's no issue with the specific example as presented.\n" ]
[ -2 ]
[ "for_loop", "python", "while_loop" ]
stackoverflow_0002363602_for_loop_python_while_loop.txt
Q: print value of a column in django How to print the test field in the following query in django res=Resources.objects.filter(test=request.profile) logging.debug(test) # won't work I wanted to check what this value is compared with.. A: You have to iterate through res and print each model's value of test in turn. A: You may also try the values_list method, eg: Resource.objects.filter(test=request.profile).values_list("test") It returns a list of tuples with the value of "test" for each matched record.
print value of a column in django
How to print the test field in the following query in django res=Resources.objects.filter(test=request.profile) logging.debug(test) # won't work I wanted to check what this value is compared with..
[ "You have to iterate through res and print each model's value of test in turn.\n", "You may also try the values_list method, eg:\nResource.objects.filter(test=request.profile).values_list(\"test\")\n\nIt returns a list of tuples with the value of \"test\" for each matched record.\n" ]
[ 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002362729_django_python.txt
Q: Python: slicing a very large binary file Say I have a binary file of 12GB and I want to slice 8GB out of the middle of it. I know the position indices I want to cut between. How do I do this? Obviously 12GB won't fit into memory, that's fine, but 8GB won't either... Which I thought was fine, but it appears binary doesn't seem to like it if you do it in chunks! I was appending 10MB at a time to a new binary file and there are discontinuities on the edges of each 10MB chunk in the new file. Is there a Pythonic way of doing this easily? A: Here's a quick example. Adapt as needed: def copypart(src,dest,start,length,bufsize=1024*1024): with open(src,'rb') as f1: f1.seek(start) with open(dest,'wb') as f2: while length: chunk = min(bufsize,length) data = f1.read(chunk) f2.write(data) length -= chunk if __name__ == '__main__': GIG = 2**30 copypart('test.bin','test2.bin',1*GIG,8*GIG)
Python: slicing a very large binary file
Say I have a binary file of 12GB and I want to slice 8GB out of the middle of it. I know the position indices I want to cut between. How do I do this? Obviously 12GB won't fit into memory, that's fine, but 8GB won't either... Which I thought was fine, but it appears binary doesn't seem to like it if you do it in chunks! I was appending 10MB at a time to a new binary file and there are discontinuities on the edges of each 10MB chunk in the new file. Is there a Pythonic way of doing this easily?
[ "Here's a quick example. Adapt as needed:\ndef copypart(src,dest,start,length,bufsize=1024*1024):\n with open(src,'rb') as f1:\n f1.seek(start)\n with open(dest,'wb') as f2:\n while length:\n chunk = min(bufsize,length)\n data = f1.read(chunk)\n f2.write(data)\n length -= chunk\n\nif __name__ == '__main__':\n GIG = 2**30\n copypart('test.bin','test2.bin',1*GIG,8*GIG)\n\n" ]
[ 8 ]
[]
[]
[ "binary", "large_files", "python" ]
stackoverflow_0002363483_binary_large_files_python.txt
Q: Google App Engine: Trouble with Datastore Query This query works: item = db.GqlQuery("SELECT * FROM Item WHERE CSIN = 13")[0] although if there are no results returned, it blows up in my face. (How can I get around this? A for loop seems dubious when I want at max one iteration.) This query does not work: item = db.GqlQuery("SELECT * FROM Item WHERE CSIN = :1", CSIN)[0] CSIN is a string representing a number. I get this error: Traceback (most recent call last): File "C:\Program Files\Google\google_appengine\google\appengine\ext\webapp\__init__.py", line 507, in __call__ handler.get(*groups) File "path\to\src\Main.py", line 42, in get item = db.GqlQuery("SELECT * FROM Item WHERE CSIN = :1", CSIN)[0] File "C:\Program Files\Google\google_appengine\google\appengine\ext\db\__init__.py", line 1717, in __getitem__ raise IndexError('The query returned fewer than %d results' % (arg+1)) IndexError: The query returned fewer than 1 results What am I doing wrong here? A: You're trying to get an item from a list (or a list-like object) that is empty. What you're doing is sort of comparable to the following: >>> results = [] # an empty list >>> item = results[0] # Raises an IndexError, because there is nothing in the list What you need to do instead is: item = db.GqlQuery("SELECT * FROM Item WHERE CSIN = :1", CSIN).get() Then, item will be either None or the first result from the query. A: It seems that that your query returns an array or list of some sort, which is empty. Trying to access its non-existing first item raises an exception. Try to figure out the length of the returned result before accessing it.
Google App Engine: Trouble with Datastore Query
This query works: item = db.GqlQuery("SELECT * FROM Item WHERE CSIN = 13")[0] although if there are no results returned, it blows up in my face. (How can I get around this? A for loop seems dubious when I want at max one iteration.) This query does not work: item = db.GqlQuery("SELECT * FROM Item WHERE CSIN = :1", CSIN)[0] CSIN is a string representing a number. I get this error: Traceback (most recent call last): File "C:\Program Files\Google\google_appengine\google\appengine\ext\webapp\__init__.py", line 507, in __call__ handler.get(*groups) File "path\to\src\Main.py", line 42, in get item = db.GqlQuery("SELECT * FROM Item WHERE CSIN = :1", CSIN)[0] File "C:\Program Files\Google\google_appengine\google\appengine\ext\db\__init__.py", line 1717, in __getitem__ raise IndexError('The query returned fewer than %d results' % (arg+1)) IndexError: The query returned fewer than 1 results What am I doing wrong here?
[ "You're trying to get an item from a list (or a list-like object) that is empty. What you're doing is sort of comparable to the following:\n>>> results = [] # an empty list\n>>> item = results[0] # Raises an IndexError, because there is nothing in the list\n\nWhat you need to do instead is:\nitem = db.GqlQuery(\"SELECT * FROM Item WHERE CSIN = :1\", CSIN).get()\n\nThen, item will be either None or the first result from the query.\n", "It seems that that your query returns an array or list of some sort, which is empty. Trying to access its non-existing first item raises an exception.\nTry to figure out the length of the returned result before accessing it.\n" ]
[ 9, 0 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0002364531_google_app_engine_google_cloud_datastore_python.txt
Q: Designing to easily migrate to Google App Engine I am going to start designing a web app shortly, and while I have lots of experience doing it in the SQL world, I have no idea what I need to take into consideration for doing so with the goal of migrating to GAE in the very near future. Alternatively, I could design the app for GAE from the start, and so in that case, what are the differences I need to take into consideration? In other words, what are the DOs and DONTs of writing your app for GAE, coming from a relational databases past. A: Just out of top of my head: It's really ONLY a key->value store, don't be fooled by things like GQL (which is just a subset of SQL SELECT) No JOINs - often you have to denormalize or forget More or less frequent timeouts (Very) slow access comparing to local SQL base. COUNT very expensive OFFSET (in SELECT) implemented on client side - so in fact you fetch all records up to offset - as pointed by Nick Johnson in one of the comments, it's not client side, so now, as LIMIT of 1000 is gone it's similar to SQL databases. (Recently removed) LIMIT of 1000 fetched rows SELECT performance decreases drastically with increasing number of returned rows Migrations are hard to do because you have to do them using normal http requests and each request is killed after 30 secs. You have to resort to task queues that process rows in batches There are pseudo foreign keys - called ReferenceProperties in Python API - but they are not enforced in any way - if someone/something delete target object then you have what is know as dangling pointer in C++ Fields that you use for queries have to be indexed, but still using key (sort of primary key for each row/instance) makes your queries run faster Building indexes on live instance can take a lot of time (and you can't decrease it) and without them your app often can't work. Beer and patience highly recommended.. A LOT of artificial limits (like the already removed max LIMIT of 1000). E.g. GQL 'IN' operator is just syntactic sugar for multiple OR-s, and there is upper limit of 30 values used. All that means that you probably can't avoid exposing inconsistent state to user, and almost for sure you cannot avoid having inconsistent state of your data (e.g. half rows migrated and half not, during manual JOIN data changes etc)
Designing to easily migrate to Google App Engine
I am going to start designing a web app shortly, and while I have lots of experience doing it in the SQL world, I have no idea what I need to take into consideration for doing so with the goal of migrating to GAE in the very near future. Alternatively, I could design the app for GAE from the start, and so in that case, what are the differences I need to take into consideration? In other words, what are the DOs and DONTs of writing your app for GAE, coming from a relational databases past.
[ "Just out of top of my head:\n\nIt's really ONLY a key->value store, don't be fooled by things like GQL (which is just a subset of SQL SELECT)\nNo JOINs - often you have to denormalize or forget\nMore or less frequent timeouts\n(Very) slow access comparing to local SQL base.\nCOUNT very expensive\nOFFSET (in SELECT) implemented on client side - so in fact you fetch all records up to offset - as pointed by Nick Johnson in one of the comments, it's not client side, so now, as LIMIT of 1000 is gone it's similar to SQL databases.\n(Recently removed) LIMIT of 1000 fetched rows\nSELECT performance decreases drastically with increasing number of returned rows\nMigrations are hard to do because you have to do them using normal http requests and each request is killed after 30 secs. You have to resort to task queues that process rows in batches\nThere are pseudo foreign keys - called ReferenceProperties in Python API - but they are not enforced in any way - if someone/something delete target object then you have what is know as dangling pointer in C++\nFields that you use for queries have to be indexed, but still using key (sort of primary key for each row/instance) makes your queries run faster\nBuilding indexes on live instance can take a lot of time (and you can't decrease it) and without them your app often can't work. Beer and patience highly recommended..\nA LOT of artificial limits (like the already removed max LIMIT of 1000). E.g. GQL 'IN' operator is just syntactic sugar for multiple OR-s, and there is upper limit of 30 values used. \n\nAll that means that you probably can't avoid exposing inconsistent state to user, and almost for sure you cannot avoid having inconsistent state of your data (e.g. half rows migrated and half not, during manual JOIN data changes etc)\n" ]
[ 7 ]
[]
[]
[ "google_app_engine", "non_relational_database", "python", "relational_database", "web2py" ]
stackoverflow_0002365647_google_app_engine_non_relational_database_python_relational_database_web2py.txt
Q: Python (Jython) Playing notes from pixels in picture This is from a class assignment: This program is about listening to colors. We will treat pictures as piano scores. Write a function called listenToPicture that takes one picture as an argument. It first shows the picture. Next, it will loop through every 4th pixel in every 4th row and do the following. It will compute the total of the red, green and blue levels of the pixel, divide that by 9, then add the result to 24. That number will be the note number played by playNote. That means that the darker the pixel, the lower the note; the lighter the pixel, the higher the note. It will play that note at full volume (127) for a tenth of a second (100 milliseconds). Every time it moves to a new row, it prints out the row number (y value) on the console. Your main function will ask the user to select a file with a picture. It will print the number of notes to be played (which is the number of pixels in the picture divided by 16; why?). It will then call the listenToPicture function. Ok I edited in what I have so far and the only thing I haven't figured out (I believe) is how to print the number of notes in the main function. By the way, thanks to everyone who helped. You guys are amazing. Is there a place to donate to this site? def main(): pic=makePicture(pickAFile()) show (pic) listenToPicture(pic) def listenToPicture(pic): w=getWidth(pic) h=getHeight(pic) for y in range(0,h,4): printNow(str(y)) for x in range (0,w,4): px=getPixel(pic,x,y) r=getRed(px) g=getGreen(px) b=getBlue(px) tot=((r+g+b)/9)+24 playNote(tot,100,127) A: Robbie is right for the width/height for loops. The loop you are using to get the pixels and play the notes looks as if it is getting ALL the pixels and playing them all every time you get a unique x and y. What you should be doing is be getting the pixel at (x,y) then pulling out the rgb values and calling play note on that. You really shouldn't even need the 3rd for loop. You're not too far off. Try writing the problem out in logical steps in plain English. I find that helps a ton before I start coding. Good Luck. A: You asked about similar things before. Well, since you didn't put any code in about actually retrieving the pixel value, I'll assume that you still aren't able to do that. I know this is going way beyond your question, but last time you were pretty vague about your question and indicated that you needed more help than just what you had asked. If any of this is not necessary then just ignore it. I'm just trying to offer some advice and you can take it or leave it. In case you haven't figured out how to read a pixel, I recommend using PIL. It has functions for opening images documented here. Then you can access a pixel in the image by its x and y value using getpixel which is documented on the same page. For playing the note I would recommend looking into the PyAudio module and just making your own sinusoids of various frequencies (depending on the magnitude of the pixel) that you write to an open audio stream. There might be better packages for this part, but this is what I have used in my small adventures in Python audio. For the audio stuff, I would try just outputting a sound at a fixed frequency before trying to actually emit a varying frequency. Edit: Your loops look better now so I took out my stuff about your loops.
Python (Jython) Playing notes from pixels in picture
This is from a class assignment: This program is about listening to colors. We will treat pictures as piano scores. Write a function called listenToPicture that takes one picture as an argument. It first shows the picture. Next, it will loop through every 4th pixel in every 4th row and do the following. It will compute the total of the red, green and blue levels of the pixel, divide that by 9, then add the result to 24. That number will be the note number played by playNote. That means that the darker the pixel, the lower the note; the lighter the pixel, the higher the note. It will play that note at full volume (127) for a tenth of a second (100 milliseconds). Every time it moves to a new row, it prints out the row number (y value) on the console. Your main function will ask the user to select a file with a picture. It will print the number of notes to be played (which is the number of pixels in the picture divided by 16; why?). It will then call the listenToPicture function. Ok I edited in what I have so far and the only thing I haven't figured out (I believe) is how to print the number of notes in the main function. By the way, thanks to everyone who helped. You guys are amazing. Is there a place to donate to this site? def main(): pic=makePicture(pickAFile()) show (pic) listenToPicture(pic) def listenToPicture(pic): w=getWidth(pic) h=getHeight(pic) for y in range(0,h,4): printNow(str(y)) for x in range (0,w,4): px=getPixel(pic,x,y) r=getRed(px) g=getGreen(px) b=getBlue(px) tot=((r+g+b)/9)+24 playNote(tot,100,127)
[ "Robbie is right for the width/height for loops.\nThe loop you are using to get the pixels and play the notes looks as if it is getting ALL the pixels and playing them all every time you get a unique x and y. What you should be doing is be getting the pixel at (x,y) then pulling out the rgb values and calling play note on that. You really shouldn't even need the 3rd for loop. You're not too far off. Try writing the problem out in logical steps in plain English. I find that helps a ton before I start coding.\nGood Luck.\n", "You asked about similar things before. Well, since you didn't put any code in about actually retrieving the pixel value, I'll assume that you still aren't able to do that. I know this is going way beyond your question, but last time you were pretty vague about your question and indicated that you needed more help than just what you had asked. If any of this is not necessary then just ignore it. I'm just trying to offer some advice and you can take it or leave it.\nIn case you haven't figured out how to read a pixel, I recommend using PIL. It has functions for opening images documented here. Then you can access a pixel in the image by its x and y value using getpixel which is documented on the same page. \nFor playing the note I would recommend looking into the PyAudio module and just making your own sinusoids of various frequencies (depending on the magnitude of the pixel) that you write to an open audio stream. There might be better packages for this part, but this is what I have used in my small adventures in Python audio.\nFor the audio stuff, I would try just outputting a sound at a fixed frequency before trying to actually emit a varying frequency.\nEdit:\nYour loops look better now so I took out my stuff about your loops.\n" ]
[ 1, 1 ]
[]
[]
[ "image_manipulation", "jython", "python" ]
stackoverflow_0002364966_image_manipulation_jython_python.txt
Q: haskell vs python typing I am looking for example where things in python would be easier to program just because it is dynamically typed? I want to compare it with Haskell type system because its static typing doesn't get in the way like c# or java. Can I program in Haskell as I can in python without static typing being a hindrance? PS: I am a python user and have played around little bit with ML and Haskell.. ... I hope it is clear now.. A: Can I program in Haskell as I can in python without static typing being a hindrance Yes. To elaborate, I would say the main gotcha will be the use of existential types in Haskell for heterogeneous data structures (regular data structures holding lists of variously typed elements). This often catches OO people used to a top "Object" type. It often catches Lisp/Scheme programmers. But I'm not sure it will matter to a Pythonista. Try to write some Haskell, and come back when you get a confusing type error. You should think of static typing as a benefit -- it checks a lot of things for you, and the more you lean on it, the less things you have to test for. In addition, it enables the compiler to make your code much faster. A: Well for one you can't create a list containing multiple types of values without wrappers (like to get a list that may contain a string or an int, you'd have to create a list of Either Int String and wrap each item in a Left or a Right). You also can't define a function that may return multiple types of values (like if someCondition then 1 else "this won't compile"), again, without using wrappers. A: Like Chris said, this is one objective question (what can a dynamically typed language do that a statically typed one can't?) and one subjective question (can I use Haskell without static typing being a hindrance). So you're going to get mostly subjective answers, because the first question is not as interesting. For me, the biggest hindrance was Haskell's IO type, because I had to stop and think about what code does I/O and what code doesn't, and explicitly pass information between the two. Everything else was pretty easy. If you commonly write if someCondition: return 1 else: return "other" Then you're making your own problems, Python just doesn't stop you from doing it. Haskell will, and that's about the only difference. The only exception is that this is sort of common in Python: if someErrorCondition: return None else: return NewItem(Success) You can't do that in Haskell because there is no common None object. But there are easy ways to work around it. I did find the type errors confusing at first, but I learned to read them in about a week. I want to echo Don's advice: just try writing some Haskell and come back when you get a confusing type error.
haskell vs python typing
I am looking for example where things in python would be easier to program just because it is dynamically typed? I want to compare it with Haskell type system because its static typing doesn't get in the way like c# or java. Can I program in Haskell as I can in python without static typing being a hindrance? PS: I am a python user and have played around little bit with ML and Haskell.. ... I hope it is clear now..
[ "\nCan I program in Haskell as I can in python without static typing being a hindrance\n\nYes. \nTo elaborate, I would say the main gotcha will be the use of existential types in Haskell for heterogeneous data structures (regular data structures holding lists of variously typed elements). This often catches OO people used to a top \"Object\" type. It often catches Lisp/Scheme programmers. But I'm not sure it will matter to a Pythonista.\nTry to write some Haskell, and come back when you get a confusing type error.\nYou should think of static typing as a benefit -- it checks a lot of things for you, and the more you lean on it, the less things you have to test for. In addition, it enables the compiler to make your code much faster.\n", "Well for one you can't create a list containing multiple types of values without wrappers (like to get a list that may contain a string or an int, you'd have to create a list of Either Int String and wrap each item in a Left or a Right).\nYou also can't define a function that may return multiple types of values (like if someCondition then 1 else \"this won't compile\"), again, without using wrappers.\n", "Like Chris said, this is one objective question (what can a dynamically typed language do that a statically typed one can't?) and one subjective question (can I use Haskell without static typing being a hindrance). So you're going to get mostly subjective answers, because the first question is not as interesting.\nFor me, the biggest hindrance was Haskell's IO type, because I had to stop and think about what code does I/O and what code doesn't, and explicitly pass information between the two. Everything else was pretty easy. If you commonly write\nif someCondition:\n return 1\nelse:\n return \"other\"\n\nThen you're making your own problems, Python just doesn't stop you from doing it. Haskell will, and that's about the only difference. The only exception is that this is sort of common in Python:\nif someErrorCondition:\n return None\nelse:\n return NewItem(Success)\n\nYou can't do that in Haskell because there is no common None object. But there are easy ways to work around it.\nI did find the type errors confusing at first, but I learned to read them in about a week.\nI want to echo Don's advice: just try writing some Haskell and come back when you get a confusing type error.\n" ]
[ 7, 5, 4 ]
[]
[]
[ "dynamic", "haskell", "python", "static", "types" ]
stackoverflow_0002365783_dynamic_haskell_python_static_types.txt
Q: Python interface for outputting MIDI files or text that's readable by audio programs I am looking for a python package or library that will allow me to programmatically output a file format (e.g. MIDI) that can be read by audio/sound processing programs, like LogicPro or iDrum. What are the best options for this? A: A large number of possibilities are listed here, especially under the "Midi Mania" header. For your requirements, and the various packages' descriptions, it seems to me that pythonmidi might suit you best, but I have no first-hand experience with it.
Python interface for outputting MIDI files or text that's readable by audio programs
I am looking for a python package or library that will allow me to programmatically output a file format (e.g. MIDI) that can be read by audio/sound processing programs, like LogicPro or iDrum. What are the best options for this?
[ "A large number of possibilities are listed here, especially under the \"Midi Mania\" header. For your requirements, and the various packages' descriptions, it seems to me that pythonmidi might suit you best, but I have no first-hand experience with it.\n" ]
[ 1 ]
[]
[]
[ "audio", "midi", "python" ]
stackoverflow_0002365884_audio_midi_python.txt
Q: How to read and extract data from a binary data file with multiple variable-length records? Using Python (3.1 or 2.6), I'm trying to read data from binary data files produced by a GPS receiver. Data for each hour is stored in a separate file, each of which is about 18 MiB. The data files have multiple variable-length records, but for now I need to extract data from just one of the records. I've got as far as being able to decode, somewhat, the header. I say somewhat because some of the numbers don't make sense, but most do. After spending a few days on this (I've started learning to program using Python), I'm not making progress, so it's time to ask for help. The reference guide gives me the message header structure and the record structure. Headers can be variable length but are usually 28 bytes. Header Field # Field Name Field Type Desc Bytes Offset 1 Sync char Hex 0xAA 1 0 2 Sync char Hex 0x44 1 1 3 Sync char Hex 0x12 1 2 4 Header Lgth uchar Length of header 1 3 5 Message ID ushort Message ID of log 2 4 8 Message Lgth ushort length of message 2 8 11 Time Status enum Quality of GPS time 1 13 12 Week ushort GPS week number 2 14 13 Milliseconds GPSec Time in ms 4 16 Record Field # Data Bytes Format Units Offset 1 Header 0 2 Number of SV Observations 4 integer n/a H *For first SV Observation* 3 PRN 4 integer n/a H+4 4 SV Azimuth angle 4 float degrees H+8 5 SV Elevation angle 4 float degrees H+12 6 C/N0 8 double db-Hz H+16 7 Total S4 8 double n/a H+24 ... 27 L2 C/N0 8 double db-Hz H+148 28 *For next SV Observation* SV Observation is satellite - there could be anywhere from 8 to 13 in view. Here's my code for trying to make sense of the header: import struct filename = "100301_110000.nvd" f = open(filename, "rb") s = f.read(28) x, y, z, lgth, msg_id, mtype, port, mlgth, seq, idletime, timestatus, week, millis, recstatus, reserved, version = struct.unpack("<cccBHcBHHBcHLLHH", s) print(x, y, z, lgth, msg_id, mtype, port, mlgth, seq, idletime, timestatus, week, millis, recstatus, reserved, version) It outputs: b'\xaa' b'D' b'\x12' 28 274 b'\x02' 32 1524 0 78 b'\xa0' 1573 126060000 10485760 3545 35358 The 3 sync fields should return xAA x44 x12. (D is the ascii equiv of x44 - I assume.) The record ID for which I'm looking is 274 - that seems correct. GPS week is returned as 1573 - that seems correct. Milliseconds is returned as 126060000 - I was expecting 126015000. How do I go about finding the records identified as 274 and extracting them? (I'm learning Python, and programming, so keep in mind the answer you give an experienced coder might be over my head.) A: You have to read in pieces. Not because of memory constraints, but because of the parsing requirements. 18MiB fits in memory easily. On a 4Gb machine it fits in memory 200 times over. Here's the usual design pattern. Read the first 4 bytes only. Use struct to unpack just those bytes. Confirm the sync bytes and get the header length. If you want the rest of the header, you know the length, read the rest of the bytes. If you don't want the header, use seek to skip past it. Read the first four bytes of a record to get the number of SV Observations. Use struct to unpack it. Do the math and read the indicated number of bytes to get all the SV Observations in the record. Unpack them and do whatever it is you're doing. I strongly suggest building namedtuple objects from the data before doing anything else with it. If you want all the data, you have to actually read all the data. "and without reading an 18 MiB file one byte at a time)?" I don't understand this constraint. You have to read all the bytes to get all the bytes. You can use the length information to read the bytes in meaningful chunks. But you can't avoid reading all the bytes. Also, lots of reads (and seeks) are often fast enough. Your OS buffers for you, so don't worry about trying to micro-optimize the number of reads. Just follow the "read length -- read data" pattern. A: 18 MB should fit comfortably in memory, so I'd just gulp the whole thing into one big string of bytes with a single with open(thefile, 'rb') as f: data = f.read() and then perform all the "parsing" on slices to advance record by record. It's more convenient, and may well be faster than doing many small reads from here and there in the file (though it doesn't affect the logic below, because in either case the "current point of interest in the data" is always moving [[always forward, as it happens]] by amounts computed based on the struct-unpacking of a few bytes at a time, to find the lengths of headers and records). Given the "start of a record" offset, you can determine its header's length by looking at just one byte ("field four", offset 3 from start of header that's the same as start of record) and look at message ID (next field, 2 bytes) to see if it's the record you care about (so a struct unpack of just those 3 bytes should suffice for that). Whether it's the record you want or not, you next need to compute the record's length (either to skip it or to get it all); for that, you compute the start of the actual record data (start of record plus length of header plus the next field of the record (the 4 bytes right after the header) times the length of an observation (32 bytes if I read you correctly). This way you either isolate the substring to be given to struct.unpack (when you've finally reached the record you want), or just add the total length of header + record to the "start of record" offset, to get the offset for the start of the next record. A: Apart from writing a parser that correctly reads the file, you may try a somewhat brute-force approach...read the data to the memory and split it using the 'Sync' sentinel. Warning - you might get some false positives. But... f = open('filename') data = f.read() messages = data.split('\xaa\x44\x12') mymessages = [ msg for msg in messages if len(msg) > 5 and msg[4:5] == '\x12\x01' ] But it is rather a very nasty hack...
How to read and extract data from a binary data file with multiple variable-length records?
Using Python (3.1 or 2.6), I'm trying to read data from binary data files produced by a GPS receiver. Data for each hour is stored in a separate file, each of which is about 18 MiB. The data files have multiple variable-length records, but for now I need to extract data from just one of the records. I've got as far as being able to decode, somewhat, the header. I say somewhat because some of the numbers don't make sense, but most do. After spending a few days on this (I've started learning to program using Python), I'm not making progress, so it's time to ask for help. The reference guide gives me the message header structure and the record structure. Headers can be variable length but are usually 28 bytes. Header Field # Field Name Field Type Desc Bytes Offset 1 Sync char Hex 0xAA 1 0 2 Sync char Hex 0x44 1 1 3 Sync char Hex 0x12 1 2 4 Header Lgth uchar Length of header 1 3 5 Message ID ushort Message ID of log 2 4 8 Message Lgth ushort length of message 2 8 11 Time Status enum Quality of GPS time 1 13 12 Week ushort GPS week number 2 14 13 Milliseconds GPSec Time in ms 4 16 Record Field # Data Bytes Format Units Offset 1 Header 0 2 Number of SV Observations 4 integer n/a H *For first SV Observation* 3 PRN 4 integer n/a H+4 4 SV Azimuth angle 4 float degrees H+8 5 SV Elevation angle 4 float degrees H+12 6 C/N0 8 double db-Hz H+16 7 Total S4 8 double n/a H+24 ... 27 L2 C/N0 8 double db-Hz H+148 28 *For next SV Observation* SV Observation is satellite - there could be anywhere from 8 to 13 in view. Here's my code for trying to make sense of the header: import struct filename = "100301_110000.nvd" f = open(filename, "rb") s = f.read(28) x, y, z, lgth, msg_id, mtype, port, mlgth, seq, idletime, timestatus, week, millis, recstatus, reserved, version = struct.unpack("<cccBHcBHHBcHLLHH", s) print(x, y, z, lgth, msg_id, mtype, port, mlgth, seq, idletime, timestatus, week, millis, recstatus, reserved, version) It outputs: b'\xaa' b'D' b'\x12' 28 274 b'\x02' 32 1524 0 78 b'\xa0' 1573 126060000 10485760 3545 35358 The 3 sync fields should return xAA x44 x12. (D is the ascii equiv of x44 - I assume.) The record ID for which I'm looking is 274 - that seems correct. GPS week is returned as 1573 - that seems correct. Milliseconds is returned as 126060000 - I was expecting 126015000. How do I go about finding the records identified as 274 and extracting them? (I'm learning Python, and programming, so keep in mind the answer you give an experienced coder might be over my head.)
[ "You have to read in pieces. Not because of memory constraints, but because of the parsing requirements. 18MiB fits in memory easily. On a 4Gb machine it fits in memory 200 times over.\nHere's the usual design pattern.\n\nRead the first 4 bytes only. Use struct to unpack just those bytes.\nConfirm the sync bytes and get the header length.\nIf you want the rest of the header, you know the length, read the rest of the bytes.\nIf you don't want the header, use seek to skip past it.\nRead the first four bytes of a record to get the number of SV Observations. Use struct to unpack it.\nDo the math and read the indicated number of bytes to get all the SV Observations in the record.\nUnpack them and do whatever it is you're doing. \nI strongly suggest building namedtuple objects from the data before doing anything else with it.\n\nIf you want all the data, you have to actually read all the data.\n\"and without reading an 18 MiB file one byte at a time)?\" I don't understand this constraint. You have to read all the bytes to get all the bytes.\nYou can use the length information to read the bytes in meaningful chunks. But you can't avoid reading all the bytes.\nAlso, lots of reads (and seeks) are often fast enough. Your OS buffers for you, so don't worry about trying to micro-optimize the number of reads.\nJust follow the \"read length -- read data\" pattern.\n", "18 MB should fit comfortably in memory, so I'd just gulp the whole thing into one big string of bytes with a single with open(thefile, 'rb') as f: data = f.read() and then perform all the \"parsing\" on slices to advance record by record. It's more convenient, and may well be faster than doing many small reads from here and there in the file (though it doesn't affect the logic below, because in either case the \"current point of interest in the data\" is always moving [[always forward, as it happens]] by amounts computed based on the struct-unpacking of a few bytes at a time, to find the lengths of headers and records).\nGiven the \"start of a record\" offset, you can determine its header's length by looking at just one byte (\"field four\", offset 3 from start of header that's the same as start of record) and look at message ID (next field, 2 bytes) to see if it's the record you care about (so a struct unpack of just those 3 bytes should suffice for that).\nWhether it's the record you want or not, you next need to compute the record's length (either to skip it or to get it all); for that, you compute the start of the actual record data (start of record plus length of header plus the next field of the record (the 4 bytes right after the header) times the length of an observation (32 bytes if I read you correctly).\nThis way you either isolate the substring to be given to struct.unpack (when you've finally reached the record you want), or just add the total length of header + record to the \"start of record\" offset, to get the offset for the start of the next record.\n", "Apart from writing a parser that correctly reads the file, you may try a somewhat brute-force approach...read the data to the memory and split it using the 'Sync' sentinel. Warning - you might get some false positives. But...\nf = open('filename')\ndata = f.read()\nmessages = data.split('\\xaa\\x44\\x12')\nmymessages = [ msg for msg in messages if len(msg) > 5 and msg[4:5] == '\\x12\\x01' ]\n\nBut it is rather a very nasty hack...\n" ]
[ 6, 2, 2 ]
[]
[]
[ "binary_data", "gps", "python" ]
stackoverflow_0002365998_binary_data_gps_python.txt
Q: Django + GAE (Google App Engine) : most convenient path for a beginner? Some background info first: Goal: a medium-level complexity web app that I will need to maintain and possibly extend for a few years. Experience: good knowledge of python, some experience of MVC frameworks (in PHP). Desiderata: using django and google app engine. I read extensively about the compatibility issues between GAE and Django, and I am aware of the GAE patch, the norel project, and other similar pieces of code. I have also understood that the SDK provides some of the features of django "out of the box". Yet, given that I have no previous experience with neither Django nor GAE, I am unable to evaluate to which extent using a patched version of Django will strip away important features, or how far the framework provided in the SDK is compatible with Django. So I am rather confused on what would be the best way to proceed in my situation: Should I simply use a patched version of Django as the differences with the original Django are so minor that I would hardly notice them? Should I write my app completely in "regular django" and try to port it to GAE only afterwards, when I will have got a grasp on Django internals and philosophy? Should I write my app using the framework provided with the SDK and port it to django only afterwards? Should I... ? Thank you in advance for your time and advice. A: I'm not sure if Django is a good fit for you. Django is a great framework for standalone applications because it provides a full stack solution: an ORM, authentication system and an admin interface, to name a few. You won't be able to use any of these on App Engine. Furthermore, many of the code samples are geared towards using the built in Webapp framework - you can very easily set cache expiration and authentication settings in app.yaml for configuration. I see one of two paths for you: Learn App Engine with Webapp. There's enough to learn about using the datastore and App Engine's services that'll keep you busy. Learn Django off App Engine. You'll learn a lot about using Django's ORM, Admin goodies, URL routing, Forms and templates By trying to learn both at the same time, you'll spend more time than you need learning the nuances of Django/GAE compatibility, time you could be spending either learning Django or GAE.
Django + GAE (Google App Engine) : most convenient path for a beginner?
Some background info first: Goal: a medium-level complexity web app that I will need to maintain and possibly extend for a few years. Experience: good knowledge of python, some experience of MVC frameworks (in PHP). Desiderata: using django and google app engine. I read extensively about the compatibility issues between GAE and Django, and I am aware of the GAE patch, the norel project, and other similar pieces of code. I have also understood that the SDK provides some of the features of django "out of the box". Yet, given that I have no previous experience with neither Django nor GAE, I am unable to evaluate to which extent using a patched version of Django will strip away important features, or how far the framework provided in the SDK is compatible with Django. So I am rather confused on what would be the best way to proceed in my situation: Should I simply use a patched version of Django as the differences with the original Django are so minor that I would hardly notice them? Should I write my app completely in "regular django" and try to port it to GAE only afterwards, when I will have got a grasp on Django internals and philosophy? Should I write my app using the framework provided with the SDK and port it to django only afterwards? Should I... ? Thank you in advance for your time and advice.
[ "I'm not sure if Django is a good fit for you. Django is a great framework for standalone applications because it provides a full stack solution: an ORM, authentication system and an admin interface, to name a few. You won't be able to use any of these on App Engine. Furthermore, many of the code samples are geared towards using the built in Webapp framework - you can very easily set cache expiration and authentication settings in app.yaml for configuration.\nI see one of two paths for you: \n\nLearn App Engine with Webapp. There's enough to learn about using the datastore and App Engine's services that'll keep you busy. \nLearn Django off App Engine. You'll learn a lot about using Django's ORM, Admin goodies, URL routing, Forms and templates\n\nBy trying to learn both at the same time, you'll spend more time than you need learning the nuances of Django/GAE compatibility, time you could be spending either learning Django or GAE. \n" ]
[ 6 ]
[]
[]
[ "django", "google_app_engine", "python", "web_applications" ]
stackoverflow_0002364364_django_google_app_engine_python_web_applications.txt
Q: Where can i get exercises for 'Dive into Python'? I'm learning python with 'Dive Into Python 3' and It's very hard to remember everything, without writing something, but there are no exercises in this book. So I ask here, where can i find them to remember everything better. A: I used ProjectEuler.net when learning Python. It also helped sharpen my math skills. A: Consider using How to Think Like a Computer Scientist instead of Dive Into Python to learn Python. The former has exercises in every chapter, is targeted for a more appropriate version of Python (Python 3 does not have the library support to make it compelling to use yet, and the version of DIP targeting Python 2 is quite old), and it does not have the reputations for errors and ugly code examples DIP has. A: Find a good Code Kata website: Here's a list I compiled. http://slott-softwarearchitect.blogspot.com/2009/08/code-kata-resources.html I've also collected lots of exercises: http://homepage.mac.com/s_lott/books/python.html This book, however, covers only Python 2.6, so it may be more confusing than helpful.
Where can i get exercises for 'Dive into Python'?
I'm learning python with 'Dive Into Python 3' and It's very hard to remember everything, without writing something, but there are no exercises in this book. So I ask here, where can i find them to remember everything better.
[ "I used ProjectEuler.net when learning Python. It also helped sharpen my math skills. \n", "Consider using How to Think Like a Computer Scientist instead of Dive Into Python to learn Python. The former has exercises in every chapter, is targeted for a more appropriate version of Python (Python 3 does not have the library support to make it compelling to use yet, and the version of DIP targeting Python 2 is quite old), and it does not have the reputations for errors and ugly code examples DIP has. \n", "Find a good Code Kata website: Here's a list I compiled.\nhttp://slott-softwarearchitect.blogspot.com/2009/08/code-kata-resources.html\nI've also collected lots of exercises: http://homepage.mac.com/s_lott/books/python.html This book, however, covers only Python 2.6, so it may be more confusing than helpful. \n" ]
[ 2, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002366056_python.txt
Q: Can you go to a line with the file operations in python? I'm parsing a file and need to keep track of where I am in the file... let's say I have file test.txt and I'm doing a while loop that reads in data constantly as each line is written to the file. In case of a crash I'm marking my position in another file with the tell() method of the file. Is there a way to mark the line and be able to go back to that line position or do I need to keep track of the bytes with tell only? #this is just example code, not the real thing f = open('test.txt') pos = open('pos.txt', 'w') f.seek(pos) while 1: readline(f) pos.write(f.tell()) Update: the files are around 1GB each A: You may like this better: http://docs.python.org/library/linecache.html "In case of a crash I'm marking my position in another file with the tell() method of the file." Good. "Is there a way to mark the line and be able to go back to that line position" That's what you are doing. You're marking the line with tell. The tell value is the position used by seek. If it helps, pretend you don't know what the units are. Pretend that tell is just a "magic" key that finds the proper line. A: Keep track of what f.tell() reports (usually the number of bytes, but not necessarily), then you can jump directly to the right position in the file. If you only keep track of the number of lines, you will have to read the file again from the beginning, counting the number of new lines seen.
Can you go to a line with the file operations in python?
I'm parsing a file and need to keep track of where I am in the file... let's say I have file test.txt and I'm doing a while loop that reads in data constantly as each line is written to the file. In case of a crash I'm marking my position in another file with the tell() method of the file. Is there a way to mark the line and be able to go back to that line position or do I need to keep track of the bytes with tell only? #this is just example code, not the real thing f = open('test.txt') pos = open('pos.txt', 'w') f.seek(pos) while 1: readline(f) pos.write(f.tell()) Update: the files are around 1GB each
[ "You may like this better: http://docs.python.org/library/linecache.html\n\"In case of a crash I'm marking my position in another file with the tell() method of the file.\"\nGood.\n\"Is there a way to mark the line and be able to go back to that line position\"\nThat's what you are doing. You're marking the line with tell. The tell value is the position used by seek. \nIf it helps, pretend you don't know what the units are. Pretend that tell is just a \"magic\" key that finds the proper line.\n", "Keep track of what f.tell() reports (usually the number of bytes, but not necessarily), then you can jump directly to the right position in the file.\nIf you only keep track of the number of lines, you will have to read the file again from the beginning, counting the number of new lines seen.\n" ]
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002366448_python.txt
Q: Is there a way to specify a fixed (or variable) number of elements for lxml in Python There must be an easier way to do this. I need some text from a large number of html documents. In my tests the most reliable way to find it is to look for specific word in the text_content of the div elements. If I want to inspect a specific element above the one that has my text I have been enumerating my list of div elements and using the index of the one that has my text to then specify a previous one by acting on the index. But I am sure there must be a better way. I can't seem to figure that out. If not clear for pair in enumerate(list_of_elements): if 'the string' in pair[1].text_content(): thelocation=pair[0] the_other_text=list_of_elements[thelocation-9].text_content() or theitem.getprevious().getprevious().getprevious().getprevious().getprevious().getprevious().getprevious().getprevious().getprevious().text_content() A: lxml supports XPath: from lxml import etree root = etree.fromstring("...your xml...") el, = root.xpath("//div[text() = 'the string']/preceding-sibling::*[9]") A: Does this do the trick? from itertools import islice ancestor = islice(theitem.iterancestors(), 4) # To get the fourth ancestor EDIT I'm an idiot, that doesn't do the trick. You'll need to wrap it up in a helper function like so: def nthparent(element, n): parent = islice(element.iterancestors(), n, n+1) return parent[0] if parent else None ancestor = nthparent(theitem, 4) # to get the 4th parent A: Use something like simplehtmldom, and then provide an index?
Is there a way to specify a fixed (or variable) number of elements for lxml in Python
There must be an easier way to do this. I need some text from a large number of html documents. In my tests the most reliable way to find it is to look for specific word in the text_content of the div elements. If I want to inspect a specific element above the one that has my text I have been enumerating my list of div elements and using the index of the one that has my text to then specify a previous one by acting on the index. But I am sure there must be a better way. I can't seem to figure that out. If not clear for pair in enumerate(list_of_elements): if 'the string' in pair[1].text_content(): thelocation=pair[0] the_other_text=list_of_elements[thelocation-9].text_content() or theitem.getprevious().getprevious().getprevious().getprevious().getprevious().getprevious().getprevious().getprevious().getprevious().text_content()
[ "lxml supports XPath:\nfrom lxml import etree\nroot = etree.fromstring(\"...your xml...\")\n\nel, = root.xpath(\"//div[text() = 'the string']/preceding-sibling::*[9]\")\n\n", "Does this do the trick?\nfrom itertools import islice\nancestor = islice(theitem.iterancestors(), 4) # To get the fourth ancestor\n\nEDIT I'm an idiot, that doesn't do the trick. You'll need to wrap it up in a helper function like so:\ndef nthparent(element, n):\n parent = islice(element.iterancestors(), n, n+1)\n return parent[0] if parent else None\n\nancestor = nthparent(theitem, 4) # to get the 4th parent\n\n", "Use something like simplehtmldom, and then provide an index?\n" ]
[ 3, 1, 0 ]
[]
[]
[ "html", "lxml", "python", "screen_scraping" ]
stackoverflow_0002367000_html_lxml_python_screen_scraping.txt
Q: on click event in wx.Panel? how can I click on a wx.Panel and that changes its color? What is the name of the event. (I want to do a similar thing as Firefox Extras) Thanks in advance! :) A: A quick google for wxpython mouse events turns up http://www.wxpython.org/docs/api/wx.MouseEvent-class.html So using this, you could do something like: class MyFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None) self.panel = wx.Panel(self) self.panel.BackgroundColour = wx.RED self.panel.Bind(wx.EVT_LEFT_UP, self.onClick) def onClick(self, event): self.panel.BackgroundColour = wx.GREEN
on click event in wx.Panel?
how can I click on a wx.Panel and that changes its color? What is the name of the event. (I want to do a similar thing as Firefox Extras) Thanks in advance! :)
[ "A quick google for wxpython mouse events turns up http://www.wxpython.org/docs/api/wx.MouseEvent-class.html\nSo using this, you could do something like:\nclass MyFrame(wx.Frame):\n def __init__(self):\n wx.Frame.__init__(self, None)\n self.panel = wx.Panel(self)\n self.panel.BackgroundColour = wx.RED\n self.panel.Bind(wx.EVT_LEFT_UP, self.onClick)\n\n def onClick(self, event):\n self.panel.BackgroundColour = wx.GREEN\n\n" ]
[ 9 ]
[]
[]
[ "panel", "python", "wxpython" ]
stackoverflow_0002367076_panel_python_wxpython.txt
Q: In Django, how do I make my sessions persist through http://example.com and http://www.example.com? If I set a session in example.com, it doesn't work on www.example.com. I'd like all subdomains, and all www, to be treated as one big thing. example.com and all its subdomains should have all the session cookies of everything. Do I change this in Apache2? A: I found the solution: SESSION_COOKIE_DOMAIN = ".example.com"
In Django, how do I make my sessions persist through http://example.com and http://www.example.com?
If I set a session in example.com, it doesn't work on www.example.com. I'd like all subdomains, and all www, to be treated as one big thing. example.com and all its subdomains should have all the session cookies of everything. Do I change this in Apache2?
[ "I found the solution:\nSESSION_COOKIE_DOMAIN = \".example.com\"\n\n" ]
[ 2 ]
[]
[]
[ "apache", "django", "python", "session" ]
stackoverflow_0002367448_apache_django_python_session.txt
Q: Why won't my Python scatter plot work? I created a very simple scatter plot using pylab. pylab.scatter(engineSize, fuelMile) pylab.show() The rest of the program isn't worth posting, because it's that line that's giving me the problem. When I change "scatter" to "plot" it graphs the data, but each point is part of a line and that makes the whole things a scribbly mess. I just want points, not a line, but I get this huge error message that ends with: File "C:\Python26\lib\site-packages\numpy\core\fromnumeric.py", line 1643, in amin return amin(axis, out) TypeError: cannot perform reduce with flexible type A: I bet engineSize, fuelMile are stings, try printing them, if that is the case, you have to convert them to float before passing them as arguments to scatter floatval = float(strval) A: Okay, so since this works, something must be wrong with your inputs. Clearly you need to post more, unless this "answer" solves your problem: >>> import pylab >>> pylab.scatter([500, 550, 700, 1100], [5.5, 6.5, 3.1, 9.7]) <matplotlib.collections.RegularPolyCollection object at 0x036F5610> >>> pylab.show() (graphing-type stuff ensues)
Why won't my Python scatter plot work?
I created a very simple scatter plot using pylab. pylab.scatter(engineSize, fuelMile) pylab.show() The rest of the program isn't worth posting, because it's that line that's giving me the problem. When I change "scatter" to "plot" it graphs the data, but each point is part of a line and that makes the whole things a scribbly mess. I just want points, not a line, but I get this huge error message that ends with: File "C:\Python26\lib\site-packages\numpy\core\fromnumeric.py", line 1643, in amin return amin(axis, out) TypeError: cannot perform reduce with flexible type
[ "I bet engineSize, fuelMile are stings, try printing them, if that is the case, you have to convert them to float before passing them as arguments to scatter\nfloatval = float(strval)\n\n", "Okay, so since this works, something must be wrong with your inputs. Clearly you need to post more, unless this \"answer\" solves your problem:\n>>> import pylab\n>>> pylab.scatter([500, 550, 700, 1100], [5.5, 6.5, 3.1, 9.7])\n<matplotlib.collections.RegularPolyCollection object at 0x036F5610>\n>>> pylab.show()\n(graphing-type stuff ensues)\n\n" ]
[ 9, 2 ]
[]
[]
[ "graph", "matplotlib", "python", "scatter" ]
stackoverflow_0001746312_graph_matplotlib_python_scatter.txt
Q: How do I implement polymorphic arithmetic operators pythonicly? I'm trying to create a class that will allow me to add/multiply/divide objects of the same class together or add/multiply numeric arguments to each member of the class So my class is for coordinates (I am aware there are great packages out there that do everything I want better than I could ever hope to on my own, but now I'm just curious). class GpsPoint(object): """A class for representing gps coordinates""" def __init__(self, x, y, z): self.x = x self.y = y self.z = z def __add__(self, other): return GpsPoint(self.x + other.x, self.y + other.y, self.z + other.z) def __radd__(self, other): return GpsPoint(self.x + other, self.y + other, self.z + other) def __str__(self): return "%d, %d, %d" % (self.x, self.y, self.z) This was my original attempt. I found it worked, but only if I used a numeric argument first >>foo = GpsPoint(1,2,3) >>print 5 + foo 6, 7, 8 >>print foo + 5 AttributeError: 'int' object has no attribute 'x' So, what is the pythonic way to do this, is there a pythonic way, is this just silly? I see what the philosophical problem is with using isinstance() and I know I could toss in a try except block I'm just curious how I should go about this. A: The "Pythonic" way is to "ask forgiveness rather than permission" - that is, instead of checking the type beforehand, try to add and, if it fails, catch the exception and deal with it, like so: class GpsPoint(object): """A class for representing gps coordinates""" def __init__(self, x, y, z): self.x = x self.y = y self.z = z def __add__(self, other): try: return GpsPoint(self.x + other.x, self.y + other.y, self.z + other.z) except AttributeError: return GpsPoint(self.x + other, self.y + other, self.z + other) def __radd__(self, other): try: return GpsPoint(self.x + other.x, self.y + other.y, self.z + other.z) except AttributeError: return GpsPoint(self.x + other, self.y + other, self.z + other) def __str__(self): return "%d, %d, %d" % (self.x, self.y, self.z) A: You are going to have to try to determine what type other is, at least to the extent that it's compatible with GpsPoint. If you can't figure it out then just return NotImplemented and the interpreter will try to handle it from there. A: Short answer: use isinstance(). There is no other way to dermine the type of "other" in your methods. Also, if you check the sources of many python libraries you will find that there are lots of places where isinstance() is used. So this is just the state of art in python:-).
How do I implement polymorphic arithmetic operators pythonicly?
I'm trying to create a class that will allow me to add/multiply/divide objects of the same class together or add/multiply numeric arguments to each member of the class So my class is for coordinates (I am aware there are great packages out there that do everything I want better than I could ever hope to on my own, but now I'm just curious). class GpsPoint(object): """A class for representing gps coordinates""" def __init__(self, x, y, z): self.x = x self.y = y self.z = z def __add__(self, other): return GpsPoint(self.x + other.x, self.y + other.y, self.z + other.z) def __radd__(self, other): return GpsPoint(self.x + other, self.y + other, self.z + other) def __str__(self): return "%d, %d, %d" % (self.x, self.y, self.z) This was my original attempt. I found it worked, but only if I used a numeric argument first >>foo = GpsPoint(1,2,3) >>print 5 + foo 6, 7, 8 >>print foo + 5 AttributeError: 'int' object has no attribute 'x' So, what is the pythonic way to do this, is there a pythonic way, is this just silly? I see what the philosophical problem is with using isinstance() and I know I could toss in a try except block I'm just curious how I should go about this.
[ "The \"Pythonic\" way is to \"ask forgiveness rather than permission\" - that is, instead of checking the type beforehand, try to add and, if it fails, catch the exception and deal with it, like so:\nclass GpsPoint(object):\n \"\"\"A class for representing gps coordinates\"\"\"\n def __init__(self, x, y, z):\n self.x = x\n self.y = y\n self.z = z\n def __add__(self, other):\n try:\n return GpsPoint(self.x + other.x, self.y + other.y, self.z + other.z)\n except AttributeError:\n return GpsPoint(self.x + other, self.y + other, self.z + other)\n def __radd__(self, other):\n try:\n return GpsPoint(self.x + other.x, self.y + other.y, self.z + other.z)\n except AttributeError:\n return GpsPoint(self.x + other, self.y + other, self.z + other)\n def __str__(self):\n return \"%d, %d, %d\" % (self.x, self.y, self.z)\n\n", "You are going to have to try to determine what type other is, at least to the extent that it's compatible with GpsPoint. If you can't figure it out then just return NotImplemented and the interpreter will try to handle it from there.\n", "Short answer: use isinstance().\nThere is no other way to dermine the type of \"other\" in your methods. Also, if you check the sources of many python libraries you will find that there are lots of places where isinstance() is used. So this is just the state of art in python:-). \n" ]
[ 6, 2, 0 ]
[]
[]
[ "polymorphism", "python", "type_conversion" ]
stackoverflow_0002367753_polymorphism_python_type_conversion.txt
Q: Sed script to edit csv file Or Python In our project we need to import the csv file to postgres. There are multiple types of files meaning the length of the file changes as some files are with fewer columns and some with all of them. We need a fast way to import this file to postgres. I want to use COPY FROM of the postgres since the speed requirement of the processing are very high(almost 150 files per minute with 20K file size each). Since the file columns numbers are not fixed, I need to pre-process the file before I pass it to the postgres procedure. The pre-processing is simply to add extra commas in the csv for columns, which are not there in the file. There are two options for me to preprocess the file - use python or use Sed. My first question is, what would be the fastest way of pre-process the file? Second question is, If I use sed how would I insert a comma after say 4th, 5th comma fields? e.g. if file has entries like 1,23,56,we,89,2009-12-06 and I need to edit the file with final output like: 1,23,56,we,,89,,2009-12-06 A: Are you aware of the fact that COPY FROM lets you specify which columns (as well as in which order they) are to be imported? COPY tablename ( column1, column2, ... ) FROM ... Specifying directly, at the Postgres level, which columns to import and in what order, will typically be the fastest and most efficient import method. This having been said, there is a much simpler (and portable) way of using sed (than what has been presented in other posts) to replace an n th occurrence, e.g. replace the 4th and 5th occurrences of a comma with double commas: echo '1,23,56,we,89,2009-12-06' | sed -e 's/,/,,/5;s/,/,,/4' produces: 1,23,56,we,,89,,2009-12-06 Notice that I replaced the rightmost fields (#5) first. I see that you have also tagged your question as perl-related, although you make no explicit reference to perl in the body of the question; here would be one possible implementation which gives you the flexibility of also reordering or otherwise processing fields: echo '1,23,56,we,89,2009-12-06' | perl -F/,/ -nae 'print "$F[0],$F[1],$F[2],$F[3],,$F[4],,$F[5]"' also produces: 1,23,56,we,,89,,2009-12-06 Very similarly with awk, for the record: echo '1,23,56,we,89,2009-12-06' | awk -F, '{print $1","$2","$3","$4",,"$5",,"$6}' I will leave Python to someone else. :) Small note on the Perl example: I am using the -a and -F options to autosplit so I have a shorter command string; however, this leaves the newline embedded in the last field ($F[5]) which is fine as long as that field doesn't have to be reordered somewhere else. Should that situation arise, slightly more typing would be needed in order to zap the newline via chomp, then split by hand and finally print our own newline character \n (the awk example above does not have this problem): perl -ne 'chomp;@F=split/,/;print "$F[0],$F[1],$F[2],$F[3],,$F[4],,$F[5]\n"' EDIT (an idea inspired by Vivin): COMMAS_TO_DOUBLE="1 4 5" echo '1,23,56,we,89,2009-12-06' | sed -e `for f in $COMMAS_TO_DOUBLE ; do echo "s/,/,,/$f" ; done | sort -t/ -k4,4nr | paste -s -d ';'` 1,,23,56,we,,89,,2009-12-06 Sorry, couldn't resist it. :) A: To answer your first question, sed would have less overhead, but might be painful. awk would be a little better (it's more powerful). Perl or Python have more overhead, but would be easier to work with (regarding Perl, that's maybe a little subjective ;). Personally, I'd use Perl). As far as the second question, I think the problem might be a little more complex. For example, don't you need to examine the string to figure out what fields are actually missing? Or is it guaranteed that it will always be the 4th and 5th? If it's the first case case, it would be way easier to do this in Python or Perl rather than in sed. Otherwise: echo "1,23,56,we,89,2009-12-06" | sed -e 's/\([^,]\+\),\([^,]\+\),\([^,]\+\),\([^,]\+\),\([^,]\+\),/\1,\2,\3,\4,,\5,,/' or (easier on the eyes): echo "1,23,56,we,89,2009-12-06" | sed -e 's/\(\([^,]\+,\)\{3\}\)\([^,]\+\),\([^,]\+\),/\1,\3,,\4,,/' This will add a comma after the 5th and 4th columns assuming there are no other commas in the text. Or you can use two seds for something that's a little less ugly (only slightly, though): echo "1,23,56,we,89,2009-12-06" | sed -e 's/\(\([^,]*,\)\{4\}\)/\1,/' | sed -e 's/\(\([^,]*,\)\{6\}\)/\1,/' A: @OP, you are processing a csv file, which have distinct fields and delimiters. Use a tool that can split on delimiters and give you fields to work with easily. sed is not one of them, although it can be done, as some of the answers suggested, but you will get sed regex that is hard to read when it gets complicated. Use tools like awk/Python/Perl where they work with fields and delimiters easily, best of all, modules that specifically tailored to processing csv is available. For your example, a simple Python approach (without the use of csv module which ideally you should try to use it) for line in open("file"): line=line.rstrip() #strip new lines sline=line.split(",") if len(sline) < 8: # you want exact 8 fields sline.insert(4,"") sline.insert(6,"") line=','.join(sline) print line output $ more file 1,23,56,we,89,2009-12-06 $ ./python.py 1,23,56,we,,89,,2009-12-06 A: sed 's/^([^,]*,){4}/&,/' <original.csv >output.csv Will add a comma after the 4th comma separated field (by matching 4 repetitions of <anything>, and then adding a comma after that). Note that there is a catch; make sure none of these values are quoted strings with commas in them. You could chain multiple replacements via pipes if necessary, or modify the regex to add in any needed commas at the same time (though that gets more complex; you'd need to use subgroup captures in your replacement text). A: Don't know regarding speed, but here is sed expr that should do the job: sed -i 's/\(\([^,]*,\)\{4\}\)/\1,/' file_name Just replace 4 by desured number of columns A: Depending on your requirements, consider using ETL software for this and future tasks. Tools like Pentaho and Talend offer you a great deal of flexibility and you don't have to write a single line of code.
Sed script to edit csv file Or Python
In our project we need to import the csv file to postgres. There are multiple types of files meaning the length of the file changes as some files are with fewer columns and some with all of them. We need a fast way to import this file to postgres. I want to use COPY FROM of the postgres since the speed requirement of the processing are very high(almost 150 files per minute with 20K file size each). Since the file columns numbers are not fixed, I need to pre-process the file before I pass it to the postgres procedure. The pre-processing is simply to add extra commas in the csv for columns, which are not there in the file. There are two options for me to preprocess the file - use python or use Sed. My first question is, what would be the fastest way of pre-process the file? Second question is, If I use sed how would I insert a comma after say 4th, 5th comma fields? e.g. if file has entries like 1,23,56,we,89,2009-12-06 and I need to edit the file with final output like: 1,23,56,we,,89,,2009-12-06
[ "Are you aware of the fact that COPY FROM lets you specify which columns (as well as in which order they) are to be imported?\nCOPY tablename ( column1, column2, ... ) FROM ...\n\nSpecifying directly, at the Postgres level, which columns to import and in what order, will typically be the fastest and most efficient import method.\nThis having been said, there is a much simpler (and portable) way of using sed (than what has been presented in other posts) to replace an n th occurrence, e.g. replace the 4th and 5th occurrences of a comma with double commas:\necho '1,23,56,we,89,2009-12-06' | sed -e 's/,/,,/5;s/,/,,/4'\n\nproduces:\n1,23,56,we,,89,,2009-12-06\n\nNotice that I replaced the rightmost fields (#5) first.\nI see that you have also tagged your question as perl-related, although you make no explicit reference to perl in the body of the question; here would be one possible implementation which gives you the flexibility of also reordering or otherwise processing fields:\necho '1,23,56,we,89,2009-12-06' |\n perl -F/,/ -nae 'print \"$F[0],$F[1],$F[2],$F[3],,$F[4],,$F[5]\"'\n\nalso produces:\n1,23,56,we,,89,,2009-12-06\n\nVery similarly with awk, for the record:\necho '1,23,56,we,89,2009-12-06' |\n awk -F, '{print $1\",\"$2\",\"$3\",\"$4\",,\"$5\",,\"$6}'\n\nI will leave Python to someone else. :)\nSmall note on the Perl example: I am using the -a and -F options to autosplit so I have a shorter command string; however, this leaves the newline embedded in the last field ($F[5]) which is fine as long as that field doesn't have to be reordered somewhere else. Should that situation arise, slightly more typing would be needed in order to zap the newline via chomp, then split by hand and finally print our own newline character \\n (the awk example above does not have this problem):\nperl -ne 'chomp;@F=split/,/;print \"$F[0],$F[1],$F[2],$F[3],,$F[4],,$F[5]\\n\"'\n\nEDIT (an idea inspired by Vivin):\nCOMMAS_TO_DOUBLE=\"1 4 5\"\necho '1,23,56,we,89,2009-12-06' |\n sed -e `for f in $COMMAS_TO_DOUBLE ; do echo \"s/,/,,/$f\" ; done |\n sort -t/ -k4,4nr | paste -s -d ';'`\n\n1,,23,56,we,,89,,2009-12-06\n\nSorry, couldn't resist it. :)\n", "To answer your first question, sed would have less overhead, but might be painful. awk would be a little better (it's more powerful). Perl or Python have more overhead, but would be easier to work with (regarding Perl, that's maybe a little subjective ;). Personally, I'd use Perl).\nAs far as the second question, I think the problem might be a little more complex. For example, don't you need to examine the string to figure out what fields are actually missing? Or is it guaranteed that it will always be the 4th and 5th? If it's the first case case, it would be way easier to do this in Python or Perl rather than in sed. Otherwise:\necho \"1,23,56,we,89,2009-12-06\" | sed -e 's/\\([^,]\\+\\),\\([^,]\\+\\),\\([^,]\\+\\),\\([^,]\\+\\),\\([^,]\\+\\),/\\1,\\2,\\3,\\4,,\\5,,/'\n\nor (easier on the eyes):\necho \"1,23,56,we,89,2009-12-06\" | sed -e 's/\\(\\([^,]\\+,\\)\\{3\\}\\)\\([^,]\\+\\),\\([^,]\\+\\),/\\1,\\3,,\\4,,/'\n\nThis will add a comma after the 5th and 4th columns assuming there are no other commas in the text.\nOr you can use two seds for something that's a little less ugly (only slightly, though):\necho \"1,23,56,we,89,2009-12-06\" | sed -e 's/\\(\\([^,]*,\\)\\{4\\}\\)/\\1,/' | sed -e 's/\\(\\([^,]*,\\)\\{6\\}\\)/\\1,/'\n\n", "@OP, you are processing a csv file, which have distinct fields and delimiters. Use a tool that can split on delimiters and give you fields to work with easily. sed is not one of them, although it can be done, as some of the answers suggested, but you will get sed regex that is hard to read when it gets complicated. Use tools like awk/Python/Perl where they work with fields and delimiters easily, best of all, modules that specifically tailored to processing csv is available. For your example, a simple Python approach (without the use of csv module which ideally you should try to use it)\nfor line in open(\"file\"):\n line=line.rstrip() #strip new lines\n sline=line.split(\",\")\n if len(sline) < 8: # you want exact 8 fields\n sline.insert(4,\"\")\n sline.insert(6,\"\")\n line=','.join(sline)\n print line\n\noutput\n$ more file\n1,23,56,we,89,2009-12-06\n\n$ ./python.py\n1,23,56,we,,89,,2009-12-06\n\n", "sed 's/^([^,]*,){4}/&,/' <original.csv >output.csv\n\nWill add a comma after the 4th comma separated field (by matching 4 repetitions of <anything>, and then adding a comma after that). Note that there is a catch; make sure none of these values are quoted strings with commas in them.\nYou could chain multiple replacements via pipes if necessary, or modify the regex to add in any needed commas at the same time (though that gets more complex; you'd need to use subgroup captures in your replacement text).\n", "Don't know regarding speed, but here is sed expr that should do the job:\nsed -i 's/\\(\\([^,]*,\\)\\{4\\}\\)/\\1,/' file_name\n\nJust replace 4 by desured number of columns\n", "Depending on your requirements, consider using ETL software for this and future tasks. Tools like Pentaho and Talend offer you a great deal of flexibility and you don't have to write a single line of code.\n" ]
[ 3, 2, 2, 0, 0, 0 ]
[]
[]
[ "awk", "python", "sed", "text_processing" ]
stackoverflow_0002367338_awk_python_sed_text_processing.txt
Q: Django url.py Different view functions with the same regex name pattern I'm filtering a few categories (cat1, cat2, cat3) to be rendered by different views then all the rest by other view functions. It is getting unwieldy to keep adding category slugs to the urlpatterns each time one is added. Can I factor that part out of the regex some how? urlpatterns = patterns('catalog.category_views', (r'^(?P<cat_slug>(cat1|cat2|cat3))/$', 'universal_category'), (r'^(?P<cat_slug>(cat1|cat2|cat3))/(?P<subcat_slug>[-\w]+)/$', 'subcat_listing'), (r'^(?P<cat_slug>(cat1|cat2|cat3))/part/(?P<part>[-\w]+)/$', 'subcat_product'), ) urlpatterns += patterns('catalog.make_views', (r'^(?P<cat_slug>[-\w]+)/$', 'category'), (r'^(?P<cat_slug>[-\w]+)/(?P<make_slug>[-\w]+)/$', 'make'), (r'^(?P<cat_slug>[-\w]+)/(?P<make_slug>[-\w]+)/(?P<model_slug>[-\w]+)/(?P<year_low>\d{4})-(?P<year_high>\d{4})/$', 'listing'), (r'^(?P<cat_slug>[-\w]+)/part/(?P<part>[-\w]+)/$', 'product'), ) A: I'd personally put this logic in the view rather than the urlspatterns. I would create a list of all the special categories so for this: special_cats = ['cat1','cat2','cat3'] Then for you view you can do something like this: def generic_cat_view(request, cat_slug): if cat_slug in special_cats: return special_view(request, cat_slug) else: #generic view Then when you add a new special category, you just need to add it to that list
Django url.py Different view functions with the same regex name pattern
I'm filtering a few categories (cat1, cat2, cat3) to be rendered by different views then all the rest by other view functions. It is getting unwieldy to keep adding category slugs to the urlpatterns each time one is added. Can I factor that part out of the regex some how? urlpatterns = patterns('catalog.category_views', (r'^(?P<cat_slug>(cat1|cat2|cat3))/$', 'universal_category'), (r'^(?P<cat_slug>(cat1|cat2|cat3))/(?P<subcat_slug>[-\w]+)/$', 'subcat_listing'), (r'^(?P<cat_slug>(cat1|cat2|cat3))/part/(?P<part>[-\w]+)/$', 'subcat_product'), ) urlpatterns += patterns('catalog.make_views', (r'^(?P<cat_slug>[-\w]+)/$', 'category'), (r'^(?P<cat_slug>[-\w]+)/(?P<make_slug>[-\w]+)/$', 'make'), (r'^(?P<cat_slug>[-\w]+)/(?P<make_slug>[-\w]+)/(?P<model_slug>[-\w]+)/(?P<year_low>\d{4})-(?P<year_high>\d{4})/$', 'listing'), (r'^(?P<cat_slug>[-\w]+)/part/(?P<part>[-\w]+)/$', 'product'), )
[ "I'd personally put this logic in the view rather than the urlspatterns.\nI would create a list of all the special categories so for this:\nspecial_cats = ['cat1','cat2','cat3']\n\nThen for you view you can do something like this:\ndef generic_cat_view(request, cat_slug):\n if cat_slug in special_cats:\n return special_view(request, cat_slug)\n else:\n #generic view\n\nThen when you add a new special category, you just need to add it to that list\n" ]
[ 4 ]
[]
[]
[ "django", "django_urls", "python" ]
stackoverflow_0002367918_django_django_urls_python.txt
Q: Passing JSON to Python script via AJAX What's the ideal way to pass a large JSON data object from Javascript through AJAX to a Python script? A: Are you using some web framework? Django has pretty decent support for JSON decoding/encoding.
Passing JSON to Python script via AJAX
What's the ideal way to pass a large JSON data object from Javascript through AJAX to a Python script?
[ "Are you using some web framework? Django has pretty decent support for JSON decoding/encoding.\n" ]
[ 1 ]
[]
[]
[ "ajax", "javascript", "json", "python" ]
stackoverflow_0002368001_ajax_javascript_json_python.txt
Q: In mako, how can I cycle through a list and display each value? I have a Python list that I'm supplying to the template: {'error_name':'Please enter a name', 'error_email':'Please enter an email'} And would like to display: <ul> <li>Please enter a name</li> <li>Please enter an email</li> </ul> A: <ul> % for prompt in whateveryoucalledit.values(): <li>${prompt}</li> % endfor </ul> where whateveryoucalledit it is the name under which you chose to pass that container (which, as a comment noticed, is a dict, not a list). The nice thing about mako, after all, is precisely that it's wonderfully close to Python itself (except for the need to "strop" things around a bit, and explicitly close blocks rather than just indend/deindent;-).
In mako, how can I cycle through a list and display each value?
I have a Python list that I'm supplying to the template: {'error_name':'Please enter a name', 'error_email':'Please enter an email'} And would like to display: <ul> <li>Please enter a name</li> <li>Please enter an email</li> </ul>
[ "<ul>\n% for prompt in whateveryoucalledit.values():\n <li>${prompt}</li>\n% endfor\n</ul>\n\nwhere whateveryoucalledit it is the name under which you chose to pass that container (which, as a comment noticed, is a dict, not a list). The nice thing about mako, after all, is precisely that it's wonderfully close to Python itself (except for the need to \"strop\" things around a bit, and explicitly close blocks rather than just indend/deindent;-).\n" ]
[ 5 ]
[]
[]
[ "mako", "pylons", "python", "templates" ]
stackoverflow_0002367682_mako_pylons_python_templates.txt
Q: How to convert from unicode with python In database I have saved string in which the problem word is: za\u0161\u010diten. [ed.: the "problem word" seems to have changed] When I want to present this string on my page (with req.write(string)). I get this error: UnicodeEncodeError: 'ascii' codec can't encode characters in position 686-687: ordinal not in range(128). I am using Python 2.X on Windows|linux|Mac. [ed.: select one] My string is actually named html_h2. Here are the details I was asked for: [ed.: whitespace inserted for legibility] >> print type(html_h2) <type 'unicode'> >> print repr(html_h2) u"\n<table bgcolor='white' border=1 cellpadding=2 cellspacing=1 rules=rows frame=box> <tr> <td align='center'> <img src=img/_up/upload/2010/03/03/… width=120 height=100/> </td> <td align='left' style=width:86%> <h3>V Gr\u010diji kot v vojni</h3> Gr\u0161ki premier je finan\u010dne razmere v dr\u017eavi, ki je skoraj pred bankrotom, primerjal z razmerami v vojni. Napovedani so ostri var\u010devalni ukrepi. </td> </tr> </table>" I insert database fields in string with %s. [ed.: irrelevant] When I do as Ignacio suggested: req.write(html_h2.encode('XXXXXX')) where XXXXXX is the charset I declared in the Content-Type header, this happens: [ed.: delete the outcome that doesn't happen] (1) It displays just like I'd hoped for. (2) I get an error message: XXXXXXXXXXXXXXXXXXXXXXXXXX A: req.write(string.encode(encoding)) where encoding is the charset you declared in the Content-Type header. A: If string refers to the string module, then yes that string doesn't have encode. If string is in fact a unicode object, then it does have an encode but perhaps string may in fact be an str object. Back to basics: please give us some information. Please show the results of: # Python 2.X print type(string) print repr(string) or # Python 3.X print(type(string)) print(ascii(string)) Then we can give you informed advice rather than uninformed guesses. Note: please edit your question to show the output, don't respond in a comment. Use copy/paste, don't type from memory.
How to convert from unicode with python
In database I have saved string in which the problem word is: za\u0161\u010diten. [ed.: the "problem word" seems to have changed] When I want to present this string on my page (with req.write(string)). I get this error: UnicodeEncodeError: 'ascii' codec can't encode characters in position 686-687: ordinal not in range(128). I am using Python 2.X on Windows|linux|Mac. [ed.: select one] My string is actually named html_h2. Here are the details I was asked for: [ed.: whitespace inserted for legibility] >> print type(html_h2) <type 'unicode'> >> print repr(html_h2) u"\n<table bgcolor='white' border=1 cellpadding=2 cellspacing=1 rules=rows frame=box> <tr> <td align='center'> <img src=img/_up/upload/2010/03/03/… width=120 height=100/> </td> <td align='left' style=width:86%> <h3>V Gr\u010diji kot v vojni</h3> Gr\u0161ki premier je finan\u010dne razmere v dr\u017eavi, ki je skoraj pred bankrotom, primerjal z razmerami v vojni. Napovedani so ostri var\u010devalni ukrepi. </td> </tr> </table>" I insert database fields in string with %s. [ed.: irrelevant] When I do as Ignacio suggested: req.write(html_h2.encode('XXXXXX')) where XXXXXX is the charset I declared in the Content-Type header, this happens: [ed.: delete the outcome that doesn't happen] (1) It displays just like I'd hoped for. (2) I get an error message: XXXXXXXXXXXXXXXXXXXXXXXXXX
[ "req.write(string.encode(encoding))\n\nwhere encoding is the charset you declared in the Content-Type header.\n", "If string refers to the string module, then yes that string doesn't have encode. If string is in fact a unicode object, then it does have an encode but perhaps string may in fact be an str object.\nBack to basics: please give us some information.\nPlease show the results of: \n# Python 2.X\nprint type(string)\nprint repr(string)\n\nor\n# Python 3.X\nprint(type(string))\nprint(ascii(string))\n\nThen we can give you informed advice rather than uninformed guesses.\nNote: please edit your question to show the output, don't respond in a comment. Use copy/paste, don't type from memory. \n" ]
[ 2, 0 ]
[]
[]
[ "python", "unicode" ]
stackoverflow_0002367744_python_unicode.txt
Q: Find text in gtk.TextView I have a gtk.Textview. I want to find and select some of the text in this TextView programmatically. I have this code but it's not working correctly. search_str = self.text_to_find.get_text() start_iter = textbuffer.get_start_iter() match_start = textbuffer.get_start_iter() match_end = textbuffer.get_end_iter() found = start_iter.forward_search(search_str,0, None) if found: textbuffer.select_range(match_start,match_end) If the text is found, then it selects all the text in the TextView, but I need it to select only the found text. A: start_iter.forward_search returns a tuple of the start and end matches so your found variable has both match_start and match_end in it this should make it work: search_str = self.text_to_find.get_text() start_iter = textbuffer.get_start_iter() # don't need these lines anymore #match_start = textbuffer.get_start_iter() #match_end = textbuffer.get_end_iter() found = start_iter.forward_search(search_str,0, None) if found: match_start,match_end = found #add this line to get match_start and match_end textbuffer.select_range(match_start,match_end)
Find text in gtk.TextView
I have a gtk.Textview. I want to find and select some of the text in this TextView programmatically. I have this code but it's not working correctly. search_str = self.text_to_find.get_text() start_iter = textbuffer.get_start_iter() match_start = textbuffer.get_start_iter() match_end = textbuffer.get_end_iter() found = start_iter.forward_search(search_str,0, None) if found: textbuffer.select_range(match_start,match_end) If the text is found, then it selects all the text in the TextView, but I need it to select only the found text.
[ "start_iter.forward_search returns a tuple of the start and end matches so your found variable has both match_start and match_end in it\nthis should make it work:\nsearch_str = self.text_to_find.get_text()\nstart_iter = textbuffer.get_start_iter()\n# don't need these lines anymore\n#match_start = textbuffer.get_start_iter() \n#match_end = textbuffer.get_end_iter() \nfound = start_iter.forward_search(search_str,0, None) \nif found:\n match_start,match_end = found #add this line to get match_start and match_end\n textbuffer.select_range(match_start,match_end)\n\n" ]
[ 6 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0002364014_gtk_pygtk_python.txt
Q: How do I use Flickzeug to get interactive tracebacks from a paste deploy WSGI pipeline? I'd like to use Flickzeug to see interactive tracebacks by adding it to my paste deploy file's pipeline. The following doesn't work. What will? [pipeline] pipeline = flickzeug myapp A: Use the filter-with directive in your application declaration. [app:main] use = ... ... filter-with = flickzeug [filter:flickzeug] use = egg:...#... ... For more information, see the first example in the Filter Composition section of the Paste Deploy documentation.
How do I use Flickzeug to get interactive tracebacks from a paste deploy WSGI pipeline?
I'd like to use Flickzeug to see interactive tracebacks by adding it to my paste deploy file's pipeline. The following doesn't work. What will? [pipeline] pipeline = flickzeug myapp
[ "Use the filter-with directive in your application declaration.\n[app:main]\nuse = ...\n...\n\nfilter-with = flickzeug\n\n\n[filter:flickzeug]\nuse = egg:...#...\n...\nFor more information, see the first example in the Filter Composition section of the Paste Deploy documentation.\n" ]
[ 0 ]
[]
[]
[ "paster", "python", "wsgi" ]
stackoverflow_0002299173_paster_python_wsgi.txt
Q: Apache/Django freezing after a few requests I'm running Django through mod_wsgi and Apache (2.2.8) on Ubuntu 8.04. I've been running Django on this setup for about 6 months without any problems. Yesterday, I moved my database (postgres 8.3) to its own server, and my Django site started refusing to load (the browser spinner would just keep spinning). It works for about 10 mintues, then just stops. Apache is still able to serve static files. Just nothing through Django. I've checked the apache error logs, and I don't see any entries that could be related. I'm not sure if this is a WSGI, Django, Apache, or Postgres issue? Any ideas? Thanks for your help! A: It sounds a lot like there's something happening between django and your newly housed database. Just to eliminate apache from the mix, you should run it as the dev server (on some random port to stop people using it) and see if you still have issues. If you do, it's the database. If it behaves, it could be apache. Edit, This looks interesting. You can test that by applying his patch (commenting out the .close()) but there are other similar bugs floating around. A: Found it! I'm using eventlet in some other code and I imported one of my modules into a django model. So eventlet was taking over and putting everything to "sleep".
Apache/Django freezing after a few requests
I'm running Django through mod_wsgi and Apache (2.2.8) on Ubuntu 8.04. I've been running Django on this setup for about 6 months without any problems. Yesterday, I moved my database (postgres 8.3) to its own server, and my Django site started refusing to load (the browser spinner would just keep spinning). It works for about 10 mintues, then just stops. Apache is still able to serve static files. Just nothing through Django. I've checked the apache error logs, and I don't see any entries that could be related. I'm not sure if this is a WSGI, Django, Apache, or Postgres issue? Any ideas? Thanks for your help!
[ "It sounds a lot like there's something happening between django and your newly housed database.\nJust to eliminate apache from the mix, you should run it as the dev server (on some random port to stop people using it) and see if you still have issues. If you do, it's the database. If it behaves, it could be apache.\nEdit, This looks interesting. You can test that by applying his patch (commenting out the .close()) but there are other similar bugs floating around.\n", "Found it! I'm using eventlet in some other code and I imported one of my modules into a django model. So eventlet was taking over and putting everything to \"sleep\".\n" ]
[ 0, 0 ]
[]
[]
[ "apache2", "django", "mod_wsgi", "postgresql", "python" ]
stackoverflow_0001300213_apache2_django_mod_wsgi_postgresql_python.txt
Q: Why does python + pylons "remember" previously specified class variables? I have a simple form in python + pylons that submits to a controller. However, each page load doesn't seem to be a fresh instantiation of the class. Rather, class variables specified on the previous page load are still accessible. What's going on here? And what's the solution? A: Pylons uses a multi-threaded application server and variables are not cleared from request to request. This is a performance issue, as re-instantiating entire class trees would be expensive. Instead of storing the data returned by the user in a class, use a sessions system (Pylons comes with one or use something like Beaker) or back-end database like SQLAlchemy, SQLObject, or PyMongo. Additionally, due to the multi-threaded nature of the framework, you should avoid shared objects (like globals) like the plague unless you are very careful to ensure you are using them in a thread-safe way (e.g. read-only). Certain Pylons-supplied objects (request/response) have been written to be thread-local, so don't worry about those. A: A common programmer oversight is that defining a list [] as a default argument or class initialiser is evaluated only once. If you have class variables such as lists, I recommend you initialise them in init. I'll give you an example. >>> class Example(object): ... a = [] ... def __init__(self): ... self.b = [] ... >>> foo = Example() >>> bar = Example() >>> foo.a [] >>> bar.a [] >>> foo.b [] >>> bar.b [] >>> foo.a.append(1) >>> foo.b.append(2) >>> foo.a [1] >>> foo.b [2] >>> bar.a [1] >>> bar.b []
Why does python + pylons "remember" previously specified class variables?
I have a simple form in python + pylons that submits to a controller. However, each page load doesn't seem to be a fresh instantiation of the class. Rather, class variables specified on the previous page load are still accessible. What's going on here? And what's the solution?
[ "Pylons uses a multi-threaded application server and variables are not cleared from request to request. This is a performance issue, as re-instantiating entire class trees would be expensive. Instead of storing the data returned by the user in a class, use a sessions system (Pylons comes with one or use something like Beaker) or back-end database like SQLAlchemy, SQLObject, or PyMongo.\nAdditionally, due to the multi-threaded nature of the framework, you should avoid shared objects (like globals) like the plague unless you are very careful to ensure you are using them in a thread-safe way (e.g. read-only). Certain Pylons-supplied objects (request/response) have been written to be thread-local, so don't worry about those.\n", "A common programmer oversight is that defining a list [] as a default argument or class initialiser is evaluated only once. If you have class variables such as lists, I recommend you initialise them in init. I'll give you an example.\n>>> class Example(object):\n... a = []\n... def __init__(self):\n... self.b = []\n... \n\n>>> foo = Example()\n>>> bar = Example()\n\n>>> foo.a\n[]\n>>> bar.a\n[]\n>>> foo.b\n[]\n>>> bar.b\n[]\n\n>>> foo.a.append(1)\n>>> foo.b.append(2)\n>>> foo.a\n[1]\n>>> foo.b\n[2]\n>>> bar.a\n[1]\n>>> bar.b\n[]\n\n" ]
[ 1, 1 ]
[]
[]
[ "pylons", "python" ]
stackoverflow_0002368482_pylons_python.txt
Q: Getting info from all related objects in django I'm trying to do something pretty simple, but I'm new to Django. I have a quiz system set up for an experiment I'm running. The relevant entries in models.py follow: class Flavor(models.Model): name = models.CharField(max_length=100) def __unicode__(self): return self.name class Passage(models.Model): name = models.CharField(max_length=100) def __unicode__(self): return self.name class PassageText(models.Model): passage = models.ForeignKey(Passage) flavor = models.ForeignKey(Flavor) contents = models.TextField() def __unicode__(self): return "[%s#%s]" % (self.passage, self.flavor) class Question(models.Model): passage = models.ForeignKey(Passage) text = models.TextField() def __unicode__(self): return "[%s#%s]" % (self.passage, self.text) class AnswerOption(models.Model): question = models.ForeignKey(Question) text = models.TextField() is_correct = models.BooleanField(default=False) def __unicode__(self): return "[%s#%s]" % (self.question, self.text) class TestSubject(models.Model): GENDER_CHOICES = ( ('M','Male'), ('F','Female'), ) EDUCATION_CHOICES = ( ('SH', 'Some high school'), ('HS', 'High school diploma'), ('SC', 'Some college'), ('CD', 'College degree'), ('MD', 'Master\'s degree'), ('PH','PhD or higher education'), ) GPA_CHOICES = ( ('1', '1.0-1.5'), ('2', '1.5-2.0'), ('3', '2.0-2.5'), ('4', '2.5-3.0'), ('5', '3.0-3.5'), ('6', '3.5-4.0'), ('7', '4.0-4.5'), ('8', '4.5-5.0'), ) ip = models.CharField(max_length=30) completed = models.BooleanField(default=False) created_time = models.DateTimeField(default=datetime.now) time_used = models.IntegerField(default=0, help_text='number of seconds used for test') age = models.PositiveIntegerField() gender = models.CharField(max_length=2, choices=GENDER_CHOICES) education = models.CharField(max_length=2, choices=EDUCATION_CHOICES) school = models.CharField(max_length=200) grad_year = models.PositiveIntegerField() gpa = models.CharField(max_length=2, choices=GPA_CHOICES) sat_verbal = models.PositiveIntegerField(blank=True) sat_math = models.PositiveIntegerField(blank=True) sat_writing = models.PositiveIntegerField(blank=True) sat_overall = models.PositiveIntegerField(blank=True) english_is_your_first_language = models.BooleanField() kerberos_name_if_applying_for_900_credit = models.CharField(max_length=200, blank=True) def __unicode__(self): return "[%s#%s]" % (self.ip, self.created_time) class TestSequence(models.Model): subject = models.ForeignKey(TestSubject) order = models.IntegerField(help_text='1..n') pt = models.ForeignKey(PassageText) time_used = models.IntegerField(default=0, help_text='number of seconds used for test') def __unicode__(self): return "[%s#%d]" % (self.subject, self.order) class QuestionSequence(models.Model): tseq = models.ForeignKey(TestSequence) order = models.IntegerField(help_text='0..n') question = models.ForeignKey(Question) selectedanswer = models.ForeignKey(AnswerOption, blank=True, null=True, default=None) def __unicode__(self): return "[%s#%d]" % (self.tseq, self.order) I want to essentially have a page that just gives me a table of all TestSubject objects (and all their properties) as well as a list of which passages they did and a count of how many questions they got right in that passage. A: Well, since no one has helped you yet, here: # *snip* -- view: context = { 'test_subjects' : TestSubject.objects.all() } return render_to_response('Template', context) # *snip* # *snip* -- template: {% for test_subject in test_subjects %} {{ test_subject.ip }} {# ... snip ... #} {% empty %} There are no test subjects. {% endfor %} secondly, it is more preferable to pass a list of "things" to a template and let it do the magic... unless you have some special reason not to do so. Passing them in as a string by "converting" and "joining" them in the view ruins the separation between data and code, and it makes your views "dirty". For more information on this subject, read: Views, Templates and Models On a side note, I think it would be better if you rethought some parts of your model design, I see some redundancy there. Storing the test subject's name would be a good and user friendly idea. Finally, shouldn't flavor be flavour? Even if you don't change it in your code, you might want to I18N it for British English speakers.
Getting info from all related objects in django
I'm trying to do something pretty simple, but I'm new to Django. I have a quiz system set up for an experiment I'm running. The relevant entries in models.py follow: class Flavor(models.Model): name = models.CharField(max_length=100) def __unicode__(self): return self.name class Passage(models.Model): name = models.CharField(max_length=100) def __unicode__(self): return self.name class PassageText(models.Model): passage = models.ForeignKey(Passage) flavor = models.ForeignKey(Flavor) contents = models.TextField() def __unicode__(self): return "[%s#%s]" % (self.passage, self.flavor) class Question(models.Model): passage = models.ForeignKey(Passage) text = models.TextField() def __unicode__(self): return "[%s#%s]" % (self.passage, self.text) class AnswerOption(models.Model): question = models.ForeignKey(Question) text = models.TextField() is_correct = models.BooleanField(default=False) def __unicode__(self): return "[%s#%s]" % (self.question, self.text) class TestSubject(models.Model): GENDER_CHOICES = ( ('M','Male'), ('F','Female'), ) EDUCATION_CHOICES = ( ('SH', 'Some high school'), ('HS', 'High school diploma'), ('SC', 'Some college'), ('CD', 'College degree'), ('MD', 'Master\'s degree'), ('PH','PhD or higher education'), ) GPA_CHOICES = ( ('1', '1.0-1.5'), ('2', '1.5-2.0'), ('3', '2.0-2.5'), ('4', '2.5-3.0'), ('5', '3.0-3.5'), ('6', '3.5-4.0'), ('7', '4.0-4.5'), ('8', '4.5-5.0'), ) ip = models.CharField(max_length=30) completed = models.BooleanField(default=False) created_time = models.DateTimeField(default=datetime.now) time_used = models.IntegerField(default=0, help_text='number of seconds used for test') age = models.PositiveIntegerField() gender = models.CharField(max_length=2, choices=GENDER_CHOICES) education = models.CharField(max_length=2, choices=EDUCATION_CHOICES) school = models.CharField(max_length=200) grad_year = models.PositiveIntegerField() gpa = models.CharField(max_length=2, choices=GPA_CHOICES) sat_verbal = models.PositiveIntegerField(blank=True) sat_math = models.PositiveIntegerField(blank=True) sat_writing = models.PositiveIntegerField(blank=True) sat_overall = models.PositiveIntegerField(blank=True) english_is_your_first_language = models.BooleanField() kerberos_name_if_applying_for_900_credit = models.CharField(max_length=200, blank=True) def __unicode__(self): return "[%s#%s]" % (self.ip, self.created_time) class TestSequence(models.Model): subject = models.ForeignKey(TestSubject) order = models.IntegerField(help_text='1..n') pt = models.ForeignKey(PassageText) time_used = models.IntegerField(default=0, help_text='number of seconds used for test') def __unicode__(self): return "[%s#%d]" % (self.subject, self.order) class QuestionSequence(models.Model): tseq = models.ForeignKey(TestSequence) order = models.IntegerField(help_text='0..n') question = models.ForeignKey(Question) selectedanswer = models.ForeignKey(AnswerOption, blank=True, null=True, default=None) def __unicode__(self): return "[%s#%d]" % (self.tseq, self.order) I want to essentially have a page that just gives me a table of all TestSubject objects (and all their properties) as well as a list of which passages they did and a count of how many questions they got right in that passage.
[ "Well, since no one has helped you yet, here:\n# *snip* -- view:\ncontext = { 'test_subjects' : TestSubject.objects.all() }\nreturn render_to_response('Template', context)\n# *snip*\n\n# *snip* -- template:\n{% for test_subject in test_subjects %}\n{{ test_subject.ip }}\n{# ... snip ... #}\n{% empty %}\nThere are no test subjects.\n{% endfor %}\n\nsecondly, it is more preferable to pass a list of \"things\" to a template and let it do the magic... unless you have some special reason not to do so. Passing them in as a string by \"converting\" and \"joining\" them in the view ruins the separation between data and code, and it makes your views \"dirty\".\nFor more information on this subject, read: Views, Templates and Models\nOn a side note, I think it would be better if you rethought some parts of your model design, I see some redundancy there. Storing the test subject's name would be a good and user friendly idea. Finally, shouldn't flavor be flavour? Even if you don't change it in your code, you might want to I18N it for British English speakers.\n" ]
[ 0 ]
[]
[]
[ "django", "object", "python", "templates", "views" ]
stackoverflow_0002368465_django_object_python_templates_views.txt
Q: Google App Engine: Basic Django Issue I'm using Django templating with Google App Engine. I'm trying unsuccessfully to print out a menu. The controller: menu_items = { 'menu_items': [ { 'href': '/', 'name': 'Home' }, { 'href': '/cart', 'name': 'Cart' } ], } render('Views/menu.html', self, {'menu_items': menu_items}) # ... def render(filename, main, template_values): path = os.path.join(os.path.dirname(__file__), filename) main.response.out.write(template.render(path, template_values)) menu.html: <ul> {% for page in menu_items %} <li><a href="{{page.href}}">{{page.name}}</a></li> {% endfor %} </ul> The HTML produced: <li><a href=""></a></li> What am I doing wrong here? A: menu_items = {'menu_items': [{'href': '/', 'name': 'Home'}, {'href': '/cart', 'name': 'Cart'}], } render('Views/menu.html', self, {'menu_items': menu_items}) Look at these lines carefully. menu_items (dictionary) has a key menu_items with a value having a type list. And you're passing menu_items (dict) to render, so for page in menu_items actually refers to 'menu_items' (key). Just change your code to look like: menu_items = [{'href': '/', 'name': 'Home'}, {'href': '/cart', 'name': 'Cart' }] and you're done...
Google App Engine: Basic Django Issue
I'm using Django templating with Google App Engine. I'm trying unsuccessfully to print out a menu. The controller: menu_items = { 'menu_items': [ { 'href': '/', 'name': 'Home' }, { 'href': '/cart', 'name': 'Cart' } ], } render('Views/menu.html', self, {'menu_items': menu_items}) # ... def render(filename, main, template_values): path = os.path.join(os.path.dirname(__file__), filename) main.response.out.write(template.render(path, template_values)) menu.html: <ul> {% for page in menu_items %} <li><a href="{{page.href}}">{{page.name}}</a></li> {% endfor %} </ul> The HTML produced: <li><a href=""></a></li> What am I doing wrong here?
[ "menu_items = {'menu_items': [{'href': '/', 'name': 'Home'},\n {'href': '/cart', 'name': 'Cart'}],\n }\nrender('Views/menu.html', self, {'menu_items': menu_items})\n\nLook at these lines carefully. menu_items (dictionary) has a key menu_items with a value having a type list. And you're passing menu_items (dict) to render, so for page in menu_items actually refers to 'menu_items' (key).\nJust change your code to look like:\nmenu_items = [{'href': '/', 'name': 'Home'}, {'href': '/cart', 'name': 'Cart' }]\n\nand you're done...\n" ]
[ 5 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0002368651_django_google_app_engine_python.txt
Q: I want my Python script to detect the version and quit gracefully in case of a mismatch I'd like to make it as general as possible - e.g. handle as many versions as possible. Since version 3 is not backwards compatible with version 2, I want to make sure that I use the right print statement. Please let me know if you have questions and feel free to share related knowledge having to do with dynamic logic based on what (e.g. libraries) is available. Suppose I have a script that will run under version 1.x, or 2.x, or 3.x only. Or a script which requires a library A or a library B. Thanks! EDIT: Now ... when it comes to Python (unlike .Net) some libraries like SciPy, Google App Engine keep you glued to particular version. On Linux, Mac Os you can switch between different Python installs on command line. This is why I want to avoid confusion - I want to remember which script is for which version of Python and what libraries it needs. I would rather have it fail in a human-readable way. A: The sys module also contains the version info (first available in version 2.0): import sys if sys.version_info[0] == 2: print("You are using Python 2.x") elif sys.version_info[0] == 3: print("You are using Python 3.x") A: In order to get around syntax errors you would have to use conditional imports, if you want to mix syntax between versions 2 and 3. # just psuedocode if version is x: import lib_x # contains version x implementation else: import lib_y # contains version y compatible implementation It is not advisable to try to maintain compatibility between python3 and older versions. That said, here are several ways of detecting the version of python being used: While not particularly human friendly, sys.hexversion will work across the widest variety of python versions, since it was added back in version 1.5.2: import sys if sys.hexversion == 0x20505f0: print "It's version 2.5.5!" You should be able to get version information from sys.version_info (added in python 2.0): import sys if sys.version_info[0] == 2: print "You are using version 2!" else: print "You are using version 1, because you would get SyntaxErrors if you were using 3!" Alternatively you could use the platform module, though that was introduced in python 2.3, and would not be available in older versions (assuming you even care about them): try: import platform if platform.python_version().startswith('2'): print "You're using python 2.x!" except ImportError, e: print "You're using something older than 2.3. Yuck." A: If the only issue is that you want to use the right print statement to avoid syntax errors, you can avoid the problem altogether by using the print() function in Python 2.6: if sys.version_info[0:2] == (2,6): # Or you could use try/except here from __future__ import print_function print("Now you can use print as a function regardless of whether you're on 2.6 or 3.x!") Of course, if you also want to support earlier versions of Python, this won't work. A: If you want to maintain a codebase that works with Python 2 and 3, you wouldn't try to make code that will run in both, which will be awkward and ugly and bugprone, you would write in Python 2 and use 2to3 to convert. (You can also write in Python 3 and use 3to2 to convert, but I believe that tool is less mature.) 2to3 is not perfect, but making Python 2 code that can be converted by it makes tons more sense than making Python 2 code that will run in a Python 3 interpretter. Edit: This was common wisdom in 2010, but turned out not to be the case. The thing to do is write a polyglot. 2to3 did not end up being all that useful Another option is Cython, a Python-like language that can be used to create C extension modules. Cython modules can be used with Python 2 and 3. When you support multiple versions of Python, it is generally better to directly check for the capability you want rather than to check a version number. Checking version numbers directly is fragile and indirect. For example, if I wanted code that would work with Python pre-2.5, I would say: try: any except NameError: def any(iterable): for item in iterable: if item: return True return False (note that this is prettymuch the only reason to catch NameError). Similarly, library availability would be checked by catching ImportError. Edit: There is a tons of tooling for abstracting this away by now. If you want a script to remember what version it is from, like you say, don't bother trying to support multiple versions at all. Put the proper version number binary in the shebang line and run the script based on that. A: FYI, if you ever want to port 2.x scripts to 3.x, you can use 2to3 source conversion tool. A: On Linux, Mac etc, you should use the standard first line: #!/usr/bin/env python2 or #!/usr/bin/env python2.6 or #!/usr/bin/env python3 On Windows, having such a first line is useful from a documentation point of view, even if Windows doesn't use it to choose the interpreter.
I want my Python script to detect the version and quit gracefully in case of a mismatch
I'd like to make it as general as possible - e.g. handle as many versions as possible. Since version 3 is not backwards compatible with version 2, I want to make sure that I use the right print statement. Please let me know if you have questions and feel free to share related knowledge having to do with dynamic logic based on what (e.g. libraries) is available. Suppose I have a script that will run under version 1.x, or 2.x, or 3.x only. Or a script which requires a library A or a library B. Thanks! EDIT: Now ... when it comes to Python (unlike .Net) some libraries like SciPy, Google App Engine keep you glued to particular version. On Linux, Mac Os you can switch between different Python installs on command line. This is why I want to avoid confusion - I want to remember which script is for which version of Python and what libraries it needs. I would rather have it fail in a human-readable way.
[ "The sys module also contains the version info (first available in version 2.0):\nimport sys\n\nif sys.version_info[0] == 2:\n print(\"You are using Python 2.x\")\nelif sys.version_info[0] == 3:\n print(\"You are using Python 3.x\")\n\n", "In order to get around syntax errors you would have to use conditional imports, if you want to mix syntax between versions 2 and 3.\n# just psuedocode\nif version is x:\n import lib_x # contains version x implementation\nelse:\n import lib_y # contains version y compatible implementation\n\nIt is not advisable to try to maintain compatibility between python3 and older versions. That said, here are several ways of detecting the version of python being used:\nWhile not particularly human friendly, sys.hexversion will work across the widest variety of python versions, since it was added back in version 1.5.2:\nimport sys\nif sys.hexversion == 0x20505f0:\n print \"It's version 2.5.5!\"\n\nYou should be able to get version information from sys.version_info (added in python 2.0):\nimport sys\nif sys.version_info[0] == 2:\n print \"You are using version 2!\"\nelse:\n print \"You are using version 1, because you would get SyntaxErrors if you were using 3!\"\n\nAlternatively you could use the platform module, though that was introduced in python 2.3, and would not be available in older versions (assuming you even care about them):\ntry:\n import platform\n if platform.python_version().startswith('2'):\n print \"You're using python 2.x!\"\nexcept ImportError, e:\n print \"You're using something older than 2.3. Yuck.\"\n\n", "If the only issue is that you want to use the right print statement to avoid syntax errors, you can avoid the problem altogether by using the print() function in Python 2.6:\nif sys.version_info[0:2] == (2,6): # Or you could use try/except here\n from __future__ import print_function\nprint(\"Now you can use print as a function regardless of whether you're on 2.6 or 3.x!\")\n\nOf course, if you also want to support earlier versions of Python, this won't work.\n", "\nIf you want to maintain a codebase that works with Python 2 and 3, you wouldn't try to make code that will run in both, which will be awkward and ugly and bugprone, you would write in Python 2 and use 2to3 to convert. (You can also write in Python 3 and use 3to2 to convert, but I believe that tool is less mature.) 2to3 is not perfect, but making Python 2 code that can be converted by it makes tons more sense than making Python 2 code that will run in a Python 3 interpretter. Edit: This was common wisdom in 2010, but turned out not to be the case. The thing to do is write a polyglot. 2to3 did not end up being all that useful\nAnother option is Cython, a Python-like language that can be used to create C extension modules. Cython modules can be used with Python 2 and 3.\nWhen you support multiple versions of Python, it is generally better to directly check for the capability you want rather than to check a version number. Checking version numbers directly is fragile and indirect.\nFor example, if I wanted code that would work with Python pre-2.5, I would say:\ntry: \n any\nexcept NameError:\n def any(iterable):\n for item in iterable:\n if item:\n return True\n return False\n\n(note that this is prettymuch the only reason to catch NameError). Similarly, library availability would be checked by catching ImportError. Edit: There is a tons of tooling for abstracting this away by now.\nIf you want a script to remember what version it is from, like you say, don't bother trying to support multiple versions at all. Put the proper version number binary in the shebang line and run the script based on that.\n\n", "FYI, if you ever want to port 2.x scripts to 3.x, you can use 2to3 source conversion tool.\n", "On Linux, Mac etc, you should use the standard first line:\n#!/usr/bin/env python2\n\nor\n#!/usr/bin/env python2.6\n\nor\n#!/usr/bin/env python3\n\nOn Windows, having such a first line is useful from a documentation point of view, even if Windows doesn't use it to choose the interpreter.\n" ]
[ 9, 8, 3, 3, 2, 2 ]
[]
[]
[ "python", "version" ]
stackoverflow_0002368574_python_version.txt
Q: python file manipulation I have a file with entries such as: 26 1 33 2 . . . and another file with sentences in english I have to write a script to print the 1st word in sentence number 26 and the 2nd word in sentence 33. How do I do it? A: The following code should do the task. With assumptions that files are not too large. You may have to do some modification to deal with edge cases (like double space, etc) # Get numers from file num = [] with open('1.txt') as file: num = file.readlines() # Get text from file text = [] with open('2.txt') as file: text = file.readlines() # Parse text into words list. data = [] for line in text: # For each paragraoh in the text sentences = l.strip().split('.') # Split it into sentences words = [] for sentence in sentences: # For each sentence in the text words = sentence.split(' ') # Split it into words list if len(words) > 0: data.append(words) # get desired result for i = range(0, len(num)/2): print data[num[i+1]][num[i]] A: Here's a general sketch: Read the first file into a list (a numeric entry in each element) Read the second file into a list (a sentence in each element) Iterate over the entry list, for each number find the sentence and print its relevant word Now, if you show some effort of how you tried to implement this in Python, you will probably get more help. A: The big issue is that you have to decide what separates "sentences". For example, is a '.' the end of a sentence? Or maybe part of an abbreviation, e.g. the one I've just used?-) Secondarily, and less difficult, what separates "words", e.g., is "TCP/IP" one word, or two? Once you have sharply defined these rules, you can easily read the file of text into a a list of "sentences" each of which is a list of "words". Then, you read the other file as a sequence of pairs of numbers, and use them as indices into the overall list and inside the sublist thus identified. But the problem of sentence and word separation is really the hard part. A: In the following code, I am assuming that sentences end with '. '. You can modify it easily to accommodate other sentence delimiters as well. Note that abbreviations will therefore be a source of bugs. Also, I am going to assume that words are delimited by spaces. sentences = [] queries = [] english = "" for line in file2: english += line while english: period = english.find('.') sentences += english[: period+1].split() english = english[period+1 :] q="" for line in file1: q += " " + line.strip() q = q.split() for i in range(0, len(q)-1, 2): sentence = q[i] word = q[i+1] queries.append((sentence, query)) for s, w in queries: print sentences[s-1][w-1] I haven't tested this, so please let me know (preferably with the case that broke it) if it doesn't work and I will look into bugs Hope this helps
python file manipulation
I have a file with entries such as: 26 1 33 2 . . . and another file with sentences in english I have to write a script to print the 1st word in sentence number 26 and the 2nd word in sentence 33. How do I do it?
[ "The following code should do the task. With assumptions that files are not too large. You may have to do some modification to deal with edge cases (like double space, etc)\n# Get numers from file\nnum = []\nwith open('1.txt') as file:\n num = file.readlines()\n\n# Get text from file \ntext = []\nwith open('2.txt') as file:\n text = file.readlines()\n\n# Parse text into words list.\ndata = []\nfor line in text: # For each paragraoh in the text\n sentences = l.strip().split('.') # Split it into sentences\n words = []\n for sentence in sentences: # For each sentence in the text\n words = sentence.split(' ') # Split it into words list\n if len(words) > 0:\n data.append(words)\n\n# get desired result\nfor i = range(0, len(num)/2):\n print data[num[i+1]][num[i]]\n\n", "Here's a general sketch:\n\nRead the first file into a list (a numeric entry in each element)\nRead the second file into a list (a sentence in each element)\nIterate over the entry list, for each number find the sentence and print its relevant word\n\nNow, if you show some effort of how you tried to implement this in Python, you will probably get more help.\n", "The big issue is that you have to decide what separates \"sentences\". For example, is a '.' the end of a sentence? Or maybe part of an abbreviation, e.g. the one I've just used?-) Secondarily, and less difficult, what separates \"words\", e.g., is \"TCP/IP\" one word, or two?\nOnce you have sharply defined these rules, you can easily read the file of text into a a list of \"sentences\" each of which is a list of \"words\". Then, you read the other file as a sequence of pairs of numbers, and use them as indices into the overall list and inside the sublist thus identified. But the problem of sentence and word separation is really the hard part.\n", "In the following code, I am assuming that sentences end with '. '. You can modify it easily to accommodate other sentence delimiters as well. Note that abbreviations will therefore be a source of bugs.\nAlso, I am going to assume that words are delimited by spaces.\nsentences = []\nqueries = []\nenglish = \"\"\n\nfor line in file2:\n english += line\nwhile english:\n period = english.find('.')\n sentences += english[: period+1].split()\n english = english[period+1 :]\nq=\"\"\nfor line in file1:\n q += \" \" + line.strip()\n\nq = q.split()\nfor i in range(0, len(q)-1, 2):\n sentence = q[i]\n word = q[i+1]\n queries.append((sentence, query))\n\nfor s, w in queries:\n print sentences[s-1][w-1]\n\nI haven't tested this, so please let me know (preferably with the case that broke it) if it doesn't work and I will look into bugs\nHope this helps\n" ]
[ 2, 1, 0, 0 ]
[]
[]
[ "file", "python", "string" ]
stackoverflow_0002368618_file_python_string.txt
Q: How do I drop a bash shell from within Python? i'm working on a python tcp shell; I'd like to be able to telnet to a port, and have it prompt me with a shell: ex. $ telnet localhost 5555 Connected to localhost. Escape character is '^]'. $ The answer below was quite helpful in getting me on my way. Here's the working code. import SocketServer, os, subprocess class EchoRequestHandler(SocketServer.BaseRequestHandler ): def setup(self): print self.client_address, 'connected!' self.request.send(str(self.client_address) + '\n') self.request.send(os.system('sh')) def handle(self): data = 'dummy' while data: data = self.request.recv(1024) self.request.send(os.popen(data.strip()).read()) if data.strip() == 'bye': return def finish(self): print self.client_address, 'disconnected!' self.request.send('bye ' + str(self.client_address) + '\n') server = SocketServer.ThreadingTCPServer(('', 7784), EchoRequestHandler) server.serve_forever() A: import os os.system('sh') # or bash, tcsh, zsh, whatever. :-P
How do I drop a bash shell from within Python?
i'm working on a python tcp shell; I'd like to be able to telnet to a port, and have it prompt me with a shell: ex. $ telnet localhost 5555 Connected to localhost. Escape character is '^]'. $ The answer below was quite helpful in getting me on my way. Here's the working code. import SocketServer, os, subprocess class EchoRequestHandler(SocketServer.BaseRequestHandler ): def setup(self): print self.client_address, 'connected!' self.request.send(str(self.client_address) + '\n') self.request.send(os.system('sh')) def handle(self): data = 'dummy' while data: data = self.request.recv(1024) self.request.send(os.popen(data.strip()).read()) if data.strip() == 'bye': return def finish(self): print self.client_address, 'disconnected!' self.request.send('bye ' + str(self.client_address) + '\n') server = SocketServer.ThreadingTCPServer(('', 7784), EchoRequestHandler) server.serve_forever()
[ "import os\nos.system('sh') # or bash, tcsh, zsh, whatever. :-P\n\n" ]
[ 9 ]
[]
[]
[ "python" ]
stackoverflow_0002368872_python.txt
Q: Google visualization api on app engine not working... (python) I'm trying to render the sortable table that's provided in Google visualization API in my app on app engine, but it's not working. The app is written in python and uses the django framework. When I copy the generated HTML/Javascript and save it as a plain html file locally, it works just fine. This leads me to believe that the problem is that http://www.google.com/jsapi'> is not getting included or is not able to run. Anyone else run into this? Am I missing some configuration piece in app.yaml? Thanks! EDIT: Here's the HTML that is being produced: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1 DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title> Test </title> <link href="/css/css.css" rel="stylesheet" type="text/css" /> <script type='text/javascript' src='http://www.google.com/jsapi'></script> <script type='text/javascript'> google.load('visualization', '1', {packages:['table']}); google.setOnLoadCallback(drawTable); function drawTable() { var data = new google.visualization.DataTable(); data.addColumn('string', 'Number'); data.addColumn('string', 'Status'); data.addColumn('string', 'Nickname'); data.addColumn('string', 'Target'); data.addColumn('string', 'Recording'); data.addRows(2); data.setCell(0, 0, '0987654321'); data.setCell(0, 1, 'Active'); data.setCell(0, 2, 'Nothing'); data.setCell(0, 3, '1234567890'); data.setCell(0, 4, 'Enabled'); data.setCell(1, 0, '0987654321'); data.setCell(1, 1, 'Active'); data.setCell(1, 2, 'Nothing'); data.setCell(1, 3, '1234567890'); data.setCell(1, 4, 'Enabled'); var table = new google.visualization.Table(document.getElementById('table_div')); table.draw(data, {showRowNumber: true}); } </script> </head> <body> <div id='table_div'></div> </body> </html> This works fine if saved as an html file. app.yaml: application: testapp version: 2 runtime: python api_version: 1 handlers: - url: /(.*\.(mp3|wav)) static_files: \1 upload: (.*\.(mp3|wav)) - url: /css static_dir: css - url: /.* script: main.py A: Wait, where are you doing the rendering? The visapi stuff goes in the client-side. Is that where you have it? (Sorry if that's obvious; it's really not entirely clear from the way you wrote the question.) More details would definitely help. A: In case anyone else has this issue - I messed up headers of the page generated by rendering with the same function I created for XML output. Including this killed it: handler.response.headers["Content-Type"] = "text/xml"
Google visualization api on app engine not working... (python)
I'm trying to render the sortable table that's provided in Google visualization API in my app on app engine, but it's not working. The app is written in python and uses the django framework. When I copy the generated HTML/Javascript and save it as a plain html file locally, it works just fine. This leads me to believe that the problem is that http://www.google.com/jsapi'> is not getting included or is not able to run. Anyone else run into this? Am I missing some configuration piece in app.yaml? Thanks! EDIT: Here's the HTML that is being produced: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1 DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title> Test </title> <link href="/css/css.css" rel="stylesheet" type="text/css" /> <script type='text/javascript' src='http://www.google.com/jsapi'></script> <script type='text/javascript'> google.load('visualization', '1', {packages:['table']}); google.setOnLoadCallback(drawTable); function drawTable() { var data = new google.visualization.DataTable(); data.addColumn('string', 'Number'); data.addColumn('string', 'Status'); data.addColumn('string', 'Nickname'); data.addColumn('string', 'Target'); data.addColumn('string', 'Recording'); data.addRows(2); data.setCell(0, 0, '0987654321'); data.setCell(0, 1, 'Active'); data.setCell(0, 2, 'Nothing'); data.setCell(0, 3, '1234567890'); data.setCell(0, 4, 'Enabled'); data.setCell(1, 0, '0987654321'); data.setCell(1, 1, 'Active'); data.setCell(1, 2, 'Nothing'); data.setCell(1, 3, '1234567890'); data.setCell(1, 4, 'Enabled'); var table = new google.visualization.Table(document.getElementById('table_div')); table.draw(data, {showRowNumber: true}); } </script> </head> <body> <div id='table_div'></div> </body> </html> This works fine if saved as an html file. app.yaml: application: testapp version: 2 runtime: python api_version: 1 handlers: - url: /(.*\.(mp3|wav)) static_files: \1 upload: (.*\.(mp3|wav)) - url: /css static_dir: css - url: /.* script: main.py
[ "Wait, where are you doing the rendering? The visapi stuff goes in the client-side. Is that where you have it? (Sorry if that's obvious; it's really not entirely clear from the way you wrote the question.)\nMore details would definitely help.\n", "In case anyone else has this issue - I messed up headers of the page generated by rendering with the same function I created for XML output.\nIncluding this killed it: handler.response.headers[\"Content-Type\"] = \"text/xml\" \n" ]
[ 0, 0 ]
[]
[]
[ "google_app_engine", "google_visualization", "python" ]
stackoverflow_0002290827_google_app_engine_google_visualization_python.txt
Q: Bad file descriptor error If I try executing the following code f = file('test','rb') fout = file('test.out','wb') for i in range(10): a = f.read(1) fout.write(a) f.close() f = fout f.seek(4) print f.read(4) Where 'test' is any arbitrary file, I get: Traceback (most recent call last): File "testbad.py", line 12, in <module> print f.read(4) IOError: [Errno 9] Bad file descriptor If however, I change just the fout line to use a temporary file: import tempfile f = file('test','rb') fout = tempfile.NamedTemporaryFile() for i in range(10): a = f.read(1) fout.write(a) f.close() f = fout f.seek(4) print f.read(4) There are no errors. Does anyone know why this is? I would have expected the first case to work, but I must be doing something wrong. Thanks in advance for any help! A: you've only opened the file fout for writing, not reading. To open for both use fout = file('test.out','r+b')
Bad file descriptor error
If I try executing the following code f = file('test','rb') fout = file('test.out','wb') for i in range(10): a = f.read(1) fout.write(a) f.close() f = fout f.seek(4) print f.read(4) Where 'test' is any arbitrary file, I get: Traceback (most recent call last): File "testbad.py", line 12, in <module> print f.read(4) IOError: [Errno 9] Bad file descriptor If however, I change just the fout line to use a temporary file: import tempfile f = file('test','rb') fout = tempfile.NamedTemporaryFile() for i in range(10): a = f.read(1) fout.write(a) f.close() f = fout f.seek(4) print f.read(4) There are no errors. Does anyone know why this is? I would have expected the first case to work, but I must be doing something wrong. Thanks in advance for any help!
[ "you've only opened the file fout for writing, not reading. To open for both use\nfout = file('test.out','r+b')\n\n" ]
[ 37 ]
[]
[]
[ "file", "python" ]
stackoverflow_0002368967_file_python.txt
Q: List fields present in a table Is there any way to to list out the fields present in a table in django models class Profile(models.Model): user = models.ForeignKey(User, unique=True) name = models.ForeignKey(School) emp = models.ForeignKey(User, unique=True) How to list out the filed names from the table Profile,(just like desc Profile; in mysql ) thanks. A: Profile._meta.fields will get you a list of fields. The name property of the field object contains the name of the field. Profile._meta.get_fields_with_model() will return a list of 2-tuples of (field, model), with model being None if the field is in Profile.
List fields present in a table
Is there any way to to list out the fields present in a table in django models class Profile(models.Model): user = models.ForeignKey(User, unique=True) name = models.ForeignKey(School) emp = models.ForeignKey(User, unique=True) How to list out the filed names from the table Profile,(just like desc Profile; in mysql ) thanks.
[ "Profile._meta.fields will get you a list of fields. The name property of the field object contains the name of the field. Profile._meta.get_fields_with_model() will return a list of 2-tuples of (field, model), with model being None if the field is in Profile.\n" ]
[ 19 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002368948_django_python.txt
Q: How do I know if jobs have been/are performing? - Crontab I have followed the suggestion in this question as I am using Django, I have set the script to store date and time of each run of the script in the db, but no entry has been stored yet in the database. Is there a way to figure out, other than typing "top" and searching through? A: First, I would probably configure cron to mail yourself any output by using MAILTO: In /etc/crontab: MAILTO=username Second, I usually add something to my script that (almost) cannot possibly fail, like the following: #!/bin/sh echo "$0 ran on `date +%c`" >> /tmp/crontab_test.log # ... rest of program If you're calling a python script directly from cron, you could do something similar or create a wrapper shell script. A: If you have sendmail installed, you can add the following to '/etc/aliases' root: your_name@domain.com After you do that, update the aliases running this command: sudo newaliases Cron will automatically email you every time a job is run. No need to specify that in the crontab file. Also, make sure you test your email capabilities (e.g. make sure you are able to send emails from the server) and lastly, create a trivial cronjob and test if you receive an email. Do not assume! A: In addition to setting up cron to send email, you can send the output of cron to a seperate syslog log facility by adding the following to your /etc/syslog.conf. # Log cron stuff cron.* /var/log/cron.log This should log a message to /var/log/cron.log each time a job is run.
How do I know if jobs have been/are performing? - Crontab
I have followed the suggestion in this question as I am using Django, I have set the script to store date and time of each run of the script in the db, but no entry has been stored yet in the database. Is there a way to figure out, other than typing "top" and searching through?
[ "First, I would probably configure cron to mail yourself any output by using MAILTO:\nIn /etc/crontab:\nMAILTO=username\n\nSecond, I usually add something to my script that (almost) cannot possibly fail, like the following:\n#!/bin/sh\necho \"$0 ran on `date +%c`\" >> /tmp/crontab_test.log\n\n# ... rest of program\n\nIf you're calling a python script directly from cron, you could do something similar or create a wrapper shell script.\n", "If you have sendmail installed, you can add the following to '/etc/aliases'\nroot: your_name@domain.com\nAfter you do that, update the aliases running this command:\nsudo newaliases\n\nCron will automatically email you every time a job is run. No need to specify that in the crontab file.\nAlso, make sure you test your email capabilities (e.g. make sure you are able to send emails from the server) and lastly, create a trivial cronjob and test if you receive an email.\nDo not assume!\n", "In addition to setting up cron to send email, you can send the output of cron to a seperate syslog log facility by adding the following to your /etc/syslog.conf.\n\n# Log cron stuff \ncron.* /var/log/cron.log \n\nThis should log a message to /var/log/cron.log each time a job is run.\n" ]
[ 5, 2, 1 ]
[]
[]
[ "crontab", "django", "linux", "python" ]
stackoverflow_0002367892_crontab_django_linux_python.txt
Q: xhtml/rst to excel conversion I am working on a reporting tool and need to generate reports in various formats including pdf, html and excel(.xls or any format which can be easily opened in excel) I am thinking of generating basic report in xhtml or restructuredtext(rst) and then converting it to other formats, I can use xhtml2pdf or rst2pdf for pdf conversion but I am not able to find any tool/library which can do xhtml or rst to excel conversion. Q1. Are there any rst or xhtml to excel converters? What are other alternatives? e.g. I am thinking of generating basic document as list of python objects and then convert them to pdf via reportlab or excel via xlwt(http://pypi.python.org/pypi/xlwt) Q2. Is there already any such python document model? Q3. How easy would be to generate rst and parse it to generate xls files using xlwt? A: For converting a dataset in XML (or XHTML) to Excel - I haven't done this myself, but MSDN provides an example XSLT (plus some irrelevant .NET code) for converting a sample dataset to Excel. It should not be too difficult, as the output is the XML format accepted by Excel.
xhtml/rst to excel conversion
I am working on a reporting tool and need to generate reports in various formats including pdf, html and excel(.xls or any format which can be easily opened in excel) I am thinking of generating basic report in xhtml or restructuredtext(rst) and then converting it to other formats, I can use xhtml2pdf or rst2pdf for pdf conversion but I am not able to find any tool/library which can do xhtml or rst to excel conversion. Q1. Are there any rst or xhtml to excel converters? What are other alternatives? e.g. I am thinking of generating basic document as list of python objects and then convert them to pdf via reportlab or excel via xlwt(http://pypi.python.org/pypi/xlwt) Q2. Is there already any such python document model? Q3. How easy would be to generate rst and parse it to generate xls files using xlwt?
[ "For converting a dataset in XML (or XHTML) to Excel -\nI haven't done this myself, but MSDN provides an example XSLT (plus some irrelevant .NET code) for converting a sample dataset to Excel. It should not be too difficult, as the output is the XML format accepted by Excel.\n" ]
[ 1 ]
[]
[]
[ "excel", "python", "restructuredtext", "xhtml", "xls" ]
stackoverflow_0002369230_excel_python_restructuredtext_xhtml_xls.txt
Q: how to geocode phone number I have a list of phone numbers with area code prefixes that I want to find a latitude/longitude location for. Is there a library (ideally Python) or service that can do this? A: You may be able to obtain limited free information (e.g. town) or, for a hefty fee, some relatively more detailed information (address), from various Whitepages-like providers. This should cover landlines as well as, to some degree, mobile (cell) lines. Be aware that in the case of mobile lines the information (billing address at best, BTW, not terminal location) may be sketchy or even misleading (the numbers can be registered to third-party companies which manages fleets of cell phones for businesses -- companies which may be registered at addresses completely different from those of the businesses using the fleet.) You would then have to resolve the street address to latitude/longitide, so it would be a two-step process. As for VoIP, you can read about GEOPRIV. Take a look inside this whitepages.com sample to see how they expect you to interact with their database (I doubt it's what you want, but it's what they offer.)
how to geocode phone number
I have a list of phone numbers with area code prefixes that I want to find a latitude/longitude location for. Is there a library (ideally Python) or service that can do this?
[ "You may be able to obtain limited free information (e.g. town) or, for a hefty fee, some relatively more detailed information (address), from various Whitepages-like providers. This should cover landlines as well as, to some degree, mobile (cell) lines. Be aware that in the case of mobile lines the information (billing address at best, BTW, not terminal location) may be sketchy or even misleading (the numbers can be registered to third-party companies which manages fleets of cell phones for businesses -- companies which may be registered at addresses completely different from those of the businesses using the fleet.) You would then have to resolve the street address to latitude/longitide, so it would be a two-step process. As for VoIP, you can read about GEOPRIV.\nTake a look inside this whitepages.com sample to see how they expect you to interact with their database (I doubt it's what you want, but it's what they offer.)\n" ]
[ 1 ]
[]
[]
[ "geocoding", "phone_number", "python" ]
stackoverflow_0002369340_geocoding_phone_number_python.txt
Q: Arguments in the middle of a string to be localized I'm a beginner in Python. My problem is pretty simple. I have a string to be localized in a python application containing parameters : print _('Hello dear user, your name is ') + params['first_name'] + ' ' + params['last_name'] + _(' and blah blah blah') This actually does the job, but is not really what I would call a nice way to do it. Not to mention that some languages would, for example, require the last name to be displayed before the first name. Is there a better way to do it ? I thought about placing custom tags like {{fn}} or {{ln}} in the translation string and replacing them by the actual values before displaying the string. But it seems not to be really more pleasant. Thanks, Pierre A: I'd suggest print 'Hello dear user, your name is %(first_name)s %(last_name)s' % params A: Something like this should do the trick : print _('Hello dear user, your name is %s %s and blah blah blah') % (params['first_name'], params['last_name']) A: I would go with templates if I were you. That would let you have a separate template for each language. For example: from string import Template s_en = Template('Hello dear user, your name is $first_name $last_name and blah blah blah') s_sco = Template('Hello, $first_name of the clan Mac$last_name...') user = {'last_name': 'Duncan', 'first_name': 'Leod'} print(s_en.substitute(user)) print(s_sco.substitute(user)) A: I thought about placing custom tags like {{fn}} or {{ln}} in the translation string and replacing them by the actual values before displaying them. That's what I would do. Placeholders in the right places for each language versions should do the job. One thing to mention that in some languages peoples names have to be modified dependent on where in a sentence and how they are used. You need to know each specific language to be able to do it correctly. A possible solution: keep "in the middle of a sentence" cases to a minimum. Keep a localizable resource separated. Instead of Hello dear user, your name is {{UserName}} use User name: {{UserName}}
Arguments in the middle of a string to be localized
I'm a beginner in Python. My problem is pretty simple. I have a string to be localized in a python application containing parameters : print _('Hello dear user, your name is ') + params['first_name'] + ' ' + params['last_name'] + _(' and blah blah blah') This actually does the job, but is not really what I would call a nice way to do it. Not to mention that some languages would, for example, require the last name to be displayed before the first name. Is there a better way to do it ? I thought about placing custom tags like {{fn}} or {{ln}} in the translation string and replacing them by the actual values before displaying the string. But it seems not to be really more pleasant. Thanks, Pierre
[ "I'd suggest \nprint 'Hello dear user, your name is %(first_name)s %(last_name)s' % params\n\n", "Something like this should do the trick :\nprint _('Hello dear user, your name is %s %s and blah blah blah') % (params['first_name'], params['last_name'])\n\n", "I would go with templates if I were you. That would let you have a separate template for each language. For example:\nfrom string import Template\ns_en = Template('Hello dear user, your name is $first_name $last_name and blah blah blah')\ns_sco = Template('Hello, $first_name of the clan Mac$last_name...')\n\nuser = {'last_name': 'Duncan', 'first_name': 'Leod'}\n\nprint(s_en.substitute(user))\nprint(s_sco.substitute(user))\n\n", "\nI thought about placing custom tags like {{fn}} or {{ln}} in the translation string and replacing them by the actual values before displaying them.\n\nThat's what I would do. Placeholders in the right places for each language versions should do the job.\nOne thing to mention that in some languages peoples names have to be modified dependent on where in a sentence and how they are used. You need to know each specific language to be able to do it correctly.\nA possible solution: keep \"in the middle of a sentence\" cases to a minimum. Keep a localizable resource separated.\nInstead of Hello dear user, your name is {{UserName}}\nuse User name: {{UserName}}\n" ]
[ 3, 1, 1, 0 ]
[]
[]
[ "internationalization", "python" ]
stackoverflow_0002370309_internationalization_python.txt
Q: How do I ensure I always get a list of matches from Python's Regular Expressions? I'm trying to pull some information (no recursion necessary) from a jsp page (malformed xml) similar to this: <td> <html:button ...></html:button> <html:submit ...></html:submit></td> And a regex: <html:(button|submit|cancel)[\s\S]*?</html:(button|submit|cancel)> re.findall() is giving me a list of tuples, like so: [('button','button'),('button','button')] Which I understand from the documentation is correct, but I'm looking to get something more like: ["<html:button ...>","<html:button ...>"] What is the appropriate way to get the outcome I expect? A: Aside from the fact that a regex probably isn't what you want to do this with, you want to put the bit you want in groups using parentheses. If you want everything up to the closing </html:whatever> tag, then you want something like this: (<html:(button|submit|cancel)[\s\S]*?)</html:(button|submit|cancel)> If you just want the <html:button> bit, use: (<html:(button|submit|cancel)>)[\s\S]*?</html:(button|submit|cancel)> e.g. from <html:button>foobar</html:submit> you get: ('<html:button>', 'button', 'submit') If you want to get the foobar from above, use: (<html:(button|submit|cancel)>)([\s\S]*?)</html:(button|submit|cancel)> to get: ('<html:button>', 'button', 'foobar', 'submit') Note that it is not, in general, possible to match opening and closing tags (note that <html:button> is opened, and </html:submit> closes in the example above). If you need to do that, use a proper parser. A: Your (button|submit|cancel) getting capture, so add ?: in brackets like (?: >>> re.findall('<html:(?:button|submit|cancel)[\s\S]*?</html:(?:button|submit|cancel)>',TheHTMLWhichShouldntParseWithRegex) ['<html:button ...></html:button>', '<html:submit ...></html:submit>']
How do I ensure I always get a list of matches from Python's Regular Expressions?
I'm trying to pull some information (no recursion necessary) from a jsp page (malformed xml) similar to this: <td> <html:button ...></html:button> <html:submit ...></html:submit></td> And a regex: <html:(button|submit|cancel)[\s\S]*?</html:(button|submit|cancel)> re.findall() is giving me a list of tuples, like so: [('button','button'),('button','button')] Which I understand from the documentation is correct, but I'm looking to get something more like: ["<html:button ...>","<html:button ...>"] What is the appropriate way to get the outcome I expect?
[ "Aside from the fact that a regex probably isn't what you want to do this with, you want to put the bit you want in groups using parentheses. If you want everything up to the closing </html:whatever> tag, then you want something like this:\n(<html:(button|submit|cancel)[\\s\\S]*?)</html:(button|submit|cancel)>\n\nIf you just want the <html:button> bit, use:\n(<html:(button|submit|cancel)>)[\\s\\S]*?</html:(button|submit|cancel)>\n\ne.g.\nfrom\n<html:button>foobar</html:submit>\n\nyou get:\n('<html:button>', 'button', 'submit')\n\nIf you want to get the foobar from above, use:\n(<html:(button|submit|cancel)>)([\\s\\S]*?)</html:(button|submit|cancel)>\n\nto get:\n('<html:button>', 'button', 'foobar', 'submit')\n\nNote that it is not, in general, possible to match opening and closing tags (note that <html:button> is opened, and </html:submit> closes in the example above). If you need to do that, use a proper parser.\n", "Your (button|submit|cancel) getting capture, so add ?: in brackets like (?:\n>>> re.findall('<html:(?:button|submit|cancel)[\\s\\S]*?</html:(?:button|submit|cancel)>',TheHTMLWhichShouldntParseWithRegex)\n['<html:button ...></html:button>', '<html:submit ...></html:submit>']\n\n" ]
[ 3, 1 ]
[]
[]
[ "findall", "python", "regex", "tuples" ]
stackoverflow_0002370369_findall_python_regex_tuples.txt
Q: best way to do this string conversion in Python I need to convert a string to another which has removed anything before the second word Example from this, string = "xyz anything else" string2 = "xyz anything else" string3 = "xyz anything else" to this, string = "anything else" string2 = "anything else" string3 = "anything else" The way I've done it doesnt please me at all, it isnt pythonic and it's too large. What it would be the best way to do it in Python? A: s.split(None, 1)[-1]
best way to do this string conversion in Python
I need to convert a string to another which has removed anything before the second word Example from this, string = "xyz anything else" string2 = "xyz anything else" string3 = "xyz anything else" to this, string = "anything else" string2 = "anything else" string3 = "anything else" The way I've done it doesnt please me at all, it isnt pythonic and it's too large. What it would be the best way to do it in Python?
[ "s.split(None, 1)[-1]\n\n" ]
[ 6 ]
[]
[]
[ "python" ]
stackoverflow_0002370974_python.txt
Q: How can I build a regular expression which has options part How can I build a regular expression in python which can match all the following? where it is a "string (a-zA-Z)" follow by a space follow by 1 or multiple 4 integers which separates by a comma: Example: someotherstring 42 1 48 17, somestring 363 1 46 17,363 1 34 17,401 3 8 14, otherstring 42 1 48 17,363 1 34 17, I have tried the following, since I need to know each integers: myRE=re.compile("(\s+) ((\d+) (\d+) (\d+) (\d+),)+" But how can I find out how many 4 integers I have? and how can I process each of them? Thank you. A: >>> test = "somestring 363 1 46 17,363 1 34 17,401 3 8 14," Here is a pyparsing processor for your input string: >>> from pyparsing import * >>> integer = Word(nums) >>> patt = Word(alphas) + OneOrMore(Group(integer*4 + Suppress(','))) Using patt.parseString returns a pyparsing ParseResults object, which has some nice list/dict/object properties. First, just printing out the results as a list: >>> patt.parseString(test).asList() ['somestring', ['363', '1', '46', '17'], ['363', '1', '34', '17'], ['401', '3', '8', '14']] See how each of your groups is grouped as a sublist? Now let's have the parser do a bit more work for us. At parse time, we already know we are parsing valid integers - anything matching Word(nums) has to be an integer. So we can add a parse action to do this conversion at parse time: >>> integer = Word(nums).setParseAction(lambda tokens:int(tokens[0])) Now, we recreate our pattern, and parsing now gives us groups of numbers: >>> patt = Word(alphas) + OneOrMore(Group(integer*4 + Suppress(','))) >>> patt.parseString(test).asList() ['somestring', [363, 1, 46, 17], [363, 1, 34, 17], [401, 3, 8, 14]] Lastly, we can also assign names to the bits parsed out of this input: >>> patt = Word(alphas)("desc") + OneOrMore(Group(integer*4 + Suppress(',')))("numgroups") The list of returned items is the same: >>> patt.parseString(test).asList() ['somestring', [363, 1, 46, 17], [363, 1, 34, 17], [401, 3, 8, 14]] But if we dump() the results, we see what we can access by name: >>> print patt.parseString(test).dump() ['somestring', [363, 1, 46, 17], [363, 1, 34, 17], [401, 3, 8, 14]] - desc: somestring - numgroups: [[363, 1, 46, 17], [363, 1, 34, 17], [401, 3, 8, 14]] We can use those names for dict-like or attribute-like access. I'm partial to the attribute style myself: >>> res = patt.parseString(test) >>> print res.desc somestring >>> print res.numgroups [[363, 1, 46, 17], [363, 1, 34, 17], [401, 3, 8, 14]] >>> for ng in res.numgroups: print sum(ng) ... 427 415 426 Here is the entire parser and output processor: test = "somestring 363 1 46 17,363 1 34 17,401 3 8 14," from pyparsing import * integer = Word(nums).setParseAction(lambda tokens:int(tokens[0])) patt = Word(alphas)("desc") + \ OneOrMore(Group(integer*4 + Suppress(',')))("numgroups") print patt.parseString(test).asList() print patt.parseString(test).dump() res = patt.parseString(test) print res.desc print res.numgroups for ng in res.numgroups: print sum(ng) A: As your data units (as I called them above) are separated by a comma AND a whitespace, you could still use split :) data = "someotherstring 42 1 48 17, somestring 363 1 46 17,363 1 34 17,401 3 8 14, otherstring 42 1 48 17,363 1 34 17" data_items = data.split(', ') for item in data_items: section_title, intdata = item.split(' ', 1) print 'Processing %s' % section_title for ints in intdata.split(','): a, b, c, d = [int(x) for x in ints.split()] # do your stuff ... A: import re str_in = "someotherstring 42 1 48 17, somestring 363 1 46 17,363 1 34 17,401 3 8 14, otherstring 42 1 48 17,363 1 34 17," list_out = re.split("[\\s,]", str_in) list_out then contains a list where the name of each section is followed by all the integers (still as strings), then a blank entry (useful for delimiting sections), and so on: ['someotherstring', '42', '1', '48', '17', '', 'somestring', '363', '1', '46', '17', '363', '1', '34', '17', '401', '3', '8', '14', '', 'otherstring', '42', '1', '48', '17', '363', '1', '34', '17', '']
How can I build a regular expression which has options part
How can I build a regular expression in python which can match all the following? where it is a "string (a-zA-Z)" follow by a space follow by 1 or multiple 4 integers which separates by a comma: Example: someotherstring 42 1 48 17, somestring 363 1 46 17,363 1 34 17,401 3 8 14, otherstring 42 1 48 17,363 1 34 17, I have tried the following, since I need to know each integers: myRE=re.compile("(\s+) ((\d+) (\d+) (\d+) (\d+),)+" But how can I find out how many 4 integers I have? and how can I process each of them? Thank you.
[ ">>> test = \"somestring 363 1 46 17,363 1 34 17,401 3 8 14,\"\n\nHere is a pyparsing processor for your input string:\n>>> from pyparsing import *\n>>> integer = Word(nums)\n>>> patt = Word(alphas) + OneOrMore(Group(integer*4 + Suppress(',')))\n\nUsing patt.parseString returns a pyparsing ParseResults object, which has some nice list/dict/object properties. First, just printing out the results as a list:\n>>> patt.parseString(test).asList()\n['somestring', ['363', '1', '46', '17'], ['363', '1', '34', '17'], ['401', '3', '8', '14']]\n\nSee how each of your groups is grouped as a sublist?\nNow let's have the parser do a bit more work for us. At parse time, we already know we are parsing valid integers - anything matching Word(nums) has to be an integer. So we can add a parse action to do this conversion at parse time:\n>>> integer = Word(nums).setParseAction(lambda tokens:int(tokens[0]))\n\nNow, we recreate our pattern, and parsing now gives us groups of numbers:\n>>> patt = Word(alphas) + OneOrMore(Group(integer*4 + Suppress(',')))\n>>> patt.parseString(test).asList()\n['somestring', [363, 1, 46, 17], [363, 1, 34, 17], [401, 3, 8, 14]]\n\nLastly, we can also assign names to the bits parsed out of this input:\n>>> patt = Word(alphas)(\"desc\") + OneOrMore(Group(integer*4 + Suppress(',')))(\"numgroups\")\n\nThe list of returned items is the same:\n>>> patt.parseString(test).asList()\n['somestring', [363, 1, 46, 17], [363, 1, 34, 17], [401, 3, 8, 14]]\n\nBut if we dump() the results, we see what we can access by name:\n>>> print patt.parseString(test).dump()\n['somestring', [363, 1, 46, 17], [363, 1, 34, 17], [401, 3, 8, 14]]\n- desc: somestring\n- numgroups: [[363, 1, 46, 17], [363, 1, 34, 17], [401, 3, 8, 14]]\n\nWe can use those names for dict-like or attribute-like access. I'm partial to the attribute style myself:\n>>> res = patt.parseString(test)\n>>> print res.desc\nsomestring\n>>> print res.numgroups\n[[363, 1, 46, 17], [363, 1, 34, 17], [401, 3, 8, 14]]\n>>> for ng in res.numgroups: print sum(ng)\n...\n427\n415\n426\n\nHere is the entire parser and output processor:\ntest = \"somestring 363 1 46 17,363 1 34 17,401 3 8 14,\"\nfrom pyparsing import *\ninteger = Word(nums).setParseAction(lambda tokens:int(tokens[0]))\npatt = Word(alphas)(\"desc\") + \\\n OneOrMore(Group(integer*4 + Suppress(',')))(\"numgroups\")\n\nprint patt.parseString(test).asList()\nprint patt.parseString(test).dump()\nres = patt.parseString(test)\nprint res.desc\nprint res.numgroups\nfor ng in res.numgroups: \n print sum(ng)\n\n", "As your data units (as I called them above) are separated by a comma AND a whitespace, you could still use split :)\ndata = \"someotherstring 42 1 48 17, somestring 363 1 46 17,363 1 34 17,401 3 8 14, otherstring 42 1 48 17,363 1 34 17\"\n\ndata_items = data.split(', ')\nfor item in data_items:\n section_title, intdata = item.split(' ', 1)\n print 'Processing %s' % section_title\n for ints in intdata.split(','):\n a, b, c, d = [int(x) for x in ints.split()]\n # do your stuff ...\n\n", "import re\nstr_in = \"someotherstring 42 1 48 17, somestring 363 1 46 17,363 1 34 17,401 3 8 14, otherstring 42 1 48 17,363 1 34 17,\"\nlist_out = re.split(\"[\\\\s,]\", str_in)\n\nlist_out then contains a list where the name of each section is followed by all the integers (still as strings), then a blank entry (useful for delimiting sections), and so on:\n['someotherstring', '42', '1', '48', '17', '', 'somestring', '363', '1', '46', '17', '363', '1', '34', '17', '401', '3', '8', '14', '', 'otherstring', '42', '1', '48', '17', '363', '1', '34', '17', '']\n\n" ]
[ 1, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002369346_python_regex.txt
Q: Unable to get set intersection to work Sorry for the double post, I will update this question if I can't get things to work :) I am trying to compare two files. I will list the two file content: File 1 File 2 "d.complex.1" "d.complex.1" 1 4 5 5 48 47 65 21 d.complex.10 d.complex.10 46 6 21 46 109 121 192 192 TI am trying to compare the contents of the two file but not in a trivial way. I will explain what I want with an example. If you observe the file content I have typed above, the d.complex.1 of file_1 has "5" similar to d.complex.1 in file_2; the same d.complex.1 in file_1 has nothing similar to d.complex.10 in file_2. What I am trying to do is just to print out those d.complex. which has nothing in similar with the other d.complex. Consider the d.complex. as a heading if you want. But all I am trying is compare the numbers below each d.complex. and if nothing matches, I want that particular d.complex. from both files to be printed. If even one number is present in both d.complex. of both files, I want it to be rejected. My Code: The method I chose to achieve this was to use sets and then do a difference. Code I wrote was: first_complex=open( "file1.txt", "r" ) first_complex_lines=first_complex.readlines() first_complex_lines=map( string.strip, first_complex_lines ) first_complex.close() second_complex=open( "file2.txt", "r" ) second_complex_lines=second_complex.readlines() second_complex_lines=map( string.strip, second_complex_lines ) second_complex.close() list_1=[] list_2=[] res_1=[] for line in first_complex_lines: if line.startswith( "d.complex" ): res_1.append( [] ) res_1[-1].append( line ) res_2=[] for line in second_complex_lines: if line.startswith( "d.complex" ): res_2.append( [] ) res_2[-1].append( line ) h=len( res_1 ) k=len( res_2 ) for i in res_1: for j in res_2: print i[0] print j[0] target_set=set ( i ) target_set_1=set( j ) for s in target_set: if s not in target_set_1: if s[0] != "d": print s The above code is giving an output like this (just an example): d.complex.1.dssp d.complex.1.dssp 1 48 65 d.complex.1.dssp d.complex.10.dssp 46 21 109 What I would like to have is: d.complex.1 d.complex.1 (name from file2) d.complex.1 d.complex.10 (name from file2) I am sorry for confusing you guys, but this is all that is required. I am so new to python so my concept above might be flawed. Also I have never used sets before :(. Can someone give me a hand here? A: The problem is that you are using the intersection instead of the difference :) If you use target_set.difference(target_set_1) you will have the results you're looking for. I'm not sure if I'm completely getting what you want, but is this what you are looking for? def complex_file_to_dict(filename): out = dict() for line in open(filename): line = line.strip() if line.startswith('d.complex'): name = line out[name] = set() elif line: out[name].add(line) return out res_1 = complex_file_to_dict('a.txt') res_2 = complex_file_to_dict('b.txt') for k, set_1 in res_1.iteritems(): print k set_2 = res_2.get(k, set()) for v in set_1 - set_2: print v print A: You need to use difference instead of intersection, since the latter will give you items that are in both sets. You can also use the set1 - set2 syntax. See the python docs for sets. I think you're after this (thanks to Rick for the original code): def complex_file_to_dict(filename): out = dict() for line in open(filename): line = line.strip() if line.startswith('d.complex'): name = line out[name] = set() elif line: out[name].add(line) return out res_1 = complex_file_to_dict('file1.txt') res_2 = complex_file_to_dict('file2.txt') for k1, set_1 in res_1.iteritems(): for k2, set_2 in res_2.iteritems(): print k1 print k2 for v in set_1 - set_2: print v print EDIT: You can change the loop to this: for k1, set_1 in res_1.iteritems(): for k2, set_2 in res_2.iteritems(): print k1 print k2, l = [v for v in set_1 - set_2] print '(' + ', '.join(l) + ')' to get the output like this: d.complex.1 d.complex.1 (1, 65, 48) d.complex.1 d.complex.10 (1, 65, 48) d.complex.10 d.complex.1 (46, 109, 192) d.complex.10 d.complex.10 (109, 21)
Unable to get set intersection to work
Sorry for the double post, I will update this question if I can't get things to work :) I am trying to compare two files. I will list the two file content: File 1 File 2 "d.complex.1" "d.complex.1" 1 4 5 5 48 47 65 21 d.complex.10 d.complex.10 46 6 21 46 109 121 192 192 TI am trying to compare the contents of the two file but not in a trivial way. I will explain what I want with an example. If you observe the file content I have typed above, the d.complex.1 of file_1 has "5" similar to d.complex.1 in file_2; the same d.complex.1 in file_1 has nothing similar to d.complex.10 in file_2. What I am trying to do is just to print out those d.complex. which has nothing in similar with the other d.complex. Consider the d.complex. as a heading if you want. But all I am trying is compare the numbers below each d.complex. and if nothing matches, I want that particular d.complex. from both files to be printed. If even one number is present in both d.complex. of both files, I want it to be rejected. My Code: The method I chose to achieve this was to use sets and then do a difference. Code I wrote was: first_complex=open( "file1.txt", "r" ) first_complex_lines=first_complex.readlines() first_complex_lines=map( string.strip, first_complex_lines ) first_complex.close() second_complex=open( "file2.txt", "r" ) second_complex_lines=second_complex.readlines() second_complex_lines=map( string.strip, second_complex_lines ) second_complex.close() list_1=[] list_2=[] res_1=[] for line in first_complex_lines: if line.startswith( "d.complex" ): res_1.append( [] ) res_1[-1].append( line ) res_2=[] for line in second_complex_lines: if line.startswith( "d.complex" ): res_2.append( [] ) res_2[-1].append( line ) h=len( res_1 ) k=len( res_2 ) for i in res_1: for j in res_2: print i[0] print j[0] target_set=set ( i ) target_set_1=set( j ) for s in target_set: if s not in target_set_1: if s[0] != "d": print s The above code is giving an output like this (just an example): d.complex.1.dssp d.complex.1.dssp 1 48 65 d.complex.1.dssp d.complex.10.dssp 46 21 109 What I would like to have is: d.complex.1 d.complex.1 (name from file2) d.complex.1 d.complex.10 (name from file2) I am sorry for confusing you guys, but this is all that is required. I am so new to python so my concept above might be flawed. Also I have never used sets before :(. Can someone give me a hand here?
[ "The problem is that you are using the intersection instead of the difference :)\nIf you use target_set.difference(target_set_1) you will have the results you're looking for.\nI'm not sure if I'm completely getting what you want, but is this what you are looking for?\ndef complex_file_to_dict(filename):\n out = dict()\n for line in open(filename):\n line = line.strip()\n if line.startswith('d.complex'):\n name = line\n out[name] = set()\n elif line:\n out[name].add(line)\n\n return out\n\nres_1 = complex_file_to_dict('a.txt')\nres_2 = complex_file_to_dict('b.txt')\n\nfor k, set_1 in res_1.iteritems():\n print k\n set_2 = res_2.get(k, set())\n for v in set_1 - set_2:\n print v\n print\n\n", "You need to use difference instead of intersection, since the latter will give you items that are in both sets. You can also use the set1 - set2 syntax. See the python docs for sets.\nI think you're after this (thanks to Rick for the original code):\ndef complex_file_to_dict(filename):\n out = dict()\n for line in open(filename):\n line = line.strip()\n if line.startswith('d.complex'):\n name = line\n out[name] = set()\n elif line:\n out[name].add(line)\n\n return out\n\nres_1 = complex_file_to_dict('file1.txt')\nres_2 = complex_file_to_dict('file2.txt')\n\nfor k1, set_1 in res_1.iteritems():\n for k2, set_2 in res_2.iteritems():\n print k1\n print k2\n for v in set_1 - set_2:\n print v\n print\n\nEDIT:\nYou can change the loop to this:\nfor k1, set_1 in res_1.iteritems():\n for k2, set_2 in res_2.iteritems():\n print k1\n print k2,\n l = [v for v in set_1 - set_2]\n print '(' + ', '.join(l) + ')'\n\nto get the output like this:\nd.complex.1\nd.complex.1 (1, 65, 48)\nd.complex.1\nd.complex.10 (1, 65, 48)\nd.complex.10\nd.complex.1 (46, 109, 192)\nd.complex.10\nd.complex.10 (109, 21)\n\n" ]
[ 2, 1 ]
[]
[]
[ "compare", "loops", "python", "set" ]
stackoverflow_0002371405_compare_loops_python_set.txt
Q: How to append EOF to file using Perl or Python? I’m trying to bulk insert data to SQL server express database. When doing bcp from Windows XP command prompt, I get the following error: C:\temp>bcp in -T -f -S Starting copy... SQLState = S1000, NativeError = 0 Error = [Microsoft][SQL Native Client]Unexpected EOF encountered in BCP data-file 0 rows copied. Network packet size (bytes): 4096 Clock Time (ms.) Total : 4391 So, there is a problem with EOF. How to append a correct EOF character to this file using Perl or Python? A: EOF is End Of File. What probably occurred is that the file is not complete; the software expects data, but there is none to be had anymore. These kinds of things happen when: the export is interrupted (quit dump software while dumping) while copying the dumpfile aborting the copy disk full during dump these kinds of things. By the way, though EOF is usually just an end of file, there does exist an EOF character. This is used because terminal (command line) input doesn't really end like a file does, but it sometimes is necessary to pass an EOF to such a utility. I don't think it's used in real files, at least not to indicate an end of file. The file system knows perfectly well when the file has ended, it doesn't need an indicator to find that out. EDIT shamelessly copied from a comment provided by John Machin It can happen (uninentionally) in real files. All it needs is (1) a data-entry user to type Ctrl-Z by mistake, see nothing on the screen, type the intended Shift-Z, and keep going and (2) validation software (written by e.g. the company president's nephew) which happily accepts Ctrl-anykey in text fields and your database has a little bomb in it, just waiting for someone to produce a query to a flat file. A: Unexpected EOF means that the bcp reader found an EOF when it was expecting more data. This EOF can be: (1) the actual physical end-of-file (no more bytes to be read). This means that you have mis-formatted data. Check near the end of your file for an incomplete record. OR (2) on Windows, where you are, programs reading a file in text mode honour the ancient convention inherited via MS-DOS from CP/M of regarding Ctrl-Z (aka ^Z aka \'x1A' aka SUB aka SUBSTITUTE) as an end-of-file marker when reading from ANY file, not just a terminal. This includes Python -- the behaviour is determined by the C stdlib. Check for '\x1A' in your data. Update responding to comments in a legible fashion: In Notepad++, you can make it display unusual characters by doing View / Show Symbol / Show All Characters. You can search by doing Ctrl-F, typing \x1a in the Find What box, and selecting the Extended radio button in the Search panel. Or you can with a little bit of Python get the line number of the first Ctrl-Z: bytes = open('bcp.dat', 'rb').read() zpos = bytes.find('\x1a') # if zpos is -1, no Ctrl-Z in file print 1 + bytes[:zpos].count('\r\n') Where your .dat was created doesn't matter. An unintentional Ctrl-Z can happen anywhere in a file created on any operating system. It is where it is being read as a text file that matters -- Windows? Bang! A: This is not a problem with missing EOF, but with EOF that is there and is not expected by bcp. I am not a bcp tool expert, but it looks like there is some problem with format of your data files.
How to append EOF to file using Perl or Python?
I’m trying to bulk insert data to SQL server express database. When doing bcp from Windows XP command prompt, I get the following error: C:\temp>bcp in -T -f -S Starting copy... SQLState = S1000, NativeError = 0 Error = [Microsoft][SQL Native Client]Unexpected EOF encountered in BCP data-file 0 rows copied. Network packet size (bytes): 4096 Clock Time (ms.) Total : 4391 So, there is a problem with EOF. How to append a correct EOF character to this file using Perl or Python?
[ "EOF is End Of File. What probably occurred is that the file is not complete; the software expects data, but there is none to be had anymore.\nThese kinds of things happen when:\n\nthe export is interrupted (quit dump software while dumping)\nwhile copying the dumpfile aborting the copy\ndisk full during dump\n\nthese kinds of things. \nBy the way, though EOF is usually just an end of file, there does exist an EOF character. This is used because terminal (command line) input doesn't really end like a file does, but it sometimes is necessary to pass an EOF to such a utility. I don't think it's used in real files, at least not to indicate an end of file. The file system knows perfectly well when the file has ended, it doesn't need an indicator to find that out.\nEDIT shamelessly copied from a comment provided by John Machin\nIt can happen (uninentionally) in real files. All it needs is (1) a data-entry user to type Ctrl-Z by mistake, see nothing on the screen, type the intended Shift-Z, and keep going and (2) validation software (written by e.g. the company president's nephew) which happily accepts Ctrl-anykey in text fields and your database has a little bomb in it, just waiting for someone to produce a query to a flat file. \n", "Unexpected EOF means that the bcp reader found an EOF when it was expecting more data. This EOF can be:\n(1) the actual physical end-of-file (no more bytes to be read). This means that you have mis-formatted data. Check near the end of your file for an incomplete record.\nOR\n(2) on Windows, where you are, programs reading a file in text mode honour the ancient convention inherited via MS-DOS from CP/M of regarding Ctrl-Z (aka ^Z aka \\'x1A' aka SUB aka SUBSTITUTE) as an end-of-file marker when reading from ANY file, not just a terminal. This includes Python -- the behaviour is determined by the C stdlib. Check for '\\x1A' in your data.\nUpdate responding to comments in a legible fashion:\nIn Notepad++, you can make it display unusual characters by doing View / Show Symbol / Show All Characters. You can search by doing Ctrl-F, typing \\x1a in the Find What box, and selecting the Extended radio button in the Search panel.\nOr you can with a little bit of Python get the line number of the first Ctrl-Z:\nbytes = open('bcp.dat', 'rb').read()\nzpos = bytes.find('\\x1a')\n# if zpos is -1, no Ctrl-Z in file\nprint 1 + bytes[:zpos].count('\\r\\n')\n\nWhere your .dat was created doesn't matter. An unintentional Ctrl-Z can happen anywhere in a file created on any operating system. It is where it is being read as a text file that matters -- Windows? Bang!\n", "This is not a problem with missing EOF, but with EOF that is there and is not expected by bcp.\nI am not a bcp tool expert, but it looks like there is some problem with format of your data files.\n" ]
[ 3, 3, 1 ]
[]
[]
[ "bcp", "perl", "python", "sql_server" ]
stackoverflow_0002371645_bcp_perl_python_sql_server.txt
Q: Python: Get system calendar format Is it possible to return the current system calendar format using Python? For example non-Gregorian calendar formats such as the Thai Buddhist calendar. A: Under windows?...for this approach you'll need to get the win32api package from here, here's a quick script to read the registry key that holds the default calendar type for the system, but each user has their own key as well, so you may have to dynamically check. This gets the iCalendarType key value which you find out more about here... Here's some code to get the value: import win32api import win32con def ReadRegistryValue(hiveKey, key, name=""): data = typeId = None try: keyHandle = win32api.RegOpenKeyEx(hiveKey, key, 0, win32con.KEY_ALL_ACCESS) data, typeId = win32api.RegQueryValueEx(keyHandle, name) win32api.RegCloseKey(keyHandle) except Exception, e: print "ReadRegistryValue failed:", hiveKey, key, name, e return "Registry Key Value is: " + data print ReadRegistryValue(win32con.HKEY_USERS,".DEFAULT\\Control Panel\\International","iCalendarType") Now....what does the value mean other than one(1)? That I couldn't find anywhere, but hopefully this gets you on the right path...
Python: Get system calendar format
Is it possible to return the current system calendar format using Python? For example non-Gregorian calendar formats such as the Thai Buddhist calendar.
[ "Under windows?...for this approach you'll need to get the win32api package from here, here's a quick script to read the registry key that holds the default calendar type for the system, but each user has their own key as well, so you may have to dynamically check. \nThis gets the iCalendarType key value which you find out more about here...\nHere's some code to get the value:\nimport win32api\nimport win32con\n\ndef ReadRegistryValue(hiveKey, key, name=\"\"):\n\n data = typeId = None\n try:\n keyHandle = win32api.RegOpenKeyEx(hiveKey, key, 0, win32con.KEY_ALL_ACCESS)\n data, typeId = win32api.RegQueryValueEx(keyHandle, name)\n win32api.RegCloseKey(keyHandle)\n except Exception, e:\n print \"ReadRegistryValue failed:\", hiveKey, key, name, e\n return \"Registry Key Value is: \" + data\n\n\nprint ReadRegistryValue(win32con.HKEY_USERS,\".DEFAULT\\\\Control Panel\\\\International\",\"iCalendarType\")\n\nNow....what does the value mean other than one(1)? That I couldn't find anywhere, but hopefully this gets you on the right path...\n" ]
[ 1 ]
[]
[]
[ "calendar", "internationalization", "python" ]
stackoverflow_0002369332_calendar_internationalization_python.txt
Q: Open a second window in PyQt I'm trying to use pyqt to show a custom QDialog window when a button on a QMainWindow is clicked. I keep getting the following error: $ python main.py DEBUG: Launch edit window Traceback (most recent call last): File "/home/james/Dropbox/Database/qt/ui_med.py", line 23, in launchEditWindow dialog = Ui_Dialog(c) File "/home/james/Dropbox/Database/qt/ui_edit.py", line 15, in __init__ QtGui.QDialog.__init__(self) TypeError: descriptor '__init__' requires a 'sip.simplewrapper' object but received a 'Ui_Dialog' I've gone over several online tutorials, but most of them stop just short of showing how to use a non built-in dialog window. I generated the code for both the main window and the dialog using pyuic4. What I think should be the relevant code is below. What am I missing here? class Ui_Dialog(object): def __init__(self, dbConnection): QtGui.QDialog.__init__(self) global c c = dbConnection class Ui_MainWindow(object): def __init__(self, dbConnection): global c c = dbConnection def launchEditWindow(self): print "DEBUG: Launch edit window" dialog = QtGui.QDialog() dialogui = Ui_Dialog(c) dialogui = setupUi(dialog) dialogui.show() class StartQT4(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) conn = sqlite3.connect('meds.sqlite') c = conn.cursor() self.ui = Ui_MainWindow(c) self.ui.setupUi(self) def main(): app = QtGui.QApplication(sys.argv) program = StartQT4() program.show() sys.exit(app.exec_()) if __name__ == '__main__': main() Bonus question: since it looks like you can't pass arguments in pyqt function callbacks, is setting something which would otherwise be passed as an argument (the poorly named "c") to be global the best way to get information into those functions? A: I've done like this in the past, and i can tell it works. assuming your button is called "Button" class Main(QtGui.QMainWindow): ''' some stuff ''' def on_Button_clicked(self, checked=None): if checked==None: return dialog = QDialog() dialog.ui = Ui_MyDialog() dialog.ui.setupUi(dialog) dialog.setAttribute(QtCore.Qt.WA_DeleteOnClose) dialog.exec_() This works for my application, and I believe it should work with yours as well. hope it'll help, it should be pretty straight forward to do the few changes needed to apply it to your case. have a good day everybody. A: Ui_Dialog should inherent from QtGui.QDialog, not object. class Ui_Dialog(QtGui.QDialog): def __init__(self, dbConnection): QtGui.QDialog.__init__(self) global c c = dbConnection A: class StartQT4(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) Why QtGui.QWidget.__init___ ??? Use insted: class StartQT4(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QMainWindow.__init__(self, parent) You must call __init__ methon from base class (name in parenthesis '()') QDialog have two useful routins: exec_() show() First wait for closing dialog and then you can access any field form dialog. Second show dialog but don't wait, so to work properly you must set some slot/signals connections to respond for dialog actions. eg. for exec_(): class Dialog(QDialog): def __init__(self, parent): QDialog.__init__(parent) line_edit = QLineEdit() ... dialog = Dialog() if dialog.exec_(): # here dialog will be shown and main script will wait for its closing (with no errors) data = dialog.line_edit.text() Small tip: can you change your ui classes into widgets (with layouts). And perhaps problem is that your __init__ should be __init__(self, parent=None, dbConnection) Because when you create new widget in existing one PyQt may try to set it as children of existing one. (So change all init to have additional parent param (must be on second position)).
Open a second window in PyQt
I'm trying to use pyqt to show a custom QDialog window when a button on a QMainWindow is clicked. I keep getting the following error: $ python main.py DEBUG: Launch edit window Traceback (most recent call last): File "/home/james/Dropbox/Database/qt/ui_med.py", line 23, in launchEditWindow dialog = Ui_Dialog(c) File "/home/james/Dropbox/Database/qt/ui_edit.py", line 15, in __init__ QtGui.QDialog.__init__(self) TypeError: descriptor '__init__' requires a 'sip.simplewrapper' object but received a 'Ui_Dialog' I've gone over several online tutorials, but most of them stop just short of showing how to use a non built-in dialog window. I generated the code for both the main window and the dialog using pyuic4. What I think should be the relevant code is below. What am I missing here? class Ui_Dialog(object): def __init__(self, dbConnection): QtGui.QDialog.__init__(self) global c c = dbConnection class Ui_MainWindow(object): def __init__(self, dbConnection): global c c = dbConnection def launchEditWindow(self): print "DEBUG: Launch edit window" dialog = QtGui.QDialog() dialogui = Ui_Dialog(c) dialogui = setupUi(dialog) dialogui.show() class StartQT4(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) conn = sqlite3.connect('meds.sqlite') c = conn.cursor() self.ui = Ui_MainWindow(c) self.ui.setupUi(self) def main(): app = QtGui.QApplication(sys.argv) program = StartQT4() program.show() sys.exit(app.exec_()) if __name__ == '__main__': main() Bonus question: since it looks like you can't pass arguments in pyqt function callbacks, is setting something which would otherwise be passed as an argument (the poorly named "c") to be global the best way to get information into those functions?
[ "I've done like this in the past, and i can tell it works.\nassuming your button is called \"Button\"\nclass Main(QtGui.QMainWindow):\n ''' some stuff '''\n def on_Button_clicked(self, checked=None):\n if checked==None: return\n dialog = QDialog()\n dialog.ui = Ui_MyDialog()\n dialog.ui.setupUi(dialog)\n dialog.setAttribute(QtCore.Qt.WA_DeleteOnClose)\n dialog.exec_()\n\nThis works for my application, and I believe it should work with yours as well. hope it'll help, it should be pretty straight forward to do the few changes needed to apply it to your case.\nhave a good day everybody.\n", "Ui_Dialog should inherent from QtGui.QDialog, not object.\nclass Ui_Dialog(QtGui.QDialog):\n def __init__(self, dbConnection):\n QtGui.QDialog.__init__(self)\n global c\n c = dbConnection\n\n", "class StartQT4(QtGui.QMainWindow):\n def __init__(self, parent=None):\n QtGui.QWidget.__init__(self, parent)\n\nWhy QtGui.QWidget.__init___ ???\nUse insted:\nclass StartQT4(QtGui.QMainWindow):\n def __init__(self, parent=None):\n QtGui.QMainWindow.__init__(self, parent)\n\nYou must call __init__ methon from base class (name in parenthesis '()')\nQDialog have two useful routins:\nexec_()\nshow()\n\nFirst wait for closing dialog and then you can access any field form dialog. Second show dialog but don't wait, so to work properly you must set some slot/signals connections to respond for dialog actions.\neg. for exec_():\nclass Dialog(QDialog):\n def __init__(self, parent):\n QDialog.__init__(parent)\n line_edit = QLineEdit()\n ...\n\ndialog = Dialog()\nif dialog.exec_(): # here dialog will be shown and main script will wait for its closing (with no errors)\n data = dialog.line_edit.text()\n\nSmall tip: can you change your ui classes into widgets (with layouts). And perhaps problem is that your __init__ should be __init__(self, parent=None, dbConnection)\nBecause when you create new widget in existing one PyQt may try to set it as children of existing one. (So change all init to have additional parent param (must be on second position)).\n" ]
[ 19, 3, 1 ]
[]
[]
[ "dialog", "pyqt", "python" ]
stackoverflow_0001807299_dialog_pyqt_python.txt
Q: function not defined but really is defined I am writing a script and in my script I have this function: def insert_image(cursor, object_id, sku): product_obj = core.Object.get(object_id) string_sku = str(sku) folder = string_sku[0] + string_sku[1] + string_sku[2] found_url = False # KLUDGE This is ugly and redundant, however putting this in an if elif elif else throws error when url not found # try this url first try urllib.urlopen("http://<path to images>/%s/%sPR-IT,PM.jpg" % (folder, sku)): urllib.URLopener().retrieve("http://<path to images>/%s/%sPR-IT,PM.jpg" % (folder, sku), "%sPR-IT,PM.jpg" % (sku)) found_url = True except: found_url = False # If that one didn't work try this one if found_url == False: try urllib.urlopen("http://<path to images>/%s/%sPK-PT,PM.jpg" % (folder, sku)): urllib.URLopener().retrieve("http://<path to images>/%s/%sPK-PT,PM.jpg" % (folder, sku), "%sPK-PT,PM.jpg" % (sku)) found_url = True except: found_url = False # If still nothing, one last attempt if found_url == False: try urllib.urlopen("http://<path to images>/%s/%sCC-PT,IM.jpg" % (folder, sku)): urllib.URLopener().retrieve("http://<path to images>/%s/%sCC-PT,IM.jpg" % (folder, sku), "%sCC-PT,IM.jpg" % (sku)) found_url = True except: found_url = False # We failed to find an image for this product, it will have to be done manually if found_url == False: log.info("Could not find the image on notions") return False # Hey we found something! Open the image.... send_image = open('%sPK-PT,PM.jpg' % sku, 'r') # ...and send it for processing if product_obj.set_image(send_image, 5, 1) == False: return False else: log.debug("Inserted Image") return True This worked fine until I added the try catches. I did have the if, elif, the function ran just fine. Here is my call and the peice of code that runs right before it: if rollback == False: # Nah -- it's all good SAVE IT! count += 1 log.debug("INSERT %s" % count) conn.commit() else: # Yeah something went wrong, errors reported why, roll it back conn.rollback() log.debug("skipped %s" % skip_count) # Insert images if rollback == False: sku = row[0] if insert_image(cursor, object_id, sku) == False: log.error("Could not get the image inserted for product: %s" % object_id) conn.rollback() else: conn.commit() My error is: 16:33:46,153 DEBUG [pylons-admin] Inserted Description 16:33:46,164 DEBUG [pylons-admin] Inserted Attributes 16:33:46,164 DEBUG [pylons-admin] INSERT 1 Traceback (most recent call last): File "<console>", line 47, in <module> NameError: name 'insert_image' is not defined I don't know what line 47 means because the call is on line 2101, again before I added the trys, it found the function just fine. I also switched the first commit to be before the insert_image call when I added the trys like you see now, before the commit was after we called insert_image. I checked indents, and spaces, and tabs w/ no avail. I use TextMate, when I run the script from TextMate, I get a syntax error here: try urllib.urlopen("http://<path to images>/%s/%sPR-IT,PM.jpg" % (folder, sku)): It points to the ( on (folder... But I don't see where I have a syntax error. Please help. I have been working on this script for a couple of weeks now, this was supposed to be the last run to test and call it finished :( A: You have syntax errors in your function: try urllib.urlopen("http://<path to images>/%s/%sPR-IT,PM.jpg" % (folder, sku)): urllib.URLopener().retrieve("http://<path to images>/%s/%sPR-IT,PM.jpg" % (folder, sku), "%sPR-IT,PM.jpg" % (sku)) found_url = True except: found_url = False It should be: try: urllib.urlopen("http://<path to images>/%s/%sPR-IT,PM.jpg" % (folder, sku)): urllib.URLopener().retrieve("http://<path to images>/%s/%sPR-IT,PM.jpg" % (folder, sku), "%sPR-IT,PM.jpg" % (sku)) found_url = True except: found_url = False You also have some broad catches, that catch those SyntaxErrors and hide errors, but insert_image is not defined this way. Never use alone except:, always put name of the Exception, that you want to catch. Otherwise you will also catch things like SyntaxError and this is very dangerous. A: This sounds like you have a whitespace issue before the method. The incorrect whitespace has moved it outside of the normal code path and if it is in a class it may not appear to be in the class any more
function not defined but really is defined
I am writing a script and in my script I have this function: def insert_image(cursor, object_id, sku): product_obj = core.Object.get(object_id) string_sku = str(sku) folder = string_sku[0] + string_sku[1] + string_sku[2] found_url = False # KLUDGE This is ugly and redundant, however putting this in an if elif elif else throws error when url not found # try this url first try urllib.urlopen("http://<path to images>/%s/%sPR-IT,PM.jpg" % (folder, sku)): urllib.URLopener().retrieve("http://<path to images>/%s/%sPR-IT,PM.jpg" % (folder, sku), "%sPR-IT,PM.jpg" % (sku)) found_url = True except: found_url = False # If that one didn't work try this one if found_url == False: try urllib.urlopen("http://<path to images>/%s/%sPK-PT,PM.jpg" % (folder, sku)): urllib.URLopener().retrieve("http://<path to images>/%s/%sPK-PT,PM.jpg" % (folder, sku), "%sPK-PT,PM.jpg" % (sku)) found_url = True except: found_url = False # If still nothing, one last attempt if found_url == False: try urllib.urlopen("http://<path to images>/%s/%sCC-PT,IM.jpg" % (folder, sku)): urllib.URLopener().retrieve("http://<path to images>/%s/%sCC-PT,IM.jpg" % (folder, sku), "%sCC-PT,IM.jpg" % (sku)) found_url = True except: found_url = False # We failed to find an image for this product, it will have to be done manually if found_url == False: log.info("Could not find the image on notions") return False # Hey we found something! Open the image.... send_image = open('%sPK-PT,PM.jpg' % sku, 'r') # ...and send it for processing if product_obj.set_image(send_image, 5, 1) == False: return False else: log.debug("Inserted Image") return True This worked fine until I added the try catches. I did have the if, elif, the function ran just fine. Here is my call and the peice of code that runs right before it: if rollback == False: # Nah -- it's all good SAVE IT! count += 1 log.debug("INSERT %s" % count) conn.commit() else: # Yeah something went wrong, errors reported why, roll it back conn.rollback() log.debug("skipped %s" % skip_count) # Insert images if rollback == False: sku = row[0] if insert_image(cursor, object_id, sku) == False: log.error("Could not get the image inserted for product: %s" % object_id) conn.rollback() else: conn.commit() My error is: 16:33:46,153 DEBUG [pylons-admin] Inserted Description 16:33:46,164 DEBUG [pylons-admin] Inserted Attributes 16:33:46,164 DEBUG [pylons-admin] INSERT 1 Traceback (most recent call last): File "<console>", line 47, in <module> NameError: name 'insert_image' is not defined I don't know what line 47 means because the call is on line 2101, again before I added the trys, it found the function just fine. I also switched the first commit to be before the insert_image call when I added the trys like you see now, before the commit was after we called insert_image. I checked indents, and spaces, and tabs w/ no avail. I use TextMate, when I run the script from TextMate, I get a syntax error here: try urllib.urlopen("http://<path to images>/%s/%sPR-IT,PM.jpg" % (folder, sku)): It points to the ( on (folder... But I don't see where I have a syntax error. Please help. I have been working on this script for a couple of weeks now, this was supposed to be the last run to test and call it finished :(
[ "You have syntax errors in your function:\ntry urllib.urlopen(\"http://<path to images>/%s/%sPR-IT,PM.jpg\" % (folder, sku)):\n urllib.URLopener().retrieve(\"http://<path to images>/%s/%sPR-IT,PM.jpg\" % (folder, sku), \"%sPR-IT,PM.jpg\" % (sku))\n found_url = True\n except:\n found_url = False\n\nIt should be:\ntry:\n urllib.urlopen(\"http://<path to images>/%s/%sPR-IT,PM.jpg\" % (folder, sku)):\n urllib.URLopener().retrieve(\"http://<path to images>/%s/%sPR-IT,PM.jpg\" % (folder, sku), \"%sPR-IT,PM.jpg\" % (sku))\n found_url = True\nexcept:\n found_url = False\n\nYou also have some broad catches, that catch those SyntaxErrors and hide errors, but insert_image is not defined this way. Never use alone except:, always put name of the Exception, that you want to catch. Otherwise you will also catch things like SyntaxError and this is very dangerous.\n", "This sounds like you have a whitespace issue before the method. The incorrect whitespace has moved it outside of the normal code path and if it is in a class it may not appear to be in the class any more\n" ]
[ 3, 0 ]
[]
[]
[ "nameerror", "python" ]
stackoverflow_0002371981_nameerror_python.txt
Q: Python - functional "find"? I need a function, which is capable of iterating over the collection, calling a supplied function with element of the collection as a parameter and returning the parameter or it's index when received "True" from supplied function. It is somethong like this: def find(f, seq, index_only=True, item_only=False): """Return first item in sequence where f(item) == True.""" index = 0 for item in seq: if f(item): if index_only: return index if item_only: return item return index, item index+= 1 raise KeyError So I am wondering whether there's anything like that in standart python toolset? A: Try itertools and for example ifilter. A: I don't think there is any such function with such exact semantics, and anyway your function is short , good enough and you can easily improve it for later use, so use it. because simple is better than complex. A: You can use itertools.dropwhile to skip over the items for which the supplied function returns False, then take the first item of the rest (if any). If you need the index rather than the item, incorporate enumerate from the Recipes section of itertools docs. To reverse truth values returned by the supplied function, use a lambda (lambda x: not pred (x), where pred is the supplied function) or a named wrapper: def negate(f): def wrapped(x): return not f(x) return wrapped Example: def odd(x): return x % 2 == 1 itertools.dropwhile(negate(odd), [2,4,1]).next() # => 1 This will throw StopIteration if no matching item is found; wrap it in a function of your own to throw an exception of your choice instead.
Python - functional "find"?
I need a function, which is capable of iterating over the collection, calling a supplied function with element of the collection as a parameter and returning the parameter or it's index when received "True" from supplied function. It is somethong like this: def find(f, seq, index_only=True, item_only=False): """Return first item in sequence where f(item) == True.""" index = 0 for item in seq: if f(item): if index_only: return index if item_only: return item return index, item index+= 1 raise KeyError So I am wondering whether there's anything like that in standart python toolset?
[ "Try itertools and for example ifilter.\n", "I don't think there is any such function with such exact semantics, and anyway your function is short , good enough and you can easily improve it for later use, so use it.\nbecause simple is better than complex.\n", "You can use itertools.dropwhile to skip over the items for which the supplied function returns False, then take the first item of the rest (if any). If you need the index rather than the item, incorporate enumerate from the Recipes section of itertools docs.\nTo reverse truth values returned by the supplied function, use a lambda (lambda x: not pred (x), where pred is the supplied function) or a named wrapper:\ndef negate(f):\n def wrapped(x):\n return not f(x)\n return wrapped\n\nExample:\ndef odd(x): return x % 2 == 1\nitertools.dropwhile(negate(odd), [2,4,1]).next()\n# => 1\n\nThis will throw StopIteration if no matching item is found; wrap it in a function of your own to throw an exception of your choice instead.\n" ]
[ 3, 3, 2 ]
[]
[]
[ "functional_programming", "lambda", "python" ]
stackoverflow_0002371979_functional_programming_lambda_python.txt
Q: Importing bytea field into PostgreSQL database via psycopg2 I have a list of values as such: row = ['0x14', '0xb6', '0xa1', '0x0', '0xa1', '0x0'] I would like to insert these into a bytea field in my PostgreSQL database, using psycopg2, but I am unfamiliar with byte strings in python. What is the best way to achieve this? A: I am not sure if this is the correct way, but the following appears to work: row = ['0x14', '0xb6', '0xa1', '0x0', '0xa1', '0x0'] as_hex = ''.join(byte[2:].zfill(2) for byte in row) # as_hex = '14b6a100a100' bytes = buffer(as_hex.decode('hex')) cur.execute("INSERT INTO mylog (binaryfield) VALUES (%(bytes)s)", {'bytes': bytes}) Just a side note, when fetching it back out of the database psycopg2 provides it as a buffer, the first 4 bytes of which are the total length, so get the original data as: cur.execute("SELECT binaryfield FROM mylog") res = cur.fetchone() my_data = str(res[4:]).encode('hex') The string can then be split into pairs and cast to integers.
Importing bytea field into PostgreSQL database via psycopg2
I have a list of values as such: row = ['0x14', '0xb6', '0xa1', '0x0', '0xa1', '0x0'] I would like to insert these into a bytea field in my PostgreSQL database, using psycopg2, but I am unfamiliar with byte strings in python. What is the best way to achieve this?
[ "I am not sure if this is the correct way, but the following appears to work: \n row = ['0x14', '0xb6', '0xa1', '0x0', '0xa1', '0x0']\n as_hex = ''.join(byte[2:].zfill(2) for byte in row)\n # as_hex = '14b6a100a100'\n bytes = buffer(as_hex.decode('hex'))\n\n cur.execute(\"INSERT INTO mylog (binaryfield) VALUES (%(bytes)s)\", \n {'bytes': bytes})\n\nJust a side note, when fetching it back out of the database psycopg2 provides it as a buffer, the first 4 bytes of which are the total length, so get the original data as:\n cur.execute(\"SELECT binaryfield FROM mylog\")\n res = cur.fetchone()\n my_data = str(res[4:]).encode('hex')\n\nThe string can then be split into pairs and cast to integers.\n" ]
[ 2 ]
[]
[]
[ "postgresql", "psycopg2", "python" ]
stackoverflow_0002371779_postgresql_psycopg2_python.txt
Q: Python XML to dictionary to iterate over items I have the following XML example <?xml version="1.0"?> <test> <items> <item>item 1</item> <item>item 2</item> </items> </test> I need to iterate over each tag in a for loop in python. If tried many things but I just can't get it.. thanks for the help A: I personally use xml.etree.cElementTree, as I've found it works really well, it's fast, easy to use, and works well with big (>2GB) files. import xml.etree.cElementTree as etree with open(xml_file_path) as xml_file: tree = etree.iterparse(xml_file) for items in tree: for item in items: print item.text In the interactive console >>> x="""<?xml version="1.0"?> <test> <items> <item>item 1</item> <item>item 2</item> </items> </test>""" >>> x '<?xml version="1.0"?>\n<test>\n <items>\n <item>item 1</item>\n <item>item 2</item>\n </items>\n</test>' >>> import xml.etree.cElementTree as etree >>> tree = etree.fromstring(x) >>> tree <Element 'test' at 0xb63ad248> >>> for i in tree: for j in i: print j <Element 'item' at 0xb63ad2f0> <Element 'item' at 0xb63ad338> >>> for i in tree: for j in i: j.text 'item 1' 'item 2' >>> A: Try xml parser from xml.sax package in standard library. from xml.sax import parse from xml.sax.handler import ContentHandler from sys import argv class Handler(ContentHandler): def startElementNS(self, name, qname, attrs): self.startElement(name, attrs) def endElementNs(self, name, qname): self.endElement(name, attrs) def startElement(self, name, qname, attrs): ... do whatever you like on tag start... def characters(self, content): ... on tag content ... def endElement(self, name): ... on tag closing ... if __name__ == "__main__": parse(argv[1], Handler()) Here I assumed argv[1] is a path to the file you'd like to parse. (first argument to parse() function is filename or stream). It is easy to convert it to for loop: just grab all the information you need in the methods above and push them into some list or stack. Iterate over it once you have finished parsing. A: import xml.dom.minidom as md x='''<?xml version="1.0"?> <test> <items> <item>item 1</item> <item>item 2</item> </items> </test> ''' xml=md.parseString(x) items=xml.getElementsByTagName("item") # [<DOM Element: item at 0xc16e40>, <DOM Element: item at 0xc16ee0>] since items is DOM Element Array, you could loop with for A: You would probably like to use something like ElementTree This is a well renowned library, I have not personally used it but I always hear good things. Also as of python 2.5 it's part of the standard library
Python XML to dictionary to iterate over items
I have the following XML example <?xml version="1.0"?> <test> <items> <item>item 1</item> <item>item 2</item> </items> </test> I need to iterate over each tag in a for loop in python. If tried many things but I just can't get it.. thanks for the help
[ "I personally use xml.etree.cElementTree, as I've found it works really well, it's fast, easy to use, and works well with big (>2GB) files.\nimport xml.etree.cElementTree as etree\n\nwith open(xml_file_path) as xml_file:\n tree = etree.iterparse(xml_file)\n for items in tree:\n for item in items:\n print item.text\n\nIn the interactive console\n>>> x=\"\"\"<?xml version=\"1.0\"?>\n<test>\n <items>\n <item>item 1</item>\n <item>item 2</item>\n </items>\n</test>\"\"\"\n>>> x\n'<?xml version=\"1.0\"?>\\n<test>\\n <items>\\n <item>item 1</item>\\n <item>item 2</item>\\n </items>\\n</test>'\n>>> import xml.etree.cElementTree as etree\n>>> tree = etree.fromstring(x)\n>>> tree\n<Element 'test' at 0xb63ad248>\n>>> for i in tree:\n for j in i:\n print j\n\n\n<Element 'item' at 0xb63ad2f0>\n<Element 'item' at 0xb63ad338>\n>>> for i in tree:\n for j in i:\n j.text\n\n'item 1'\n'item 2'\n>>>\n\n", "Try xml parser from xml.sax package in standard library.\n\nfrom xml.sax import parse\nfrom xml.sax.handler import ContentHandler\nfrom sys import argv\n\nclass Handler(ContentHandler):\n def startElementNS(self, name, qname, attrs):\n self.startElement(name, attrs)\n\n def endElementNs(self, name, qname):\n self.endElement(name, attrs)\n\n def startElement(self, name, qname, attrs):\n ... do whatever you like on tag start...\n\n def characters(self, content):\n ... on tag content ...\n\n def endElement(self, name):\n ... on tag closing ...\n\nif __name__ == \"__main__\":\n parse(argv[1], Handler())\n\n\nHere I assumed argv[1] is a path to the file you'd like to parse. (first argument to parse() function is filename or stream). It is easy to convert it to for loop: just grab all the information you need in the methods above and push them into some list or stack. Iterate over it once you have finished parsing.\n", "import xml.dom.minidom as md\n\nx='''<?xml version=\"1.0\"?>\n<test>\n <items>\n <item>item 1</item>\n <item>item 2</item>\n </items>\n</test>\n'''\n\nxml=md.parseString(x)\n\nitems=xml.getElementsByTagName(\"item\")\n# [<DOM Element: item at 0xc16e40>, <DOM Element: item at 0xc16ee0>]\n\nsince items is DOM Element Array, you could loop with for\n", "You would probably like to use something like ElementTree This is a well renowned library, I have not personally used it but I always hear good things. \nAlso as of python 2.5 it's part of the standard library\n" ]
[ 7, 1, 1, 0 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0002372217_python_xml.txt
Q: Is there a Python version of CPAN? So I've been using Perl for several years now and I'm starting to dabble a little in Python. Is there a sort of CPAN but for Python? What's the normal way to manage modules in Python? Any direction would be greatly appreciated. FWIW I use Linux so Windows-only solutions aren't really useful to me. A: The repository formerly known as Cheese Shop. PyPI The Python Package Index is a repository of software for the Python programming language. There are currently 9140 packages here. To contact the PyPI admins, please use the Get help or Bug reports links. Also, take a look at SIG for Python Resource Cataloguing This SIG exists in order to discuss and build a catalog of Python resources. The SIG charter is: The Python Catalog SIG (Special Interest Group) aims at producing a master index of Python software and other resources. It will begin by figuring out what the requirements are, converging on a design for the data schema, and producing an implementation. ("Implementation" will almost certainly include mean a set of CGI scripts for browsing the catalog, and may also contain a standard library module for automatically fetching and installing modules, if the SIG decides that's a worthwhile feature.) A: Check out Python eggs / easy_install
Is there a Python version of CPAN?
So I've been using Perl for several years now and I'm starting to dabble a little in Python. Is there a sort of CPAN but for Python? What's the normal way to manage modules in Python? Any direction would be greatly appreciated. FWIW I use Linux so Windows-only solutions aren't really useful to me.
[ "The repository formerly known as Cheese Shop.\n\nPyPI\nThe Python Package Index is a repository of software for the Python programming language. There are currently 9140 packages here. To contact the PyPI admins, please use the Get help or Bug reports links.\n\nAlso, take a look at\n\nSIG for Python Resource Cataloguing\nThis SIG exists in order to discuss and build a catalog of Python resources. The SIG charter is:\n\nThe Python Catalog SIG (Special Interest Group) aims at producing a master index of Python software and other resources. It will begin by figuring out what the requirements are, converging on a design for the data schema, and producing an implementation. (\"Implementation\" will almost certainly include mean a set of CGI scripts for browsing the catalog, and may also contain a standard library module for automatically fetching and installing modules, if the SIG decides that's a worthwhile feature.)\n\n\n", "Check out Python eggs / easy_install\n" ]
[ 12, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002372445_python.txt
Q: More efficient solution to loop nesting required I am trying to compare two files. I will list the two file content: File 1 File 2 "d.complex.1" "d.complex.1" 1 4 5 5 48 47 65 21 d.complex.10 d.complex.10 46 5 21 46 109 121 192 192 There are totally 2000 d.complex in each file. I am trying to compare both the files but the problem is the values listed under d.complex.1 in first file has to be checked with all the 2000 d.complex entries in the second file and if the entry do not match, they are to be printed out. For example in the above files, in file1 d.complex.1 number 48 is not present in file2 d.complex.1; so that number has to be stored in a list (to print out later). Then again the same d.complex.1 has to be compared with d.complex.10 of file2 and since 1, 48 and 65 are not there, they have to be appended to a list. The method I chose to achieve this was to use sets and then do a intersection. Code I wrote was: first_complex=open( "file1.txt", "r" ) first_complex_lines=first_complex.readlines() first_complex_lines=map( string.strip, first_complex_lines ) first_complex.close() second_complex=open( "file2.txt", "r" ) second_complex_lines=second_complex.readlines() second_complex_lines=map( string.strip, second_complex_lines ) second_complex.close() list_1=[] list_2=[] res_1=[] for line in first_complex_lines: if line.startswith( "d.complex" ): res_1.append( [] ) res_1[-1].append( line ) res_2=[] for line in second_complex_lines: if line.startswith( "d.complex" ): res_2.append( [] ) res_2[-1].append( line ) h=len( res_1 ) k=len( res_2 ) for i in res_1: for j in res_2: print i[0] print j[0] target_set=set ( i ) target_set_1=set( j ) for s in target_set: if s not in target_set_1: print s The above code is giving an output like this (just an example): 1 48 65 d.complex.1.dssp d.complex.1.dssp 46 21 109 d.complex.1.dssp d.complex.1.dssp d.complex.10.dssp Though the above answer is correct, I want a more efficient way of doing this, can anyone help me? Also two d.complex.1.dssp are printed instead of one which is also not good. What I would like to have is: d.complex.1 d.complex.1 (name from file2) 1 48 65 d.complex.1 d.complex.10 (name from file2) 1 48 65 I am so new to python so my concept above might be flawed. Also I have never used sets before :(. Can someone give me a hand here? A: Pointers: Use list comprehensions or generator expressions to simplify data processing. More readable Just generate the sets once. Use functions to not repeat yourself, especially doing the same task twice. I've made a few assumptions about your input data, you might want to try something like this. def parsefile(filename): ret = {} cur = None for line in ( x.strip() for x in open(filename,'r')): if line.startswith('d.complex'): cur = set() ret[line] = cur if not cur or not line.isdigit(): continue cur.add(int(line)) return ret def compareStructures(first,second): # Iterate through key,value pairs in first for firstcmplx, firstmembers in first.iteritems(): # Iterate through key,value pairs in second for secondcmplx, secondmembers in second.iteritems(): notinsecond = firstmembers- secondmembers if notinsecond: # There are items in first that aren't in second print firstcmplx print secondcmplx print "\n".join([ str(x) for x in notinsecond]) first = parsefile("myFirstFile.txt") second = parsefile("mySecondFile.txt") compareStructures(first,second) Edited for fixes.. shows how much I rely on running the code to test it :) Thanks Alex A: There's already a good answer, by @MattH, focused on the Python details of your problem, and while it can be improved in several details the improvements would only gain you some percentage points in efficiency -- worthwhile but not great. The only hope for a huge boost in efficiency (as opposed to "kai-zen" incremental improvement) is a drastic change in the algorithm -- which may or may not be possible depending on characteristics of your data that you do not reveal, and some details about your precise requirements. The crucial part is: roughly, what range of numbers will be present in the file, and roughly, how many numbers per "d.complex.N" stanza? You already told us there are going to be about 2000 stanzas per file (and that's also crucial of course) and the impression is that in each file they're going to be ordered by contiguous increasing N -- 1, 2, 3, and so on (is that so?). Your algorithm builds two maps stanza->numbers (not with top efficiency, but that's what @MattH's answer focuses on enhancing) so then inevitably it needs N squared stanza-to-stanza checks -- as N is 2,000, it needs 4 million such checks. Consider building reversed maps, number->stanzas -- if the range of numbers and the typical size of (amount of numbers in) a stanza are both reasonably limited, those will be more compact. For example, if the numbers are between 1 and 200, and there are about 4 numbers per stanzas, this implies a number will typically be in (2000 * 4) / 200 -> 40 stanzas, so such mappings would have 200 entries of about 40 stanzas each. It only needs 200 squared (40,000) checks, rather than 4 million, to obtain the joint information for each number (then, depending on exact need for output format, formatting that info may require very substantial effort again -- if you absolutely require as final result 4 million "stanza-pairs" section as the output, then of course there's no way to avoid 4 million "output operations, which will be inevitably very costly). But all of this depends on those numbers that you're not telling us -- average stanza population, and range of numbers in the files, as well as details on what constraints you must absolutely respect for output format (if the numbers are reasonable, the output format constraints are going to be the key constraint on the big-O performance you can get out of any program). Remember, to quote Fred Brooks: Show me your flowcharts and conceal your tables, and I shall continue to be mystified. Show me your tables, and I won’t usually need your flowcharts; they’ll be obvious. Brooks was writing in the '60s (though his collection of essays, "The Mythical Man-Month", was published later, in the '70s), whence the quaint use of "flowcharts" (where we'd say code or algorithms) and "tables" (where we'd say data or data structures) -- but the general concept is still perfectly valid: the organization and nature of your data, in all kinds of programs focused on data processing (such as yours), can be even more important than the organization of the code, especially since it constrains the latter;-).
More efficient solution to loop nesting required
I am trying to compare two files. I will list the two file content: File 1 File 2 "d.complex.1" "d.complex.1" 1 4 5 5 48 47 65 21 d.complex.10 d.complex.10 46 5 21 46 109 121 192 192 There are totally 2000 d.complex in each file. I am trying to compare both the files but the problem is the values listed under d.complex.1 in first file has to be checked with all the 2000 d.complex entries in the second file and if the entry do not match, they are to be printed out. For example in the above files, in file1 d.complex.1 number 48 is not present in file2 d.complex.1; so that number has to be stored in a list (to print out later). Then again the same d.complex.1 has to be compared with d.complex.10 of file2 and since 1, 48 and 65 are not there, they have to be appended to a list. The method I chose to achieve this was to use sets and then do a intersection. Code I wrote was: first_complex=open( "file1.txt", "r" ) first_complex_lines=first_complex.readlines() first_complex_lines=map( string.strip, first_complex_lines ) first_complex.close() second_complex=open( "file2.txt", "r" ) second_complex_lines=second_complex.readlines() second_complex_lines=map( string.strip, second_complex_lines ) second_complex.close() list_1=[] list_2=[] res_1=[] for line in first_complex_lines: if line.startswith( "d.complex" ): res_1.append( [] ) res_1[-1].append( line ) res_2=[] for line in second_complex_lines: if line.startswith( "d.complex" ): res_2.append( [] ) res_2[-1].append( line ) h=len( res_1 ) k=len( res_2 ) for i in res_1: for j in res_2: print i[0] print j[0] target_set=set ( i ) target_set_1=set( j ) for s in target_set: if s not in target_set_1: print s The above code is giving an output like this (just an example): 1 48 65 d.complex.1.dssp d.complex.1.dssp 46 21 109 d.complex.1.dssp d.complex.1.dssp d.complex.10.dssp Though the above answer is correct, I want a more efficient way of doing this, can anyone help me? Also two d.complex.1.dssp are printed instead of one which is also not good. What I would like to have is: d.complex.1 d.complex.1 (name from file2) 1 48 65 d.complex.1 d.complex.10 (name from file2) 1 48 65 I am so new to python so my concept above might be flawed. Also I have never used sets before :(. Can someone give me a hand here?
[ "Pointers:\n\nUse list comprehensions or generator expressions to simplify data processing. More readable\nJust generate the sets once.\nUse functions to not repeat yourself, especially doing the same task twice.\n\nI've made a few assumptions about your input data, you might want to try something like this.\ndef parsefile(filename):\n ret = {}\n cur = None\n for line in ( x.strip() for x in open(filename,'r')):\n if line.startswith('d.complex'):\n cur = set()\n ret[line] = cur\n if not cur or not line.isdigit():\n continue\n cur.add(int(line))\n return ret\n\ndef compareStructures(first,second):\n # Iterate through key,value pairs in first\n for firstcmplx, firstmembers in first.iteritems():\n # Iterate through key,value pairs in second\n for secondcmplx, secondmembers in second.iteritems():\n notinsecond = firstmembers- secondmembers\n if notinsecond:\n # There are items in first that aren't in second\n print firstcmplx\n print secondcmplx\n print \"\\n\".join([ str(x) for x in notinsecond])\n\nfirst = parsefile(\"myFirstFile.txt\")\nsecond = parsefile(\"mySecondFile.txt\")\n\ncompareStructures(first,second)\n\nEdited for fixes.. shows how much I rely on running the code to test it :) Thanks Alex\n", "There's already a good answer, by @MattH, focused on the Python details of your problem, and while it can be improved in several details the improvements would only gain you some percentage points in efficiency -- worthwhile but not great.\nThe only hope for a huge boost in efficiency (as opposed to \"kai-zen\" incremental improvement) is a drastic change in the algorithm -- which may or may not be possible depending on characteristics of your data that you do not reveal, and some details about your precise requirements.\nThe crucial part is: roughly, what range of numbers will be present in the file, and roughly, how many numbers per \"d.complex.N\" stanza? You already told us there are going to be about 2000 stanzas per file (and that's also crucial of course) and the impression is that in each file they're going to be ordered by contiguous increasing N -- 1, 2, 3, and so on (is that so?).\nYour algorithm builds two maps stanza->numbers (not with top efficiency, but that's what @MattH's answer focuses on enhancing) so then inevitably it needs N squared stanza-to-stanza checks -- as N is 2,000, it needs 4 million such checks.\nConsider building reversed maps, number->stanzas -- if the range of numbers and the typical size of (amount of numbers in) a stanza are both reasonably limited, those will be more compact. For example, if the numbers are between 1 and 200, and there are about 4 numbers per stanzas, this implies a number will typically be in (2000 * 4) / 200 -> 40 stanzas, so such mappings would have 200 entries of about 40 stanzas each. It only needs 200 squared (40,000) checks, rather than 4 million, to obtain the joint information for each number (then, depending on exact need for output format, formatting that info may require very substantial effort again -- if you absolutely require as final result 4 million \"stanza-pairs\" section as the output, then of course there's no way to avoid 4 million \"output operations, which will be inevitably very costly).\nBut all of this depends on those numbers that you're not telling us -- average stanza population, and range of numbers in the files, as well as details on what constraints you must absolutely respect for output format (if the numbers are reasonable, the output format constraints are going to be the key constraint on the big-O performance you can get out of any program).\nRemember, to quote Fred Brooks:\n\nShow me your flowcharts and conceal\n your tables, and I shall continue to\n be mystified. Show me your tables, and\n I won’t usually need your flowcharts;\n they’ll be obvious.\n\nBrooks was writing in the '60s (though his collection of essays, \"The Mythical Man-Month\", was published later, in the '70s), whence the quaint use of \"flowcharts\" (where we'd say code or algorithms) and \"tables\" (where we'd say data or data structures) -- but the general concept is still perfectly valid: the organization and nature of your data, in all kinds of programs focused on data processing (such as yours), can be even more important than the organization of the code, especially since it constrains the latter;-).\n" ]
[ 1, 1 ]
[]
[]
[ "for_loop", "loops", "nested", "python" ]
stackoverflow_0002371956_for_loop_loops_nested_python.txt
Q: Flickr API automated login using Python library flickrapi I have a web application that I want to sync with Flickr. I don't want the users to have to log into Flickr so I plan to use a single login. I believe I'll need to do something like this: import flickrapi flickr = flickrapi.FlickrAPI(myKey, mySecret) (token, frob) = flickr.get_token_part_one(perms='write', my_auth_callback) flickr.get_token_part_two((token, frob,)) flickr.what_have_you(... I don't know what my_auth_callback should look like though. I suspect it will have to post my login information to flickr. Could I do the get_token_part_one step just once manually perhaps and then re-use it in get_token_part_two? Edit Wooble has it. Here are some explicit directions that I wrote down using the Django shell and the flickrapi library. import flickrapi api_key = "xxxx...xxxx" api_secret = "xxxx...xxxx" _flickr = flickrapi.FlickrAPI(api_key, api_secret) _flickr.web_login_url("write") # Go to that url. # That sends you back to the callback url you set by "editing the # authentication workflow" on your flicks admin page located on the site. # This callback url will contain a frob in the form # xxxxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxx-xxxxxxxx _flickr.get_token("xxxxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxx-xxxxxxxx") # That returns the token. Then test with import flickrapi from django.conf import settings _flickr = flickrapi.FlickrAPI(api_key, api_secret, token=api_token) _flickr.groups_pools_getGroups() A: If you don't want your users to authenticate with Flickr, you don't need to use the token-getting code at all. Just get a token for yourself once and include it with your code. Note that "syncing" other users' photos with your own account probably breaks Flickr's TOS.
Flickr API automated login using Python library flickrapi
I have a web application that I want to sync with Flickr. I don't want the users to have to log into Flickr so I plan to use a single login. I believe I'll need to do something like this: import flickrapi flickr = flickrapi.FlickrAPI(myKey, mySecret) (token, frob) = flickr.get_token_part_one(perms='write', my_auth_callback) flickr.get_token_part_two((token, frob,)) flickr.what_have_you(... I don't know what my_auth_callback should look like though. I suspect it will have to post my login information to flickr. Could I do the get_token_part_one step just once manually perhaps and then re-use it in get_token_part_two? Edit Wooble has it. Here are some explicit directions that I wrote down using the Django shell and the flickrapi library. import flickrapi api_key = "xxxx...xxxx" api_secret = "xxxx...xxxx" _flickr = flickrapi.FlickrAPI(api_key, api_secret) _flickr.web_login_url("write") # Go to that url. # That sends you back to the callback url you set by "editing the # authentication workflow" on your flicks admin page located on the site. # This callback url will contain a frob in the form # xxxxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxx-xxxxxxxx _flickr.get_token("xxxxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxx-xxxxxxxx") # That returns the token. Then test with import flickrapi from django.conf import settings _flickr = flickrapi.FlickrAPI(api_key, api_secret, token=api_token) _flickr.groups_pools_getGroups()
[ "If you don't want your users to authenticate with Flickr, you don't need to use the token-getting code at all. Just get a token for yourself once and include it with your code.\nNote that \"syncing\" other users' photos with your own account probably breaks Flickr's TOS.\n" ]
[ 1 ]
[]
[]
[ "django", "flickr", "python" ]
stackoverflow_0002373194_django_flickr_python.txt
Q: any python socket server framework? I'm looking for a python socket server framework - not to handle http, but to handle tcp sockets. I've done it myself, but adding all the features is tedious. This framework would handle thread pooling, socket setup, signal handling, etc. A big feature is code-reloading. If I use apache/mod_python, or django, or whatever, I don't have to restart the server to get it to use new/changed code. Anybody know how that's done? thanks! Colin A: Twisted is the usual suspect. Reloading in the case of mod_wsgi is easy since only the WSGI server needs to be restarted, not the whole web server (not that restarting the web server is all that hard, mind you...). A: Use Apache, mod_wsgi in daemon mode and follow these guidelines. Update: I mentioned Apache because you did in your question - I assumed you were talking about a web application that also acted as a socket server. The Python library has socket servers (see the documentation). AFAIK you can't do hot code reloading in Python without potentially losing packets, for that you would need something specifically designed for hot code reloading, such as Erlang, or else just have a dumb socket receiver which receives and queues packets, and a smarter backend process which does code reloading and packet handling. In that case, your receiver would be acting as a proxy.
any python socket server framework?
I'm looking for a python socket server framework - not to handle http, but to handle tcp sockets. I've done it myself, but adding all the features is tedious. This framework would handle thread pooling, socket setup, signal handling, etc. A big feature is code-reloading. If I use apache/mod_python, or django, or whatever, I don't have to restart the server to get it to use new/changed code. Anybody know how that's done? thanks! Colin
[ "Twisted is the usual suspect. Reloading in the case of mod_wsgi is easy since only the WSGI server needs to be restarted, not the whole web server (not that restarting the web server is all that hard, mind you...).\n", "Use Apache, mod_wsgi in daemon mode and follow these guidelines.\nUpdate: I mentioned Apache because you did in your question - I assumed you were talking about a web application that also acted as a socket server.\nThe Python library has socket servers (see the documentation). AFAIK you can't do hot code reloading in Python without potentially losing packets, for that you would need something specifically designed for hot code reloading, such as Erlang, or else just have a dumb socket receiver which receives and queues packets, and a smarter backend process which does code reloading and packet handling. In that case, your receiver would be acting as a proxy.\n" ]
[ 4, 2 ]
[]
[]
[ "frameworks", "python", "tcp" ]
stackoverflow_0002373430_frameworks_python_tcp.txt
Q: fast java/python/C++ ipc I notice this thread: Fastish Python/Jython IPC, and I have a similar problem, but in different language. I have a Java front-end and a C++ back-end, which I am thinking about rewrite it in Python in some near future. What will be the best IPC? I prefer socket to HTTP, as I am trying to avoid the HTTP overhead. And XML-RPC is an example one to avoid! Are there any library to deal with cross platform RPC (JSON/XML etc.)? Newbie in this field, thanks ahead! A: For the C++ backend you can use xmlrpc++ (LGPL'ed) - I'm planning to use it myself. It has very clean code so you can modify it easily if you need to. As for the frontends in Java/Python, you could make use of Apache XML-RPC (don't know anything about it) or Python's xmlrpclib (very easy to use). XML-RPC should be cross-platform. I've tried xmlrpc++ as server and xmlrpclib as client and it seems to work correctly, even when using faults, i.e. passing errors to the client.
fast java/python/C++ ipc
I notice this thread: Fastish Python/Jython IPC, and I have a similar problem, but in different language. I have a Java front-end and a C++ back-end, which I am thinking about rewrite it in Python in some near future. What will be the best IPC? I prefer socket to HTTP, as I am trying to avoid the HTTP overhead. And XML-RPC is an example one to avoid! Are there any library to deal with cross platform RPC (JSON/XML etc.)? Newbie in this field, thanks ahead!
[ "For the C++ backend you can use xmlrpc++ (LGPL'ed) - I'm planning to use it myself. It has very clean code so you can modify it easily if you need to.\nAs for the frontends in Java/Python, you could make use of Apache XML-RPC (don't know anything about it) or Python's xmlrpclib (very easy to use).\nXML-RPC should be cross-platform. I've tried xmlrpc++ as server and xmlrpclib as client and it seems to work correctly, even when using faults, i.e. passing errors to the client.\n" ]
[ 2 ]
[]
[]
[ "c++", "ipc", "java", "python", "rpc" ]
stackoverflow_0002373540_c++_ipc_java_python_rpc.txt