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: How to share a dictionary between multiple processes in python without locking I need to share a huge dictionary (around 1 gb in size) between multiple processs, however since all processes will always read from it. I dont need locking. Is there any way to share a dictionary without locking? The multiprocessing module in python provides an Array class which allows sharing without locking by setting lock=false however There is no such option for Dictionary provided by manager in multiprocessing module. A: Well, in fact the dict on a Manager has no locks at all! I guess this is true for the other shared object you can create through the manager too. How i know this? I tried: from multiprocessing import Process, Manager def f(d): for i in range(10000): d['blah'] += 1 if __name__ == '__main__': manager = Manager() d = manager.dict() d['blah'] = 0 procs = [ Process(target=f, args=(d,)) for _ in range(10) ] for p in procs: p.start() for p in procs: p.join() print d If there were locks on d, the result would be 100000. But instead, the result is pretty random and so this is just a nice illustration why locks are needed when you modify stuff ;-) So just go ahead and use manager.dict().
How to share a dictionary between multiple processes in python without locking
I need to share a huge dictionary (around 1 gb in size) between multiple processs, however since all processes will always read from it. I dont need locking. Is there any way to share a dictionary without locking? The multiprocessing module in python provides an Array class which allows sharing without locking by setting lock=false however There is no such option for Dictionary provided by manager in multiprocessing module.
[ "Well, in fact the dict on a Manager has no locks at all! I guess this is true for the other shared object you can create through the manager too. How i know this? I tried:\nfrom multiprocessing import Process, Manager\n\ndef f(d):\n for i in range(10000):\n d['blah'] += 1\n\nif __name__ == '__main__':\n manager = Manager()\n\n d = manager.dict()\n d['blah'] = 0\n procs = [ Process(target=f, args=(d,)) for _ in range(10) ]\n for p in procs:\n p.start()\n for p in procs:\n p.join()\n\n print d\n\nIf there were locks on d, the result would be 100000. But instead, the result is pretty random and so this is just a nice illustration why locks are needed when you modify stuff ;-)\nSo just go ahead and use manager.dict().\n" ]
[ 5 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0002936626_multithreading_python.txt
Q: Application closes on Nokia E71 when using urllib.urlopen Im running the following code on my Nokia E71. But after the text input, the program closes abruptly. I have a GPRS connection on my phone,but i still seem to be having some problem with urllib.urlopen The code is as follows : import appuifw,urllib amountInDollars = appuifw.query(u"Enter amount in Dollars","text") data=urllib.urlopen("http://www.google.com").read() appuifw.note(u"Hey","info") Any way to fix this problem ? Thank You A: Rewriting to: import appuifw,urllib amountInDollars = appuifw.query(u"Enter amount in Dollars","text") f=urllib.urlopen("http://www.google.com") data=f.read() f.close() appuifw.note(u"Hey","info") it should work now.
Application closes on Nokia E71 when using urllib.urlopen
Im running the following code on my Nokia E71. But after the text input, the program closes abruptly. I have a GPRS connection on my phone,but i still seem to be having some problem with urllib.urlopen The code is as follows : import appuifw,urllib amountInDollars = appuifw.query(u"Enter amount in Dollars","text") data=urllib.urlopen("http://www.google.com").read() appuifw.note(u"Hey","info") Any way to fix this problem ? Thank You
[ "Rewriting to:\nimport appuifw,urllib\n\namountInDollars = appuifw.query(u\"Enter amount in Dollars\",\"text\") \nf=urllib.urlopen(\"http://www.google.com\")\ndata=f.read()\nf.close()\nappuifw.note(u\"Hey\",\"info\")\n\nit should work now.\n" ]
[ 2 ]
[]
[]
[ "pys60", "python" ]
stackoverflow_0002878493_pys60_python.txt
Q: class browsing in django I'd like to browse active classes in Django. I think I'd learn a lot that way. So what's a good way to do that? I could use IDLE if I knew how to start Django from within IDLE. But as I'm new to Python/Django, I'm not particularly wedded to IDLE. Other alternatives? A: I imagine what you mean by class browsing. If you are comfortable with the terminal you could try to inspect python/django objects via the shell and autocompletion. $ ./manage shell Python 2.6.4 (r264:75706, Feb 6 2010, 01:49:44) Type "copyright", "credits" or "license" for more information. IPython 0.10 -- An enhanced Interactive Python. ? -> Introduction and overview of IPython's features. %quickref -> Quick reference. help -> Python's own help system. object? -> Details about 'object'. ?object also works, ?? prints more. In [1]: from your.app.models import * In [2]: ... You may also like this enhanced version of the Django shell. I also recommend the django documentation, e.g. if you like to learn about Request and Response objects: http://docs.djangoproject.com/en/1.2/ref/request-response/#ref-request-response How to enable tab-completion in the default python shell: http://algorithmicallyrandom.blogspot.com/2009/09/tab-completion-in-python-shell-how-to.html A: playing with the API You can easily get a django project loaded in IDLE. All it needs is the project on sys.path and os.environ['DJANGO_SETTINGS_MODULE'] set to the settings package. E.g. import sys import os sys.path.append("/path/to/parent") # under which myproject is hosted os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings' import myproject.myapp.models # or whatever Should be all you need. A: I suggest adding django-command-extensions addon application and then using: ./manage.py shell_plus which loads all models from all applications at startup, saving a lot of time on typing "from myapp.models import MyModel" And of course IPython - which is used by shell_plus if found - is superior to the default shell.
class browsing in django
I'd like to browse active classes in Django. I think I'd learn a lot that way. So what's a good way to do that? I could use IDLE if I knew how to start Django from within IDLE. But as I'm new to Python/Django, I'm not particularly wedded to IDLE. Other alternatives?
[ "I imagine what you mean by class browsing. If you are comfortable with the terminal you could try to inspect python/django objects via the shell and autocompletion. \n$ ./manage shell\nPython 2.6.4 (r264:75706, Feb 6 2010, 01:49:44) \nType \"copyright\", \"credits\" or \"license\" for more information.\n\nIPython 0.10 -- An enhanced Interactive Python.\n? -> Introduction and overview of IPython's features.\n%quickref -> Quick reference.\nhelp -> Python's own help system.\nobject? -> Details about 'object'. ?object also works, ?? prints more.\n\nIn [1]: from your.app.models import *\nIn [2]: \n...\n\nYou may also like this enhanced version of the Django shell.\nI also recommend the django documentation, e.g. if you like to learn about Request and Response objects:\n\nhttp://docs.djangoproject.com/en/1.2/ref/request-response/#ref-request-response\n\nHow to enable tab-completion in the default python shell:\n\nhttp://algorithmicallyrandom.blogspot.com/2009/09/tab-completion-in-python-shell-how-to.html\n\n", "playing with the API\nYou can easily get a django project loaded in IDLE. All it needs is the project on sys.path and os.environ['DJANGO_SETTINGS_MODULE'] set to the settings package. \nE.g. \nimport sys\nimport os\nsys.path.append(\"/path/to/parent\") # under which myproject is hosted\nos.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'\nimport myproject.myapp.models # or whatever\n\nShould be all you need.\n", "I suggest adding django-command-extensions addon application and then using:\n ./manage.py shell_plus\n\nwhich loads all models from all applications at startup, saving a lot of time on typing \"from myapp.models import MyModel\"\nAnd of course IPython - which is used by shell_plus if found - is superior to the default shell. \n" ]
[ 1, 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002936838_django_python.txt
Q: How to parse a directory tree in python? I have a directory called "notes" within the notes I have categories which are named "science", "maths" ... within those folder are sub-categories, such as "Quantum Mechanics", "Linear Algebra". ./notes --> ./notes/maths ------> ./notes/maths/linear_algebra --> ./notes/physics/ ------> ./notes/physics/quantum_mechanics My problem is that I don't know how to put the categories and subcategories into TWO SEPARATE list/array. A: You could utilize os.walk. #!/usr/bin/env python import os for root, dirs, files in os.walk('notes'): print(root, dirs, files) Naive two level traversing: import os from os.path import isdir, join def cats_and_subs(root='notes'): """ Collect categories and subcategories. """ categories = filter(lambda d: isdir(join(root, d)), os.listdir(root)) sub_categories = [] for c in categories: sub_categories += filter(lambda d: isdir(join(root, c, d)), os.listdir(join(root, c))) # categories and sub_categories are arrays, # categories would hold stuff like 'science', 'maths' # sub_categories would contain 'Quantum Mechanics', 'Linear Algebra', ... return (categories, sub_categories) if __name__ == '__main__': print(cats_and_subs(root='/path/to/your/notes')) A: os.walk is pretty much ideal for this. By default it will do a top-down walk, and you can terminate it easily at the 2nd level by settings 'dirnames' to be empty at that point. import os pth = "/path/to/notes" def getCats(pth): cats = [] subcats = [] for (dirpath, dirnames, filenames) in os.walk(pth): #print dirpath+"\n\t", "\n\t".join(dirnames), "\n%d files"%(len(filenames)) if dirpath == pth: cats = dirnames else: subcats.extend(dirnames) dirnames[:]=[] # don't walk any further downwards # subcats = list(set(subcats)) # uncomment this if you want 'subcats' to be unique return (cats, subcats)
How to parse a directory tree in python?
I have a directory called "notes" within the notes I have categories which are named "science", "maths" ... within those folder are sub-categories, such as "Quantum Mechanics", "Linear Algebra". ./notes --> ./notes/maths ------> ./notes/maths/linear_algebra --> ./notes/physics/ ------> ./notes/physics/quantum_mechanics My problem is that I don't know how to put the categories and subcategories into TWO SEPARATE list/array.
[ "You could utilize os.walk.\n#!/usr/bin/env python\n\nimport os\nfor root, dirs, files in os.walk('notes'):\n print(root, dirs, files)\n\n\nNaive two level traversing:\nimport os\nfrom os.path import isdir, join\n\ndef cats_and_subs(root='notes'):\n \"\"\"\n Collect categories and subcategories.\n \"\"\"\n categories = filter(lambda d: isdir(join(root, d)), os.listdir(root))\n sub_categories = []\n for c in categories:\n sub_categories += filter(lambda d: isdir(join(root, c, d)), \n os.listdir(join(root, c)))\n \n # categories and sub_categories are arrays,\n # categories would hold stuff like 'science', 'maths'\n # sub_categories would contain 'Quantum Mechanics', 'Linear Algebra', ...\n return (categories, sub_categories)\n\nif __name__ == '__main__':\n print(cats_and_subs(root='/path/to/your/notes'))\n\n", "os.walk is pretty much ideal for this. By default it will do a top-down walk, and you can terminate it easily at the 2nd level by settings 'dirnames' to be empty at that point.\nimport os\npth = \"/path/to/notes\"\ndef getCats(pth):\n cats = []\n subcats = []\n for (dirpath, dirnames, filenames) in os.walk(pth):\n #print dirpath+\"\\n\\t\", \"\\n\\t\".join(dirnames), \"\\n%d files\"%(len(filenames))\n if dirpath == pth:\n cats = dirnames\n else:\n subcats.extend(dirnames)\n dirnames[:]=[] # don't walk any further downwards\n # subcats = list(set(subcats)) # uncomment this if you want 'subcats' to be unique\n return (cats, subcats)\n\n" ]
[ 16, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002936909_python.txt
Q: Reading and writing to/from memory in Python Let's imagine a situation: I have two Python programs. The first one will write some data (str) to computer memory, and then exit. I will then start the second program which will read the in-memory data saved by the first program. Is this possible? A: Sort of. python p1.py | python p2.py If p1 writes to stdout, the data goes to memory. If p2 reads from stdin, it reads from memory. The issue is that there's no "I will then start the second program". You must start both programs so that they share the appropriate memory (in this case, the buffer between stdout and stdin.) A: What are all these nonsense answers? Of course you can share memory the way you asked, there's no technical reason you shouldn't be able to persist memory other than lack of usermode API. In Linux you can use shared memory segments which persist even after the program that made them is gone. You can view/edit them with ipcs(1). To create them, see shmget(2) and the related syscalls. Alternatively you can use POSIX shared memory, which is probably more portable. See shm_overview(7) I suppose you can do it on Windows like this. A: Store you data into "memory" using things like databases, eg dbm, sqlite, shelve, pickle, etc where your 2nd program can pick up later. A: No. Once the first program exits, its memory is completely gone. You need to write to disk. A: The first one will write some data (str) to computer memory, and then exit. The OS will then ensure all that memory is zeroed before any other program can see it. (This is an important security measure, as the first program may have been processing your bank statement or may have had your password). You need to write to persistent storage - probably disk. (Or you could use a ramdisk, but that's unlikely to make any difference to real-world performance). Alternatively, why do you have 2 programs? Why not one program that does both tasks? A: Yes. Define a RAM file-system. http://www.vanemery.com/Linux/Ramdisk/ramdisk.html http://www.cyberciti.biz/faq/howto-create-linux-ram-disk-filesystem/ A: You can also set up persistent shared memory area and have one program write to it and the other read it. However, setting up such things is somewhat dependent on the underlying O/S. A: Maybe the poster is talking about something like shared memory? Have a look at this: http://poshmodule.sourceforge.net/
Reading and writing to/from memory in Python
Let's imagine a situation: I have two Python programs. The first one will write some data (str) to computer memory, and then exit. I will then start the second program which will read the in-memory data saved by the first program. Is this possible?
[ "Sort of.\npython p1.py | python p2.py\n\nIf p1 writes to stdout, the data goes to memory. If p2 reads from stdin, it reads from memory. \nThe issue is that there's no \"I will then start the second program\". You must start both programs so that they share the appropriate memory (in this case, the buffer between stdout and stdin.)\n", "What are all these nonsense answers? Of course you can share memory the way you asked, there's no technical reason you shouldn't be able to persist memory other than lack of usermode API.\nIn Linux you can use shared memory segments which persist even after the program that made them is gone. You can view/edit them with ipcs(1). To create them, see shmget(2) and the related syscalls.\nAlternatively you can use POSIX shared memory, which is probably more portable. See shm_overview(7)\nI suppose you can do it on Windows like this.\n", "Store you data into \"memory\" using things like databases, eg dbm, sqlite, shelve, pickle, etc where your 2nd program can pick up later.\n", "No.\nOnce the first program exits, its memory is completely gone.\nYou need to write to disk.\n", "\nThe first one will write some data\n (str) to computer memory, and then\n exit.\n\nThe OS will then ensure all that memory is zeroed before any other program can see it. (This is an important security measure, as the first program may have been processing your bank statement or may have had your password).\nYou need to write to persistent storage - probably disk. (Or you could use a ramdisk, but that's unlikely to make any difference to real-world performance).\nAlternatively, why do you have 2 programs? Why not one program that does both tasks?\n", "Yes.\nDefine a RAM file-system. \nhttp://www.vanemery.com/Linux/Ramdisk/ramdisk.html\nhttp://www.cyberciti.biz/faq/howto-create-linux-ram-disk-filesystem/\n", "You can also set up persistent shared memory area and have one program write to it and the other read it. However, setting up such things is somewhat dependent on the underlying O/S. \n", "Maybe the poster is talking about something like shared memory? Have a look at this: http://poshmodule.sourceforge.net/\n" ]
[ 5, 3, 2, 1, 1, 1, 1, 1 ]
[]
[]
[ "buffer", "memory", "python" ]
stackoverflow_0002499491_buffer_memory_python.txt
Q: A UnicodeDecodeError that occurs with json in python on Windows, but not Mac On windows, I have the following problem: >>> string = "Don´t Forget To Breathe" >>> import json,os,codecs >>> f = codecs.open("C:\\temp.txt","w","UTF-8") >>> json.dump(string,f) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Python26\lib\json\__init__.py", line 180, in dump for chunk in iterable: File "C:\Python26\lib\json\encoder.py", line 294, in _iterencode yield encoder(o) UnicodeDecodeError: 'utf8' codec can't decode bytes in position 3-5: invalid data (Notice the non-ascii apostrophe in the string.) However, my friend, on his mac (also using python2.6), can run through this like a breeze: > string = "Don´t Forget To Breathe" > import json,os,codecs > f = codecs.open("/tmp/temp.txt","w","UTF-8") > json.dump(string,f) > f.close(); open('/tmp/temp.txt').read() '"Don\\u00b4t Forget To Breathe"' Why is this? I've also tried using UTF-16 and UTF-32 with json and codecs, but to no avail. A: What does repr(string) show on each machine? On my Mac the apostrophe shows as \xc2\xb4 (utf8 coding, 2 bytes) so of course the utf8 codec can deal with it; on your Windows it clearly isn't doing that since it talks about three bytes being a problem - so on Windows you must have some other, non-utf8 encoding set for your console. Your general problem is that, in Python pre-3, you should not enter a byte string ("...." as you used, rather than u"....") with non-ascii content (unless specifically as escape strings): this may (depending on how the session is set) fail directly or produce bytes, according to some codec set as the default one, which are not the exact bytes you expect (because you're not aware of the exact default codec in use). Use explicit Unicode literals string = u"Don´t Forget To Breathe" and you should be OK (or if you have any problem it will emerge right at the time of this assignment, at which point we may go into the issue of "how to I set a default encoding for my interactive sessions" if that's what you require).
A UnicodeDecodeError that occurs with json in python on Windows, but not Mac
On windows, I have the following problem: >>> string = "Don´t Forget To Breathe" >>> import json,os,codecs >>> f = codecs.open("C:\\temp.txt","w","UTF-8") >>> json.dump(string,f) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Python26\lib\json\__init__.py", line 180, in dump for chunk in iterable: File "C:\Python26\lib\json\encoder.py", line 294, in _iterencode yield encoder(o) UnicodeDecodeError: 'utf8' codec can't decode bytes in position 3-5: invalid data (Notice the non-ascii apostrophe in the string.) However, my friend, on his mac (also using python2.6), can run through this like a breeze: > string = "Don´t Forget To Breathe" > import json,os,codecs > f = codecs.open("/tmp/temp.txt","w","UTF-8") > json.dump(string,f) > f.close(); open('/tmp/temp.txt').read() '"Don\\u00b4t Forget To Breathe"' Why is this? I've also tried using UTF-16 and UTF-32 with json and codecs, but to no avail.
[ "What does repr(string) show on each machine? On my Mac the apostrophe shows as \\xc2\\xb4 (utf8 coding, 2 bytes) so of course the utf8 codec can deal with it; on your Windows it clearly isn't doing that since it talks about three bytes being a problem - so on Windows you must have some other, non-utf8 encoding set for your console.\nYour general problem is that, in Python pre-3, you should not enter a byte string (\"....\" as you used, rather than u\"....\") with non-ascii content (unless specifically as escape strings): this may (depending on how the session is set) fail directly or produce bytes, according to some codec set as the default one, which are not the exact bytes you expect (because you're not aware of the exact default codec in use). Use explicit Unicode literals\nstring = u\"Don´t Forget To Breathe\"\n\nand you should be OK (or if you have any problem it will emerge right at the time of this assignment, at which point we may go into the issue of \"how to I set a default encoding for my interactive sessions\" if that's what you require).\n" ]
[ 2 ]
[]
[]
[ "json", "python", "serialization", "unicode" ]
stackoverflow_0002937095_json_python_serialization_unicode.txt
Q: django - variable declared in base project does not appear in app I have a variable called STATIC_URL, declared in settings.py in my base project: STATIC_URL = '/site_media/static/' This is used, for example, in my site_base.html, which links to CSS files as follows: <link rel="stylesheet" href="{{ STATIC_URL }}css/site_tabs.css" /> I have a bunch of templates related to different apps which extend site_base.html, and when I look at them in my browser the CSS is linked correctly as <link rel="stylesheet" href="/site_media/static/css/site_tabs.css" /> (These came with a default pinax distribution.) I created a new app called 'courses' which lives in the ...../apps/courses folder. I have a view for one of the pages in courses called courseinstance.html which extends site_base.html just like the other ones. However, when this one renders in my browser it comes out as <link rel="stylesheet" href="css/site_tabs.css" /> as if STATIC_URL were equal to "" for this app. Do I have to make some sort of declaration to get my app to take on the same variable values as the project? I don't have a settings.py file for the app. by the way, the app is listed in my list of INSTALLED_APPS and it gets served up fine, just without the link to the CSS file (so the page looks funny). Thanks in advance for your help. A: Variables in settings.py are not available to the templates. What is available to a template is determined by the view that renders it. When the template is rendered you pass in a dictionary which is the "context" for the template. The context is a dictionary of names of variables and their values. To pass a value from the settings onto the template, you usually have to something like this: from django.conf import settings def my_view(request): # view logic context = { 'STATIC_URL': settings.STATIC_URL, # other template variables here } # render the template and produce a response Your STATIC_URL settings seems to be very similar to the MEDIA_URL setting. MEDIA_URL is made available to all templates via a default context processor. You can do something similar by writing your own context processor. You can take a look at how the default context processors are implemented in the django source to get an idea. A: def courseinstance(request, courseinstance_id): p = get_object_or_404(CourseInstance, pk=courseinstance_id) return render_to_response('courses/courseinstance.html', {'courseinstance': p}, context_instance=RequestContext(request)) #added this part to fix problem
django - variable declared in base project does not appear in app
I have a variable called STATIC_URL, declared in settings.py in my base project: STATIC_URL = '/site_media/static/' This is used, for example, in my site_base.html, which links to CSS files as follows: <link rel="stylesheet" href="{{ STATIC_URL }}css/site_tabs.css" /> I have a bunch of templates related to different apps which extend site_base.html, and when I look at them in my browser the CSS is linked correctly as <link rel="stylesheet" href="/site_media/static/css/site_tabs.css" /> (These came with a default pinax distribution.) I created a new app called 'courses' which lives in the ...../apps/courses folder. I have a view for one of the pages in courses called courseinstance.html which extends site_base.html just like the other ones. However, when this one renders in my browser it comes out as <link rel="stylesheet" href="css/site_tabs.css" /> as if STATIC_URL were equal to "" for this app. Do I have to make some sort of declaration to get my app to take on the same variable values as the project? I don't have a settings.py file for the app. by the way, the app is listed in my list of INSTALLED_APPS and it gets served up fine, just without the link to the CSS file (so the page looks funny). Thanks in advance for your help.
[ "Variables in settings.py are not available to the templates. What is available to a template is determined by the view that renders it. When the template is rendered you pass in a dictionary which is the \"context\" for the template. The context is a dictionary of names of variables and their values.\nTo pass a value from the settings onto the template, you usually have to something like this:\nfrom django.conf import settings\ndef my_view(request):\n # view logic\n context = {\n 'STATIC_URL': settings.STATIC_URL,\n # other template variables here\n }\n # render the template and produce a response\n\nYour STATIC_URL settings seems to be very similar to the MEDIA_URL setting.\nMEDIA_URL is made available to all templates via a default context processor. You can do something similar by writing your own context processor. You can take a look at how the default context processors are implemented in the django source to get an idea.\n", "def courseinstance(request, courseinstance_id):\n p = get_object_or_404(CourseInstance, pk=courseinstance_id)\n return render_to_response('courses/courseinstance.html', {'courseinstance': p},\n context_instance=RequestContext(request)) #added this part to fix problem\n\n" ]
[ 2, 0 ]
[]
[]
[ "django", "pinax", "python" ]
stackoverflow_0002937041_django_pinax_python.txt
Q: python web script send job to printer Is it possible for my python web app to provide an option the for user to automatically send jobs to the locally connected printer? Or will the user always have to use the browser to manually print out everything. A: If your Python webapp is running inside a browser on the client machine, I don't see any other way than manually for the user. Some workarounds you might want to investigate: if you web app is installed on the client machine, you will be able to connect directly to the printer, as you have access to the underlying OS system. you could potentially create a plugin that can be installed on the browser that does this for him, but I have no clue as how this works technically. what is it that you want to print ? You could generate a pdf that contains everything that the user needs to print, in one go ? A: You can serve to the user's browser a webpage that includes the necessary Javascript code to perform the printing if the user clicks to request it, as shown for example here (a pretty dated article, but the key idea of using Javascript to call window.print has not changed, and the article has some useful suggestions, e.g. on making a printer-friendly page; you can locate lots of other articles mentioning window.print with a web search, if you wish). Calling window.print (from the Javascript part of the page that your Python server-side code will serve) will actually (in all browsers/OSs I know) bring up a print dialog, so the user gets system-appropriate options (picking a printer if he has several, maybe saving as PDF instead of doing an actual print if his system supports that, etc, etc).
python web script send job to printer
Is it possible for my python web app to provide an option the for user to automatically send jobs to the locally connected printer? Or will the user always have to use the browser to manually print out everything.
[ "If your Python webapp is running inside a browser on the client machine, I don't see any other way than manually for the user.\nSome workarounds you might want to investigate:\n\nif you web app is installed on the client machine, you will be able to connect directly to the printer, as you have access to the underlying OS system.\nyou could potentially create a plugin that can be installed on the browser that does this for him, but I have no clue as how this works technically.\nwhat is it that you want to print ? You could generate a pdf that contains everything that the user needs to print, in one go ?\n\n", "You can serve to the user's browser a webpage that includes the necessary Javascript code to perform the printing if the user clicks to request it, as shown for example here (a pretty dated article, but the key idea of using Javascript to call window.print has not changed, and the article has some useful suggestions, e.g. on making a printer-friendly page; you can locate lots of other articles mentioning window.print with a web search, if you wish).\nCalling window.print (from the Javascript part of the page that your Python server-side code will serve) will actually (in all browsers/OSs I know) bring up a print dialog, so the user gets system-appropriate options (picking a printer if he has several, maybe saving as PDF instead of doing an actual print if his system supports that, etc, etc).\n" ]
[ 0, 0 ]
[]
[]
[ "printing", "python", "web_applications" ]
stackoverflow_0002936384_printing_python_web_applications.txt
Q: Pass arguments from django-registration to django-profiles when user registers I'm using both django-registrations and django-profiles. When the user registers I'd like to ask them to fill in the form fields from profiles as well as the usual username and password. How do I combine these two into one sign up page? A: Recently, I answered a question (on SO) on adjusting the RegistrationForm class. In this RegistrationForm you could prompt the user for his profile information. You should process this data in the register method of the DefaultBackend.
Pass arguments from django-registration to django-profiles when user registers
I'm using both django-registrations and django-profiles. When the user registers I'd like to ask them to fill in the form fields from profiles as well as the usual username and password. How do I combine these two into one sign up page?
[ "Recently, I answered a question (on SO) on adjusting the RegistrationForm class. In this RegistrationForm you could prompt the user for his profile information. You should process this data in the register method of the DefaultBackend. \n" ]
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002937245_django_python.txt
Q: Sqlite3 "chained" query I need to create a configuration file from a data file that looks as follows: MAN1_TIME '01-JAN-2010 00:00:00.0000 UTC' MAN1_RX 123.45 MAN1_RY 123.45 MAN1_RZ 123.45 MAN1_NEXT 'MAN2' MAN2_TIME '01-MAR-2010 00:00:00.0000 UTC' MAN2_RX 123.45 [...] MAN2_NEXT 'MANX' [...] MANX_TIME [...] This file describes different "legs" of a trajectory. In this case, MAN1 is chained to MAN2, and MAN2 to MANX. In the original file, the chains are not as obvious (i.e., they are non-sequential). I've managed to read the file and store in an Sqlite3 database (I'm using the Python interface). The table is stored with three columns: Id, Par, and Val; for instance, Id='MAN1', Par='RX', and Val='123.45'. I'm interested in querying such database for obtaining the information related to 'n' legs. In English, that would be: "Select RX,RY,RZ for the next five legs starting on MAN1" So the query would go to MAN1, retrieve RX, RY, RZ, then read the parameter NEXT and go to that Id, retrieve RX, RY, RZ; read the parameter NEXT; go to that one ... like this five times. How can I pass such query with "dynamic parameters"? Thank you. A: I found the answer to my own question in the SQLAlchemy website. From the documentation: The adjacency list pattern is a common relational pattern whereby a table contains a foreign key reference to itself. This is the most common and simple way to represent hierarchical data in flat tables. The other way is the “nested sets” model, sometimes called “modified preorder”. Despite what many online articles say about modified preorder, the adjacency list model is probably the most appropriate pattern for the large majority of hierarchical storage needs, for reasons of concurrency, reduced complexity, and that modified preorder has little advantage over an application which can fully load subtrees into the application space. SQLAlchemy commonly refers to an adjacency list relationship as a self-referential mapper. In this example, we’ll work with a single table called treenodes to represent a tree structure: A graph such as the following: root --+---> child1 +---> child2 --+--> subchild1 | +--> subchild2 +---> child3 Would be represented with data such as: id parent_id data --- ------- ---- 1 NULL root 2 1 child1 3 1 child2 4 3 subchild1 5 3 subchild2 6 1 child3 A: Following OMG Ponies's comment, and http://sqllessons.com/categories.html, perhaps try something like this: select MAN1.RX as MAN1_RX, MAN1.RY as MAN1_RY, MAN1.RZ as MAN1_RZ, MAN2.RX as MAN2_RX, MAN2.RY as MAN2_RY, MAN2.RZ as MAN2_RZ, MAN3.RX as MAN3_RX, MAN3.RY as MAN3_RY, MAN3.RZ as MAN3_RZ, from table as MAN1 left outer join table as MAN2 on MAN1.NEXT = MAN2.Id left outer join table as MAN3 on MAN3.NEXT = MAN2.Id where MAN1.Id = 'MAN1' PS. I'm not terribly familiar with sqlite, but assuming it does not have direct hierarchical query syntax, then this link (http://www.dbforums.com/mysql/1638233-equivalent-start-connect-mysql.html) points to the above work-around.
Sqlite3 "chained" query
I need to create a configuration file from a data file that looks as follows: MAN1_TIME '01-JAN-2010 00:00:00.0000 UTC' MAN1_RX 123.45 MAN1_RY 123.45 MAN1_RZ 123.45 MAN1_NEXT 'MAN2' MAN2_TIME '01-MAR-2010 00:00:00.0000 UTC' MAN2_RX 123.45 [...] MAN2_NEXT 'MANX' [...] MANX_TIME [...] This file describes different "legs" of a trajectory. In this case, MAN1 is chained to MAN2, and MAN2 to MANX. In the original file, the chains are not as obvious (i.e., they are non-sequential). I've managed to read the file and store in an Sqlite3 database (I'm using the Python interface). The table is stored with three columns: Id, Par, and Val; for instance, Id='MAN1', Par='RX', and Val='123.45'. I'm interested in querying such database for obtaining the information related to 'n' legs. In English, that would be: "Select RX,RY,RZ for the next five legs starting on MAN1" So the query would go to MAN1, retrieve RX, RY, RZ, then read the parameter NEXT and go to that Id, retrieve RX, RY, RZ; read the parameter NEXT; go to that one ... like this five times. How can I pass such query with "dynamic parameters"? Thank you.
[ "I found the answer to my own question in the SQLAlchemy website. From the documentation:\n\nThe adjacency list pattern is a common\n relational pattern whereby a table\n contains a foreign key reference to\n itself. This is the most common and\n simple way to represent hierarchical\n data in flat tables. The other way is\n the “nested sets” model, sometimes\n called “modified preorder”. Despite\n what many online articles say about\n modified preorder, the adjacency list\n model is probably the most appropriate\n pattern for the large majority of\n hierarchical storage needs, for\n reasons of concurrency, reduced\n complexity, and that modified preorder\n has little advantage over an\n application which can fully load\n subtrees into the application space.\nSQLAlchemy commonly refers to an\n adjacency list relationship as a\n self-referential mapper. In this\n example, we’ll work with a single\n table called treenodes to represent a\n tree structure:\n\nA graph such as the following:\nroot --+---> child1\n +---> child2 --+--> subchild1\n | +--> subchild2\n +---> child3\n\nWould be represented with data such as:\nid parent_id data\n--- ------- ----\n1 NULL root\n2 1 child1\n3 1 child2\n4 3 subchild1\n5 3 subchild2\n6 1 child3\n\n", "Following OMG Ponies's comment, and http://sqllessons.com/categories.html,\nperhaps try something like this:\nselect \n MAN1.RX as MAN1_RX,\n MAN1.RY as MAN1_RY,\n MAN1.RZ as MAN1_RZ,\n MAN2.RX as MAN2_RX,\n MAN2.RY as MAN2_RY,\n MAN2.RZ as MAN2_RZ,\n MAN3.RX as MAN3_RX,\n MAN3.RY as MAN3_RY,\n MAN3.RZ as MAN3_RZ,\n from table as MAN1\nleft outer\n join table as MAN2\n on MAN1.NEXT = MAN2.Id\nleft outer\n join table as MAN3\n on MAN3.NEXT = MAN2.Id\nwhere MAN1.Id = 'MAN1'\n\nPS. I'm not terribly familiar with sqlite, but assuming it does not have direct hierarchical query syntax, then this link (http://www.dbforums.com/mysql/1638233-equivalent-start-connect-mysql.html) points to the above work-around.\n" ]
[ 1, 0 ]
[]
[]
[ "python", "sql", "sqlite" ]
stackoverflow_0001892111_python_sql_sqlite.txt
Q: Python: Improving long cumulative sum I have a program that operates on a large set of experimental data. The data is stored as a list of objects that are instances of a class with the following attributes: time_point - the time of the sample cluster - the name of the cluster of nodes from which the sample was taken node - the name of the node from which the sample was taken qty1 = the value of the sample for the first quantity qty2 = the value of the sample for the second quantity I need to derive some values from the data set, grouped in three ways - once for the sample as a whole, once for each cluster of nodes, and once for each node. The values I need to derive depend on the (time sorted) cumulative sums of qty1 and qty2: the maximum value of the element-wise sum of the cumulative sums of qty1 and qty2, the time point at which that maximum value occurred, and the values of qty1 and qty2 at that time point. I came up with the following solution: dataset.sort(key=operator.attrgetter('time_point')) # For the whole set sys_qty1 = 0 sys_qty2 = 0 sys_combo = 0 sys_max = 0 # For the cluster grouping cluster_qty1 = defaultdict(int) cluster_qty2 = defaultdict(int) cluster_combo = defaultdict(int) cluster_max = defaultdict(int) cluster_peak = defaultdict(int) # For the node grouping node_qty1 = defaultdict(int) node_qty2 = defaultdict(int) node_combo = defaultdict(int) node_max = defaultdict(int) node_peak = defaultdict(int) for t in dataset: # For the whole system ###################################################### sys_qty1 += t.qty1 sys_qty2 += t.qty2 sys_combo = sys_qty1 + sys_qty2 if sys_combo > sys_max: sys_max = sys_combo # The Peak class is to record the time point and the cumulative quantities system_peak = Peak(time_point=t.time_point, qty1=sys_qty1, qty2=sys_qty2) # For the cluster grouping ################################################## cluster_qty1[t.cluster] += t.qty1 cluster_qty2[t.cluster] += t.qty2 cluster_combo[t.cluster] = cluster_qty1[t.cluster] + cluster_qty2[t.cluster] if cluster_combo[t.cluster] > cluster_max[t.cluster]: cluster_max[t.cluster] = cluster_combo[t.cluster] cluster_peak[t.cluster] = Peak(time_point=t.time_point, qty1=cluster_qty1[t.cluster], qty2=cluster_qty2[t.cluster]) # For the node grouping ##################################################### node_qty1[t.node] += t.qty1 node_qty2[t.node] += t.qty2 node_combo[t.node] = node_qty1[t.node] + node_qty2[t.node] if node_combo[t.node] > node_max[t.node]: node_max[t.node] = node_combo[t.node] node_peak[t.node] = Peak(time_point=t.time_point, qty1=node_qty1[t.node], qty2=node_qty2[t.node]) This produces the correct output, but I'm wondering if it can be made more readable/Pythonic, and/or faster/more scalable. The above is attractive in that it only loops through the (large) dataset once, but unattractive in that I've essentially copied/pasted three copies of the same algorithm. To avoid the copy/paste issues of the above, I tried this also: def find_peaks(level, dataset): def grouping(object, attr_name): if attr_name == 'system': return attr_name else: return object.__dict__[attrname] cuml_qty1 = defaultdict(int) cuml_qty2 = defaultdict(int) cuml_combo = defaultdict(int) level_max = defaultdict(int) level_peak = defaultdict(int) for t in dataset: cuml_qty1[grouping(t, level)] += t.qty1 cuml_qty2[grouping(t, level)] += t.qty2 cuml_combo[grouping(t, level)] = (cuml_qty1[grouping(t, level)] + cuml_qty2[grouping(t, level)]) if cuml_combo[grouping(t, level)] > level_max[grouping(t, level)]: level_max[grouping(t, level)] = cuml_combo[grouping(t, level)] level_peak[grouping(t, level)] = Peak(time_point=t.time_point, qty1=node_qty1[grouping(t, level)], qty2=node_qty2[grouping(t, level)]) return level_peak system_peak = find_peaks('system', dataset) cluster_peak = find_peaks('cluster', dataset) node_peak = find_peaks('node', dataset) For the (non-grouped) system-level calculations, I also came up with this, which is pretty: dataset.sort(key=operator.attrgetter('time_point')) def cuml_sum(seq): rseq = [] t = 0 for i in seq: t += i rseq.append(t) return rseq time_get = operator.attrgetter('time_point') q1_get = operator.attrgetter('qty1') q2_get = operator.attrgetter('qty2') timeline = [time_get(t) for t in dataset] cuml_qty1 = cuml_sum([q1_get(t) for t in dataset]) cuml_qty2 = cuml_sum([q2_get(t) for t in dataset]) cuml_combo = [q1 + q2 for q1, q2 in zip(cuml_qty1, cuml_qty2)] combo_max = max(cuml_combo) time_max = timeline.index(combo_max) q1_at_max = cuml_qty1.index(time_max) q2_at_max = cuml_qty2.index(time_max) However, despite this version's cool use of list comprehensions and zip(), it loops through the dataset three times just for the system-level calculations, and I can't think of a good way to do the cluster-level and node-level calaculations without doing something slow like: timeline = defaultdict(int) cuml_qty1 = defaultdict(int) #...etc. for c in cluster_list: timeline[c] = [time_get(t) for t in dataset if t.cluster == c] cuml_qty1[c] = [q1_get(t) for t in dataset if t.cluster == c] #...etc. Does anyone here at Stack Overflow have suggestions for improvements? The first snippet above runs well for my initial dataset (on the order of a million records), but later datasets will have more records and clusters/nodes, so scalability is a concern. This is my first non-trivial use of Python, and I want to make sure I'm taking proper advantage of the language (this is replacing a very convoluted set of SQL queries, and earlier versions of the Python version were essentially very ineffecient straight transalations of what that did). I don't normally do much programming, so I may be missing something elementary. Many thanks! A: This seems like a classic opportunity to apply a little object-orientation. I would suggest making the derived data a class and abstracting the cumulative sum calculation to something which works on that class. Something like: class DerivedData(object): def __init__(self): self.qty1 = 0.0 self.qty2 = 0.0 self.combo = 0.0 self.max = 0.0 self.peak = Peak(time_point=0.0, qty1=0.0, qty2=0.0) def accumulate(self, data): self.qty1 += data.qty1 self.qty2 += data.qty2 self.combo = self.qty1 + self.qty2 if self.combo > self.max: self.max = self.combo self.peak = Peak(time_point=data.time_point, qty1=self.qty1, qty2=self.qty2) sys = DerivedData() clusters = defaultdict(DerivedData) nodes = defaultdict(DerivedData) dataset.sort(key=operator.attrgetter('time_point')) for t in dataset: sys.accumulate(t) clusters[t.cluster].accumulate(t) nodes[t.node].accumulate(t) This solution abstracts out the logic for finding the peaks but still only goes through the data set once.
Python: Improving long cumulative sum
I have a program that operates on a large set of experimental data. The data is stored as a list of objects that are instances of a class with the following attributes: time_point - the time of the sample cluster - the name of the cluster of nodes from which the sample was taken node - the name of the node from which the sample was taken qty1 = the value of the sample for the first quantity qty2 = the value of the sample for the second quantity I need to derive some values from the data set, grouped in three ways - once for the sample as a whole, once for each cluster of nodes, and once for each node. The values I need to derive depend on the (time sorted) cumulative sums of qty1 and qty2: the maximum value of the element-wise sum of the cumulative sums of qty1 and qty2, the time point at which that maximum value occurred, and the values of qty1 and qty2 at that time point. I came up with the following solution: dataset.sort(key=operator.attrgetter('time_point')) # For the whole set sys_qty1 = 0 sys_qty2 = 0 sys_combo = 0 sys_max = 0 # For the cluster grouping cluster_qty1 = defaultdict(int) cluster_qty2 = defaultdict(int) cluster_combo = defaultdict(int) cluster_max = defaultdict(int) cluster_peak = defaultdict(int) # For the node grouping node_qty1 = defaultdict(int) node_qty2 = defaultdict(int) node_combo = defaultdict(int) node_max = defaultdict(int) node_peak = defaultdict(int) for t in dataset: # For the whole system ###################################################### sys_qty1 += t.qty1 sys_qty2 += t.qty2 sys_combo = sys_qty1 + sys_qty2 if sys_combo > sys_max: sys_max = sys_combo # The Peak class is to record the time point and the cumulative quantities system_peak = Peak(time_point=t.time_point, qty1=sys_qty1, qty2=sys_qty2) # For the cluster grouping ################################################## cluster_qty1[t.cluster] += t.qty1 cluster_qty2[t.cluster] += t.qty2 cluster_combo[t.cluster] = cluster_qty1[t.cluster] + cluster_qty2[t.cluster] if cluster_combo[t.cluster] > cluster_max[t.cluster]: cluster_max[t.cluster] = cluster_combo[t.cluster] cluster_peak[t.cluster] = Peak(time_point=t.time_point, qty1=cluster_qty1[t.cluster], qty2=cluster_qty2[t.cluster]) # For the node grouping ##################################################### node_qty1[t.node] += t.qty1 node_qty2[t.node] += t.qty2 node_combo[t.node] = node_qty1[t.node] + node_qty2[t.node] if node_combo[t.node] > node_max[t.node]: node_max[t.node] = node_combo[t.node] node_peak[t.node] = Peak(time_point=t.time_point, qty1=node_qty1[t.node], qty2=node_qty2[t.node]) This produces the correct output, but I'm wondering if it can be made more readable/Pythonic, and/or faster/more scalable. The above is attractive in that it only loops through the (large) dataset once, but unattractive in that I've essentially copied/pasted three copies of the same algorithm. To avoid the copy/paste issues of the above, I tried this also: def find_peaks(level, dataset): def grouping(object, attr_name): if attr_name == 'system': return attr_name else: return object.__dict__[attrname] cuml_qty1 = defaultdict(int) cuml_qty2 = defaultdict(int) cuml_combo = defaultdict(int) level_max = defaultdict(int) level_peak = defaultdict(int) for t in dataset: cuml_qty1[grouping(t, level)] += t.qty1 cuml_qty2[grouping(t, level)] += t.qty2 cuml_combo[grouping(t, level)] = (cuml_qty1[grouping(t, level)] + cuml_qty2[grouping(t, level)]) if cuml_combo[grouping(t, level)] > level_max[grouping(t, level)]: level_max[grouping(t, level)] = cuml_combo[grouping(t, level)] level_peak[grouping(t, level)] = Peak(time_point=t.time_point, qty1=node_qty1[grouping(t, level)], qty2=node_qty2[grouping(t, level)]) return level_peak system_peak = find_peaks('system', dataset) cluster_peak = find_peaks('cluster', dataset) node_peak = find_peaks('node', dataset) For the (non-grouped) system-level calculations, I also came up with this, which is pretty: dataset.sort(key=operator.attrgetter('time_point')) def cuml_sum(seq): rseq = [] t = 0 for i in seq: t += i rseq.append(t) return rseq time_get = operator.attrgetter('time_point') q1_get = operator.attrgetter('qty1') q2_get = operator.attrgetter('qty2') timeline = [time_get(t) for t in dataset] cuml_qty1 = cuml_sum([q1_get(t) for t in dataset]) cuml_qty2 = cuml_sum([q2_get(t) for t in dataset]) cuml_combo = [q1 + q2 for q1, q2 in zip(cuml_qty1, cuml_qty2)] combo_max = max(cuml_combo) time_max = timeline.index(combo_max) q1_at_max = cuml_qty1.index(time_max) q2_at_max = cuml_qty2.index(time_max) However, despite this version's cool use of list comprehensions and zip(), it loops through the dataset three times just for the system-level calculations, and I can't think of a good way to do the cluster-level and node-level calaculations without doing something slow like: timeline = defaultdict(int) cuml_qty1 = defaultdict(int) #...etc. for c in cluster_list: timeline[c] = [time_get(t) for t in dataset if t.cluster == c] cuml_qty1[c] = [q1_get(t) for t in dataset if t.cluster == c] #...etc. Does anyone here at Stack Overflow have suggestions for improvements? The first snippet above runs well for my initial dataset (on the order of a million records), but later datasets will have more records and clusters/nodes, so scalability is a concern. This is my first non-trivial use of Python, and I want to make sure I'm taking proper advantage of the language (this is replacing a very convoluted set of SQL queries, and earlier versions of the Python version were essentially very ineffecient straight transalations of what that did). I don't normally do much programming, so I may be missing something elementary. Many thanks!
[ "This seems like a classic opportunity to apply a little object-orientation. I would suggest making the derived data a class and abstracting the cumulative sum calculation to something which works on that class.\nSomething like:\nclass DerivedData(object):\n def __init__(self):\n self.qty1 = 0.0\n self.qty2 = 0.0\n self.combo = 0.0\n self.max = 0.0\n self.peak = Peak(time_point=0.0, qty1=0.0, qty2=0.0)\n\n def accumulate(self, data):\n self.qty1 += data.qty1\n self.qty2 += data.qty2\n self.combo = self.qty1 + self.qty2\n if self.combo > self.max:\n self.max = self.combo\n self.peak = Peak(time_point=data.time_point,\n qty1=self.qty1,\n qty2=self.qty2)\n\nsys = DerivedData()\nclusters = defaultdict(DerivedData)\nnodes = defaultdict(DerivedData)\n\ndataset.sort(key=operator.attrgetter('time_point'))\n\nfor t in dataset:\n sys.accumulate(t)\n clusters[t.cluster].accumulate(t)\n nodes[t.node].accumulate(t)\n\nThis solution abstracts out the logic for finding the peaks but still only goes through the data set once.\n" ]
[ 3 ]
[]
[]
[ "list_comprehension", "python" ]
stackoverflow_0002937383_list_comprehension_python.txt
Q: how to compare the checksums in a list corresponding to a file path with the file path in the operating system In Python? how to compare the checksums in a list corresponding to a file path with the file path in the operating system In Python? import os,sys,libxml2 files=[] sha1s=[] doc = libxml2.parseFile('files.xml') for path in doc.xpathEval('//File/Path'): files.append(path.content) for sha1 in doc.xpathEval('//File/Hash'): sha1s.append(sha1.content) for entry in zip(files,sha1s): print entry the files.xml contains <Files> <File> <Path>usr/share/doc/dialog/samples/form1</Path> <Type>doc</Type> <Size>1222</Size> <Uid>0</Uid> <Gid>0</Gid> <Mode>0755</Mode> <Hash>49744d73e8667d0e353923c0241891d46ebb9032</Hash> </File> <File> <Path>usr/share/doc/dialog/samples/form3</Path> <Type>doc</Type> <Size>1294</Size> <Uid>0</Uid> <Gid>0</Gid> <Mode>0755</Mode> <Hash>f30277f73e468232c59a526baf3a5ce49519b959</Hash> </File> </Files> I need to compare the sha1 checksum in between tags corresponding to the file specified in between the tags, with the same file path in base Operating system. A: import hashlib import libxml2 doc = libxml2.parseFile('files.xml') filePaths = ["/" + path.content for path in doc.xpathEval('//File/Path')] xmlDigests = [hash.content for hash in doc.xpathEval('//File/Hash')] for filePath, xmlDigest in zip(filePaths, xmlDigests): with open(filePath) as inFile: digester = hashlib.sha1() digester.update(inFile.read()) fileDigest = digester.hexdigest() if xmlDigest != fileDigest: print "Mismatch for %s (XML: %s, FILESYSTEM: %s)" % (filePath, xmlDigest, fileDigest)
how to compare the checksums in a list corresponding to a file path with the file path in the operating system In Python?
how to compare the checksums in a list corresponding to a file path with the file path in the operating system In Python? import os,sys,libxml2 files=[] sha1s=[] doc = libxml2.parseFile('files.xml') for path in doc.xpathEval('//File/Path'): files.append(path.content) for sha1 in doc.xpathEval('//File/Hash'): sha1s.append(sha1.content) for entry in zip(files,sha1s): print entry the files.xml contains <Files> <File> <Path>usr/share/doc/dialog/samples/form1</Path> <Type>doc</Type> <Size>1222</Size> <Uid>0</Uid> <Gid>0</Gid> <Mode>0755</Mode> <Hash>49744d73e8667d0e353923c0241891d46ebb9032</Hash> </File> <File> <Path>usr/share/doc/dialog/samples/form3</Path> <Type>doc</Type> <Size>1294</Size> <Uid>0</Uid> <Gid>0</Gid> <Mode>0755</Mode> <Hash>f30277f73e468232c59a526baf3a5ce49519b959</Hash> </File> </Files> I need to compare the sha1 checksum in between tags corresponding to the file specified in between the tags, with the same file path in base Operating system.
[ "import hashlib\nimport libxml2\n\ndoc = libxml2.parseFile('files.xml')\nfilePaths = [\"/\" + path.content for path in doc.xpathEval('//File/Path')]\nxmlDigests = [hash.content for hash in doc.xpathEval('//File/Hash')]\n\nfor filePath, xmlDigest in zip(filePaths, xmlDigests):\n with open(filePath) as inFile:\n digester = hashlib.sha1()\n digester.update(inFile.read())\n fileDigest = digester.hexdigest()\n if xmlDigest != fileDigest:\n print \"Mismatch for %s (XML: %s, FILESYSTEM: %s)\" % (filePath,\n xmlDigest, fileDigest)\n\n" ]
[ 0 ]
[]
[]
[ "checksum", "compare", "python", "sha1" ]
stackoverflow_0002908118_checksum_compare_python_sha1.txt
Q: Using Python to get a CSV output for the following example I'm back again with my ongoing saga of Student-Project Allocation questions. Thanks to Moron (who does not match his namesake) I've got a bit of direction for an evaluation portion of my project. Going with the idea of the Assignment Problem and Hungarian Algorithm I would like to express my data in the form of a .csv file which would end up looking like this in spreadsheet form. This is based on the structure I saw here. | | Project 1 | Project 2 | Project 3 | |----------|-----------|-----------|-----------| |Student1 | | 2 | 1 | |----------|-----------|-----------|-----------| |Student2 | 1 | 2 | 3 | |----------|-----------|-----------|-----------| |Student3 | 1 | 3 | 2 | |----------|-----------|-----------|-----------| To make it less cryptic: the rows are the Students/Agents and the columns represent Projects/Task. Obviously ONE project can be assigned to ONE student. That, in short, is what my project is about. The fields represent the preference weights the students have placed upon the projects (ranging from 1 to 10). If blank, that student does not want that project and there's no chance of him/her being assigned such. Anyway, my data is stored within dictionaries. Specifically the students and projects dictionaries such that: students[student_id] = Student(student_id, student_name, alloc_proj, alloc_proj_rank, preferences) where preferences is in the form of a dictionary such that preferences[rank] = {project_id} and projects[project_id] = Project(project_id, project_name) I'm aware that sorted(students.keys()) will give me a sorted list of all the student IDs which will populate the row labels and sorted(projects.keys()) will give me the list I need to populate the column labels. Thus for each student, I'd go into their preferences dictionary and match the applicable projects to ranks. I can do that much. Where I'm failing is understanding how to create a .csv file. Any help, pointers or good tutorials will be highly appreciated. A: Check out the csv module. Basically, you just need to get your data into some kind of sequence (list, tuple, etc.), and then you can just do csv.writerow() import csv cot=csv.writer(open('file.csv','wb')) tmp=[['','Project 1','Project 2','Project 3'], ['Student1','','2','1'], ['Student2','1','2','3'], ['Student3','1','3','2']] for t in tmp: cot.writerow(t) A: The csv module was made for just that.
Using Python to get a CSV output for the following example
I'm back again with my ongoing saga of Student-Project Allocation questions. Thanks to Moron (who does not match his namesake) I've got a bit of direction for an evaluation portion of my project. Going with the idea of the Assignment Problem and Hungarian Algorithm I would like to express my data in the form of a .csv file which would end up looking like this in spreadsheet form. This is based on the structure I saw here. | | Project 1 | Project 2 | Project 3 | |----------|-----------|-----------|-----------| |Student1 | | 2 | 1 | |----------|-----------|-----------|-----------| |Student2 | 1 | 2 | 3 | |----------|-----------|-----------|-----------| |Student3 | 1 | 3 | 2 | |----------|-----------|-----------|-----------| To make it less cryptic: the rows are the Students/Agents and the columns represent Projects/Task. Obviously ONE project can be assigned to ONE student. That, in short, is what my project is about. The fields represent the preference weights the students have placed upon the projects (ranging from 1 to 10). If blank, that student does not want that project and there's no chance of him/her being assigned such. Anyway, my data is stored within dictionaries. Specifically the students and projects dictionaries such that: students[student_id] = Student(student_id, student_name, alloc_proj, alloc_proj_rank, preferences) where preferences is in the form of a dictionary such that preferences[rank] = {project_id} and projects[project_id] = Project(project_id, project_name) I'm aware that sorted(students.keys()) will give me a sorted list of all the student IDs which will populate the row labels and sorted(projects.keys()) will give me the list I need to populate the column labels. Thus for each student, I'd go into their preferences dictionary and match the applicable projects to ranks. I can do that much. Where I'm failing is understanding how to create a .csv file. Any help, pointers or good tutorials will be highly appreciated.
[ "Check out the csv module. Basically, you just need to get your data into some kind of sequence (list, tuple, etc.), and then you can just do csv.writerow()\nimport csv\ncot=csv.writer(open('file.csv','wb'))\n\ntmp=[['','Project 1','Project 2','Project 3'],\n ['Student1','','2','1'],\n ['Student2','1','2','3'],\n ['Student3','1','3','2']]\nfor t in tmp:\n cot.writerow(t)\n\n", "The csv module was made for just that.\n" ]
[ 5, 3 ]
[]
[]
[ "csv", "project", "python" ]
stackoverflow_0002937586_csv_project_python.txt
Q: Update model instance with dynamic field names What I want to do is pretty simple: f=Foobar.objects.get(id=1) foo='somefield' bar='somevalue' f.foo=bar f.save() This doesn't work as it tries to update the f object's 'foo' field, which of course doesn't exist. How can I accomplish this? A: You can use setattr: f = Foobar.objects.get(id=1) foo = 'somefield' bar = 'somevalue' setattr(f, foo, bar) # f.foo=bar f.save() [setattr] is the counterpart of getattr(). The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it.
Update model instance with dynamic field names
What I want to do is pretty simple: f=Foobar.objects.get(id=1) foo='somefield' bar='somevalue' f.foo=bar f.save() This doesn't work as it tries to update the f object's 'foo' field, which of course doesn't exist. How can I accomplish this?
[ "You can use setattr:\nf = Foobar.objects.get(id=1)\nfoo = 'somefield'\nbar = 'somevalue'\nsetattr(f, foo, bar) # f.foo=bar\nf.save()\n\n\n[setattr] is the counterpart of getattr(). The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. \n\n" ]
[ 35 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002937661_django_python.txt
Q: What is a flexible, hybrid python collection object? As a way to get used to python, I am trying to translate some of my code to python from Autohotkey_L. I am immediately running into tons of choices for collection objects. Can you help me figure out a built in type or a 3rd party contributed type that has as much as possible, the functionality of the AutoHotkey_L object type and its methods. AutoHotkey_L Objects have features of a python dict, list, and a class instance. I understand that there are tradeoffs for space and speed, but I am just interested in functionality rather than optimization issues. A: Don't write Python as <another-language>. Write Python as Python. The data structure should be chosen just to have the minimal ability you need to use. list — an ordered sequence of elements, with 1 flexible end. collections.deque — an ordered sequence of elements, with 2 flexible ends (e.g. a queue). set / frozenset — an unordered sequence of unique elements. collections.Counter — an unordered sequence of non-unique elements. dict — an unordered key-value relationship. collections.OrderedDict — an ordered key-value relationship. bytes / bytearray — a list of bytes. array.array — a homogeneous list of primitive types. Looking at the interface of Object, dict would be the most suitable for finding a value by key collections.OrderedDict would be the most suitable for the push/pop stuff. when you need MinIndex / MaxIndex, where a sorted key-value relationship (e.g. red black tree) is required. There's no such type in the standard library, but there are 3rd party implementations. A: It would be impossible to recommend a particular class without knowing how you intend on using it. If you are using this particular object as an ordered sequence where elements can be repeated, then you should use a list; if you are looking up values by their key, then use a dictionary. You will get very different algorithmic runtime complexity with the different data types. It really does not take that much time to determine when to use which type.... I suggest you give it some further consideration. If you really can't decide, though, here is a possibility: class AutoHotKeyObject(object): def __init__(self): self.list_value = [] self.dict_value = {} def getDict(self): return self.dict_value def getList(self): return self.list_value With the above, you could use both the list and dictionary features, like so: obj = AutoHotKeyObject() obj.getList().append(1) obj.getList().append(2) obj.getList().append(3) print obj.getList() # Prints [1, 2, 3] obj.getDict()['a'] = 1 obj.getDict()['b'] = 2 print obj.getDict() # Prints {'a':1, 'b':2}
What is a flexible, hybrid python collection object?
As a way to get used to python, I am trying to translate some of my code to python from Autohotkey_L. I am immediately running into tons of choices for collection objects. Can you help me figure out a built in type or a 3rd party contributed type that has as much as possible, the functionality of the AutoHotkey_L object type and its methods. AutoHotkey_L Objects have features of a python dict, list, and a class instance. I understand that there are tradeoffs for space and speed, but I am just interested in functionality rather than optimization issues.
[ "Don't write Python as <another-language>. Write Python as Python.\nThe data structure should be chosen just to have the minimal ability you need to use.\n\nlist — an ordered sequence of elements, with 1 flexible end.\ncollections.deque — an ordered sequence of elements, with 2 flexible ends (e.g. a queue).\nset / frozenset — an unordered sequence of unique elements.\ncollections.Counter — an unordered sequence of non-unique elements.\ndict — an unordered key-value relationship.\ncollections.OrderedDict — an ordered key-value relationship.\nbytes / bytearray — a list of bytes.\narray.array — a homogeneous list of primitive types.\n\nLooking at the interface of Object, \n\ndict would be the most suitable for finding a value by key\ncollections.OrderedDict would be the most suitable for the push/pop stuff.\n\nwhen you need MinIndex / MaxIndex, where a sorted key-value relationship (e.g. red black tree) is required. There's no such type in the standard library, but there are 3rd party implementations.\n", "It would be impossible to recommend a particular class without knowing how you intend on using it. If you are using this particular object as an ordered sequence where elements can be repeated, then you should use a list; if you are looking up values by their key, then use a dictionary. You will get very different algorithmic runtime complexity with the different data types. It really does not take that much time to determine when to use which type.... I suggest you give it some further consideration.\nIf you really can't decide, though, here is a possibility:\nclass AutoHotKeyObject(object):\n def __init__(self):\n self.list_value = []\n self.dict_value = {}\n def getDict(self):\n return self.dict_value\n def getList(self):\n return self.list_value\n\nWith the above, you could use both the list and dictionary features, like so:\nobj = AutoHotKeyObject()\nobj.getList().append(1)\nobj.getList().append(2)\nobj.getList().append(3)\nprint obj.getList() # Prints [1, 2, 3]\nobj.getDict()['a'] = 1\nobj.getDict()['b'] = 2\nprint obj.getDict() # Prints {'a':1, 'b':2}\n\n" ]
[ 10, 1 ]
[]
[]
[ "autohotkey", "data_structures", "python" ]
stackoverflow_0002937842_autohotkey_data_structures_python.txt
Q: linear combinations in python/numpy greetings, I'm not sure if this is a dumb question or not. Lets say I have 3 numpy arrays, A1,A2,A3, and 3 floats, c1,c2,c3 and I'd like to evaluate B = A1*c1+ A2*c2+ A3*c3 will numpy compute this as for example, E1 = A1*c1 E2 = A2*c2 E3 = A3*c3 D1 = E1+E2 B = D1+E3 or is it more clever than that? In c++ I had a neat way to abstract this kind of operation. I defined series of general 'LC' template functions, LC for linear combination like: template<class T,class D> void LC( T & R, T & L0,D C0, T & L1,D C1, T & L2,D C2) { R = L0*C0 +L1*C1 +L2*C2; } and then specialized this for various types, so for instance, for an array the code looked like for (int i=0; i<L0.length; i++) R.array[i] = L0.array[i]*C0 + L1.array[i]*C1 + L2.array[i]*C2; thus avoiding having to create new intermediate arrays. This may look messy but it worked really well. I could do something similar in python, but I'm not sure if its nescesary. Thanks in advance for any insight. -nick A: While numpy, in theory, could at any time always upgrade its internals to perform wondrous optimizations, at the present time it does not: B = A1*c1 + A2*c2 + A3*c3 will indeed produce and then discard intermediate temporary arrays ("spending" some auxiliary memory, of course -- nothing else). B = A1 * c1 followed by B += A2 * c2; B += A3 * c3, again at this time, will therefore avoid spending some of that temporary memory. Of course, you'll be able to tell the difference only if you're operating in an environment with scarce real memory (where some of that auxiliary memory is just virtual and leads to page faults) and for sufficiently large arrays to "spend" all real memory and then some. Under such extreme conditions, however, a little refactoring can buy you some performance. A: This is the idea behind numexpr (A Fast numerical array expression evaluator for Python and NumPy). You might give this package a try before compiling your own routines.
linear combinations in python/numpy
greetings, I'm not sure if this is a dumb question or not. Lets say I have 3 numpy arrays, A1,A2,A3, and 3 floats, c1,c2,c3 and I'd like to evaluate B = A1*c1+ A2*c2+ A3*c3 will numpy compute this as for example, E1 = A1*c1 E2 = A2*c2 E3 = A3*c3 D1 = E1+E2 B = D1+E3 or is it more clever than that? In c++ I had a neat way to abstract this kind of operation. I defined series of general 'LC' template functions, LC for linear combination like: template<class T,class D> void LC( T & R, T & L0,D C0, T & L1,D C1, T & L2,D C2) { R = L0*C0 +L1*C1 +L2*C2; } and then specialized this for various types, so for instance, for an array the code looked like for (int i=0; i<L0.length; i++) R.array[i] = L0.array[i]*C0 + L1.array[i]*C1 + L2.array[i]*C2; thus avoiding having to create new intermediate arrays. This may look messy but it worked really well. I could do something similar in python, but I'm not sure if its nescesary. Thanks in advance for any insight. -nick
[ "While numpy, in theory, could at any time always upgrade its internals to perform wondrous optimizations, at the present time it does not: B = A1*c1 + A2*c2 + A3*c3 will indeed produce and then discard intermediate temporary arrays (\"spending\" some auxiliary memory, of course -- nothing else). \nB = A1 * c1 followed by B += A2 * c2; B += A3 * c3, again at this time, will therefore avoid spending some of that temporary memory.\nOf course, you'll be able to tell the difference only if you're operating in an environment with scarce real memory (where some of that auxiliary memory is just virtual and leads to page faults) and for sufficiently large arrays to \"spend\" all real memory and then some. Under such extreme conditions, however, a little refactoring can buy you some performance.\n", "This is the idea behind numexpr (A Fast numerical array expression evaluator for Python and NumPy). You might give this package a try before compiling your own routines.\n" ]
[ 7, 3 ]
[]
[]
[ "arrays", "linear_algebra", "numpy", "python" ]
stackoverflow_0002937669_arrays_linear_algebra_numpy_python.txt
Q: Sort and limit queryset by comment count and date using queryset.extra() (django) I am trying to sort/narrow a queryset of objects based on the number of comments each object has as well as by the timeframe during which the comments were posted. Am using a queryset.extra() method (using django_comments which utilizes generic foreign keys). I got the idea for using queryset.extra() (and the code) from here. This is a follow-up question to my initial question yesterday (which shows I am making some progress). Current Code: What I have so far works in that it will sort by the number of comments; however, I want to extend the functionality and also be able to pass a time frame argument (eg, 7 days) and return an ordered list of the most commented posts in that time frame. Here is what my view looks like with the basic functionality in tact: import datetime from django.contrib.comments.models import Comment from django.contrib.contenttypes.models import ContentType from django.db.models import Count, Sum from django.views.generic.list_detail import object_list def custom_object_list(request, queryset, *args, **kwargs): '''Extending the list_detail.object_list to allow some sorting. Example: http://example.com/video?sort_by=comments&days=7 Would get a list of the videos sorted by most comments in the last seven days. ''' try: # this is where I started working on the date business ... days = int(request.GET.get('days', None)) period = datetime.datetime.utcnow() - datetime.timedelta(days=int(days)) except (ValueError, TypeError): days = None period = None sort_by = request.GET.get('sort_by', None) ctype = ContentType.objects.get_for_model(queryset.model) if sort_by == 'comments': queryset = queryset.extra(select={ 'count' : """ SELECT COUNT(*) AS comment_count FROM django_comments WHERE content_type_id=%s AND object_pk=%s.%s """ % ( ctype.pk, queryset.model._meta.db_table, queryset.model._meta.pk.name ), }, order_by=['-count']).order_by('-count', '-created') return object_list(request, queryset, *args, **kwargs) What I've Tried: I am not well versed in SQL but I did try just to add another WHERE criteria by hand to see if I could make some progress: SELECT COUNT(*) AS comment_count FROM django_comments WHERE content_type_id=%s AND object_pk=%s.%s AND submit_date='2010-05-01 12:00:00' But that didn't do anything except mess around with my sort order. Any ideas on how I can add this extra layer of functionality? Thanks for any help or insight. A: Try this [updated to include time difference (cutoff_date) ] queryset = queryset.extra(select={ 'comment_count' : """ SELECT COUNT(*) FROM django_comments WHERE django_comments.content_type_id=%s AND django_comments.object_pk=%s.%s AND django_comments.submit_date < '%s' """ % ( ctype.pk, queryset.model._meta.db_table, queryset.model._meta.pk.name, cutoff_date ), }).order_by('-comment_count', '-created') To get a good cutoff_date, I'd recommend using the awesome-in-a-box relativedelta from python-dateutil module: from datetime import relativedelta from datetime import date cutoff_date = date.today() - relativedelta(weeks =1) #relativedelta does all the heavy lifting
Sort and limit queryset by comment count and date using queryset.extra() (django)
I am trying to sort/narrow a queryset of objects based on the number of comments each object has as well as by the timeframe during which the comments were posted. Am using a queryset.extra() method (using django_comments which utilizes generic foreign keys). I got the idea for using queryset.extra() (and the code) from here. This is a follow-up question to my initial question yesterday (which shows I am making some progress). Current Code: What I have so far works in that it will sort by the number of comments; however, I want to extend the functionality and also be able to pass a time frame argument (eg, 7 days) and return an ordered list of the most commented posts in that time frame. Here is what my view looks like with the basic functionality in tact: import datetime from django.contrib.comments.models import Comment from django.contrib.contenttypes.models import ContentType from django.db.models import Count, Sum from django.views.generic.list_detail import object_list def custom_object_list(request, queryset, *args, **kwargs): '''Extending the list_detail.object_list to allow some sorting. Example: http://example.com/video?sort_by=comments&days=7 Would get a list of the videos sorted by most comments in the last seven days. ''' try: # this is where I started working on the date business ... days = int(request.GET.get('days', None)) period = datetime.datetime.utcnow() - datetime.timedelta(days=int(days)) except (ValueError, TypeError): days = None period = None sort_by = request.GET.get('sort_by', None) ctype = ContentType.objects.get_for_model(queryset.model) if sort_by == 'comments': queryset = queryset.extra(select={ 'count' : """ SELECT COUNT(*) AS comment_count FROM django_comments WHERE content_type_id=%s AND object_pk=%s.%s """ % ( ctype.pk, queryset.model._meta.db_table, queryset.model._meta.pk.name ), }, order_by=['-count']).order_by('-count', '-created') return object_list(request, queryset, *args, **kwargs) What I've Tried: I am not well versed in SQL but I did try just to add another WHERE criteria by hand to see if I could make some progress: SELECT COUNT(*) AS comment_count FROM django_comments WHERE content_type_id=%s AND object_pk=%s.%s AND submit_date='2010-05-01 12:00:00' But that didn't do anything except mess around with my sort order. Any ideas on how I can add this extra layer of functionality? Thanks for any help or insight.
[ "Try this [updated to include time difference (cutoff_date) ]\n queryset = queryset.extra(select={\n 'comment_count' : \"\"\"\n SELECT COUNT(*)\n FROM django_comments\n WHERE\n django_comments.content_type_id=%s AND\n django_comments.object_pk=%s.%s AND\n django_comments.submit_date < '%s'\n \"\"\" % ( ctype.pk, \n queryset.model._meta.db_table, \n queryset.model._meta.pk.name,\n cutoff_date ),\n }).order_by('-comment_count', '-created')\n\nTo get a good cutoff_date, I'd recommend using the awesome-in-a-box relativedelta from python-dateutil module:\nfrom datetime import relativedelta\nfrom datetime import date\n\ncutoff_date = date.today() - relativedelta(weeks =1) #relativedelta does all the heavy lifting\n\n" ]
[ 1 ]
[]
[]
[ "django", "mysql", "python", "sql" ]
stackoverflow_0002938519_django_mysql_python_sql.txt
Q: Caveats to be aware of when using threading in Python? I'm quite new to threading in Python and have a couple of beginner questions. When starting more than say fifty threads using the Python threading module I start getting MemoryError. The threads themselves are very slim and not very memory hungry, so it seems like it is the overhead of the threading that causes the memory issues. Is there something I can do to increase the memory capacity or otherwise make Python allow for a larger number of threads? What is the maximum number of threads you've been able to run in your Python code using the threading module? Did you do any tricks to achieve that number? Are there any other caveats to be aware of when using the threading module? A: Your question cannot be answered in a general way, as good usage of threading always depends on concrete problem to be solved. You also do not tell us, which Python version you are using, so I assume you use the "default" CPython and not IronPython or something like that. To give you some hints and ideas to further think about your problem: Why do you need so much treads? Your machine will probably not be able to run them in parallel anyway. Have a look at Stackless Python. Don't know the current status of the project, but I think it was designed for that kind of problems. The global interpreter lock prevents pure Python code from really running in parallel. But C methods can be run in parallel, so in real life it's sometimes hard to guess, how Python will behave regarding parallelization. Python has many good libraries. Have a look whether one of them already has a solution for your design problem. If your problem is network related, have a look at Twisted for example. A: The Global Interpreter Lock is known to have a strong impact on the performance limitations of standard CPython. Thus the multiprocessing module notes: multiprocessing is a package that supports spawning processes using an API similar to the threading module. The multiprocessing package offers both local and remote concurrency, effectively side-stepping the Global Interpreter Lock by using subprocesses instead of threads. Due to this, the multiprocessing module allows the programmer to fully leverage multiple processors on a given machine. It runs on both Unix and Windows. The GIL probably isn't the cause of your MemoryErrors, but it is something to be aware of. A: Eventlets-Threads have been designed for low memory consumption. The general purpose call spawn can be easily used to spawn new threads.
Caveats to be aware of when using threading in Python?
I'm quite new to threading in Python and have a couple of beginner questions. When starting more than say fifty threads using the Python threading module I start getting MemoryError. The threads themselves are very slim and not very memory hungry, so it seems like it is the overhead of the threading that causes the memory issues. Is there something I can do to increase the memory capacity or otherwise make Python allow for a larger number of threads? What is the maximum number of threads you've been able to run in your Python code using the threading module? Did you do any tricks to achieve that number? Are there any other caveats to be aware of when using the threading module?
[ "Your question cannot be answered in a general way, as good usage of threading always depends on concrete problem to be solved. You also do not tell us, which Python version you are using, so I assume you use the \"default\" CPython and not IronPython or something like that. To give you some hints and ideas to further think about your problem:\n\nWhy do you need so much treads? Your machine will probably not be able to run them in parallel anyway.\nHave a look at Stackless Python. Don't know the current status of the project, but I think it was designed for that kind of problems.\nThe global interpreter lock prevents pure Python code from really running in parallel. But C methods can be run in parallel, so in real life it's sometimes hard to guess, how Python will behave regarding parallelization.\nPython has many good libraries. Have a look whether one of them already has a solution for your design problem. If your problem is network related, have a look at Twisted for example.\n\n", "The Global Interpreter Lock is known to have a strong impact on the performance limitations of standard CPython. Thus the multiprocessing module notes:\n\nmultiprocessing is a package that\n supports spawning processes using an\n API similar to the threading module.\n The multiprocessing package offers\n both local and remote concurrency,\n effectively side-stepping the Global\n Interpreter Lock by using subprocesses\n instead of threads. Due to this, the\n multiprocessing module allows the\n programmer to fully leverage multiple\n processors on a given machine. It runs\n on both Unix and Windows.\n\nThe GIL probably isn't the cause of your MemoryErrors, but it is something to be aware of.\n", "Eventlets-Threads have been designed for low memory consumption.\nThe general purpose call spawn can be easily used to spawn new threads.\n" ]
[ 5, 2, 1 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0002938405_multithreading_python.txt
Q: Python making sure x is an int, and not a pesky float For example: import random x = random.randint(1, 6) y = 2 new = x / y ... now, lets say x turns out to be 5. How can I catch if it's an int or a float before doing other things in my program? A: By default, integer division works a little unexpected in python 2, if you don't from __future__ import division Example: >>> 5 / 3 1 >>> isinstance(5 / 3, int) True Explanation: Why doesn’t this division work in python? Finally, you can always convert numbers to int: >>> from __future__ import division >>> int(5/3) 1 A: If you want want new to always be an int, one option is floor division: new = x // y Another is to round: new = int(round(x/y)) If instead, you just wanted to check if new is a float, that's a little unusual in Python (usually, type-checking isn't necessary). If so, tell us more about why you want to check and you'll get better guidance. A: isinstance(x, int) But it's rare you need to do this. Double-checking the standard library is probably not one of those times. :) Note that you can also catch exceptions in some cases (though that wouldn't apply to this example). A: If you don't mind the value being truncated (5.7 would become 5), you can simply cast it to an int. must_be_an_int = int(x) If for some reason x is something that python can't convert to an int, it will raise a ValueError exception.
Python making sure x is an int, and not a pesky float
For example: import random x = random.randint(1, 6) y = 2 new = x / y ... now, lets say x turns out to be 5. How can I catch if it's an int or a float before doing other things in my program?
[ "By default, integer division works a little unexpected in python 2, if you don't \nfrom __future__ import division\n\nExample:\n>>> 5 / 3\n1\n>>> isinstance(5 / 3, int)\nTrue\n\nExplanation: Why doesn’t this division work in python?\nFinally, you can always convert numbers to int:\n>>> from __future__ import division\n>>> int(5/3)\n1\n\n", "If you want want new to always be an int, one option is floor division:\nnew = x // y\n\nAnother is to round:\nnew = int(round(x/y))\n\nIf instead, you just wanted to check if new is a float, that's a little unusual in Python (usually, type-checking isn't necessary). If so, tell us more about why you want to check and you'll get better guidance.\n", "isinstance(x, int)\n\nBut it's rare you need to do this. Double-checking the standard library is probably not one of those times. :)\nNote that you can also catch exceptions in some cases (though that wouldn't apply to this example).\n", "If you don't mind the value being truncated (5.7 would become 5), you can simply cast it to an int.\nmust_be_an_int = int(x)\n\nIf for some reason x is something that python can't convert to an int, it will raise a ValueError exception.\n" ]
[ 2, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002939279_python.txt
Q: Python how to handle # in a dictionary I've got some json from last.fm's api which I've serialised into a dictionary using simplejson. A quick example of the basic structure is below. { "artist": "similar": { "artist": { "name": "Blah", "image": [{ "#text": "URLHERE", "size": "small" }, { "#text": "URLHERE", "size": "medium" }, { "#text": "URLHERE", "size": "large" }] } } } Any ideas how I can access the image urls of various different sizes? Thanks, Jack A: Python does not have any problem with # in strings used as dict keys. >>> import json >>> j = '{"#foo": 6}' >>> print json.loads(j) {u'#foo': 6} >>> print json.loads(j)[u'#foo'] 6 >>> print json.loads(j)['#foo'] 6 There are, however, problems with the JSON you post. For one, it isn't valid (perhaps you're missing a couple commas?). For two, you have a JSON object with the same key "image" three times, which cannot coexist and do anything useful. A: In Javascript, these two syntaxes are equivalent: o.foo o['foo'] In Python they are not. The first gives you the foo attribute, the second gives you the foo key. (It's debatable whether this was a good idea or not.) In Python, you wouldn't be able to access #text as: o.#text because the hash will start a comment, and you'll have a syntax error. But you want o['#text'] in any case. A: You can get what you want from the image list with a list comprehension. Something like desired = [x for x in images if minSize < x['size'] < maxSize] Here, images would be the list of dicts from the inner level of you data structure.
Python how to handle # in a dictionary
I've got some json from last.fm's api which I've serialised into a dictionary using simplejson. A quick example of the basic structure is below. { "artist": "similar": { "artist": { "name": "Blah", "image": [{ "#text": "URLHERE", "size": "small" }, { "#text": "URLHERE", "size": "medium" }, { "#text": "URLHERE", "size": "large" }] } } } Any ideas how I can access the image urls of various different sizes? Thanks, Jack
[ "Python does not have any problem with # in strings used as dict keys. \n>>> import json\n>>> j = '{\"#foo\": 6}'\n>>> print json.loads(j)\n{u'#foo': 6}\n>>> print json.loads(j)[u'#foo']\n6\n>>> print json.loads(j)['#foo']\n6\n\nThere are, however, problems with the JSON you post. For one, it isn't valid (perhaps you're missing a couple commas?). For two, you have a JSON object with the same key \"image\" three times, which cannot coexist and do anything useful.\n", "In Javascript, these two syntaxes are equivalent:\no.foo\no['foo']\n\nIn Python they are not. The first gives you the foo attribute, the second gives you the foo key. (It's debatable whether this was a good idea or not.) In Python, you wouldn't be able to access #text as:\no.#text\n\nbecause the hash will start a comment, and you'll have a syntax error.\nBut you want\no['#text']\n\nin any case.\n", "You can get what you want from the image list with a list comprehension. Something like\ndesired = [x for x in images if minSize < x['size'] < maxSize]\n\nHere, images would be the list of dicts from the inner level of you data structure.\n" ]
[ 4, 3, 0 ]
[]
[]
[ "api", "json", "python" ]
stackoverflow_0002938911_api_json_python.txt
Q: SSL and WSGI apps - Python I have a WSGI app that I would like to place behind SSL. My WSGI server is gevent. What would a good way to serve the app through SSL in this case be? A: The gevent.wsgi module does not have built-in SSL support. If you're using it, put it behind nginx which would receive request over HTTPS but proxy them to your gevent app using non-encrypted HTTP. The gevent.pywsgi module does have built-in SSL support and has a compatible interface. Set the keyfile and certfile arguments to make the server use SSL. Here's an example: wsgiserver_ssl.py: #!/usr/bin/python """Secure WSGI server example based on gevent.pywsgi""" from __future__ import print_function from gevent import pywsgi def hello_world(env, start_response): if env['PATH_INFO'] == '/': start_response('200 OK', [('Content-Type', 'text/html')]) return [b"<b>hello world</b>"] else: start_response('404 Not Found', [('Content-Type', 'text/html')]) return [b'<h1>Not Found</h1>'] print('Serving on https://127.0.0.1:8443') server = pywsgi.WSGIServer(('0.0.0.0', 8443), hello_world, keyfile='server.key', certfile='server.crt') # to start the server asynchronously, call server.start() # we use blocking serve_forever() here because we have no other jobs server.serve_forever() A: It looks like gevent now has an ssl module. If you have a web server implemented on top of gevent, I imagine you could modify it to wrap incoming connections with that module's ssl socket class before passing it on to the http handlers. http://blog.gevent.org/2010/02/05/version-0-12-0-released/ http://www.gevent.org/gevent.ssl.html Otherwise, you could always use good old apache + mod_wsgi to serve your wsgi app. A: I would let the http server deal with the ssl transport.
SSL and WSGI apps - Python
I have a WSGI app that I would like to place behind SSL. My WSGI server is gevent. What would a good way to serve the app through SSL in this case be?
[ "The gevent.wsgi module does not have built-in SSL support. If you're using it, put it behind nginx which would receive request over HTTPS but proxy them to your gevent app using non-encrypted HTTP.\nThe gevent.pywsgi module does have built-in SSL support and has a compatible interface. Set the keyfile and certfile arguments to make the server use SSL. Here's an example: wsgiserver_ssl.py:\n#!/usr/bin/python\n\"\"\"Secure WSGI server example based on gevent.pywsgi\"\"\"\n\nfrom __future__ import print_function\nfrom gevent import pywsgi\n\n\ndef hello_world(env, start_response):\n if env['PATH_INFO'] == '/':\n start_response('200 OK', [('Content-Type', 'text/html')])\n return [b\"<b>hello world</b>\"]\n else:\n start_response('404 Not Found', [('Content-Type', 'text/html')])\n return [b'<h1>Not Found</h1>']\n\nprint('Serving on https://127.0.0.1:8443')\nserver = pywsgi.WSGIServer(('0.0.0.0', 8443), hello_world, keyfile='server.key', certfile='server.crt')\n# to start the server asynchronously, call server.start()\n# we use blocking serve_forever() here because we have no other jobs\nserver.serve_forever()\n\n", "It looks like gevent now has an ssl module. If you have a web server implemented on top of gevent, I imagine you could modify it to wrap incoming connections with that module's ssl socket class before passing it on to the http handlers.\nhttp://blog.gevent.org/2010/02/05/version-0-12-0-released/\nhttp://www.gevent.org/gevent.ssl.html\nOtherwise, you could always use good old apache + mod_wsgi to serve your wsgi app.\n", "I would let the http server deal with the ssl transport.\n" ]
[ 9, 3, 2 ]
[]
[]
[ "gevent", "python", "ssl", "wsgi" ]
stackoverflow_0002857273_gevent_python_ssl_wsgi.txt
Q: Django how to handle # in variable name I've got a dictionary in python which is assigned as a template variable. One of the keys is named "#text" but when i try to access it using {{ artist.image.3."#text"}} I get an error which is File "/home/jack/Desktop/test/appengine/lib/django/django/template/__init__.py", line 558, in __init__ raise TemplateSyntaxError, "Could not parse the remainder: %s" % token[upto:] TemplateSyntaxError: Could not parse the remainder: "#text" So how can I use this in the template? I've tried putting quotes around it but to no avail. I'd like to not modify the dictionary if possible, but if its easy enough to do then I guess its okay. Thanks A: Django except such variables to be proper names, you have two options if possible just change #text to text or something like that else write a template filter which excepts key name and returns value e.g. @register.filter def get_key(d, key): return d[key] usage: {{ my_dict|get_key:'#text' }} Read http://docs.djangoproject.com/en/dev/howto/custom-template-tags/ to see how to write and use template filters and tags.
Django how to handle # in variable name
I've got a dictionary in python which is assigned as a template variable. One of the keys is named "#text" but when i try to access it using {{ artist.image.3."#text"}} I get an error which is File "/home/jack/Desktop/test/appengine/lib/django/django/template/__init__.py", line 558, in __init__ raise TemplateSyntaxError, "Could not parse the remainder: %s" % token[upto:] TemplateSyntaxError: Could not parse the remainder: "#text" So how can I use this in the template? I've tried putting quotes around it but to no avail. I'd like to not modify the dictionary if possible, but if its easy enough to do then I guess its okay. Thanks
[ "Django except such variables to be proper names, you have two options\n\nif possible just change #text to text or something like that\nelse write a template filter which excepts key name and returns value\n\ne.g.\n@register.filter\ndef get_key(d, key):\n return d[key]\n\nusage:\n {{ my_dict|get_key:'#text' }}\n\nRead http://docs.djangoproject.com/en/dev/howto/custom-template-tags/ to see how to write and use template filters and tags.\n" ]
[ 0 ]
[]
[]
[ "django_templates", "python" ]
stackoverflow_0002939267_django_templates_python.txt
Q: How to split line at non-printing ascii character in Python How can I split a line in Python at a non-printing ascii character (such as the long minus sign hex 0x97 , Octal 227)? I won't need the character itself. The information after it will be saved as a variable. A: You can use re.split. >>> import re >>> re.split('\W+', 'Words, words, words.') ['Words', 'words', 'words', ''] Adjust the pattern to only include the characters you want to keep. See also: stripping-non-printable-characters-from-a-string-in-python Example (w/ the long minus): >>> # \xe2\x80\x93 represents a long dash (or long minus) >>> s = 'hello – world' >>> s 'hello \xe2\x80\x93 world' >>> import re >>> re.split("\xe2\x80\x93", s) ['hello ', ' world'] Or, the same with unicode: >>> # \u2013 represents a long dash, long minus or so called en-dash >>> s = u'hello – world' >>> s u'hello \u2013 world' >>> import re >>> re.split(u"\u2013", s) [u'hello ', u' world'] A: _, _, your_result= your_input_string.partition('\x97') or your_result= your_input_string.partition('\x97')[2] If your_input_string does not contain a '\x97', then your_result will be empty. If your_input_string contains multiple '\x97' characters, your_result will contain everything after the first '\x97' character, including other '\x97' characters. A: Just use the string/unicode split method (They don't really care about the string you split upon (other than it is a constant. If you want to use a Regex then use re.split) To get the split string either escape it like the other people have shown "\x97" or use chr(0x97) for strings (0-255) or unichr(0x97) for unicode so an example would be 'will not be split'.split(chr(0x97)) 'will be split here:\x97 and this is the second string'.split(chr(0x97))
How to split line at non-printing ascii character in Python
How can I split a line in Python at a non-printing ascii character (such as the long minus sign hex 0x97 , Octal 227)? I won't need the character itself. The information after it will be saved as a variable.
[ "You can use re.split.\n>>> import re\n>>> re.split('\\W+', 'Words, words, words.')\n['Words', 'words', 'words', '']\n\nAdjust the pattern to only include the characters you want to keep.\nSee also: stripping-non-printable-characters-from-a-string-in-python\n\nExample (w/ the long minus):\n>>> # \\xe2\\x80\\x93 represents a long dash (or long minus)\n>>> s = 'hello – world'\n>>> s\n'hello \\xe2\\x80\\x93 world'\n>>> import re\n>>> re.split(\"\\xe2\\x80\\x93\", s)\n['hello ', ' world']\n\nOr, the same with unicode:\n>>> # \\u2013 represents a long dash, long minus or so called en-dash\n>>> s = u'hello – world'\n>>> s\nu'hello \\u2013 world'\n>>> import re\n>>> re.split(u\"\\u2013\", s)\n[u'hello ', u' world']\n\n", "_, _, your_result= your_input_string.partition('\\x97')\n\nor\nyour_result= your_input_string.partition('\\x97')[2]\n\nIf your_input_string does not contain a '\\x97', then your_result will be empty. If your_input_string contains multiple '\\x97' characters, your_result will contain everything after the first '\\x97' character, including other '\\x97' characters.\n", "Just use the string/unicode split method (They don't really care about the string you split upon (other than it is a constant. If you want to use a Regex then use re.split)\nTo get the split string either escape it like the other people have shown\n\"\\x97\"\nor\nuse chr(0x97) for strings (0-255) or unichr(0x97) for unicode\nso an example would be\n'will not be split'.split(chr(0x97))\n\n'will be split here:\\x97 and this is the second string'.split(chr(0x97))\n\n" ]
[ 5, 2, 1 ]
[]
[]
[ "ascii", "extended_ascii", "python", "split" ]
stackoverflow_0002936174_ascii_extended_ascii_python_split.txt
Q: set / line intersection solution I have two lists in python and I want to know if they intersect at the same index. Is there a mathematical way of solving this? For example if I have [9,8,7,6,5] and [3,4,5,6,7] I'd like a simple and efficient formula/algorithm that finds that at index 3 they intersect. I know I could do a search just wondering if there is a better way. I know there is a formula to solve two lines in y = mx + b form by subtracting them from each other but my "line" isn't truly a line because its limited to the items in the list and it may have curves. Any help is appreciated. A: You could take the set-theoretic intersection of the coordinates in both lists: intersecting_points = set(enumerate(list1)).intersection(set(enumerate(list2))) ...enumerate gives you an iterable of tuples of indexes and values - in other words, (0,9),(1,8),(2,7),etc. http://docs.python.org/library/stdtypes.html#set-types-set-frozenset ...make sense? Of course, that won't truly give you geometric intersection - for example, [1,2] intersects with [2,1] at [x=0.5,y=1.5] - if that's what you want, then you have to solve the linear equations at each interval. A: from itertools import izip def find_intersection(lineA, lineB): for pos, (A0, B0, A1, B1) in enumerate(izip(lineA, lineB, lineA[1:], lineB[1:])): #check integer intersections if A0 == B0: #check required if the intersection is at position 0 return pos if A1 == B1: #check required if the intersection is at last position return pos + 1 #check for intersection between points if (A0 > B0 and A1 < B1) or (A0 < B0 and A1 > B1): #intersection between pos and pos+1! return pos + solve_linear_equation(A0,A1,B0,B1) #no intersection return None ...where solve_linear_equation finds the intersection between segments (0,A0)→(1,A1) and (0,B0)→(1,B1). A: I assume one dimension in your list is assumed e.g. [9,8,7,6,5] are heights at x1,x2,x3,x4,x5 right? in that case how your list will represent curves like y=0 ? In any case I don't think there can be any shortcut for calculating intersection of generic or random curves, best solution is to do a efficient search. A: import itertools def intersect_at_same_index(seq1, seq2): return ( idx for idx, (item1, item2) in enumerate(itertools.izip(seq1, seq2)) if item1 == item2).next() This will return the index where the two sequences have equal items, and raise a StopIteration if all item pairs are different. If you don't like this behaviour, enclose the return statement in a try statement, and at the except StopIteration clause return your favourite failure indicator (e.g. -1, None…)
set / line intersection solution
I have two lists in python and I want to know if they intersect at the same index. Is there a mathematical way of solving this? For example if I have [9,8,7,6,5] and [3,4,5,6,7] I'd like a simple and efficient formula/algorithm that finds that at index 3 they intersect. I know I could do a search just wondering if there is a better way. I know there is a formula to solve two lines in y = mx + b form by subtracting them from each other but my "line" isn't truly a line because its limited to the items in the list and it may have curves. Any help is appreciated.
[ "You could take the set-theoretic intersection of the coordinates in both lists:\nintersecting_points = set(enumerate(list1)).intersection(set(enumerate(list2)))\n\n...enumerate gives you an iterable of tuples of indexes and values - in other words, (0,9),(1,8),(2,7),etc. \nhttp://docs.python.org/library/stdtypes.html#set-types-set-frozenset\n...make sense? Of course, that won't truly give you geometric intersection - for example, [1,2] intersects with [2,1] at [x=0.5,y=1.5] - if that's what you want, then you have to solve the linear equations at each interval.\n", "from itertools import izip\ndef find_intersection(lineA, lineB):\n for pos, (A0, B0, A1, B1) in enumerate(izip(lineA, lineB, lineA[1:], lineB[1:])):\n #check integer intersections\n if A0 == B0: #check required if the intersection is at position 0\n return pos\n if A1 == B1: #check required if the intersection is at last position\n return pos + 1\n #check for intersection between points\n if (A0 > B0 and A1 < B1) or\n (A0 < B0 and A1 > B1):\n #intersection between pos and pos+1!\n return pos + solve_linear_equation(A0,A1,B0,B1)\n #no intersection\n return None\n\n...where solve_linear_equation finds the intersection between segments (0,A0)→(1,A1) and (0,B0)→(1,B1).\n", "I assume one dimension in your list is assumed e.g. [9,8,7,6,5] are heights at x1,x2,x3,x4,x5 right? in that case how your list will represent curves like y=0 ?\nIn any case I don't think there can be any shortcut for calculating intersection of generic or random curves, best solution is to do a efficient search.\n", "import itertools\n\ndef intersect_at_same_index(seq1, seq2):\n return (\n idx\n for idx, (item1, item2)\n in enumerate(itertools.izip(seq1, seq2))\n if item1 == item2).next()\n\nThis will return the index where the two sequences have equal items, and raise a StopIteration if all item pairs are different. If you don't like this behaviour, enclose the return statement in a try statement, and at the except StopIteration clause return your favourite failure indicator (e.g. -1, None…)\n" ]
[ 4, 1, 0, 0 ]
[]
[]
[ "intersection", "list", "python", "set" ]
stackoverflow_0002939513_intersection_list_python_set.txt
Q: Convert data retrieved from MySQL database into JSON object using Python/Django I have a MySQL database called People which contains the following schema <id,name,foodchoice1,foodchoice2>. The database contains a list of people and the two choices of food they wish to have at a party (for example). I want to create some kind of Python web-service that will output a JSON object. An example of output should be like: { "guestlist": [{ "id": 1, "name": "Bob", "choice1": "chicken", "choice2": "pasta" }, { "id": 2, "name": "Alice", "choice1": "pasta", "choice2": "chicken" }], "partyname": "My awesome party", "day": "1", "month": "June", "2010": "null" } Basically every guest is stored into a dictionary 'guestlist' along with their choices of food. At the end of the JSON object is just some additional information that only needs to be mentioned once. Currently, I have a Django Model/View setup where the Model will query the server, retrieve the results and store them in variables. The View should call the Model, and be able to just create the JSON object, but I've been running into some problems. Do I need to use a standard Model/View structure of Django or is there a simple solution? A: If you ever need anything more fancy than just a dump of a specific queryset in JSON, consider using django-piston to help automate the creation of APIs. A: You can serialize any django model: http://docs.djangoproject.com/en/1.2/topics/serialization/#topics-serialization The serializers support both xml and json, and they take in querysets. Take a look at: http://docs.djangoproject.com/en/1.2/topics/serialization/#id2 Another approach is to build a dictionary yourself using the orm and serialize it using simplejson.
Convert data retrieved from MySQL database into JSON object using Python/Django
I have a MySQL database called People which contains the following schema <id,name,foodchoice1,foodchoice2>. The database contains a list of people and the two choices of food they wish to have at a party (for example). I want to create some kind of Python web-service that will output a JSON object. An example of output should be like: { "guestlist": [{ "id": 1, "name": "Bob", "choice1": "chicken", "choice2": "pasta" }, { "id": 2, "name": "Alice", "choice1": "pasta", "choice2": "chicken" }], "partyname": "My awesome party", "day": "1", "month": "June", "2010": "null" } Basically every guest is stored into a dictionary 'guestlist' along with their choices of food. At the end of the JSON object is just some additional information that only needs to be mentioned once. Currently, I have a Django Model/View setup where the Model will query the server, retrieve the results and store them in variables. The View should call the Model, and be able to just create the JSON object, but I've been running into some problems. Do I need to use a standard Model/View structure of Django or is there a simple solution?
[ "If you ever need anything more fancy than just a dump of a specific queryset in JSON, consider using django-piston to help automate the creation of APIs.\n", "You can serialize any django model: http://docs.djangoproject.com/en/1.2/topics/serialization/#topics-serialization\nThe serializers support both xml and json, and they take in querysets. Take a look at: http://docs.djangoproject.com/en/1.2/topics/serialization/#id2\nAnother approach is to build a dictionary yourself using the orm and serialize it using simplejson.\n" ]
[ 2, 0 ]
[]
[]
[ "django", "json", "python" ]
stackoverflow_0002939973_django_json_python.txt
Q: Python/PyParsing: Difficulty with setResultsName I think I'm making a mistake in how I call setResultsName(): from pyparsing import * DEPT_CODE = Regex(r'[A-Z]{2,}').setResultsName("Dept Code") COURSE_NUMBER = Regex(r'[0-9]{4}').setResultsName("Course Number") COURSE_NUMBER.setParseAction(lambda s, l, toks : int(toks[0])) course = DEPT_CODE + COURSE_NUMBER course.setResultsName("course") statement = course From IDLE: >>> myparser import * >>> statement.parseString("CS 2110") (['CS', 2110], {'Dept Code': [('CS', 0)], 'Course Number': [(2110, 1)]}) The output I hope for: >>> myparser import * >>> statement.parseString("CS 2110") (['CS', 2110], {'Course': ['CS', 2110], 'Dept Code': [('CS', 0)], 'Course Number': [(2110, 1)]}) Does setResultsName() only work for terminals? A: If you change the definition of course to course = (DEPT_CODE + COURSE_NUMBER).setResultsName("Course") you get the following behavior: x=statement.parseString("CS 2110") print(repr(x)) # (['CS', 2110], {'Course': [((['CS', 2110], {'Dept Code': [('CS', 0)], 'Course Number': [(2110, 1)]}), 0)], 'Dept Code': [('CS', 0)], 'Course Number': [(2110, 1)]}) print(x['Dept Code']) # CS print(x['Course Number']) # 2110 print(x['Course']) # ['CS', 2110] That's not exactly the repr you wanted, but does it suffice? Note, from the docs: [setResultsName] returns a copy of the original ParserElement object; this is so that the client can define a basic element, such as an integer, and reference it in multiple places with different names. So course.setResultsName("Course") does not work because it doesn't affect course. You would instead have to say course=course.setResultsName("Course"). That's an alternative way to do what I did above.
Python/PyParsing: Difficulty with setResultsName
I think I'm making a mistake in how I call setResultsName(): from pyparsing import * DEPT_CODE = Regex(r'[A-Z]{2,}').setResultsName("Dept Code") COURSE_NUMBER = Regex(r'[0-9]{4}').setResultsName("Course Number") COURSE_NUMBER.setParseAction(lambda s, l, toks : int(toks[0])) course = DEPT_CODE + COURSE_NUMBER course.setResultsName("course") statement = course From IDLE: >>> myparser import * >>> statement.parseString("CS 2110") (['CS', 2110], {'Dept Code': [('CS', 0)], 'Course Number': [(2110, 1)]}) The output I hope for: >>> myparser import * >>> statement.parseString("CS 2110") (['CS', 2110], {'Course': ['CS', 2110], 'Dept Code': [('CS', 0)], 'Course Number': [(2110, 1)]}) Does setResultsName() only work for terminals?
[ "If you change the definition of course to \ncourse = (DEPT_CODE + COURSE_NUMBER).setResultsName(\"Course\")\n\nyou get the following behavior:\nx=statement.parseString(\"CS 2110\")\nprint(repr(x))\n# (['CS', 2110], {'Course': [((['CS', 2110], {'Dept Code': [('CS', 0)], 'Course Number': [(2110, 1)]}), 0)], 'Dept Code': [('CS', 0)], 'Course Number': [(2110, 1)]})\nprint(x['Dept Code'])\n# CS\nprint(x['Course Number'])\n# 2110\nprint(x['Course'])\n# ['CS', 2110]\n\nThat's not exactly the repr you wanted, but does it suffice?\nNote, from the docs:\n\n[setResultsName] returns a copy of\n the original ParserElement object;\n this is so that the client can define\n a basic element, such as an integer,\n and reference it in multiple places\n with different names.\n\nSo course.setResultsName(\"Course\") does not work because it doesn't affect course. You would instead have to say course=course.setResultsName(\"Course\"). That's an alternative way to do what I did above.\n" ]
[ 5 ]
[]
[]
[ "nlp", "pyparsing", "python" ]
stackoverflow_0002940166_nlp_pyparsing_python.txt
Q: Why doesn't this list comprehension do what I expect it to do? The original list project_keys = sorted(projects.keys()) is [101, 102, 103, 104, 105, 106, 107, 108, 109, 110] where the following projects were deemed invalid this year: 108, 109, 110. Thus: for project in projects.itervalues(): # The projects dictionary is mapped to the Project class if project.invalid: # Where invalid is a Bool parameter in the Project class project_keys.remove(project.proj_id) print project_keys This will return a list of integers (which are project id's) as such: [101, 102, 103, 104, 105, 106, 107] Sweet. Now, I wanted it try the same thing using a list comprehension. project_keys = [project_keys.remove(project.proj_id) for project in projects.itervalues() if project.invalid print project_keys This returns: [None, None, None] So I'm populating a list with the same number as the removed elements but they're Nones? Can someone point out what I'm doing wrong? Additionally, why would I use a list comprehension over the for-if block at the top? Conciseness? Looks nicer? A: Your list comprehension works using side-effects. Just executing it should update project_keys to give the result you want. [project_keys.remove(project.proj_id) for project in projects.itervalues() if project.invalid] The return value from remove is None. Assigning the result of the list comprehension to project_keys is where you are going wrong. A simple loop is probably clearer here though. A list comprehension that uses side-effects can be confusing. However you can solve your problem in a slightly different way: project_keys = sorted(project.proj_id for project in projects.itervalues() if not project.invalid) This keeps the projects you are interested in, instead of removing those that you're not interested in. The example I gave above uses a generator expression instead of a list comprehension, but it would work with either. A: You, sir, have misunderstood list comprehensions. What you probably wanted (in words) I want to remove all project ids that are invalid. What you wrote project_keys = [project_keys.remove(project.proj_id) for project in projects.itervalues() if project.invalid] What is actually going on dummy = [] for project in projects.itervalues(): if project.invalid: dummy.append(project_keys.remove(project.proj_id)) #what are you project_keys = dummy #removing items from? del dummy What is actually going on (now with more "functional") mapped-fun = lambda project: project_keys.remove(project.proj_id) filtering-fun = lambda project: project.invalid project_keys = map(mapped-fun, filter(filtering-fun, projects.itervalues())) As you can see, list comprehensions are not syntactical sugar around for loops. Rather, list comprehensions are syntactical sugar around map() and filter(): apply a function to all items in a sequence that match a condition and get a list of results in return. Here, by function it is actually meant a side-effect-free transformation of input into output. This means that you "cannot" use methods that change the input itself, like list.sort(); you'll have to use their functional equivalents, like sorted(). By "cannot", however, I don't mean you'll get error messages or nasal demons; I mean you are abusing the language. In your case, the evaluation of the list comprehension that happens as you assign it to a variable does indeed produce the intended side-effects -- but does it produce them on the intended variables? See, the only reason why this can execute without an error is that before this list comprehension, there was another list called project_keys and it's that list you are actually changing! Lists comprehensions are a result of functional programming, which rejects side effects. Keep that in mind when using lists comprehensions. So here's a thought process you can use to actually get the list comprehension you wanted. What you actually wanted (in words) I want all project ids that are valid (= not invalid.) What you actually wanted dummy = [] for project in projects.itervalues(): if not project.invalid: dummy.append(project.proj_id) project_keys = dummy del dummy What you actually wanted (now with more functional) mapped-fun = lambda project: project.proj_id filtering-fun = lambda project: not project.invalid project_keys = map(mapped-fun, filter(filtering-fun, projects.itervalues())) What you actually wanted (now as a list comprehension) project_keys = [project.proj_id for project in projects.itervalues() if not project.invalid]
Why doesn't this list comprehension do what I expect it to do?
The original list project_keys = sorted(projects.keys()) is [101, 102, 103, 104, 105, 106, 107, 108, 109, 110] where the following projects were deemed invalid this year: 108, 109, 110. Thus: for project in projects.itervalues(): # The projects dictionary is mapped to the Project class if project.invalid: # Where invalid is a Bool parameter in the Project class project_keys.remove(project.proj_id) print project_keys This will return a list of integers (which are project id's) as such: [101, 102, 103, 104, 105, 106, 107] Sweet. Now, I wanted it try the same thing using a list comprehension. project_keys = [project_keys.remove(project.proj_id) for project in projects.itervalues() if project.invalid print project_keys This returns: [None, None, None] So I'm populating a list with the same number as the removed elements but they're Nones? Can someone point out what I'm doing wrong? Additionally, why would I use a list comprehension over the for-if block at the top? Conciseness? Looks nicer?
[ "Your list comprehension works using side-effects. Just executing it should update project_keys to give the result you want.\n[project_keys.remove(project.proj_id)\n for project in projects.itervalues()\n if project.invalid]\n\nThe return value from remove is None. Assigning the result of the list comprehension to project_keys is where you are going wrong.\nA simple loop is probably clearer here though. A list comprehension that uses side-effects can be confusing.\nHowever you can solve your problem in a slightly different way:\nproject_keys = sorted(project.proj_id\n for project in projects.itervalues()\n if not project.invalid)\n\nThis keeps the projects you are interested in, instead of removing those that you're not interested in. The example I gave above uses a generator expression instead of a list comprehension, but it would work with either.\n", "You, sir, have misunderstood list comprehensions.\nWhat you probably wanted (in words)\n\nI want to remove all project ids that are invalid.\n\nWhat you wrote\nproject_keys = [project_keys.remove(project.proj_id)\n for project in projects.itervalues() if project.invalid]\n\nWhat is actually going on\ndummy = []\nfor project in projects.itervalues():\n if project.invalid:\n dummy.append(project_keys.remove(project.proj_id)) #what are you\nproject_keys = dummy #removing items from?\ndel dummy \n\nWhat is actually going on (now with more \"functional\")\nmapped-fun = lambda project: project_keys.remove(project.proj_id)\nfiltering-fun = lambda project: project.invalid\nproject_keys = map(mapped-fun, filter(filtering-fun, projects.itervalues()))\n\n\nAs you can see, list comprehensions are not syntactical sugar around for loops. Rather, list comprehensions are syntactical sugar around map() and filter(): apply a function to all items in a sequence that match a condition and get a list of results in return.\nHere, by function it is actually meant a side-effect-free transformation of input into output. This means that you \"cannot\" use methods that change the input itself, like list.sort(); you'll have to use their functional equivalents, like sorted().\nBy \"cannot\", however, I don't mean you'll get error messages or nasal demons; I mean you are abusing the language. In your case, the evaluation of the list comprehension that happens as you assign it to a variable does indeed produce the intended side-effects -- but does it produce them on the intended variables?\nSee, the only reason why this can execute without an error is that before this list comprehension, there was another list called project_keys and it's that list you are actually changing!\nLists comprehensions are a result of functional programming, which rejects side effects. Keep that in mind when using lists comprehensions.\n\nSo here's a thought process you can use to actually get the list comprehension you wanted.\nWhat you actually wanted (in words)\n\nI want all project ids that are valid (= not invalid.)\n\nWhat you actually wanted\ndummy = []\nfor project in projects.itervalues():\n if not project.invalid:\n dummy.append(project.proj_id)\nproject_keys = dummy\ndel dummy\n\nWhat you actually wanted (now with more functional)\nmapped-fun = lambda project: project.proj_id\nfiltering-fun = lambda project: not project.invalid\nproject_keys = map(mapped-fun, filter(filtering-fun, projects.itervalues()))\n\nWhat you actually wanted (now as a list comprehension)\nproject_keys = [project.proj_id for project in projects.itervalues()\n if not project.invalid]\n\n" ]
[ 6, 4 ]
[]
[]
[ "list_comprehension", "python" ]
stackoverflow_0002940053_list_comprehension_python.txt
Q: Fixing color in scatter plots in matplotlib I want to fix the color range on multiple scatter plots and add in a colorbar to each plot (which will be the same in each figure). Essentially, I'm fixing all aspects of the axes and colorspace etc. so that the plots are directly comparable by eye. For the life of me, I can't seem to figure out all the various ways of fixing the color-range. I've tried vmin, vmax, but it doesn't seem to do anything, I've also tried clim(x,y) and that doesn't seem to work either. This must come up here and there, I can't be the only one that wants to compare various subsets of data amongst plots... so, how do you fix the colors so that each data keeps it's color between plots and doesn't get remapped to a different color due to the change in max/min of the subset -v- the whole set? A: Setting vmin and vmax should do this. Here's an example: import matplotlib.pyplot as plt xyc = range(20) plt.subplot(121) plt.scatter(xyc[:13], xyc[:13], c=xyc[:13], s=35, vmin=0, vmax=20) plt.colorbar() plt.xlim(0, 20) plt.ylim(0, 20) plt.subplot(122) plt.scatter(xyc[8:20], xyc[8:20], c=xyc[8:20], s=35, vmin=0, vmax=20) plt.colorbar() plt.xlim(0, 20) plt.ylim(0, 20) plt.show() And the plot this produces: A: Ok, this isn't really an answer-but a follow-up. The results of my coding altering Tom's code above. [not sure that I want to remove the answer check-mark, as the code above does work, and is an answer to the question!] It doesn't appear to work for my data!! Below is modified code that can be used with my data to produce a plot which wasn't working for me for some strange reason. The input came by way of the h5py functions (hdf5 data file import). In the below, rf85 is a subset of the arrays for the large batch of experiments where the RF power applied to the system was approximately 85 watts forward. I'm basically slicing and dicing the data in various ways to try and see a trend. This is the 85 watts compared to the full dataset that's current input (there's more data, but this is what I have for now). import numpy import matplotlib.pyplot as plt CurrentsArray = [array([ 0.83333333, 0.8 , 0.57142857, 0.83333333, 1.03333333, 0.25 , 0.81666667, 0.35714286, 0.26 , 0.57142857, 0.83333333, 0.47368421, 0.80645161, 0.47368421, 0.52631579, 0.36666667, 0.47368421, 0.57142857, 0.47368421, 0.47368421, 0.47368421, 0.47368421, 0.47368421, 0.61764706, 0.81081081, 0.41666667, 0.47368421, 0.47368421, 0.45 , 0.73333333, 0.8 , 0.8 , 0.8 , 0.47368421, 0.45 , 0.47368421, 0.83333333, 0.47368421, 0.22222222, 0.32894737, 0.57142857, 0.83333333, 0.83333333, 1. , 1. , 0.46666667])] growthTarray = [array([ 705., 620., 705., 725., 712., 705., 680., 680., 620., 660., 660., 740., 721., 730., 720., 720., 730., 705., 690., 705., 680., 715., 705., 670., 705., 705., 650., 725., 725., 650., 650., 650., 714., 740., 710., 717., 737., 740., 660., 705., 725., 650., 710., 703., 700., 650.])] CuSearray = [array([ 0.46395015, 0.30287259, 0.43496888, 0.46931773, 0.47685844, 0.44894925, 0.50727844, 0.45076198, 0.44977095, 0.41455029, 0.38089693, 0.98174953, 0.48600461, 0.65466528, 0.40563053, 0.22990327, 0.54372179, 0.43143358, 0.92515847, 0.73701742, 0.64152173, 0.52708783, 0.51794063, 0.49 , 0.48878252, 0.45119732, 0.2190089 , 0.43470776, 0.43509758, 0.52697697, 0.21576805, 0.32913721, 0.48828072, 0.62201997, 0.71442359, 0.55454867, 0.50981136, 0.48212956, 0.46 , 0.45732419, 0.43402525, 0.40290777, 0.38594786, 0.36777306, 0.36517926, 0.29880924])] PFarray = [array([ 384., 285., 280., 274., 185., 185., 184., 184., 184., 184., 184., 181., 110., 100., 100., 100., 85., 85., 84., 84., 84., 84., 84., 84., 84., 84., 84., 84., 84., 84., 84., 84., 27., 20., 5., 5., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0.])] rf85growthTarray = [array([ 730., 705., 690., 705., 680., 715., 705., 670., 705., 705., 650., 725., 725., 650., 650., 650.])] rf85CuSearray = [array([ 0.54372179, 0.43143358, 0.92515847, 0.73701742, 0.64152173, 0.52708783, 0.51794063, 0.49 , 0.48878252, 0.45119732, 0.2190089 , 0.43470776, 0.43509758, 0.52697697, 0.21576805, 0.32913721])] rf85PFarray = [array([ 85., 85., 84., 84., 84., 84., 84., 84., 84., 84., 84., 84., 84., 84., 84., 84.])] rf85CurrentsArray = [array([ 0.54372179, 0.43143358, 0.92515847, 0.73701742, 0.64152173, 0.52708783, 0.51794063, 0.49 , 0.48878252, 0.45119732, 0.2190089 , 0.43470776, 0.43509758, 0.52697697, 0.21576805, 0.32913721])] Datavmax = max(max(CurrentsArray)) Datavmin = min(min(CurrentsArray)) plt.subplot(121) plt.scatter(growthTarray, CuSearray, PFarray, CurrentsArray, vmin=Datavmin, vmax=Datavmax, alpha=0.75) plt.colorbar() plt.xlim(600,760) plt.ylim(0,2.5) plt.subplot(122) plt.scatter(rf85growthTarray, rf85CuSearray, rf85PFarray, rf85CurrentsArray, vmin=Datavmin, vmax=Datavmax, alpha=0.75) plt.colorbar() plt.xlim(600,760) plt.ylim(0,2.5) plt.show() And finally, the output: Please note that this is not the perfect output for my work, but I didn't expend effort making it perfect. What is important however: datapoints that you'll recognize as the same between plots do not contain the same color as should be the case based on the vmin vmax use above (as Tom's code suggests). This is insane. :( I do hope someone can shed light on this for me! I'm positive my code is not that great, so please don't worry about offending in anyway when it comes to my code!! Extra bag of firey-hot cheetos to anyone who can suggest a way forward. -Allen UPDATE- Tom10 caught the problem - I had inadvertently used the wrong data for one of my sub-arrays, causing the values to give different color levels than expected (i.e., my data was wrong!) Big props to Tom for this- I wish I could give him another up-vote, but due to my method of asking this question, I can't (sorry Tom!) Please also see his wonderful example of plotting text at the data positions mentioned below. Here's an updated image showing that Tom's method does indeed work, and that the plotting was a problem in my own code:
Fixing color in scatter plots in matplotlib
I want to fix the color range on multiple scatter plots and add in a colorbar to each plot (which will be the same in each figure). Essentially, I'm fixing all aspects of the axes and colorspace etc. so that the plots are directly comparable by eye. For the life of me, I can't seem to figure out all the various ways of fixing the color-range. I've tried vmin, vmax, but it doesn't seem to do anything, I've also tried clim(x,y) and that doesn't seem to work either. This must come up here and there, I can't be the only one that wants to compare various subsets of data amongst plots... so, how do you fix the colors so that each data keeps it's color between plots and doesn't get remapped to a different color due to the change in max/min of the subset -v- the whole set?
[ "Setting vmin and vmax should do this.\nHere's an example:\nimport matplotlib.pyplot as plt\n\nxyc = range(20)\n\nplt.subplot(121)\nplt.scatter(xyc[:13], xyc[:13], c=xyc[:13], s=35, vmin=0, vmax=20)\nplt.colorbar()\nplt.xlim(0, 20)\nplt.ylim(0, 20)\n\nplt.subplot(122)\nplt.scatter(xyc[8:20], xyc[8:20], c=xyc[8:20], s=35, vmin=0, vmax=20) \nplt.colorbar()\nplt.xlim(0, 20)\nplt.ylim(0, 20)\n\nplt.show()\n\nAnd the plot this produces:\n\n\n", "Ok, this isn't really an answer-but a follow-up. The results of my coding altering Tom's code above. [not sure that I want to remove the answer check-mark, as the code above does work, and is an answer to the question!]\nIt doesn't appear to work for my data!! Below is modified code that can be used with my data to produce a plot which wasn't working for me for some strange reason. The input came by way of the h5py functions (hdf5 data file import).\nIn the below, rf85 is a subset of the arrays for the large batch of experiments where the RF power applied to the system was approximately 85 watts forward. I'm basically slicing and dicing the data in various ways to try and see a trend. This is the 85 watts compared to the full dataset that's current input (there's more data, but this is what I have for now).\nimport numpy\nimport matplotlib.pyplot as plt\n\nCurrentsArray = [array([ 0.83333333, 0.8 , 0.57142857, 0.83333333, 1.03333333,\n 0.25 , 0.81666667, 0.35714286, 0.26 , 0.57142857,\n 0.83333333, 0.47368421, 0.80645161, 0.47368421, 0.52631579,\n 0.36666667, 0.47368421, 0.57142857, 0.47368421, 0.47368421,\n 0.47368421, 0.47368421, 0.47368421, 0.61764706, 0.81081081,\n 0.41666667, 0.47368421, 0.47368421, 0.45 , 0.73333333,\n 0.8 , 0.8 , 0.8 , 0.47368421, 0.45 ,\n 0.47368421, 0.83333333, 0.47368421, 0.22222222, 0.32894737,\n 0.57142857, 0.83333333, 0.83333333, 1. , 1. ,\n 0.46666667])]\n\ngrowthTarray = [array([ 705., 620., 705., 725., 712., 705., 680., 680., 620.,\n 660., 660., 740., 721., 730., 720., 720., 730., 705.,\n 690., 705., 680., 715., 705., 670., 705., 705., 650.,\n 725., 725., 650., 650., 650., 714., 740., 710., 717.,\n 737., 740., 660., 705., 725., 650., 710., 703., 700., 650.])]\n\nCuSearray = [array([ 0.46395015, 0.30287259, 0.43496888, 0.46931773, 0.47685844,\n 0.44894925, 0.50727844, 0.45076198, 0.44977095, 0.41455029,\n 0.38089693, 0.98174953, 0.48600461, 0.65466528, 0.40563053,\n 0.22990327, 0.54372179, 0.43143358, 0.92515847, 0.73701742,\n 0.64152173, 0.52708783, 0.51794063, 0.49 , 0.48878252,\n 0.45119732, 0.2190089 , 0.43470776, 0.43509758, 0.52697697,\n 0.21576805, 0.32913721, 0.48828072, 0.62201997, 0.71442359,\n 0.55454867, 0.50981136, 0.48212956, 0.46 , 0.45732419,\n 0.43402525, 0.40290777, 0.38594786, 0.36777306, 0.36517926,\n 0.29880924])]\n\nPFarray = [array([ 384., 285., 280., 274., 185., 185., 184., 184., 184.,\n 184., 184., 181., 110., 100., 100., 100., 85., 85.,\n 84., 84., 84., 84., 84., 84., 84., 84., 84.,\n 84., 84., 84., 84., 84., 27., 20., 5., 5.,\n 1., 0., 0., 0., 0., 0., 0., 0., 0., 0.])]\n\nrf85growthTarray = [array([ 730., 705., 690., 705., 680., 715., 705., 670., 705.,\n 705., 650., 725., 725., 650., 650., 650.])]\n\nrf85CuSearray = [array([ 0.54372179, 0.43143358, 0.92515847, 0.73701742, 0.64152173,\n 0.52708783, 0.51794063, 0.49 , 0.48878252, 0.45119732,\n 0.2190089 , 0.43470776, 0.43509758, 0.52697697, 0.21576805,\n 0.32913721])]\n\nrf85PFarray = [array([ 85., 85., 84., 84., 84., 84., 84., 84., 84., 84., 84.,\n 84., 84., 84., 84., 84.])]\n\nrf85CurrentsArray = [array([ 0.54372179, 0.43143358, 0.92515847, 0.73701742, 0.64152173,\n 0.52708783, 0.51794063, 0.49 , 0.48878252, 0.45119732,\n 0.2190089 , 0.43470776, 0.43509758, 0.52697697, 0.21576805,\n 0.32913721])]\n\nDatavmax = max(max(CurrentsArray))\nDatavmin = min(min(CurrentsArray))\n\nplt.subplot(121)\nplt.scatter(growthTarray, CuSearray, PFarray, CurrentsArray, vmin=Datavmin, vmax=Datavmax, alpha=0.75)\nplt.colorbar()\nplt.xlim(600,760)\nplt.ylim(0,2.5)\n\nplt.subplot(122)\nplt.scatter(rf85growthTarray, rf85CuSearray, rf85PFarray, rf85CurrentsArray, vmin=Datavmin, vmax=Datavmax, alpha=0.75)\nplt.colorbar()\nplt.xlim(600,760)\nplt.ylim(0,2.5)\n\nplt.show()\n\nAnd finally, the output:\n\n\nPlease note that this is not the perfect output for my work, but I didn't expend effort making it perfect. What is important however: datapoints that you'll recognize as the same between plots do not contain the same color as should be the case based on the vmin vmax use above (as Tom's code suggests).\nThis is insane. :( I do hope someone can shed light on this for me! I'm positive my code is not that great, so please don't worry about offending in anyway when it comes to my code!!\nExtra bag of firey-hot cheetos to anyone who can suggest a way forward.\n-Allen\nUPDATE- Tom10 caught the problem - I had inadvertently used the wrong data for one of my sub-arrays, causing the values to give different color levels than expected (i.e., my data was wrong!) Big props to Tom for this- I wish I could give him another up-vote, but due to my method of asking this question, I can't (sorry Tom!)\nPlease also see his wonderful example of plotting text at the data positions mentioned below.\nHere's an updated image showing that Tom's method does indeed work, and that the plotting was a problem in my own code:\n\n\n" ]
[ 52, 0 ]
[]
[]
[ "colors", "matplotlib", "python", "scatter_plot" ]
stackoverflow_0002925806_colors_matplotlib_python_scatter_plot.txt
Q: Parsing an RDF file in python Does anyone know how to pars RDF file in Python to get all the values within a specific tag? thanks A: Are you using an RDF library? Otherwise, perhaps you should. For example, see the documentation of three RDF libraries for Python: Redland RDF libraries RDFLib RDF/XML parser
Parsing an RDF file in python
Does anyone know how to pars RDF file in Python to get all the values within a specific tag? thanks
[ "Are you using an RDF library? Otherwise, perhaps you should. For example, see the documentation of three RDF libraries for Python:\n\nRedland RDF libraries\nRDFLib\nRDF/XML parser\n\n" ]
[ 11 ]
[]
[]
[ "parsing", "python", "rdf", "xml" ]
stackoverflow_0002940454_parsing_python_rdf_xml.txt
Q: Is it possible to create a python iterator over pre-defined mutable data? I might be doing this wrong, if I am, let me know, but I'm curious if the following is possible: I have a class that holds a number of dictionaries, each of which pairs names to a different set of objects of a given class. For example: items = {"ball" : ItemInstance1, "sword" : ItemInstance2} people = {"Jerry" : PersonInstance1, "Bob" : PersonInstance2, "Jill" : PersonInstance3} My class would then hold the current items and people that are availible, and these would be subject to change as the state changes: Class State: def __init__(self, items, people): self.items = items self.people = people I would like to define a iter() and next() method such that it iterates through all of the values in its attributes. My first question is whether or not this is possible. If it is, will it be able to support a situation as follows: I define items and people as above then: state = State(items, people) for names, thing in state: print name + " is " + thing.color items[cheese] = ItemInstance3 for names, thing in state: print name + " weighs " + thing.weight While I feel like this would be usefull in the code I have, I don't know if it's either possible or the right approach. Everything I've read about user defined iterators has suggested that each instance of them is one use only. A: If I understand you question correctly then adding the following method to your class should do it: def __iter__(self): import itertools return itertools.chain(self.items.itervalues(), self.people.itervalues()) This chains together two iterators, and the ones chosen here are for the values of items and the values of people. To make your later code work though, you'll want to iterate over the items - the key-value pairs. In which case this would do it: def __iter__(self): import itertools return itertools.chain(self.items.iteritems(), self.people.iteritems()) A: There are lots of ways to do what you want. You can indeed have such a State class, and implement the iter() method (http://docs.python.org/library/stdtypes.html). You could also create a generator function: def iterate_two(l1, l2): for k in l1: yield k, l1[k] for k in l2: yield k, l2[k] You can use itertools.chain. You can use list comprehensions and generator expressions. Etc. I, personally, wouldn't create the State class as you suggest, if all it is is an iterator mechanism - I'd probably use a list comprehension.
Is it possible to create a python iterator over pre-defined mutable data?
I might be doing this wrong, if I am, let me know, but I'm curious if the following is possible: I have a class that holds a number of dictionaries, each of which pairs names to a different set of objects of a given class. For example: items = {"ball" : ItemInstance1, "sword" : ItemInstance2} people = {"Jerry" : PersonInstance1, "Bob" : PersonInstance2, "Jill" : PersonInstance3} My class would then hold the current items and people that are availible, and these would be subject to change as the state changes: Class State: def __init__(self, items, people): self.items = items self.people = people I would like to define a iter() and next() method such that it iterates through all of the values in its attributes. My first question is whether or not this is possible. If it is, will it be able to support a situation as follows: I define items and people as above then: state = State(items, people) for names, thing in state: print name + " is " + thing.color items[cheese] = ItemInstance3 for names, thing in state: print name + " weighs " + thing.weight While I feel like this would be usefull in the code I have, I don't know if it's either possible or the right approach. Everything I've read about user defined iterators has suggested that each instance of them is one use only.
[ "If I understand you question correctly then adding the following method to your class should do it:\ndef __iter__(self):\n import itertools\n return itertools.chain(self.items.itervalues(), self.people.itervalues())\n\nThis chains together two iterators, and the ones chosen here are for the values of items and the values of people.\nTo make your later code work though, you'll want to iterate over the items - the key-value pairs. In which case this would do it:\ndef __iter__(self):\n import itertools\n return itertools.chain(self.items.iteritems(), self.people.iteritems())\n\n", "There are lots of ways to do what you want. You can indeed have such a State class, and implement the iter() method (http://docs.python.org/library/stdtypes.html).\nYou could also create a generator function:\n def iterate_two(l1, l2):\n for k in l1:\n yield k, l1[k]\n for k in l2:\n yield k, l2[k]\n\nYou can use itertools.chain. You can use list comprehensions and generator expressions. Etc.\nI, personally, wouldn't create the State class as you suggest, if all it is is an iterator mechanism - I'd probably use a list comprehension.\n" ]
[ 2, 1 ]
[]
[]
[ "class", "iterator", "python" ]
stackoverflow_0002940519_class_iterator_python.txt
Q: Google App Engine appcfg.py data_upload Authentication fail I am using appcfg.py to upload data to datastore from a csv file. But every time I try, I am getting error: [info ] Authentication failed even if i am using Admin id and password. In my app.yaml file I am having: handlers: - url: /remote_api script: $PYTHON_LIB/google/appengine/ext/remote_api/handler.py login: admin - url: .* script: MainHandler.py Can anybody please help me? Thanks in advance. A: That app.yaml file looks good to me, but are you sure it's been deployed to the server? The docs explicitly note that you need to update your app on the server before using appcfg.py to bulk upload data will work, so you might try the suggested command: appcfg.py update <app-directory> You might also look at deleting your session cookies, particularly if appcfg.py isn't asking you for your authentication each time -- it may have saved an incorrect password. Hope some of this helps! A: If your administrator is an Apps for Domains account (eg, @yourdomain.com), and your app uses Google Accounts authentication, you won't be able to authenticate as an admin on your app. You need to add a Google Accounts (eg, @google.com) account as an administrator, and use that to upload.
Google App Engine appcfg.py data_upload Authentication fail
I am using appcfg.py to upload data to datastore from a csv file. But every time I try, I am getting error: [info ] Authentication failed even if i am using Admin id and password. In my app.yaml file I am having: handlers: - url: /remote_api script: $PYTHON_LIB/google/appengine/ext/remote_api/handler.py login: admin - url: .* script: MainHandler.py Can anybody please help me? Thanks in advance.
[ "That app.yaml file looks good to me, but are you sure it's been deployed to the server? The docs explicitly note that you need to update your app on the server before using appcfg.py to bulk upload data will work, so you might try the suggested command:\nappcfg.py update <app-directory>\n\nYou might also look at deleting your session cookies, particularly if appcfg.py isn't asking you for your authentication each time -- it may have saved an incorrect password.\nHope some of this helps!\n", "If your administrator is an Apps for Domains account (eg, @yourdomain.com), and your app uses Google Accounts authentication, you won't be able to authenticate as an admin on your app. You need to add a Google Accounts (eg, @google.com) account as an administrator, and use that to upload.\n" ]
[ 2, 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002895397_google_app_engine_python.txt
Q: Using custom Qt subclasses in Python First off: I'm new to both Qt and SWIG. Currently reading documentation for both of these, but this is a time consuming task, so I'm looking for some spoilers. It's good to know up-front whether something just won't work. I'm attempting to formulate a modular architecture for some in-house software. The core components are in C++ and exposed via SWIG to Python for experimentation and rapid prototyping of new components. Qt seems like it has some classes I could use to avoid re-inventing the wheel too much here, but I'm concerned about how some of the bits will fit together. Specifically, if I create some C++ classes, I'll need to expose them via SWIG. Some of these classes likely subclass Qt classes or otherwise have Qt stuff exposed in their public interfaces. This seems like it could raise some complications. There are already two interfaces for Qt in Python, PyQt and PySide. Will probably use PySide for licensing reasons. About how painful should I expect it to be to get a SWIG-wrapped custom subclass of a Qt class to play nice with either of these? What complications should I know about upfront? A: PyQt exposes C++ code to Python via SIP; PySide does so via Shiboken. Both have roughly the same capabilities as SWIG (except that they only support "extended C++ to Python", while SWIG has back-ends for Ruby, Perl, Java, and so forth as well). Neither SWIG nor SIP and Shiboken are designed to interoperate with each other. You couldn't conveniently use SWIG to wrap any code using the C++ extensions that Qt requires (to support signals and slots) and I have no idea what perils may await you in trying to interoperate SIP-wrapped (or Shiboken-wrapped) and SWIG-wrapped code. Why, may I ask, have you chosen to use two separate and equivalent ways to wrap different parts of your C++ codebase (Qt via SIP or Shiboken, everything else via SWIG)? If you can still reconsider this weird design decision I would earnestly recommend that you do so. If your choice of SWIG is carved in stone, I predict big trouble any time you're wrapping C++ code using Qt extensions (i.e., slots or signals) and a generally thoroughly miserable time for all involved. If you pick one way to wrap, and stick with it, the problems should be enormously reduced. I have no real-world experience with Shiboken (it's a bit too new, and I hardly ever do GUI apps these days any more... my world's all web app!-), but have used SIP in this role in the past (way back before it was decently documented -- these days it seems to me that it's splendidly documented, and superficial perusal of Shiboken gives me the same impression) and I can recommend it highly (indeed if I could choose it would be an option probably preferable to SWIG even if no Qt code was involved in a project).
Using custom Qt subclasses in Python
First off: I'm new to both Qt and SWIG. Currently reading documentation for both of these, but this is a time consuming task, so I'm looking for some spoilers. It's good to know up-front whether something just won't work. I'm attempting to formulate a modular architecture for some in-house software. The core components are in C++ and exposed via SWIG to Python for experimentation and rapid prototyping of new components. Qt seems like it has some classes I could use to avoid re-inventing the wheel too much here, but I'm concerned about how some of the bits will fit together. Specifically, if I create some C++ classes, I'll need to expose them via SWIG. Some of these classes likely subclass Qt classes or otherwise have Qt stuff exposed in their public interfaces. This seems like it could raise some complications. There are already two interfaces for Qt in Python, PyQt and PySide. Will probably use PySide for licensing reasons. About how painful should I expect it to be to get a SWIG-wrapped custom subclass of a Qt class to play nice with either of these? What complications should I know about upfront?
[ "PyQt exposes C++ code to Python via SIP; PySide does so via Shiboken. Both have roughly the same capabilities as SWIG (except that they only support \"extended C++ to Python\", while SWIG has back-ends for Ruby, Perl, Java, and so forth as well). Neither SWIG nor SIP and Shiboken are designed to interoperate with each other. You couldn't conveniently use SWIG to wrap any code using the C++ extensions that Qt requires (to support signals and slots) and I have no idea what perils may await you in trying to interoperate SIP-wrapped (or Shiboken-wrapped) and SWIG-wrapped code.\nWhy, may I ask, have you chosen to use two separate and equivalent ways to wrap different parts of your C++ codebase (Qt via SIP or Shiboken, everything else via SWIG)? If you can still reconsider this weird design decision I would earnestly recommend that you do so.\nIf your choice of SWIG is carved in stone, I predict big trouble any time you're wrapping C++ code using Qt extensions (i.e., slots or signals) and a generally thoroughly miserable time for all involved. If you pick one way to wrap, and stick with it, the problems should be enormously reduced. I have no real-world experience with Shiboken (it's a bit too new, and I hardly ever do GUI apps these days any more... my world's all web app!-), but have used SIP in this role in the past (way back before it was decently documented -- these days it seems to me that it's splendidly documented, and superficial perusal of Shiboken gives me the same impression) and I can recommend it highly (indeed if I could choose it would be an option probably preferable to SWIG even if no Qt code was involved in a project).\n" ]
[ 9 ]
[]
[]
[ "c++", "python", "qt", "swig" ]
stackoverflow_0002940686_c++_python_qt_swig.txt
Q: PyParsing: What does Combine() do? What is the difference between: foo = TOKEN1 + TOKEN2 and foo = Combine(TOKEN1 + TOKEN2) Thanks. UPDATE: Based on my experimentation, it seems like Combine() is for terminals, where you're trying to build an expression to match on, whereas plain + is for non-terminals. But I'm not sure. A: Combine has 2 effects: it concatenates all the tokens into a single string it requires the matching tokens to all be adjacent with no intervening whitespace If you create an expression like realnum = Word(nums) + "." + Word(nums) Then realnum.parseString("3.14") will return a list of 3 tokens: the leading '3', the '.', and the trailing '14'. But if you wrap this in Combine, as in: realnum = Combine(Word(nums) + "." + Word(nums)) then realnum.parseString("3.14") will return '3.14' (which you could then convert to a float using a parse action). And since Combine suppresses pyparsing's default whitespace skipping between tokens, you won't accidentally find "3.14" in "The answer is 3. 14 is the next answer."
PyParsing: What does Combine() do?
What is the difference between: foo = TOKEN1 + TOKEN2 and foo = Combine(TOKEN1 + TOKEN2) Thanks. UPDATE: Based on my experimentation, it seems like Combine() is for terminals, where you're trying to build an expression to match on, whereas plain + is for non-terminals. But I'm not sure.
[ "Combine has 2 effects:\n\nit concatenates all the tokens into a single string\nit requires the matching tokens to all be adjacent with no intervening whitespace\n\nIf you create an expression like \nrealnum = Word(nums) + \".\" + Word(nums)\n\nThen realnum.parseString(\"3.14\") will return a list of 3 tokens: the leading '3', the '.', and the trailing '14'. But if you wrap this in Combine, as in:\nrealnum = Combine(Word(nums) + \".\" + Word(nums))\n\nthen realnum.parseString(\"3.14\") will return '3.14' (which you could then convert to a float using a parse action). And since Combine suppresses pyparsing's default whitespace skipping between tokens, you won't accidentally find \"3.14\" in \"The answer is 3. 14 is the next answer.\"\n" ]
[ 19 ]
[]
[]
[ "nlp", "parsing", "pyparsing", "python" ]
stackoverflow_0002940489_nlp_parsing_pyparsing_python.txt
Q: PyParsing: Not all tokens passed to setParseAction() I'm parsing sentences like "CS 2110 or INFO 3300". I would like to output a format like: [[("CS" 2110)], [("INFO", 3300)]] To do this, I thought I could use setParseAction(). However, the print statements in statementParse() suggest that only the last tokens are actually passed: >>> statement.parseString("CS 2110 or INFO 3300") Match [{Suppress:("or") Re:('[A-Z]{2,}') Re:('[0-9]{4}')}] at loc 7(1,8) string CS 2110 or INFO 3300 loc: 7 tokens: ['INFO', 3300] Matched [{Suppress:("or") Re:('[A-Z]{2,}') Re:('[0-9]{4}')}] -> ['INFO', 3300] (['CS', 2110, 'INFO', 3300], {'Course': [(2110, 1), (3300, 3)], 'DeptCode': [('CS', 0), ('INFO', 2)]}) I expected all the tokens to be passed, but it's only ['INFO', 3300]. Am I doing something wrong? Or is there another way that I can produce the desired output? Here is the pyparsing code: from pyparsing import * def statementParse(str, location, tokens): print "string %s" % str print "loc: %s " % location print "tokens: %s" % tokens DEPT_CODE = Regex(r'[A-Z]{2,}').setResultsName("DeptCode") COURSE_NUMBER = Regex(r'[0-9]{4}').setResultsName("CourseNumber") OR_CONJ = Suppress("or") COURSE_NUMBER.setParseAction(lambda s, l, toks : int(toks[0])) course = DEPT_CODE + COURSE_NUMBER.setResultsName("Course") statement = course + Optional(OR_CONJ + course).setParseAction(statementParse).setDebug() A: Works better if you set the parse action on both course and the Optional (you were setting only on the Optional!): >>> statement = (course + Optional(OR_CONJ + course)).setParseAction(statementParse).setDebug() >>> statement.parseString("CS 2110 or INFO 3300") gives Match {Re:('[A-Z]{2,}') Re:('[0-9]{4}') [{Suppress:("or") Re:('[A-Z]{2,}') Re:('[0-9]{4}')}]} at loc 0(1,1) string CS 2110 or INFO 3300 loc: 0 tokens: ['CS', 2110, 'INFO', 3300] Matched {Re:('[A-Z]{2,}') Re:('[0-9]{4}') [{Suppress:("or") Re:('[A-Z]{2,}') Re:('[0-9]{4}')}]} -> ['CS', 2110, 'INFO', 3300] (['CS', 2110, 'INFO', 3300], {'Course': [(2110, 1), (3300, 3)], 'DeptCode': [('CS', 0), ('INFO', 2)]}) though I suspect what you actually want is to set the parse action on each course, not on the statement: >>> statement = course + Optional(OR_CONJ + course) >>> statement.parseString("CS 2110 or INFO 3300") Match {Re:('[A-Z]{2,}') Re:('[0-9]{4}')} at loc 0(1,1) string CS 2110 or INFO 3300 loc: 0 tokens: ['CS', 2110] Matched {Re:('[A-Z]{2,}') Re:('[0-9]{4}')} -> ['CS', 2110] Match {Re:('[A-Z]{2,}') Re:('[0-9]{4}')} at loc 10(1,11) string CS 2110 or INFO 3300 loc: 10 tokens: ['INFO', 3300] Matched {Re:('[A-Z]{2,}') Re:('[0-9]{4}')} -> ['INFO', 3300] (['CS', 2110, 'INFO', 3300], {'Course': [(2110, 1), (3300, 3)], 'DeptCode': [('CS', 0), ('INFO', 2)]}) A: In order to keep the token bits from "CS 2110" and "INFO 3300", I suggest you wrap your definition of course in a Group: course = Group(DEPT_CODE + COURSE_NUMBER).setResultsName("Course") It also looks like you are charging head-on at parsing out some kind of search expression, like "x and y or z". There is some subtlety to this problem, and I suggest you check out some of the examples at the pyparsing wiki on how to build up these kinds of expressions. Otherwise you will end up with a bird's nest of Optional("or" + this) and ZeroOrMore( "and" + that) pieces. As a last-ditch, you may even just use something with operatorPrecedence, like: DEPT_CODE = Regex(r'[A-Z]{2,}').setResultsName("DeptCode") COURSE_NUMBER = Regex(r'[0-9]{4}').setResultsName("CourseNumber") course = Group(DEPT_CODE + COURSE_NUMBER) courseSearch = operatorPrecedence(course, [ ("not", 1, opAssoc.RIGHT), ("and", 2, opAssoc.LEFT), ("or", 2, opAssoc.LEFT), ]) (You may have to download the latest 1.5.3 version from the SourceForge SVN for this to work.)
PyParsing: Not all tokens passed to setParseAction()
I'm parsing sentences like "CS 2110 or INFO 3300". I would like to output a format like: [[("CS" 2110)], [("INFO", 3300)]] To do this, I thought I could use setParseAction(). However, the print statements in statementParse() suggest that only the last tokens are actually passed: >>> statement.parseString("CS 2110 or INFO 3300") Match [{Suppress:("or") Re:('[A-Z]{2,}') Re:('[0-9]{4}')}] at loc 7(1,8) string CS 2110 or INFO 3300 loc: 7 tokens: ['INFO', 3300] Matched [{Suppress:("or") Re:('[A-Z]{2,}') Re:('[0-9]{4}')}] -> ['INFO', 3300] (['CS', 2110, 'INFO', 3300], {'Course': [(2110, 1), (3300, 3)], 'DeptCode': [('CS', 0), ('INFO', 2)]}) I expected all the tokens to be passed, but it's only ['INFO', 3300]. Am I doing something wrong? Or is there another way that I can produce the desired output? Here is the pyparsing code: from pyparsing import * def statementParse(str, location, tokens): print "string %s" % str print "loc: %s " % location print "tokens: %s" % tokens DEPT_CODE = Regex(r'[A-Z]{2,}').setResultsName("DeptCode") COURSE_NUMBER = Regex(r'[0-9]{4}').setResultsName("CourseNumber") OR_CONJ = Suppress("or") COURSE_NUMBER.setParseAction(lambda s, l, toks : int(toks[0])) course = DEPT_CODE + COURSE_NUMBER.setResultsName("Course") statement = course + Optional(OR_CONJ + course).setParseAction(statementParse).setDebug()
[ "Works better if you set the parse action on both course and the Optional (you were setting only on the Optional!):\n>>> statement = (course + Optional(OR_CONJ + course)).setParseAction(statementParse).setDebug()\n>>> statement.parseString(\"CS 2110 or INFO 3300\") \n\ngives\nMatch {Re:('[A-Z]{2,}') Re:('[0-9]{4}') [{Suppress:(\"or\") Re:('[A-Z]{2,}') Re:('[0-9]{4}')}]} at loc 0(1,1)\nstring CS 2110 or INFO 3300\nloc: 0 \ntokens: ['CS', 2110, 'INFO', 3300]\nMatched {Re:('[A-Z]{2,}') Re:('[0-9]{4}') [{Suppress:(\"or\") Re:('[A-Z]{2,}') Re:('[0-9]{4}')}]} -> ['CS', 2110, 'INFO', 3300]\n(['CS', 2110, 'INFO', 3300], {'Course': [(2110, 1), (3300, 3)], 'DeptCode': [('CS', 0), ('INFO', 2)]})\n\nthough I suspect what you actually want is to set the parse action on each course, not on the statement:\n>>> statement = course + Optional(OR_CONJ + course)\n>>> statement.parseString(\"CS 2110 or INFO 3300\") Match {Re:('[A-Z]{2,}') Re:('[0-9]{4}')} at loc 0(1,1)\nstring CS 2110 or INFO 3300\nloc: 0 \ntokens: ['CS', 2110]\nMatched {Re:('[A-Z]{2,}') Re:('[0-9]{4}')} -> ['CS', 2110]\nMatch {Re:('[A-Z]{2,}') Re:('[0-9]{4}')} at loc 10(1,11)\nstring CS 2110 or INFO 3300\nloc: 10 \ntokens: ['INFO', 3300]\nMatched {Re:('[A-Z]{2,}') Re:('[0-9]{4}')} -> ['INFO', 3300]\n(['CS', 2110, 'INFO', 3300], {'Course': [(2110, 1), (3300, 3)], 'DeptCode': [('CS', 0), ('INFO', 2)]})\n\n", "In order to keep the token bits from \"CS 2110\" and \"INFO 3300\", I suggest you wrap your definition of course in a Group:\ncourse = Group(DEPT_CODE + COURSE_NUMBER).setResultsName(\"Course\")\n\nIt also looks like you are charging head-on at parsing out some kind of search expression, like \"x and y or z\". There is some subtlety to this problem, and I suggest you check out some of the examples at the pyparsing wiki on how to build up these kinds of expressions. Otherwise you will end up with a bird's nest of Optional(\"or\" + this) and ZeroOrMore(\n\"and\" + that) pieces. As a last-ditch, you may even just use something with operatorPrecedence, like:\nDEPT_CODE = Regex(r'[A-Z]{2,}').setResultsName(\"DeptCode\") \nCOURSE_NUMBER = Regex(r'[0-9]{4}').setResultsName(\"CourseNumber\")\ncourse = Group(DEPT_CODE + COURSE_NUMBER)\n\ncourseSearch = operatorPrecedence(course, \n [\n (\"not\", 1, opAssoc.RIGHT),\n (\"and\", 2, opAssoc.LEFT),\n (\"or\", 2, opAssoc.LEFT),\n ])\n\n(You may have to download the latest 1.5.3 version from the SourceForge SVN for this to work.)\n" ]
[ 2, 2 ]
[]
[]
[ "nlp", "parsing", "pyparsing", "python" ]
stackoverflow_0002940516_nlp_parsing_pyparsing_python.txt
Q: How do I split filenames from paths using python? I have a list of files that look like this: Input /foo/bar/baz/d4dc7c496100e8ce0166e84699b4e267fe652faeb070db18c76669d1c6f69f92.mp4 /foo/baz/bar/60d24a24f19a6b6c1c4734e0f288720c9ce429bc41c2620d32e01e934bfcd344.mp4 /bar/baz/foo/cd53fe086717a9f6fecb1d0567f6d76e93c48d7790c55e83e83dd1c43251e40e.mp4 And I would like to split out the filenames from the path while retaining both. Output ['/foo/bar/baz/', 'd4dc7c496100e8ce0166e84699b4e267fe652faeb070db18c76669d1c6f69f92.mp4'] ['/foo/baz/bar/', '60d24a24f19a6b6c1c4734e0f288720c9ce429bc41c2620d32e01e934bfcd344.mp4'] ['/bar/baz/foo', 'd53fe086717a9f6fecb1d0567f6d76e93c48d7790c55e83e83dd1c43251e40e.mp4'] How would one go about this? Thanks! A: os.path.split does exactly what you require, and I quote...: os.path.split(path) Split the pathname path into a pair, (head, tail) where tail is the last pathname component and head is everything leading up to that. The tail part will never contain a slash; if path ends in a slash, tail will be empty. If there is no slash in path, head will be empty. If path is empty, both head and tail are empty. Trailing slashes are stripped from head unless it is the root (one or more slashes only). In nearly all cases, join(head, tail) equals path (the only exception being when there were multiple slashes separating head from tail). So, given a list (named e.g. paths) of complete paths, split_paths = [os.path.split(p) for p in paths] should be exactly the list-of-tuples you desire. If there's any actual reason that make you request a list-of-lists instead of the natural list-of-tuples, that's not hard to make: split_paths_as_lists = [list(os.path.split(p)) for p in paths]
How do I split filenames from paths using python?
I have a list of files that look like this: Input /foo/bar/baz/d4dc7c496100e8ce0166e84699b4e267fe652faeb070db18c76669d1c6f69f92.mp4 /foo/baz/bar/60d24a24f19a6b6c1c4734e0f288720c9ce429bc41c2620d32e01e934bfcd344.mp4 /bar/baz/foo/cd53fe086717a9f6fecb1d0567f6d76e93c48d7790c55e83e83dd1c43251e40e.mp4 And I would like to split out the filenames from the path while retaining both. Output ['/foo/bar/baz/', 'd4dc7c496100e8ce0166e84699b4e267fe652faeb070db18c76669d1c6f69f92.mp4'] ['/foo/baz/bar/', '60d24a24f19a6b6c1c4734e0f288720c9ce429bc41c2620d32e01e934bfcd344.mp4'] ['/bar/baz/foo', 'd53fe086717a9f6fecb1d0567f6d76e93c48d7790c55e83e83dd1c43251e40e.mp4'] How would one go about this? Thanks!
[ "os.path.split does exactly what you require, and I quote...:\nos.path.split(path)\n\n\nSplit the pathname path into a pair,\n (head, tail) where tail is the last\n pathname component and head is\n everything leading up to that. The\n tail part will never contain a slash;\n if path ends in a slash, tail will be\n empty. If there is no slash in path,\n head will be empty. If path is empty,\n both head and tail are empty. Trailing\n slashes are stripped from head unless\n it is the root (one or more slashes\n only). In nearly all cases, join(head,\n tail) equals path (the only exception\n being when there were multiple slashes\n separating head from tail).\n\nSo, given a list (named e.g. paths) of complete paths,\nsplit_paths = [os.path.split(p) for p in paths]\n\nshould be exactly the list-of-tuples you desire. If there's any actual reason that make you request a list-of-lists instead of the natural list-of-tuples, that's not hard to make:\nsplit_paths_as_lists = [list(os.path.split(p)) for p in paths]\n\n" ]
[ 17 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002940909_python_regex.txt
Q: How to send file from C# to apache with mod_wsgi (django) and python? How to send file from C# to apache with mod_wsgi (django) and python? It will be nice to see code example in both c# (client) and python (server). A: In C#, you can just use WebClient.UploadFile. For Django, it obviously depends what you're doing, but the documentation has simple examples.
How to send file from C# to apache with mod_wsgi (django) and python?
How to send file from C# to apache with mod_wsgi (django) and python? It will be nice to see code example in both c# (client) and python (server).
[ "In C#, you can just use WebClient.UploadFile. For Django, it obviously depends what you're doing, but the documentation has simple examples.\n" ]
[ 2 ]
[]
[]
[ "apache", "c#", "mod_wsgi", "python" ]
stackoverflow_0002940948_apache_c#_mod_wsgi_python.txt
Q: how to show the right word in my code, my code is : os.urandom(64) My code is: print os.urandom(64) which outputs: > "D:\Python25\pythonw.exe" "D:\zjm_code\a.py" \xd0\xc8=<\xdbD' \xdf\xf0\xb3>\xfc\xf2\x99\x93 =S\xb2\xcd'\xdbD\x8d\xd0\\xbc{&YkD[\xdd\x8b\xbd\x82\x9e\xad\xd5\x90\x90\xdcD9\xbf9.\xeb\x9b>\xef#n\x84 which isn't readable, so I tried this: print os.urandom(64).decode("utf-8") but then I get: > "D:\Python25\pythonw.exe" "D:\zjm_code\a.py" Traceback (most recent call last): File "D:\zjm_code\a.py", line 17, in <module> print os.urandom(64).decode("utf-8") File "D:\Python25\lib\encodings\utf_8.py", line 16, in decode return codecs.utf_8_decode(input, errors, True) UnicodeDecodeError: 'utf8' codec can't decode bytes in position 0-3: invalid data What should I do to get human-readable output? A: No shortage of choices. Here's a couple: >>> os.urandom(64).encode('hex') '0bf760072ea10140d57261d2cd16bf7af1747e964c2e117700bd84b7acee331ee39fae5cff6f3f3fc3ee3f9501c9fa38ecda4385d40f10faeb75eb3a8f557909' >>> os.urandom(64).encode('base64') 'ZuYDN1BiB0ln73+9P8eoQ3qn3Q74QzCXSViu8lqueKAOUYchMXYgmz6WDmgJm1DyTX598zE2lClX\n4iEXXYZfRA==\n' A: os.urandom is giving you a 64-bytes string. Encoding it in hex is probably the best way to make it "human readable" to some extent. E.g.: >>> s = os.urandom(64) >>> s.encode('hex') '4c28351a834d80674df3b6eb5f59a2fd0df2ed2a708d14548e4a88c7139e91ef4445a8b88db28ceb3727851c02ce1822b3c7b55a977fa4f4c4f2a0e278ca569e' Of course this gives you 128 characters in the result, which may be too long a line to read comfortably; it's easy to split it up, though -- e.g.: >>> print s[:32].encode('hex') 4c28351a834d80674df3b6eb5f59a2fd0df2ed2a708d14548e4a88c7139e91ef >>> print s[32:].encode('hex') 4445a8b88db28ceb3727851c02ce1822b3c7b55a977fa4f4c4f2a0e278ca569e two chunks of 64 characters each shown on separate lines may be easier on the eye. A: Random bytes are not likely to be unicode characters, so I'm not suprised that you get encoding errors. Instead you need to convert them somehow. If all you're trying to do is see what they are, then something like: print [ord(o) for o in os.urandom(64)] Or, if you'd prefer to have it as hex 0-9a-f: print ''.join( [hex(ord(o))[2:] for o in os.urandom(64)] )
how to show the right word in my code, my code is : os.urandom(64)
My code is: print os.urandom(64) which outputs: > "D:\Python25\pythonw.exe" "D:\zjm_code\a.py" \xd0\xc8=<\xdbD' \xdf\xf0\xb3>\xfc\xf2\x99\x93 =S\xb2\xcd'\xdbD\x8d\xd0\\xbc{&YkD[\xdd\x8b\xbd\x82\x9e\xad\xd5\x90\x90\xdcD9\xbf9.\xeb\x9b>\xef#n\x84 which isn't readable, so I tried this: print os.urandom(64).decode("utf-8") but then I get: > "D:\Python25\pythonw.exe" "D:\zjm_code\a.py" Traceback (most recent call last): File "D:\zjm_code\a.py", line 17, in <module> print os.urandom(64).decode("utf-8") File "D:\Python25\lib\encodings\utf_8.py", line 16, in decode return codecs.utf_8_decode(input, errors, True) UnicodeDecodeError: 'utf8' codec can't decode bytes in position 0-3: invalid data What should I do to get human-readable output?
[ "No shortage of choices. Here's a couple:\n>>> os.urandom(64).encode('hex')\n'0bf760072ea10140d57261d2cd16bf7af1747e964c2e117700bd84b7acee331ee39fae5cff6f3f3fc3ee3f9501c9fa38ecda4385d40f10faeb75eb3a8f557909'\n>>> os.urandom(64).encode('base64')\n'ZuYDN1BiB0ln73+9P8eoQ3qn3Q74QzCXSViu8lqueKAOUYchMXYgmz6WDmgJm1DyTX598zE2lClX\\n4iEXXYZfRA==\\n'\n\n", "os.urandom is giving you a 64-bytes string. Encoding it in hex is probably the best way to make it \"human readable\" to some extent. E.g.:\n>>> s = os.urandom(64)\n>>> s.encode('hex')\n'4c28351a834d80674df3b6eb5f59a2fd0df2ed2a708d14548e4a88c7139e91ef4445a8b88db28ceb3727851c02ce1822b3c7b55a977fa4f4c4f2a0e278ca569e'\n\nOf course this gives you 128 characters in the result, which may be too long a line to read comfortably; it's easy to split it up, though -- e.g.:\n>>> print s[:32].encode('hex')\n4c28351a834d80674df3b6eb5f59a2fd0df2ed2a708d14548e4a88c7139e91ef\n>>> print s[32:].encode('hex')\n4445a8b88db28ceb3727851c02ce1822b3c7b55a977fa4f4c4f2a0e278ca569e\n\ntwo chunks of 64 characters each shown on separate lines may be easier on the eye.\n", "Random bytes are not likely to be unicode characters, so I'm not suprised that you get encoding errors. Instead you need to convert them somehow. If all you're trying to do is see what they are, then something like:\nprint [ord(o) for o in os.urandom(64)]\n\nOr, if you'd prefer to have it as hex 0-9a-f:\nprint ''.join( [hex(ord(o))[2:] for o in os.urandom(64)] )\n\n" ]
[ 8, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002941070_python.txt
Q: django file serving issues I have in my url patterns, urlpatterns += patterns('', (r'^(?P<path>.*)$', 'django.views.static.serve', {'document_root': '/home/tipu/Dropbox/dev/workspace/search/images'}) In my template when I do <link rel="stylesheet" type="text/css" href="{{ MEDIA_URL }}style.css" /> It serves the css just fine. But the file logo.png, that's in the same directory as style.css, doesn't show when I do this: <img src = "{{ MEDIA_URL }}logo.png" id = "logo" /> Any idea why? Edit: Here they are in the same directory: http://i.imgur.com/Wlssb.png root@tipu_ubuntu:/home/tipu/Dropbox/dev/workspace/search# curl -I http://localhost:8080/logo.png HTTP/1.1 404 Not Found Date: Sun, 30 May 2010 19:56:54 GMT Server: Apache/2.2.14 (Ubuntu) Vary: Accept-Encoding Connection: close Content-Type: text/html; charset=iso-8859-1 root@tipu_ubuntu:/home/tipu/Dropbox/dev/workspace/search# curl -I http://localhost:8080/style.css HTTP/1.1 200 OK Date: Sun, 30 May 2010 19:57:06 GMT Server: Apache/2.2.14 (Ubuntu) Last-Modified: Thu, 27 May 2010 03:28:14 GMT Content-Length: 1447 Content-Type: text/css Vary: Accept-Encoding Connection: close A: Very strange. What error code is returned when you run curl -I http://localhost:8000/logo.png? Just off the top of my head, the possible problems could be: Typo (in the file name or in the template) Permissions Bad data (is it really a PNG? Did it get emptied somehow?) Also, the urlpatterns you've got there seem to put media at /. I presume that's what you want? A: I didn't fix the problem at hand, BUT, I was able to end up serving files through apache itself. I used the solution found here: http://oebfare.com/blog/2007/dec/31/django-and-static-files/ A: That Django url looks OK to me. The two curl requests are hitting Apache (Server: Apache/2.2.14 (Ubuntu)), not Django, so your urlpatterns may not have anything to do with the errors that you're seeing. Are you sure that Apache is looking at that directory and not a different one? Try swapping the image out for a different one and see if it changes - if it doesn't, you'll know that you're getting your directory paths confused.
django file serving issues
I have in my url patterns, urlpatterns += patterns('', (r'^(?P<path>.*)$', 'django.views.static.serve', {'document_root': '/home/tipu/Dropbox/dev/workspace/search/images'}) In my template when I do <link rel="stylesheet" type="text/css" href="{{ MEDIA_URL }}style.css" /> It serves the css just fine. But the file logo.png, that's in the same directory as style.css, doesn't show when I do this: <img src = "{{ MEDIA_URL }}logo.png" id = "logo" /> Any idea why? Edit: Here they are in the same directory: http://i.imgur.com/Wlssb.png root@tipu_ubuntu:/home/tipu/Dropbox/dev/workspace/search# curl -I http://localhost:8080/logo.png HTTP/1.1 404 Not Found Date: Sun, 30 May 2010 19:56:54 GMT Server: Apache/2.2.14 (Ubuntu) Vary: Accept-Encoding Connection: close Content-Type: text/html; charset=iso-8859-1 root@tipu_ubuntu:/home/tipu/Dropbox/dev/workspace/search# curl -I http://localhost:8080/style.css HTTP/1.1 200 OK Date: Sun, 30 May 2010 19:57:06 GMT Server: Apache/2.2.14 (Ubuntu) Last-Modified: Thu, 27 May 2010 03:28:14 GMT Content-Length: 1447 Content-Type: text/css Vary: Accept-Encoding Connection: close
[ "Very strange. What error code is returned when you run curl -I http://localhost:8000/logo.png?\nJust off the top of my head, the possible problems could be:\n\nTypo (in the file name or in the template)\nPermissions\nBad data (is it really a PNG? Did it get emptied somehow?)\n\nAlso, the urlpatterns you've got there seem to put media at /. I presume that's what you want?\n", "I didn't fix the problem at hand, BUT, I was able to end up serving files through apache itself. I used the solution found here: http://oebfare.com/blog/2007/dec/31/django-and-static-files/\n", "That Django url looks OK to me.\nThe two curl requests are hitting Apache (Server: Apache/2.2.14 (Ubuntu)), not Django, so your urlpatterns may not have anything to do with the errors that you're seeing. Are you sure that Apache is looking at that directory and not a different one? Try swapping the image out for a different one and see if it changes - if it doesn't, you'll know that you're getting your directory paths confused.\n" ]
[ 0, 0, 0 ]
[]
[]
[ "django", "python", "serving" ]
stackoverflow_0002940034_django_python_serving.txt
Q: Django doesn't refresh my request object when reloading the current page I have a Django web site which I want ot be viewable in different languages. Until this morning everything was working fine. Here is the deal. I go to my say About Us page and it is in English. Below it there is the change language button and when I press it everything "magically" translates to Bulgarian just the way I want it. On the other hand I have a JS menu from which the user is able to browse through the products. I click on 'T-Shirt' then a sub-menu opens bellow the previously pressed containing different categories - Men, Women, Children. The link guides me to a page where the exact clothes I have requested are listed. BUT... When I try to change the language THEN, nothing happens. I go to the Abouts Page, change the language from there, return to the clothes catalog and the language is changed... I will no paste some code. This is my change button code: function changeLanguage() { if (getCookie('language') == 'EN') { setCookie("language", 'BG'); } else { setCookie("language", 'EN'); } window.location.reload(); } My About Us page: @base def aboutUs(request): return """<b>%s</b>""" % getTranslation("About Us Text", request.COOKIES['language']) The @base method: def base(myfunc): def inner_func(*args, **kwargs): try: args[0].COOKIES['language'] except: args[0].COOKIES['language'] = 'BG' # raise Exception(request) # if I am in the AboutUs page # and I click on the language change button # the cookie value in the request object changes # if however I am in the displayClothes page # the value stays the same # some code I removed contents = myfunc(*args, **kwargs) return render_to_response('index.html', {'title': title, 'categoriesByCollection': categoriesByCollection.iteritems(), 'keys': enumerate(keys), 'values': enumerate(values), 'contents': contents, 'btnHome':getTranslation("Home Button", args[0].COOKIES['language']), 'btnProducts':getTranslation("Products Button", args[0].COOKIES['language']), 'btnOrders':getTranslation("Orders Button", args[0].COOKIES['language']), 'btnAboutUs':getTranslation("About Us Button", args[0].COOKIES['language']), 'btnContacts':getTranslation("Contact Us Button", args[0].COOKIES['language']), 'btnChangeLanguage':getTranslation("Button Change Language", args[0].COOKIES['language'])}) return inner_func And the catalog page: @base def displayClothes(request, category, collection, page): clothesToDisplay = getClothesFromCollectionAndCategory(request, category, collection) contents = "" # some code I removed return """%s""" % (contents) Let me explain that you needn't be alarmed by the large quantities of code I have posted. You don't have to understand it or even look at all of it. I've published it just in case because I really can't understand the origins of the bug. Now this is how I have narrowed the problem. I am debuging with "raise Exception(request)" every time I want to know what's inside my request object. When I place this in my aboutUs method, the language cookie value changes every time I press the language button. But NOT when I am in the displayClothes method. There the language stays the same. Also I tried putting the exception line in the beginning of the @base method. It turns out the situation there is exactly the same. When I am in my About Us page and click on the button, the language in my request object changes, but when I press the button while in the catalog page it remains unchanged. That is all I could find, and I have no idea as to how Django distinguishes my pages and in what way. P.S. The JavaScript I think works perfectly, I have tested it in multiple ways. Thank you, I hope some of you will read this enormous post, and don't hesitate to ask for more code excerpts. A: That's far too much code to read through. You really need to make an effort to trim it down. If you're sure that the error is somewhere in displayClothes, then I would comment bits out until you no longer get the error. But there doesn't appear to be anything there which changes the cookies in that view, so I don't know how successful you'll be. Also make sure that you're checking against what's actually in the request for AboutUs, not just what you think it is. A side note: you're hard coding HTML directly into your views. I'm pretty sure that you don't really want to do that - Django has templates for a reason.
Django doesn't refresh my request object when reloading the current page
I have a Django web site which I want ot be viewable in different languages. Until this morning everything was working fine. Here is the deal. I go to my say About Us page and it is in English. Below it there is the change language button and when I press it everything "magically" translates to Bulgarian just the way I want it. On the other hand I have a JS menu from which the user is able to browse through the products. I click on 'T-Shirt' then a sub-menu opens bellow the previously pressed containing different categories - Men, Women, Children. The link guides me to a page where the exact clothes I have requested are listed. BUT... When I try to change the language THEN, nothing happens. I go to the Abouts Page, change the language from there, return to the clothes catalog and the language is changed... I will no paste some code. This is my change button code: function changeLanguage() { if (getCookie('language') == 'EN') { setCookie("language", 'BG'); } else { setCookie("language", 'EN'); } window.location.reload(); } My About Us page: @base def aboutUs(request): return """<b>%s</b>""" % getTranslation("About Us Text", request.COOKIES['language']) The @base method: def base(myfunc): def inner_func(*args, **kwargs): try: args[0].COOKIES['language'] except: args[0].COOKIES['language'] = 'BG' # raise Exception(request) # if I am in the AboutUs page # and I click on the language change button # the cookie value in the request object changes # if however I am in the displayClothes page # the value stays the same # some code I removed contents = myfunc(*args, **kwargs) return render_to_response('index.html', {'title': title, 'categoriesByCollection': categoriesByCollection.iteritems(), 'keys': enumerate(keys), 'values': enumerate(values), 'contents': contents, 'btnHome':getTranslation("Home Button", args[0].COOKIES['language']), 'btnProducts':getTranslation("Products Button", args[0].COOKIES['language']), 'btnOrders':getTranslation("Orders Button", args[0].COOKIES['language']), 'btnAboutUs':getTranslation("About Us Button", args[0].COOKIES['language']), 'btnContacts':getTranslation("Contact Us Button", args[0].COOKIES['language']), 'btnChangeLanguage':getTranslation("Button Change Language", args[0].COOKIES['language'])}) return inner_func And the catalog page: @base def displayClothes(request, category, collection, page): clothesToDisplay = getClothesFromCollectionAndCategory(request, category, collection) contents = "" # some code I removed return """%s""" % (contents) Let me explain that you needn't be alarmed by the large quantities of code I have posted. You don't have to understand it or even look at all of it. I've published it just in case because I really can't understand the origins of the bug. Now this is how I have narrowed the problem. I am debuging with "raise Exception(request)" every time I want to know what's inside my request object. When I place this in my aboutUs method, the language cookie value changes every time I press the language button. But NOT when I am in the displayClothes method. There the language stays the same. Also I tried putting the exception line in the beginning of the @base method. It turns out the situation there is exactly the same. When I am in my About Us page and click on the button, the language in my request object changes, but when I press the button while in the catalog page it remains unchanged. That is all I could find, and I have no idea as to how Django distinguishes my pages and in what way. P.S. The JavaScript I think works perfectly, I have tested it in multiple ways. Thank you, I hope some of you will read this enormous post, and don't hesitate to ask for more code excerpts.
[ "That's far too much code to read through. You really need to make an effort to trim it down.\nIf you're sure that the error is somewhere in displayClothes, then I would comment bits out until you no longer get the error. But there doesn't appear to be anything there which changes the cookies in that view, so I don't know how successful you'll be. Also make sure that you're checking against what's actually in the request for AboutUs, not just what you think it is.\nA side note: you're hard coding HTML directly into your views. I'm pretty sure that you don't really want to do that - Django has templates for a reason.\n" ]
[ 1 ]
[]
[]
[ "django", "javascript", "python", "refresh", "request" ]
stackoverflow_0002938045_django_javascript_python_refresh_request.txt
Q: nested for loop Just learning Python and trying to do a nested for loop. What I'd like to do in the end is place a bunch of email addresses in a file and have this script find the info, like the sending IP of mail ID. For now i'm testing it on my /var/log/auth.log file Here is my code so far: #!/usr/bin/python # this section puts emails from file(SpamEmail) in to a array(array) in_file = open("testFile", "r") array = in_file.readlines() in_file.close() # this section opens and reads the target file, in this case 'auth.log' log = open("/var/log/auth.log", "r") auth = log.readlines() for email in array: print "Searching for " +email, for line in auth: if line.find(email) > -1: about = line.split() print about[0], print Inside 'testfile' I have the word 'disconnect' cause I know it's in the auth.log file. It just doesn't find the word 'disconnect'. In the line of "if line.find(email) > -1:" i can replace email and put "disconnect" the scripts finds it fine. Any idea? Thanks in advance. Gary A: I'm not quite sure what you're asking, but an obvious problem with the above is that readlines() returns a list of lines, each of which (except potentially the last) will have a \n line terminator. So email will have a newline at the end of it, so won't be found in line unless it's right at the end. So perhaps something like: with open('testFile', 'r') as f: emails= f.read().split('\n') with open('/var/log/auth.log', 'r') as f: lines= f.read().split('\n') for email in emails: for linei, line in enumerate(lines): if email in line: print 'Line %d, found:' % linei print line A: I got it. I needed to add from __future__ import with_statement.
nested for loop
Just learning Python and trying to do a nested for loop. What I'd like to do in the end is place a bunch of email addresses in a file and have this script find the info, like the sending IP of mail ID. For now i'm testing it on my /var/log/auth.log file Here is my code so far: #!/usr/bin/python # this section puts emails from file(SpamEmail) in to a array(array) in_file = open("testFile", "r") array = in_file.readlines() in_file.close() # this section opens and reads the target file, in this case 'auth.log' log = open("/var/log/auth.log", "r") auth = log.readlines() for email in array: print "Searching for " +email, for line in auth: if line.find(email) > -1: about = line.split() print about[0], print Inside 'testfile' I have the word 'disconnect' cause I know it's in the auth.log file. It just doesn't find the word 'disconnect'. In the line of "if line.find(email) > -1:" i can replace email and put "disconnect" the scripts finds it fine. Any idea? Thanks in advance. Gary
[ "I'm not quite sure what you're asking, but an obvious problem with the above is that readlines() returns a list of lines, each of which (except potentially the last) will have a \\n line terminator. So email will have a newline at the end of it, so won't be found in line unless it's right at the end.\nSo perhaps something like:\nwith open('testFile', 'r') as f:\n emails= f.read().split('\\n')\nwith open('/var/log/auth.log', 'r') as f:\n lines= f.read().split('\\n')\n\nfor email in emails:\n for linei, line in enumerate(lines):\n if email in line:\n print 'Line %d, found:' % linei\n print line\n\n", "I got it. I needed to add from __future__ import with_statement.\n" ]
[ 1, 0 ]
[]
[]
[ "loops", "nested", "python" ]
stackoverflow_0002932214_loops_nested_python.txt
Q: How to Not Force Login After Users Close Their Browser on gae ...Like Django's session or cookies Does anyone have a simple way of allowing this? A: Under Application Settings in the App Engine dashboard, you can choose either 1 day, 1 week, or 2 week cookie expiration, assuming you're using the Users API. I don't believe the cookie should ever be set to expire when the browser is closed, unless the user's browser setting is causing this behavior. I can certainly stay logged in to my applications when restarting my browser. A: There are plenty of session libraries that let you do persistent sessions on App Engine; Nick's Blog has a good article here showing off both Beaker and gaeutilities session facilities in a concise manner.
How to Not Force Login After Users Close Their Browser on gae
...Like Django's session or cookies Does anyone have a simple way of allowing this?
[ "Under Application Settings in the App Engine dashboard, you can choose either 1 day, 1 week, or 2 week cookie expiration, assuming you're using the Users API. \nI don't believe the cookie should ever be set to expire when the browser is closed, unless the user's browser setting is causing this behavior. I can certainly stay logged in to my applications when restarting my browser.\n", "There are plenty of session libraries that let you do persistent sessions on App Engine; Nick's Blog has a good article here showing off both Beaker and gaeutilities session facilities in a concise manner.\n" ]
[ 2, 1 ]
[]
[]
[ "authentication", "google_app_engine", "python", "session" ]
stackoverflow_0002941021_authentication_google_app_engine_python_session.txt
Q: Trying to provide a global logging function I typically write my scripts with a structure like s #!/usr/bin/python import stuff def do_things(): print "FOO" def main(): do_things() if __name__ == "__main__": main() The problem I have is I'd like to have a logging function that is defined globally and I"m not really sure how to do this. I tried a decorator function but if I define it in main I can't call it from other functions in the script. It seems like something that should be easy to do but not something I have experience with. A: import logging Python's logging library should satisfy your requirements.
Trying to provide a global logging function
I typically write my scripts with a structure like s #!/usr/bin/python import stuff def do_things(): print "FOO" def main(): do_things() if __name__ == "__main__": main() The problem I have is I'd like to have a logging function that is defined globally and I"m not really sure how to do this. I tried a decorator function but if I define it in main I can't call it from other functions in the script. It seems like something that should be easy to do but not something I have experience with.
[ "import logging\n\nPython's logging library should satisfy your requirements.\n" ]
[ 4 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0002941173_logging_python.txt
Q: How to remove commas etc from a matrix in python say ive got a matrix that looks like: [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] how can i make it on seperate lines: [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] and then remove commas etc: 0 0 0 0 0 And also to make it blank instead of 0's, so that numbers can be put in later, so in the end it will be like: _ 1 2 _ 1 _ 1 (spaces not underscores) thanks A: This allocates 4 spaces for each number in the matrix. You may have to adjust this depending on your data of course. This also uses the string format method introduced in Python 2.6. Ask if you'd like to see how to do it the old way. matrix=[[0, 1, 2, 0, 0], [0, 1, 0, 0, 0], [20, 0, 0, 0, 1]] for row in matrix: data=(str(num) if num else ' ' for num in row]) # This changes 0 to a space print(' '.join(['{0:4}'.format(elt) for elt in data])) yields 1 2 1 20 1 A: Here is a shorter version of ~untubu's answer M = [[0, 1, 2, 0, 0], [0, 1, 0, 0, 0], [20, 0, 0, 0, 1]] for row in M: print " ".join('{0:4}'.format(i or " ") for i in row) A: #!/usr/bin/env python m = [[80, 0, 3, 20, 2], [0, 2, 101, 0, 6], [0, 72 ,0, 0, 20]] def prettify(m): for r in m: print ' '.join(map(lambda e: '%4s' % e, r)).replace(" 0 ", " ") prettify(m) # => prints ... # 80 3 20 2 # 2 101 6 # 72 20 A: This answer also calculates the appropriate field length, instead of guessing 4 :) def pretty_print(matrix): matrix = [[str(x) if x else "" for x in row] for row in matrix] field_length = max(len(x) for row in matrix for x in row) return "\n".join(" ".join("%%%ds" % field_length % x for x in row) for row in matrix) There is an iteration too much here, so if performance in critical you'll want to do the initial str() pass and field_length calculation in a single non-functional loop. >>> matrix=[[0, 1, 2, 0, 0], [0, 1, 0, 0, 0], [20, 1, 1, 1, 0.30314]] >>> print pretty_print(matrix) 1 2 1 20 1 1 1 0.30314 >>> matrix=[[1, 0, 0], [0, 1, 0], [0, 0, 1]] >>> print pretty_print(matrix) 1 1 1 A: def matrix_to_string(matrix, col): lines = [] for e in matrix: lines.append(str(["{0:>{1}}".format(str(x), col) for x in e])[1:-1].replace(',','').replace('\'','')) pattern = re.compile(r'\b0\b') lines = [re.sub(pattern, ' ', e) for e in lines] return '\n'.join(lines) Example: matrix = [[0,1,0,3],[1,2,3,4],[10,20,30,40]] print(matrix_to_string(matrix, 2)) Output: 1 3 1 2 3 4 10 20 30 40 A: If you are doing a lot with matrices, I strongly suggest using numpy (3rd party package) matrix. It has a lot of features that are annoying to do with iteration (e.g., scalar multiplication and matrix addition). http://docs.scipy.org/doc/numpy/reference/generated/numpy.matrix.html Then, if you want to make "print" output your particular format, just inherit from numpy's matrix and replace the repr and str methods with some of the solutions presented by the others here. class MyMatrix(numpy.matrix): def __repr__(self): repr = numpy.matrix.__repr__(self) ... return pretty_repr __str__ = __repr__
How to remove commas etc from a matrix in python
say ive got a matrix that looks like: [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] how can i make it on seperate lines: [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] and then remove commas etc: 0 0 0 0 0 And also to make it blank instead of 0's, so that numbers can be put in later, so in the end it will be like: _ 1 2 _ 1 _ 1 (spaces not underscores) thanks
[ "This allocates 4 spaces for each number in the matrix. You may have to adjust this depending on your data of course.\nThis also uses the string format method introduced in Python 2.6. Ask if you'd like to see how to do it the old way.\nmatrix=[[0, 1, 2, 0, 0], [0, 1, 0, 0, 0], [20, 0, 0, 0, 1]]\nfor row in matrix:\n data=(str(num) if num else ' ' for num in row]) # This changes 0 to a space\n print(' '.join(['{0:4}'.format(elt) for elt in data]))\n\nyields\n 1 2 \n 1 \n20 1 \n\n", "Here is a shorter version of ~untubu's answer\nM = [[0, 1, 2, 0, 0], [0, 1, 0, 0, 0], [20, 0, 0, 0, 1]]\nfor row in M:\n print \" \".join('{0:4}'.format(i or \" \") for i in row)\n\n", "#!/usr/bin/env python\n\nm = [[80, 0, 3, 20, 2], [0, 2, 101, 0, 6], [0, 72 ,0, 0, 20]]\n\ndef prettify(m):\n for r in m:\n print ' '.join(map(lambda e: '%4s' % e, r)).replace(\" 0 \", \" \")\n\nprettify(m)\n\n# => prints ...\n# 80 3 20 2\n# 2 101 6\n# 72 20\n\n", "This answer also calculates the appropriate field length, instead of guessing 4 :)\ndef pretty_print(matrix):\n matrix = [[str(x) if x else \"\" for x in row] for row in matrix]\n field_length = max(len(x) for row in matrix for x in row)\n return \"\\n\".join(\" \".join(\"%%%ds\" % field_length % x for x in row)\n for row in matrix)\n\nThere is an iteration too much here, so if performance in critical you'll want to do the initial str() pass and field_length calculation in a single non-functional loop.\n>>> matrix=[[0, 1, 2, 0, 0], [0, 1, 0, 0, 0], [20, 1, 1, 1, 0.30314]]\n>>> print pretty_print(matrix)\n 1 2 \n 1 \n 20 1 1 1 0.30314\n>>> matrix=[[1, 0, 0], [0, 1, 0], [0, 0, 1]]\n>>> print pretty_print(matrix)\n1 \n 1 \n 1\n\n", "def matrix_to_string(matrix, col):\n lines = []\n for e in matrix:\n lines.append(str([\"{0:>{1}}\".format(str(x), col) for x in e])[1:-1].replace(',','').replace('\\'',''))\n pattern = re.compile(r'\\b0\\b')\n lines = [re.sub(pattern, ' ', e) for e in lines]\n return '\\n'.join(lines)\n\nExample:\nmatrix = [[0,1,0,3],[1,2,3,4],[10,20,30,40]]\nprint(matrix_to_string(matrix, 2))\n\nOutput:\n 1 3\n 1 2 3 4\n10 20 30 40\n\n", "If you are doing a lot with matrices, I strongly suggest using numpy (3rd party package) matrix. It has a lot of features that are annoying to do with iteration (e.g., scalar multiplication and matrix addition).\nhttp://docs.scipy.org/doc/numpy/reference/generated/numpy.matrix.html\nThen, if you want to make \"print\" output your particular format, just inherit from numpy's matrix and replace the repr and str methods with some of the solutions presented by the others here.\nclass MyMatrix(numpy.matrix):\n def __repr__(self):\n repr = numpy.matrix.__repr__(self)\n\n ...\n\n return pretty_repr\n\n __str__ = __repr__\n\n" ]
[ 4, 3, 1, 1, 0, 0 ]
[]
[]
[ "matrix", "python" ]
stackoverflow_0002937353_matrix_python.txt
Q: Django attribute error: 'module' object has no attribute 'is_usable' I got the following error when calling the url in Django. It's working before, I guess it's related with some accidental changes I made, but I have no idea what they are. Thanks before for the help, Robert Environment: Request Method: GET Request URL: http://localhost:8000/time/ Django Version: 1.2 Python Version: 2.6.1 Installed Applications: ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.admin', 'djlearn.books'] Installed Middleware: ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware') Traceback: File "/Library/Python/2.6/site-packages/django/core/handlers/base.py" in get_response 100. response = callback(request, *callback_args, **callback_kwargs) File "/Users/rhenru/Workspace/django/djlearn/src/djlearn/../djlearn/views.py" in current_datetime 16. return render_to_response('current_datetime.html',{'current_date':now,}) File "/Library/Python/2.6/site-packages/django/shortcuts/__init__.py" in render_to_response 20. return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs) File "/Library/Python/2.6/site-packages/django/template/loader.py" in render_to_string 181. t = get_template(template_name) File "/Library/Python/2.6/site-packages/django/template/loader.py" in get_template 157. template, origin = find_template(template_name) File "/Library/Python/2.6/site-packages/django/template/loader.py" in find_template 128. loader = find_template_loader(loader_name) File "/Library/Python/2.6/site-packages/django/template/loader.py" in find_template_loader 111. if not func.is_usable: Exception Type: AttributeError at /time/ Exception Value: 'module' object has no attribute 'is_usable' A: It looks like Django is looking for a usable template loader, but is finding something in settings.TEMPLATE_LOADERS that isn't honoring the template loader function protocol (described briefly here.) Is it possible that one of your recent changes was to either settings.TEMPLATE_LOADERS or to a custom template loader? If the latter, your template function needs an is_usable attribute, presumably set to True.
Django attribute error: 'module' object has no attribute 'is_usable'
I got the following error when calling the url in Django. It's working before, I guess it's related with some accidental changes I made, but I have no idea what they are. Thanks before for the help, Robert Environment: Request Method: GET Request URL: http://localhost:8000/time/ Django Version: 1.2 Python Version: 2.6.1 Installed Applications: ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.admin', 'djlearn.books'] Installed Middleware: ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware') Traceback: File "/Library/Python/2.6/site-packages/django/core/handlers/base.py" in get_response 100. response = callback(request, *callback_args, **callback_kwargs) File "/Users/rhenru/Workspace/django/djlearn/src/djlearn/../djlearn/views.py" in current_datetime 16. return render_to_response('current_datetime.html',{'current_date':now,}) File "/Library/Python/2.6/site-packages/django/shortcuts/__init__.py" in render_to_response 20. return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs) File "/Library/Python/2.6/site-packages/django/template/loader.py" in render_to_string 181. t = get_template(template_name) File "/Library/Python/2.6/site-packages/django/template/loader.py" in get_template 157. template, origin = find_template(template_name) File "/Library/Python/2.6/site-packages/django/template/loader.py" in find_template 128. loader = find_template_loader(loader_name) File "/Library/Python/2.6/site-packages/django/template/loader.py" in find_template_loader 111. if not func.is_usable: Exception Type: AttributeError at /time/ Exception Value: 'module' object has no attribute 'is_usable'
[ "It looks like Django is looking for a usable template loader, but is finding something in settings.TEMPLATE_LOADERS that isn't honoring the template loader function protocol (described briefly here.)\nIs it possible that one of your recent changes was to either settings.TEMPLATE_LOADERS or to a custom template loader? If the latter, your template function needs an is_usable attribute, presumably set to True.\n" ]
[ 4 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002941108_django_python.txt
Q: small code redundancy within while-loops (doesn't feel clean) So, in Python (though I think it can be applied to many languages), I find myself with something like this quite often: the_input = raw_input("what to print?\n") while the_input != "quit": print the_input the_input = raw_input("what to print?\n") Maybe I'm being too picky, but I don't like how the line the_input = raw_input("what to print?\n") has to get repeated. It decreases maintainability and organization. But I don't see any workarounds for avoiding the duplicate code without further worsening the problem. In some languages, I could write something like this: while ((the_input=raw_input("what to print?\n")) != "quit") { print the_input } This is definitely not Pythonic, and Python doesn't even allow for assignment within loop conditions AFAIK. This valid code fixes the redundancy, while 1: the_input = raw_input("what to print?\n") if the_input == "quit": break print the_input But doesn't feel quite right either. The while 1 implies that this loop will run forever; I'm using a loop, but giving it a fake condition and putting the real one inside it. Am I being too picky? Is there a better way to do this? Perhaps there's some language construct designed for this that I don't know of? A: Think iterators -- e.g., in this specific case: for the_input in iter(lambda: raw_input('what to print?\n'), 'quit'): print the_input Most loops in Python, except at the very lowest levels of abstractions, are best implemented as for loops with the help of some underling iterator which captures the "looping logic" -- the iter built-in can help (like here), sometimes genexps (generator expressions) can, sometimes the standard library module itertools comes to the rescue. Most often you will choose to code custom generator functions (ones using yield), or more occasionally (when you need really sophisticated state management) a custom iterator class (one defining the __iter__ special method as return self, and next [[or __next__ in the latest versions of Python]] to return "the next value from the iteration). Capturing the looping logic apart from whatever it is that you do on the various items sequentially produced by the loop itself is the key abstraction-helper here!
small code redundancy within while-loops (doesn't feel clean)
So, in Python (though I think it can be applied to many languages), I find myself with something like this quite often: the_input = raw_input("what to print?\n") while the_input != "quit": print the_input the_input = raw_input("what to print?\n") Maybe I'm being too picky, but I don't like how the line the_input = raw_input("what to print?\n") has to get repeated. It decreases maintainability and organization. But I don't see any workarounds for avoiding the duplicate code without further worsening the problem. In some languages, I could write something like this: while ((the_input=raw_input("what to print?\n")) != "quit") { print the_input } This is definitely not Pythonic, and Python doesn't even allow for assignment within loop conditions AFAIK. This valid code fixes the redundancy, while 1: the_input = raw_input("what to print?\n") if the_input == "quit": break print the_input But doesn't feel quite right either. The while 1 implies that this loop will run forever; I'm using a loop, but giving it a fake condition and putting the real one inside it. Am I being too picky? Is there a better way to do this? Perhaps there's some language construct designed for this that I don't know of?
[ "Think iterators -- e.g., in this specific case:\nfor the_input in iter(lambda: raw_input('what to print?\\n'), 'quit'):\n print the_input\n\nMost loops in Python, except at the very lowest levels of abstractions, are best implemented as for loops with the help of some underling iterator which captures the \"looping logic\" -- the iter built-in can help (like here), sometimes genexps (generator expressions) can, sometimes the standard library module itertools comes to the rescue.\nMost often you will choose to code custom generator functions (ones using yield), or more occasionally (when you need really sophisticated state management) a custom iterator class (one defining the __iter__ special method as return self, and next [[or __next__ in the latest versions of Python]] to return \"the next value from the iteration).\nCapturing the looping logic apart from whatever it is that you do on the various items sequentially produced by the loop itself is the key abstraction-helper here!\n" ]
[ 30 ]
[]
[]
[ "maintainability", "organization", "python", "redundancy" ]
stackoverflow_0002941272_maintainability_organization_python_redundancy.txt
Q: Custom constructors for models in Google App Engine (python) I'm getting back to programming for Google App Engine and I've found, in old, unused code, instances in which I wrote constructors for models. It seems like a good idea, but there's no mention of it online and I can't test to see if it works. Here's a contrived example, with no error-checking, etc.: class Dog(db.Model): name = db.StringProperty(required=True) breeds = db.StringListProperty() age = db.IntegerProperty(default=0) def __init__(self, name, breed_list, **kwargs): db.Model.__init__(**kwargs) self.name = name self.breeds = breed_list.split() rufus = Dog('Rufus', 'spaniel terrier labrador') rufus.put() The **kwargs are passed on to the Model constructor in case the model is constructed with a specified parent or key_name, or in case other properties (like age) are specified. This constructor differs from the default in that it requires that a name and breed_list be specified (although it can't ensure that they're strings), and it parses breed_list in a way that the default constructor could not. Is this a legitimate form of instantiation, or should I just use functions or static/class methods? And if it works, why aren't custom constructors used more often? A: In your example, why not use the default syntax instead of a custom constructor: rufus = Dog( name='Rufus', breeds=['spaniel','terrier','labrador'] ) Your version makes it less clear semantically IMHO. As for overriding Model constructors, Google recommends against it (see for example: http://groups.google.com/group/google-appengine/browse_thread/thread/9a651f6f58875bfe/111b975da1b4b4db?lnk=gst&q=python+constructors#111b975da1b4b4db) and that's why we don't see it in Google's code. I think it's unfortunate because constructor overriding can be useful in some cases, like creating a temporary property. One problem I know of is with Expando, anything you define in the constructor gets auto-serialized in the protocol buffer. But for base Models I am not sure what are the risks, and I too would be happy to learn more. A: There's usually no need to do something like that; the default constructor will assign name, and when working with a list it almost always makes more sense to pass an actual list instead of a space-separated string (just imagine the fun if you passed "cocker spaniel" instead of just "spaniel" there, for one thing...). That said, if you really need to do computation when instantiating a Model subclass instance, there's probably nothing inherently wrong with it. I think most people probably prefer to get the data into the right form and then create the entity, which is why you're not seeing a lot of examples like that.
Custom constructors for models in Google App Engine (python)
I'm getting back to programming for Google App Engine and I've found, in old, unused code, instances in which I wrote constructors for models. It seems like a good idea, but there's no mention of it online and I can't test to see if it works. Here's a contrived example, with no error-checking, etc.: class Dog(db.Model): name = db.StringProperty(required=True) breeds = db.StringListProperty() age = db.IntegerProperty(default=0) def __init__(self, name, breed_list, **kwargs): db.Model.__init__(**kwargs) self.name = name self.breeds = breed_list.split() rufus = Dog('Rufus', 'spaniel terrier labrador') rufus.put() The **kwargs are passed on to the Model constructor in case the model is constructed with a specified parent or key_name, or in case other properties (like age) are specified. This constructor differs from the default in that it requires that a name and breed_list be specified (although it can't ensure that they're strings), and it parses breed_list in a way that the default constructor could not. Is this a legitimate form of instantiation, or should I just use functions or static/class methods? And if it works, why aren't custom constructors used more often?
[ "In your example, why not use the default syntax instead of a custom constructor:\nrufus = Dog( name='Rufus', breeds=['spaniel','terrier','labrador'] )\n\nYour version makes it less clear semantically IMHO.\nAs for overriding Model constructors, Google recommends against it (see for example: http://groups.google.com/group/google-appengine/browse_thread/thread/9a651f6f58875bfe/111b975da1b4b4db?lnk=gst&q=python+constructors#111b975da1b4b4db) and that's why we don't see it in Google's code.\nI think it's unfortunate because constructor overriding can be useful in some cases, like creating a temporary property.\nOne problem I know of is with Expando, anything you define in the constructor gets auto-serialized in the protocol buffer.\nBut for base Models I am not sure what are the risks, and I too would be happy to learn more.\n", "There's usually no need to do something like that; the default constructor will assign name, and when working with a list it almost always makes more sense to pass an actual list instead of a space-separated string (just imagine the fun if you passed \"cocker spaniel\" instead of just \"spaniel\" there, for one thing...).\nThat said, if you really need to do computation when instantiating a Model subclass instance, there's probably nothing inherently wrong with it. I think most people probably prefer to get the data into the right form and then create the entity, which is why you're not seeing a lot of examples like that.\n" ]
[ 2, 1 ]
[]
[]
[ "constructor", "google_app_engine", "python" ]
stackoverflow_0002937823_constructor_google_app_engine_python.txt
Q: indexing for faster search of lists in a file? I have a file with around 100k lists and have a another file with again a list of around an average of 50. I want to compare 2nd item of list in second file with the 2nd element of 1st file and repeat this for each of the 50 lists in 2nd file and get the result of all the matching element. I have written the code for all this,but this is taking a lot of time as it need to check the whole the 100k list some 50 times. I want to improve the speed. I cant not post my code as it is part of big code and will be difficult to infer anything from that. A: You can afford to read all the "lakh" (hundred thousands) lines from the first file in memory once: import collections d = collections.defaultdict(list) with open('lakhlists.txt') as f: for line in f: aslist = line.split() # assuming whitespace separators d[aslist[1]].append(aslist) you don't give us many crucial parameters but I'd bet this will fit in memory (for reasonable guesses at list lengths) on typical model platforms. Assuming this part works, just looping over the other, small files, and indexing into d should be trivial in comparison;-) If you care to express your specs, and the relevant numbers, more precisely (and ideally in English), maybe more specific help can be offered!
indexing for faster search of lists in a file?
I have a file with around 100k lists and have a another file with again a list of around an average of 50. I want to compare 2nd item of list in second file with the 2nd element of 1st file and repeat this for each of the 50 lists in 2nd file and get the result of all the matching element. I have written the code for all this,but this is taking a lot of time as it need to check the whole the 100k list some 50 times. I want to improve the speed. I cant not post my code as it is part of big code and will be difficult to infer anything from that.
[ "You can afford to read all the \"lakh\" (hundred thousands) lines from the first file in memory once:\nimport collections\nd = collections.defaultdict(list)\n\nwith open('lakhlists.txt') as f:\n for line in f:\n aslist = line.split() # assuming whitespace separators\n d[aslist[1]].append(aslist)\n\nyou don't give us many crucial parameters but I'd bet this will fit in memory (for reasonable guesses at list lengths) on typical model platforms. Assuming this part works, just looping over the other, small files, and indexing into d should be trivial in comparison;-)\nIf you care to express your specs, and the relevant numbers, more precisely (and ideally in English), maybe more specific help can be offered!\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0002941525_python.txt
Q: Errors Installing PIL on Mac OS Tiger I'm trying to install the Python Imaging Library on Mac OS X 10.4, but I get errors. I'm not sure where the error starts, it's just a huge wall of text when executing sudo python setup.py install. But the last few lines are: ... collect2: ld returned 1 exit status lipo: can't open input file: /var/tmp//ccNKvQpP.out (No such file or directory) error: command 'gcc' failed with exit status 1 I've googled, but none of the results are working. A: It is a good idea to install the Fink package manager, if you have not yet done so: you have a single point entry to many open-source packages; they have been configured to as to be precisely adapted to Mac OS X. Once you have installed Fink, a simple fink install pil will do. If there is any package not in Fink that you wish to install, make sure to follow their advice on what environment variables should be defined. This way, you'll have less trouble compiling more recent versions of some packages, etc., in case you need them.
Errors Installing PIL on Mac OS Tiger
I'm trying to install the Python Imaging Library on Mac OS X 10.4, but I get errors. I'm not sure where the error starts, it's just a huge wall of text when executing sudo python setup.py install. But the last few lines are: ... collect2: ld returned 1 exit status lipo: can't open input file: /var/tmp//ccNKvQpP.out (No such file or directory) error: command 'gcc' failed with exit status 1 I've googled, but none of the results are working.
[ "It is a good idea to install the Fink package manager, if you have not yet done so: you have a single point entry to many open-source packages; they have been configured to as to be precisely adapted to Mac OS X.\nOnce you have installed Fink, a simple\nfink install pil\n\nwill do.\nIf there is any package not in Fink that you wish to install, make sure to follow their advice on what environment variables should be defined. This way, you'll have less trouble compiling more recent versions of some packages, etc., in case you need them.\n" ]
[ 0 ]
[]
[]
[ "macos", "osx_tiger", "python" ]
stackoverflow_0002941209_macos_osx_tiger_python.txt
Q: Converting a single ordered list in python to a dictionary, pythonically I can't seem to find an elegant way to start from t and result in s. >>>t = ['a',2,'b',3,'c',4] #magic >>>print s {'a': 2, 'c': 4, 'b': 3} Solutions I've come up with that seems less than elegant : s = dict() for i in xrange(0, len(t),2): s[t[i]]=t[i+1] # or something fancy with slices that I haven't figured out yet It's obviously easily solved, but, again, it seems like there's a better way. Is there? A: I'd use itertools, but, if you think that's complicated (as you've hinted in a comment), then maybe: def twobytwo(t): it = iter(t) for x in it: yield x, next(it) d = dict(twobytwo(t)) or equivalently, and back to itertools again, def twobytwo(t): a, b = itertools.tee(iter(t)) next(b) return itertools.izip(a, b) d = dict(twobytwo(t)) or, if you insist on being inline, in a season-appropriate "trick or treat" mood: d = dict((x, next(it)) for it in (iter(t),) for x in it) me, I consider this a trick, but some might find it a treat. IOW, I find this kind of thing scary, but apparently in the US around this time of the years things are supposed to be;-). Basically, the problem boils down to "how do I walk a list 2 items at a time", because dict is quite happy to take a sequence of 2-tuples and make it into a dictionary. All the solutions I'm showing here ensure only O(1) extra space is taken (beyond the space, obviously O(N), that's needed for the input list and the output dict, of course). The suggested approach in the docs (everybody should be familiar with that page, the itertool recipes) is the function pairwise on that page, which is basically the second one I suggested here. I do think every site-packages directory should contain an iterutils.py file with those recipes (pity such a file's not already a part of python's stdlib!-). A: Same idea as Lukáš Lalinský's answer, different idiom: >>> dict(zip(*([iter(t)] * 2))) {'a': 2, 'c': 4, 'b': 3} This uses the dict, zip and iter functions. It's advantage over Lukáš' answer is that it works for any iterable. How it works: iter(t) creates an iterator over the list t. [iter(t)] * 2 creates a list with two elements, which reference the same iterator. zip is a function which take two iterable objects and pairs their elements: the first elements together, the second elements together, etc., until one iterable is exhausted. zip(*([iter(t)] * 2)) causes the same iterator over t to be passed as both arguments to zip. zip will thus take the first and second element of t and pair them up. And then the third and fourth. And then the fifth and sixth, etc. dict takes an iterable containing (key, value) pairs and creates a dctionary out of them. dict(zip(*([iter(t)] * 2))) creates the dictionary as requested by the OP. A: Not exactly efficient, but if you don't need it for very large lists: dict(zip(t[::2], t[1::2])) Or your version using a generator: dict(t[i:i+2] for i in xrange(0, len(t), 2)) A: Guys, guys, use itertools. Your low-RAM users will thank you when the lists get large. >>> from itertools import izip, islice >>> t = ['a',2,'b',3,'c',4] >>> s = dict(izip(islice(t, 0, None, 2), islice(t, 1, None, 2))) >>> s {'a': 2, 'c': 4, 'b': 3} It might not look pretty, but it won't make unnecessary in-memory copies. A: Using the stream module: >>> from stream import chop >>> t = ['a',2,'b',3,'c',4] >>> s = t >> chop(2) >> dict >>> s {'a': 2, 'c': 4, 'b': 3} It should be noted that this module is fairly obscure and doesn't really "play by the rules" of what's typically considered politically correct Python. So if you are just learning Python, please don't go this route; stick to what's in the standard library. A: dict(zip(t[::2], t[1::2])) probably not the most efficient. works in python 3; you might need to import zip, in python 2.x
Converting a single ordered list in python to a dictionary, pythonically
I can't seem to find an elegant way to start from t and result in s. >>>t = ['a',2,'b',3,'c',4] #magic >>>print s {'a': 2, 'c': 4, 'b': 3} Solutions I've come up with that seems less than elegant : s = dict() for i in xrange(0, len(t),2): s[t[i]]=t[i+1] # or something fancy with slices that I haven't figured out yet It's obviously easily solved, but, again, it seems like there's a better way. Is there?
[ "I'd use itertools, but, if you think that's complicated (as you've hinted in a comment), then maybe:\ndef twobytwo(t):\n it = iter(t)\n for x in it:\n yield x, next(it)\n\nd = dict(twobytwo(t))\n\nor equivalently, and back to itertools again,\ndef twobytwo(t):\n a, b = itertools.tee(iter(t))\n next(b)\n return itertools.izip(a, b)\n\nd = dict(twobytwo(t))\n\nor, if you insist on being inline, in a season-appropriate \"trick or treat\" mood:\nd = dict((x, next(it)) for it in (iter(t),) for x in it)\n\nme, I consider this a trick, but some might find it a treat. IOW, I find this kind of thing scary, but apparently in the US around this time of the years things are supposed to be;-).\nBasically, the problem boils down to \"how do I walk a list 2 items at a time\", because dict is quite happy to take a sequence of 2-tuples and make it into a dictionary. All the solutions I'm showing here ensure only O(1) extra space is taken (beyond the space, obviously O(N), that's needed for the input list and the output dict, of course).\nThe suggested approach in the docs (everybody should be familiar with that page, the itertool recipes) is the function pairwise on that page, which is basically the second one I suggested here. I do think every site-packages directory should contain an iterutils.py file with those recipes (pity such a file's not already a part of python's stdlib!-).\n", "Same idea as Lukáš Lalinský's answer, different idiom:\n>>> dict(zip(*([iter(t)] * 2)))\n{'a': 2, 'c': 4, 'b': 3}\n\nThis uses the dict, zip and iter functions. It's advantage over Lukáš' answer is that it works for any iterable. How it works:\n\niter(t) creates an iterator over the list t.\n[iter(t)] * 2 creates a list with two elements, which reference the same iterator.\nzip is a function which take two iterable objects and pairs their elements: the first elements together, the second elements together, etc., until one iterable is exhausted.\nzip(*([iter(t)] * 2)) causes the same iterator over t to be passed as both arguments to zip. zip will thus take the first and second element of t and pair them up. And then the third and fourth. And then the fifth and sixth, etc.\ndict takes an iterable containing (key, value) pairs and creates a dctionary out of them.\ndict(zip(*([iter(t)] * 2))) creates the dictionary as requested by the OP.\n\n", "Not exactly efficient, but if you don't need it for very large lists:\ndict(zip(t[::2], t[1::2]))\n\nOr your version using a generator:\ndict(t[i:i+2] for i in xrange(0, len(t), 2))\n\n", "Guys, guys, use itertools. Your low-RAM users will thank you when the lists get large.\n>>> from itertools import izip, islice\n>>> t = ['a',2,'b',3,'c',4]\n>>> s = dict(izip(islice(t, 0, None, 2), islice(t, 1, None, 2)))\n>>> s\n{'a': 2, 'c': 4, 'b': 3}\n\nIt might not look pretty, but it won't make unnecessary in-memory copies.\n", "Using the stream module:\n>>> from stream import chop\n>>> t = ['a',2,'b',3,'c',4]\n>>> s = t >> chop(2) >> dict\n>>> s\n{'a': 2, 'c': 4, 'b': 3}\n\nIt should be noted that this module is fairly obscure and doesn't really \"play by the rules\" of what's typically considered politically correct Python. So if you are just learning Python, please don't go this route; stick to what's in the standard library.\n", "dict(zip(t[::2], t[1::2]))\n\nprobably not the most efficient. works in python 3; you might need to import zip, in python 2.x\n" ]
[ 10, 9, 7, 6, 2, 1 ]
[]
[]
[ "dictionary", "list", "python", "python_itertools" ]
stackoverflow_0001639772_dictionary_list_python_python_itertools.txt
Q: Coding the Python way I've just spent the last half semester at Uni learning python. I've really enjoyed it, and was hoping for a few tips on how to write more 'pythonic' code. This is the __init__ class from a recent assignment I did. At the time I wrote it, I was trying to work out how I could re-write this using lambdas, or in a neater, more efficient way, but ran out of time. def __init__(self, dir): def _read_files(_, dir, files): for file in files: if file == "classes.txt": class_list = readtable(dir+"/"+file) for item in class_list: Enrol.class_info_dict[item[0]] = item[1:] if item[1] in Enrol.classes_dict: Enrol.classes_dict[item[1]].append(item[0]) else: Enrol.classes_dict[item[1]] = [item[0]] elif file == "subjects.txt": subject_list = readtable(dir+"/"+file) for item in subject_list: Enrol.subjects_dict[item[0]] = item[1] elif file == "venues.txt": venue_list = readtable(dir+"/"+file) for item in venue_list: Enrol.venues_dict[item[0]] = item[1:] elif file.endswith('.roll'): roll_list = readlines(dir+"/"+file) file = os.path.splitext(file)[0] Enrol.class_roll_dict[file] = roll_list for item in roll_list: if item in Enrol.enrolled_dict: Enrol.enrolled_dict[item].append(file) else: Enrol.enrolled_dict[item] = [file] try: os.path.walk(dir, _read_files, None) except: print "There was a problem reading the directory" As you can see, it's a little bulky. If anyone has the time or inclination, I'd really appreciate a few tips on some python best-practices. Thanks. A: Couple things that can clean up your code a bit: Use the dictionary's setdefault. If the key is missing, then it sets it to the default you provide it with, then returns it. Otherwise, it just ignores the 2nd parameter and returns what was in the dictionary. This avoids the clunky if-statements. Enrol.venues_dict.setdefault(key, []).append(file) >>> x = {} >>> x.setdefault(99, []).append(5) >>> x.setdefault(99, []).append(6) >>> x {99: [5, 6]} >>> x.setdefault(100, []).append(1) >>> x {99: [5, 6], 100: [1]} The other possibility is to use os.path.join to make file paths. This is safer than just doing string concatenation. os.path.join(dir, file) Other than that, looks good in terms of style, IMO. A: In addition to orangeoctopus's suggestions to use setdefault, you can refactor the if-else into a dispatcher (the typical replacement for big if-else and switch statements): # list of 2-tuples: (bool func(string filename), handler_function) handlers = [ ((lambda fn: fn == "classes.txt"), HandleClasses), ((lambda fn: fn == "subjects.txt"), HandleSubjects), ((lambda fn: fn.endswith(".roll")), HandleRoll) ] then do for filename in files: for matcher, handler in handlers: if matcher(filename): handler(filename) break A: Another important point if you want to use you script for long (some would say very long) is to not use deprecated functions in new code: os.path.walk dissapeared in python 3.x. Now you can use os.walk instead. However os.walk is different to os.path.walk : it does not accept a processing function in its signature. So refactoring your code will imply a little bit more than changing names.
Coding the Python way
I've just spent the last half semester at Uni learning python. I've really enjoyed it, and was hoping for a few tips on how to write more 'pythonic' code. This is the __init__ class from a recent assignment I did. At the time I wrote it, I was trying to work out how I could re-write this using lambdas, or in a neater, more efficient way, but ran out of time. def __init__(self, dir): def _read_files(_, dir, files): for file in files: if file == "classes.txt": class_list = readtable(dir+"/"+file) for item in class_list: Enrol.class_info_dict[item[0]] = item[1:] if item[1] in Enrol.classes_dict: Enrol.classes_dict[item[1]].append(item[0]) else: Enrol.classes_dict[item[1]] = [item[0]] elif file == "subjects.txt": subject_list = readtable(dir+"/"+file) for item in subject_list: Enrol.subjects_dict[item[0]] = item[1] elif file == "venues.txt": venue_list = readtable(dir+"/"+file) for item in venue_list: Enrol.venues_dict[item[0]] = item[1:] elif file.endswith('.roll'): roll_list = readlines(dir+"/"+file) file = os.path.splitext(file)[0] Enrol.class_roll_dict[file] = roll_list for item in roll_list: if item in Enrol.enrolled_dict: Enrol.enrolled_dict[item].append(file) else: Enrol.enrolled_dict[item] = [file] try: os.path.walk(dir, _read_files, None) except: print "There was a problem reading the directory" As you can see, it's a little bulky. If anyone has the time or inclination, I'd really appreciate a few tips on some python best-practices. Thanks.
[ "Couple things that can clean up your code a bit:\nUse the dictionary's setdefault. If the key is missing, then it sets it to the default you provide it with, then returns it. Otherwise, it just ignores the 2nd parameter and returns what was in the dictionary. This avoids the clunky if-statements.\nEnrol.venues_dict.setdefault(key, []).append(file)\n\n>>> x = {}\n>>> x.setdefault(99, []).append(5) \n>>> x.setdefault(99, []).append(6)\n>>> x\n{99: [5, 6]}\n>>> x.setdefault(100, []).append(1)\n>>> x\n{99: [5, 6], 100: [1]}\n\nThe other possibility is to use os.path.join to make file paths. This is safer than just doing string concatenation.\nos.path.join(dir, file)\n\nOther than that, looks good in terms of style, IMO.\n", "In addition to orangeoctopus's suggestions to use setdefault, you can refactor the if-else into a dispatcher (the typical replacement for big if-else and switch statements):\n# list of 2-tuples: (bool func(string filename), handler_function)\nhandlers = [\n ((lambda fn: fn == \"classes.txt\"), HandleClasses),\n ((lambda fn: fn == \"subjects.txt\"), HandleSubjects),\n ((lambda fn: fn.endswith(\".roll\")), HandleRoll)\n]\n\nthen do\nfor filename in files:\n for matcher, handler in handlers:\n if matcher(filename):\n handler(filename)\n break\n\n", "Another important point if you want to use you script for long (some would say very long) is to not use deprecated functions in new code: \nos.path.walk dissapeared in python 3.x. Now you can use os.walk instead. However os.walk is different to os.path.walk : it does not accept a processing function in its signature. So refactoring your code will imply a little bit more than changing names. \n" ]
[ 5, 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0002941271_python.txt
Q: Dynamically loading modules in Python (+ multi processing question) I am writing a Python package which reads the list of modules (along with ancillary data) from a configuration file. I then want to iterate through each of the dynamically loaded modules and invoke a do_work() function in it which will spawn a new process, so that the code runs ASYNCHRONOUSLY in a separate process. At the moment, I am importing the list of all known modules at the beginning of my main script - this is a nasty hack I feel, and is not very flexible, as well as being a maintenance pain. This is the function that spawns the processes. I will like to modify it to dynamically load the module when it is encountered. The key in the dictionary is the name of the module containing the code: def do_work(work_info): for (worker, dataset) in work_info.items(): #import the module defined by variable worker here... # [Edit] NOT using threads anymore, want to spawn processes asynchronously here... #t = threading.Thread(target=worker.do_work, args=[dataset]) # I'll NOT dameonize since spawned children need to clean up on shutdown # Since the threads will be holding resources #t.daemon = True #t.start() Question 1 When I call the function in my script (as written above), I get the following error: AttributeError: 'str' object has no attribute 'do_work' Which makes sense, since the dictionary key is a string (name of the module to be imported). When I add the statement: import worker before spawning the thread, I get the error: ImportError: No module named worker This is strange, since the variable name rather than the value it holds are being used - when I print the variable, I get the value (as I expect) whats going on? Question 2 As I mentioned in the comments section, I realize that the do_work() function written in the spawned children needs to cleanup after itself. My understanding is to write a clean_up function that is called when do_work() has completed successfully, or an unhandled exception is caught - is there anything more I need to do to ensure resources don't leak or leave the OS in an unstable state? Question 3 If I comment out the t.daemon flag statement, will the code stil run ASYNCHRONOUSLY?. The work carried out by the spawned children are pretty intensive, and I don't want to have to be waiting for one child to finish before spawning another child. BTW, I am aware that threading in Python is in reality, a kind of time sharing/slicing - thats ok Lastly is there a better (more Pythonic) way of doing what I'm trying to do? [Edit] After reading a little more about Pythons GIL and the threading (ahem - hack) in Python, I think its best to use separate processes instead (at least IIUC, the script can take advantage of multiple processes if they are available), so I will be spawning new processes instead of threads. I have some sample code for spawning processes, but it is a bit trivial (using lambad functions). I would like to know how to expand it, so that it can deal with running functions in a loaded module (like I am doing above). This is a snippet of what I have: def do_mp_bench(): q = mp.Queue() # Not only thread safe, but "process safe" p1 = mp.Process(target=lambda: q.put(sum(range(10000000)))) p2 = mp.Process(target=lambda: q.put(sum(range(10000000)))) p1.start() p2.start() r1 = q.get() r2 = q.get() return r1 + r2 How may I modify this to process a dictionary of modules and run a do_work() function in each loaded module in a new process? A: Question 1: use __import__(). Question 2: why not just do the cleanup at the end of the do_work() function? Question 3: IIRC daemon thread just means that the program won't automatically wait for this thread to end. A: This was revised to make use of import() documentation here: import and refactored to utilize the requested multiprocessing module as documented here: multiprocessing. This hasn't been tested. def do_work(work_info): q = mp.Queue() for (worker, dataset) in work_info.items(): xworker = __import__(worker) p = mp.Process(target=xworker.do_work, args=dataset).start() q.put(p) while not q.empty(): r = q.get()
Dynamically loading modules in Python (+ multi processing question)
I am writing a Python package which reads the list of modules (along with ancillary data) from a configuration file. I then want to iterate through each of the dynamically loaded modules and invoke a do_work() function in it which will spawn a new process, so that the code runs ASYNCHRONOUSLY in a separate process. At the moment, I am importing the list of all known modules at the beginning of my main script - this is a nasty hack I feel, and is not very flexible, as well as being a maintenance pain. This is the function that spawns the processes. I will like to modify it to dynamically load the module when it is encountered. The key in the dictionary is the name of the module containing the code: def do_work(work_info): for (worker, dataset) in work_info.items(): #import the module defined by variable worker here... # [Edit] NOT using threads anymore, want to spawn processes asynchronously here... #t = threading.Thread(target=worker.do_work, args=[dataset]) # I'll NOT dameonize since spawned children need to clean up on shutdown # Since the threads will be holding resources #t.daemon = True #t.start() Question 1 When I call the function in my script (as written above), I get the following error: AttributeError: 'str' object has no attribute 'do_work' Which makes sense, since the dictionary key is a string (name of the module to be imported). When I add the statement: import worker before spawning the thread, I get the error: ImportError: No module named worker This is strange, since the variable name rather than the value it holds are being used - when I print the variable, I get the value (as I expect) whats going on? Question 2 As I mentioned in the comments section, I realize that the do_work() function written in the spawned children needs to cleanup after itself. My understanding is to write a clean_up function that is called when do_work() has completed successfully, or an unhandled exception is caught - is there anything more I need to do to ensure resources don't leak or leave the OS in an unstable state? Question 3 If I comment out the t.daemon flag statement, will the code stil run ASYNCHRONOUSLY?. The work carried out by the spawned children are pretty intensive, and I don't want to have to be waiting for one child to finish before spawning another child. BTW, I am aware that threading in Python is in reality, a kind of time sharing/slicing - thats ok Lastly is there a better (more Pythonic) way of doing what I'm trying to do? [Edit] After reading a little more about Pythons GIL and the threading (ahem - hack) in Python, I think its best to use separate processes instead (at least IIUC, the script can take advantage of multiple processes if they are available), so I will be spawning new processes instead of threads. I have some sample code for spawning processes, but it is a bit trivial (using lambad functions). I would like to know how to expand it, so that it can deal with running functions in a loaded module (like I am doing above). This is a snippet of what I have: def do_mp_bench(): q = mp.Queue() # Not only thread safe, but "process safe" p1 = mp.Process(target=lambda: q.put(sum(range(10000000)))) p2 = mp.Process(target=lambda: q.put(sum(range(10000000)))) p1.start() p2.start() r1 = q.get() r2 = q.get() return r1 + r2 How may I modify this to process a dictionary of modules and run a do_work() function in each loaded module in a new process?
[ "Question 1: use __import__().\nQuestion 2: why not just do the cleanup at the end of the do_work() function?\nQuestion 3: IIRC daemon thread just means that the program won't automatically wait for this thread to end.\n", "This was revised to make use of import() documentation here: import and refactored to utilize the requested multiprocessing module as documented here: multiprocessing. This hasn't been tested.\ndef do_work(work_info):\n q = mp.Queue()\n for (worker, dataset) in work_info.items():\n xworker = __import__(worker)\n p = mp.Process(target=xworker.do_work, args=dataset).start()\n q.put(p)\n while not q.empty():\n r = q.get()\n\n" ]
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002942025_python.txt
Q: SQLAlchemy - relationship limited on more than just the foreign key I have a wiki db layout with Page and Revisions. Each Revision has a page_id referencing the Page, a page relationship to the referenced page; each Page has a all_revisions relationship to all its revisions. So far so common. But I want to implement different epochs for the pages: If a page was deleted and is recreated, the new revisions have a new epoch. To help find the correct revisions, each page has a current_epoch field. Now I want to provide a revisions relation on the page that only contains its revisions, but only those where the epochs match. This is what I've tried: revisions = relationship('Revision', primaryjoin = and_( 'Page.id == Revision.page_id', 'Page.current_epoch == Revision.epoch', ), foreign_keys=['Page.id', 'Page.current_epoch'] ) Full code (you may run that as it is) However this always raises ArgumentError: Could not determine relationship direction for primaryjoin condition ...`, I've tried all I had come to mind, it didn't work. What am I doing wrong? Is this a bad approach for doing this, how could it be done other than with a relationship? A: Try installing relationship after both classes are created: Page.revisions = relationship( 'Revision', primaryjoin = (Page.id==Revision.page_id) & \ (Page.current_epoch==Revision.epoch), foreign_keys=[Page.id, Page.current_epoch], uselist=True, ) BTW, your test is not correct: revisions property loads data from database while you haven't added them to session. Update: The problem in your code is that primaryjoin parameter is not string, so it's not evaluated. Using string in primaryjoin works fine: class Page(Base): # [skipped] revisions = relationship( 'Revision', primaryjoin = '(Page.id==Revision.page_id) & '\ '(Page.current_epoch==Revision.epoch)', foreign_keys=[id, current_epoch], uselist=True, )
SQLAlchemy - relationship limited on more than just the foreign key
I have a wiki db layout with Page and Revisions. Each Revision has a page_id referencing the Page, a page relationship to the referenced page; each Page has a all_revisions relationship to all its revisions. So far so common. But I want to implement different epochs for the pages: If a page was deleted and is recreated, the new revisions have a new epoch. To help find the correct revisions, each page has a current_epoch field. Now I want to provide a revisions relation on the page that only contains its revisions, but only those where the epochs match. This is what I've tried: revisions = relationship('Revision', primaryjoin = and_( 'Page.id == Revision.page_id', 'Page.current_epoch == Revision.epoch', ), foreign_keys=['Page.id', 'Page.current_epoch'] ) Full code (you may run that as it is) However this always raises ArgumentError: Could not determine relationship direction for primaryjoin condition ...`, I've tried all I had come to mind, it didn't work. What am I doing wrong? Is this a bad approach for doing this, how could it be done other than with a relationship?
[ "Try installing relationship after both classes are created:\nPage.revisions = relationship(\n 'Revision',\n primaryjoin = (Page.id==Revision.page_id) & \\\n (Page.current_epoch==Revision.epoch),\n foreign_keys=[Page.id, Page.current_epoch],\n uselist=True,\n)\n\nBTW, your test is not correct: revisions property loads data from database while you haven't added them to session.\nUpdate: The problem in your code is that primaryjoin parameter is not string, so it's not evaluated. Using string in primaryjoin works fine:\nclass Page(Base):\n # [skipped]\n revisions = relationship(\n 'Revision',\n primaryjoin = '(Page.id==Revision.page_id) & '\\\n '(Page.current_epoch==Revision.epoch)',\n foreign_keys=[id, current_epoch],\n uselist=True,\n )\n\n" ]
[ 4 ]
[]
[]
[ "database", "python", "relationship", "sqlalchemy" ]
stackoverflow_0002935605_database_python_relationship_sqlalchemy.txt
Q: Setting System.Drawing.Color through .NET COM Interop I am trying to use Aspose.Words library through COM Interop. There is one critical problem: I cannot set color. It is supposed to work by assigning to DocumentBuilder.Font.Color, but when I try to do it I get OLE error 0x80131509. My problem is pretty much like this one. update: Code Sample: from win32com.client import Dispatch Doc = Dispatch("Aspose.Words.Document") Builder = Dispatch("Aspose.Words.DocumentBuilder") Builder.Document = Doc print Builder.Font.Size print Builder.Font.Color Result: 12.0 Traceback (most recent call last): File "aaa.py", line 6, in <module> print Builder.Font.Color File "D:\Python26\lib\site-packages\win32com\client\dynamic.py", line 501, in __getattr__ ret = self._oleobj_.Invoke(retEntry.dispid,0,invoke_type,1) pywintypes.com_error: (-2146233079, 'OLE error 0x80131509', None, None) Using something like Font.Color = 0xff0000 fails with same error message While this code works ok: using Aspose.Words; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.Font.Color = System.Drawing.Color.Blue; builder.Write("aaa"); doc.Save("c:\\1.doc"); } } } So it looks like COM Interop problem. A: Please, check the answer provided here: http://www.aspose.com/community/forums/thread/240901/create-a-pivot-table-from-multiple-data-ranges.aspx I think, this approach should help you to resolve the problem.
Setting System.Drawing.Color through .NET COM Interop
I am trying to use Aspose.Words library through COM Interop. There is one critical problem: I cannot set color. It is supposed to work by assigning to DocumentBuilder.Font.Color, but when I try to do it I get OLE error 0x80131509. My problem is pretty much like this one. update: Code Sample: from win32com.client import Dispatch Doc = Dispatch("Aspose.Words.Document") Builder = Dispatch("Aspose.Words.DocumentBuilder") Builder.Document = Doc print Builder.Font.Size print Builder.Font.Color Result: 12.0 Traceback (most recent call last): File "aaa.py", line 6, in <module> print Builder.Font.Color File "D:\Python26\lib\site-packages\win32com\client\dynamic.py", line 501, in __getattr__ ret = self._oleobj_.Invoke(retEntry.dispid,0,invoke_type,1) pywintypes.com_error: (-2146233079, 'OLE error 0x80131509', None, None) Using something like Font.Color = 0xff0000 fails with same error message While this code works ok: using Aspose.Words; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.Font.Color = System.Drawing.Color.Blue; builder.Write("aaa"); doc.Save("c:\\1.doc"); } } } So it looks like COM Interop problem.
[ "Please, check the answer provided here:\nhttp://www.aspose.com/community/forums/thread/240901/create-a-pivot-table-from-multiple-data-ranges.aspx\nI think, this approach should help you to resolve the problem.\n" ]
[ 0 ]
[]
[]
[ ".net", "aspose", "com", "interop", "python" ]
stackoverflow_0002934640_.net_aspose_com_interop_python.txt
Q: Application in which I need Auto-update just like Gmail inbox,calendar Face-Book etc I have made application in which I have kept calendar. Now I need that if admin changes his calendar and if it is affected to user and if that user is currently looking that calendar then whatever changes Admin has done that should reflect to user without refreshing the page, just like when email comes to Gmail then without refreshing we can see the inbox marked as unread... So to implement that what should I do? I am using J-query for user interface and Python as back-end? A: go to $.ajax() A: Python Comet Server this thread contains info on a comet like server for python, this would give you the real time browser data push I think you are referring to. I believe gmail does it by using an iframe hack and a setinterval check using some javascript ajax call.
Application in which I need Auto-update just like Gmail inbox,calendar Face-Book etc
I have made application in which I have kept calendar. Now I need that if admin changes his calendar and if it is affected to user and if that user is currently looking that calendar then whatever changes Admin has done that should reflect to user without refreshing the page, just like when email comes to Gmail then without refreshing we can see the inbox marked as unread... So to implement that what should I do? I am using J-query for user interface and Python as back-end?
[ "go to $.ajax()\n", "Python Comet Server this thread contains info on a comet like server for python, this would give you the real time browser data push I think you are referring to. I believe gmail does it by using an iframe hack and a setinterval check using some javascript ajax call.\n" ]
[ 2, 0 ]
[]
[]
[ "google_apps", "jquery", "python" ]
stackoverflow_0002942691_google_apps_jquery_python.txt
Q: python dictionary with constant value-type I bumped into a case where I need a big (=huge) python dictionary, which turned to be quite memory-consuming. However, since all of the values are of a single type (long) - as well as the keys, I figured I can use python (or numpy, doesn't really matter) array for the values ; and wrap the needed interface (in: x ; out: d[x]) with an object which actually uses these arrays for the keys and values storage. I can use a index-conversion object (input --> index, of 1..n, where n is the different-values counter), and return array[index]. I can elaborate on some techniques of how to implement such an indexing-methods with reasonable memory requirement, it works and even pretty good. However, I wonder if there is such a data-structure-object already exists (in python, or wrapped to python from C/++), in any package (I checked collections, and some Google searches). Any comment will be welcome, thanks. A: This kind of task is a typical database-type access (large volume of data in columns of a given type). You would create a simple table with indexed keys, for fast access. I don't have experience with it, but you might want to check out the standard sqlite3 module. If your keys do not change over time, you could alternatively put all your data in two Python memory-optimized arrays (standard array module); one array contains the sorted keys, and the other one the corresponding values. You could then find key indexes through the optimized bisect.bisect function. A: You might try using std::map. Boost.Python provides a Python wrapping for std::map out-of-the-box.
python dictionary with constant value-type
I bumped into a case where I need a big (=huge) python dictionary, which turned to be quite memory-consuming. However, since all of the values are of a single type (long) - as well as the keys, I figured I can use python (or numpy, doesn't really matter) array for the values ; and wrap the needed interface (in: x ; out: d[x]) with an object which actually uses these arrays for the keys and values storage. I can use a index-conversion object (input --> index, of 1..n, where n is the different-values counter), and return array[index]. I can elaborate on some techniques of how to implement such an indexing-methods with reasonable memory requirement, it works and even pretty good. However, I wonder if there is such a data-structure-object already exists (in python, or wrapped to python from C/++), in any package (I checked collections, and some Google searches). Any comment will be welcome, thanks.
[ "This kind of task is a typical database-type access (large volume of data in columns of a given type). You would create a simple table with indexed keys, for fast access. I don't have experience with it, but you might want to check out the standard sqlite3 module.\nIf your keys do not change over time, you could alternatively put all your data in two Python memory-optimized arrays (standard array module); one array contains the sorted keys, and the other one the corresponding values. You could then find key indexes through the optimized bisect.bisect function.\n", "You might try using std::map. Boost.Python provides a Python wrapping for std::map out-of-the-box.\n" ]
[ 2, 0 ]
[]
[]
[ "arrays", "data_structures", "dictionary", "python" ]
stackoverflow_0002942375_arrays_data_structures_dictionary_python.txt
Q: Python doesn't work properly when I execute a script after using Right Click >> Command Prompt Here This is a weird bug. I know it's something funky going on with my PATH variable, but no idea how to fix it. If I have a script C:\Test\test.py and I execute it from within IDLE, it works fine. If I open up Command Prompt using Run>>cmd.exe and navigate manually it works fine. But if I use Windows 7's convenient Right Click on folder >> Command Prompt Here then type test.py it fails with import errors. I also cannot just type "python" to reach a python shell session if I use the latter method above. Any ideas? Edit: printing the python path for the command prompt that works yields the correct paths. Printing it on the non-working "Command prompt here" yields: Environment variable python not defined". A: First of all, I work on Windows7 (among others) and running python from the command line works for me using "Command Prompt Here". Make sure you have the directory containing python.exe in your PATH environment variable, by running "Command Prompt Here" and running set. Now for import errors. When importing, Python looks for modules in directories specified in the sys.path list. The PYTHONPATH environment variable is added to this list, along with some default directories, and the directory of the given Python script. However, in IDLE this directory is the directory of IDLE, so this could be causing the difference you are seeing when running things from IDLE compared to running them from the command line. See http://docs.python.org/tutorial/modules.html#the-module-search-path for details. Here is my advice on how to resolve this issue. You didn't mention what import errors you are recieving, but try running the script inside IDLE and checking the problematic modules' .__file__ attribute to see where they are. Then compare the sys.path from inside IDLE to sys.path you get when running Python from the command line. This should give you the information required to resolve your import errors. A: I don't use Windows much, but maybe when you open Right Click -> Command Prompt, the PATH is different from navigate manually. First try to print your PATH (oh I have no ideal how to do this) and see if it different in 2 situation. A: You can check the currently present enviroment variables with the "set" command on the command line. For python to work you need at least PYTHONPATH pointing to your python libs and the path to python.exe should be included in your PATH variable.
Python doesn't work properly when I execute a script after using Right Click >> Command Prompt Here
This is a weird bug. I know it's something funky going on with my PATH variable, but no idea how to fix it. If I have a script C:\Test\test.py and I execute it from within IDLE, it works fine. If I open up Command Prompt using Run>>cmd.exe and navigate manually it works fine. But if I use Windows 7's convenient Right Click on folder >> Command Prompt Here then type test.py it fails with import errors. I also cannot just type "python" to reach a python shell session if I use the latter method above. Any ideas? Edit: printing the python path for the command prompt that works yields the correct paths. Printing it on the non-working "Command prompt here" yields: Environment variable python not defined".
[ "First of all, I work on Windows7 (among others) and running python from the command line works for me using \"Command Prompt Here\". Make sure you have the directory containing python.exe in your PATH environment variable, by running \"Command Prompt Here\" and running set.\nNow for import errors. When importing, Python looks for modules in directories specified in the sys.path list. The PYTHONPATH environment variable is added to this list, along with some default directories, and the directory of the given Python script. However, in IDLE this directory is the directory of IDLE, so this could be causing the difference you are seeing when running things from IDLE compared to running them from the command line.\nSee http://docs.python.org/tutorial/modules.html#the-module-search-path for details.\nHere is my advice on how to resolve this issue. You didn't mention what import errors you are recieving, but try running the script inside IDLE and checking the problematic modules' .__file__ attribute to see where they are. Then compare the sys.path from inside IDLE to sys.path you get when running Python from the command line. This should give you the information required to resolve your import errors.\n", "I don't use Windows much, but maybe when you open Right Click -> Command Prompt, the PATH is different from navigate manually. First try to print your PATH (oh I have no ideal how to do this) and see if it different in 2 situation.\n", "You can check the currently present enviroment variables with the \"set\" command on the command line. For python to work you need at least PYTHONPATH pointing to your python libs and the path to python.exe should be included in your PATH variable.\n" ]
[ 2, 1, 0 ]
[]
[]
[ "path", "python", "windows_7" ]
stackoverflow_0002943071_path_python_windows_7.txt
Q: midi input in python I'm coding a demo in python and I need to read a MIDI file in python (no real-time stuff is needed). In particular, I'm looking for a library which preserves channel information. The most promising libraries I found are: http://code.google.com/p/midiutil/ http://www.mxm.dk/products/public/pythonmidi Any experience with those? Thanks a lot Nicola Montecchio A: I've been using MXM's library in harpy for some time now, and am quite satisfied with it. Fast enough for my purposes, and easy to extend. I suppose it does what you need, seeing as how I use it to split MIDI files into single channel files.
midi input in python
I'm coding a demo in python and I need to read a MIDI file in python (no real-time stuff is needed). In particular, I'm looking for a library which preserves channel information. The most promising libraries I found are: http://code.google.com/p/midiutil/ http://www.mxm.dk/products/public/pythonmidi Any experience with those? Thanks a lot Nicola Montecchio
[ "I've been using MXM's library in harpy for some time now, and am quite satisfied with it. Fast enough for my purposes, and easy to extend. I suppose it does what you need, seeing as how I use it to split MIDI files into single channel files.\n" ]
[ 2 ]
[]
[]
[ "file", "midi", "python" ]
stackoverflow_0002942381_file_midi_python.txt
Q: Django: Sum on an date attribute grouped by month/year I'd like to put this query from SQL to Django: "select date_format(date, '%Y-%m') as month, sum(quantity) as hours from hourentries group by date_format(date, '%Y-%m') order by date;" The part that causes problem is to group by month when aggregating. I tried this (which seemed logical), but it didn't work : HourEntries.objects.order_by("date").values("date__month").aggregate(Sum("quantity")) A: aggregate can only generate one aggregate value. You can get the aggregate sum of Hours of the current month by the following query. from datetime import datetime this_month = datetime.now().month HourEntries.objects.filter(date__month=this_month).aggregate(Sum("quantity")) So, to obtain the aggregate values of HourEntry's all the months, you can loop over the queryset for all the months in the db. But it is better to use the raw sql. HourEntries.objects.raw("select date_format(date, '%Y-%m') as month, sum(quantity) as hours from hourentries group by date_format(date, '%Y-%m') order by date;") A: I guess you cannot aggregate on "quantity" after using values("date__month"), as this leaves only "date" and "month" in the QuerySet.
Django: Sum on an date attribute grouped by month/year
I'd like to put this query from SQL to Django: "select date_format(date, '%Y-%m') as month, sum(quantity) as hours from hourentries group by date_format(date, '%Y-%m') order by date;" The part that causes problem is to group by month when aggregating. I tried this (which seemed logical), but it didn't work : HourEntries.objects.order_by("date").values("date__month").aggregate(Sum("quantity"))
[ "aggregate can only generate one aggregate value.\nYou can get the aggregate sum of Hours of the current month by the following query.\nfrom datetime import datetime\nthis_month = datetime.now().month\nHourEntries.objects.filter(date__month=this_month).aggregate(Sum(\"quantity\"))\n\nSo, to obtain the aggregate values of HourEntry's all the months, you can loop over the queryset for all the months in the db. But it is better to use the raw sql.\nHourEntries.objects.raw(\"select date_format(date, '%Y-%m') as month, sum(quantity) as hours from hourentries group by date_format(date, '%Y-%m') order by date;\")\n\n", "I guess you cannot aggregate on \"quantity\" after using values(\"date__month\"), as this leaves only \"date\" and \"month\" in the QuerySet.\n" ]
[ 2, 0 ]
[]
[]
[ "django", "django_orm", "python" ]
stackoverflow_0002943314_django_django_orm_python.txt
Q: Python for Windows Extensions - what does it do? Can someone explain what this library does? Apparently, one of the things it does is allow automatic detection of SDKs. No, they don't mention what it does on their website :-(. A: It provides Python bindings for the Win32 API and for COM. A: you can find many examples of use of win32com and other win32 packages in here. In addition, Tim Golden's win32 How do I? and Mike Driscoll blog are very rich sources for win32 examples. If you install Activepython you get win32all/pywin bundled and with a collection of docs on the package. With ActivePython you also get a shell/IDE with tools to inspect and work with com objects
Python for Windows Extensions - what does it do?
Can someone explain what this library does? Apparently, one of the things it does is allow automatic detection of SDKs. No, they don't mention what it does on their website :-(.
[ "It provides Python bindings for the Win32 API and for COM.\n", "you can find many examples of use of win32com and other win32 packages in here.\nIn addition, Tim Golden's win32 How do I? and Mike Driscoll blog are very rich sources for win32 examples. \nIf you install Activepython you get win32all/pywin bundled and with a collection of docs on the package.\nWith ActivePython you also get a shell/IDE with tools to inspect and work with com objects \n" ]
[ 8, 5 ]
[]
[]
[ "python" ]
stackoverflow_0002943739_python.txt
Q: Dynamic resize with MPlayer and PyGTK I've wrote a piece of code in python and pygtk for an embeded mplayer in a gui. I assume I use GtkSocket and the slave mode of mplayer with the -wid option. But I've got an issue, when the size of my GTK window is smaller than my stream, the stream appears to be cropped. And when the size of my window is bigger than my stream, the stream appear centred inside the widget which embed MPlayer. (a gtk.Frame but I've also try with a gtk.DrawingArea) I would like to know how I can get my stream resize dynamically depending on the window's size. I don't want to use Glade or any GUI builder. Thanks in advance for any help, and please excuse my poor english. A: You'll want to connect to the 'size-allocate' signal of whatever widget you embedded MPlayer in. Once you know the new size of the widget, say 200x300, send the commands set_property width 300 set_property height 200 to MPlayer in slave mode. (See http://www.mplayerhq.hu/DOCS/tech/slave.txt for a list of slave mode commands.) A: You need to tell mplayer to zoom video according to window size. This can be done either in command line (-zoom) or in the configuration file (zoom = 1).
Dynamic resize with MPlayer and PyGTK
I've wrote a piece of code in python and pygtk for an embeded mplayer in a gui. I assume I use GtkSocket and the slave mode of mplayer with the -wid option. But I've got an issue, when the size of my GTK window is smaller than my stream, the stream appears to be cropped. And when the size of my window is bigger than my stream, the stream appear centred inside the widget which embed MPlayer. (a gtk.Frame but I've also try with a gtk.DrawingArea) I would like to know how I can get my stream resize dynamically depending on the window's size. I don't want to use Glade or any GUI builder. Thanks in advance for any help, and please excuse my poor english.
[ "You'll want to connect to the 'size-allocate' signal of whatever widget you embedded MPlayer in. Once you know the new size of the widget, say 200x300, send the commands\nset_property width 300\nset_property height 200\n\nto MPlayer in slave mode.\n(See http://www.mplayerhq.hu/DOCS/tech/slave.txt for a list of slave mode commands.)\n", "You need to tell mplayer to zoom video according to window size. This can be done either in command line (-zoom) or in the configuration file (zoom = 1).\n" ]
[ 1, 1 ]
[]
[]
[ "gtk", "mplayer", "pygtk", "python" ]
stackoverflow_0002417705_gtk_mplayer_pygtk_python.txt
Q: How to add a '-' apex in Python I have a problem: i can't find the '-' apex character... i'm writing code on math function: and i want to insert representation like ², ³. i found that print '\xb2, \xb3' work good. now, i have to insert negative numbers at the apex, like :¯². so, i need the ¯ charachter. How can i find that? A: >>> print('\xaf') # or '\u00af' ¯ # macron >>> print('\u2212') − # minus >>> print('\u207b') ⁻ # superscript minus You'll need u'' notation in python-2.x
How to add a '-' apex in Python
I have a problem: i can't find the '-' apex character... i'm writing code on math function: and i want to insert representation like ², ³. i found that print '\xb2, \xb3' work good. now, i have to insert negative numbers at the apex, like :¯². so, i need the ¯ charachter. How can i find that?
[ ">>> print('\\xaf') # or '\\u00af'\n¯ # macron\n>>> print('\\u2212')\n− # minus\n>>> print('\\u207b')\n⁻ # superscript minus\n\nYou'll need u'' notation in python-2.x\n" ]
[ 3 ]
[]
[]
[ "character", "python", "unicode" ]
stackoverflow_0002944460_character_python_unicode.txt
Q: Generate all permutations with sort constraint I have a list consisting of other lists and some zeroes, for example: x = [[1, 1, 2], [1, 1, 1, 2], [1, 1, 2], 0, 0, 0] I would like to generate all the combinations of this list while keeping the order of the inner lists unchanged, so [[1, 1, 2], 0, 0, [1, 1, 1, 2], [1, 1, 2], 0] is fine, but [[1, 1, 1, 2], [1, 1, 2], 0, 0, [1, 1, 2], 0] isn't. I've got the feeling that this should be fairly easy in Python, but I just don't see it. Could somebody help me out? A: One hint: If there are z zeros and t lists then the number of combinations you describe is choose(z+t, z). (The stars and bars trick will help to see why that's true.) To generate those combinations, you could generate all the length-z subsets of {1,...,z+t}. Each of those would give the positions of the zeros. Even better, here's a generalization of your question: https://stackoverflow.com/questions/2944987/all-the-ways-to-intersperse Your input x can be converted into a form y suitable for the above generalization as follows: x = [[1,1,2], [1,1,1,2], [1,1,2], 0, 0, 0] lists = [i for i in x if i != 0] zeros = [i for i in x if i == 0] y = [lists, zeros] A: I'd do something like...: >>> import itertools >>> x = [[1, 1, 2], [1, 1, 1, 2], [1, 1, 2], 0, 0, 0] >>> numzeros = x.count(0) >>> listlen = len(x) >>> where0s = itertools.combinations(range(listlen), numzeros) >>> nonzeros = [y for y in x if y != 0] >>> for w in where0s: ... result = [0] * listlen ... picker = iter(nonzeros) ... for i in range(listlen): ... if i not in w: ... result[i] = next(picker) ... print result ... [0, 0, 0, [1, 1, 2], [1, 1, 1, 2], [1, 1, 2]] [0, 0, [1, 1, 2], 0, [1, 1, 1, 2], [1, 1, 2]] [0, 0, [1, 1, 2], [1, 1, 1, 2], 0, [1, 1, 2]] [0, 0, [1, 1, 2], [1, 1, 1, 2], [1, 1, 2], 0] [0, [1, 1, 2], 0, 0, [1, 1, 1, 2], [1, 1, 2]] [0, [1, 1, 2], 0, [1, 1, 1, 2], 0, [1, 1, 2]] [0, [1, 1, 2], 0, [1, 1, 1, 2], [1, 1, 2], 0] [0, [1, 1, 2], [1, 1, 1, 2], 0, 0, [1, 1, 2]] [0, [1, 1, 2], [1, 1, 1, 2], 0, [1, 1, 2], 0] [0, [1, 1, 2], [1, 1, 1, 2], [1, 1, 2], 0, 0] [[1, 1, 2], 0, 0, 0, [1, 1, 1, 2], [1, 1, 2]] [[1, 1, 2], 0, 0, [1, 1, 1, 2], 0, [1, 1, 2]] [[1, 1, 2], 0, 0, [1, 1, 1, 2], [1, 1, 2], 0] [[1, 1, 2], 0, [1, 1, 1, 2], 0, 0, [1, 1, 2]] [[1, 1, 2], 0, [1, 1, 1, 2], 0, [1, 1, 2], 0] [[1, 1, 2], 0, [1, 1, 1, 2], [1, 1, 2], 0, 0] [[1, 1, 2], [1, 1, 1, 2], 0, 0, 0, [1, 1, 2]] [[1, 1, 2], [1, 1, 1, 2], 0, 0, [1, 1, 2], 0] [[1, 1, 2], [1, 1, 1, 2], 0, [1, 1, 2], 0, 0] [[1, 1, 2], [1, 1, 1, 2], [1, 1, 2], 0, 0, 0] >>> Can be micro-optimized in many ways, of course, but I hope the general idea is clear: identify all the set of indices that could have zeros, and put the non-zero items of the original list in the other places in order. A: In python 2.6, import itertools def intersperse(x, numzeroes): for indices in itertools.combinations(range(len(x) + numzeroes), numzeroes): y = x[:] for i in indices: y.insert(0, i) yield y x = [[1, 1, 2], [1, 1, 1, 2], [1, 1, 2]] list(intersperse(x, 3))
Generate all permutations with sort constraint
I have a list consisting of other lists and some zeroes, for example: x = [[1, 1, 2], [1, 1, 1, 2], [1, 1, 2], 0, 0, 0] I would like to generate all the combinations of this list while keeping the order of the inner lists unchanged, so [[1, 1, 2], 0, 0, [1, 1, 1, 2], [1, 1, 2], 0] is fine, but [[1, 1, 1, 2], [1, 1, 2], 0, 0, [1, 1, 2], 0] isn't. I've got the feeling that this should be fairly easy in Python, but I just don't see it. Could somebody help me out?
[ "One hint: If there are z zeros and t lists then the number of combinations you describe is choose(z+t, z). (The stars and bars trick will help to see why that's true.)\nTo generate those combinations, you could generate all the length-z subsets of {1,...,z+t}.\nEach of those would give the positions of the zeros.\nEven better, here's a generalization of your question:\nhttps://stackoverflow.com/questions/2944987/all-the-ways-to-intersperse\nYour input x can be converted into a form y suitable for the above generalization as follows:\nx = [[1,1,2], [1,1,1,2], [1,1,2], 0, 0, 0]\nlists = [i for i in x if i != 0]\nzeros = [i for i in x if i == 0]\ny = [lists, zeros]\n\n", "I'd do something like...:\n>>> import itertools\n>>> x = [[1, 1, 2], [1, 1, 1, 2], [1, 1, 2], 0, 0, 0]\n>>> numzeros = x.count(0)\n>>> listlen = len(x)\n>>> where0s = itertools.combinations(range(listlen), numzeros)\n>>> nonzeros = [y for y in x if y != 0]\n>>> for w in where0s:\n... result = [0] * listlen\n... picker = iter(nonzeros)\n... for i in range(listlen):\n... if i not in w:\n... result[i] = next(picker)\n... print result\n... \n[0, 0, 0, [1, 1, 2], [1, 1, 1, 2], [1, 1, 2]]\n[0, 0, [1, 1, 2], 0, [1, 1, 1, 2], [1, 1, 2]]\n[0, 0, [1, 1, 2], [1, 1, 1, 2], 0, [1, 1, 2]]\n[0, 0, [1, 1, 2], [1, 1, 1, 2], [1, 1, 2], 0]\n[0, [1, 1, 2], 0, 0, [1, 1, 1, 2], [1, 1, 2]]\n[0, [1, 1, 2], 0, [1, 1, 1, 2], 0, [1, 1, 2]]\n[0, [1, 1, 2], 0, [1, 1, 1, 2], [1, 1, 2], 0]\n[0, [1, 1, 2], [1, 1, 1, 2], 0, 0, [1, 1, 2]]\n[0, [1, 1, 2], [1, 1, 1, 2], 0, [1, 1, 2], 0]\n[0, [1, 1, 2], [1, 1, 1, 2], [1, 1, 2], 0, 0]\n[[1, 1, 2], 0, 0, 0, [1, 1, 1, 2], [1, 1, 2]]\n[[1, 1, 2], 0, 0, [1, 1, 1, 2], 0, [1, 1, 2]]\n[[1, 1, 2], 0, 0, [1, 1, 1, 2], [1, 1, 2], 0]\n[[1, 1, 2], 0, [1, 1, 1, 2], 0, 0, [1, 1, 2]]\n[[1, 1, 2], 0, [1, 1, 1, 2], 0, [1, 1, 2], 0]\n[[1, 1, 2], 0, [1, 1, 1, 2], [1, 1, 2], 0, 0]\n[[1, 1, 2], [1, 1, 1, 2], 0, 0, 0, [1, 1, 2]]\n[[1, 1, 2], [1, 1, 1, 2], 0, 0, [1, 1, 2], 0]\n[[1, 1, 2], [1, 1, 1, 2], 0, [1, 1, 2], 0, 0]\n[[1, 1, 2], [1, 1, 1, 2], [1, 1, 2], 0, 0, 0]\n>>> \n\nCan be micro-optimized in many ways, of course, but I hope the general idea is clear: identify all the set of indices that could have zeros, and put the non-zero items of the original list in the other places in order.\n", "In python 2.6,\nimport itertools\n\ndef intersperse(x, numzeroes):\n for indices in itertools.combinations(range(len(x) + numzeroes), numzeroes):\n y = x[:]\n for i in indices:\n y.insert(0, i)\n yield y\n\nx = [[1, 1, 2], [1, 1, 1, 2], [1, 1, 2]]\nlist(intersperse(x, 3))\n\n" ]
[ 2, 2, 0 ]
[]
[]
[ "combinatorics", "list", "python" ]
stackoverflow_0002944590_combinatorics_list_python.txt
Q: Whats wrong with this task queue setup? I've setup this task queue implementation on a site I host for a customer, it has a cron job which runs each morning at 2am "/admin/tasks/queue", this queues up emails to be sent out, "/admin/tasks/email", and uses cursors so as to do the queuing in small chunks. For some reason last night /admin/tasks/queue kept getting run by this code and so sent out my whole quota of emails :/. Have I done something wrong with this code? class QueueUpEmail(webapp.RequestHandler): def post(self): subscribers = Subscriber.all() subscribers.filter("verified =", True) last_cursor = memcache.get('daily_email_cursor') if last_cursor: subscribers.with_cursor(last_cursor) subs = subscribers.fetch(10) logging.debug("POST - subs count = %i" % len(subs)) if len(subs) < 10: logging.debug("POST - Less than 10 subscribers in subs") # Subscribers left is less than 10, don't reschedule the task for sub in subs: task = taskqueue.Task(url='/admin/tasks/email', params={'email': sub.emailaddress, 'day': sub.day_no}) task.add("email") memcache.delete('daily_email_cursor') else: logging.debug("POST - Greater than 10 subscibers left in subs - reschedule") # Subscribers is 10 or greater, reschedule for sub in subs: task = taskqueue.Task(url='/admin/tasks/email', params={'email': sub.emailaddress, 'day': sub.day_no}) task.add("email") cursor = subscribers.cursor() memcache.set('daily_email_cursor', cursor) task = taskqueue.Task(url="/admin/tasks/queue", params={}) task.add("queueup") A: I can see a couple of potential problems. First, you store your cursor in memcache, which is not guaranteed to persist anything. If you get a cache miss halfway through your processing, you'll re-send every message again. Secondly, tasks will get re-tried if they fail for any reason; they're supposed to be designed to be idempotent for this reason. In the case of sending emails, of course, this is nearly impossible, since once a message is sent it can't be rolled back if your task dies for some other reason after sending it. At a minimum, I'd recommend trying to update a "last emailed date" field on each Subscriber entity after sending them the message. This in itself isn't foolproof, of course, since the email send could succeed and the update of the entity could fail after that. It would also add overhead to the whole process, since you'd be doing a write for each subscriber.
Whats wrong with this task queue setup?
I've setup this task queue implementation on a site I host for a customer, it has a cron job which runs each morning at 2am "/admin/tasks/queue", this queues up emails to be sent out, "/admin/tasks/email", and uses cursors so as to do the queuing in small chunks. For some reason last night /admin/tasks/queue kept getting run by this code and so sent out my whole quota of emails :/. Have I done something wrong with this code? class QueueUpEmail(webapp.RequestHandler): def post(self): subscribers = Subscriber.all() subscribers.filter("verified =", True) last_cursor = memcache.get('daily_email_cursor') if last_cursor: subscribers.with_cursor(last_cursor) subs = subscribers.fetch(10) logging.debug("POST - subs count = %i" % len(subs)) if len(subs) < 10: logging.debug("POST - Less than 10 subscribers in subs") # Subscribers left is less than 10, don't reschedule the task for sub in subs: task = taskqueue.Task(url='/admin/tasks/email', params={'email': sub.emailaddress, 'day': sub.day_no}) task.add("email") memcache.delete('daily_email_cursor') else: logging.debug("POST - Greater than 10 subscibers left in subs - reschedule") # Subscribers is 10 or greater, reschedule for sub in subs: task = taskqueue.Task(url='/admin/tasks/email', params={'email': sub.emailaddress, 'day': sub.day_no}) task.add("email") cursor = subscribers.cursor() memcache.set('daily_email_cursor', cursor) task = taskqueue.Task(url="/admin/tasks/queue", params={}) task.add("queueup")
[ "I can see a couple of potential problems. First, you store your cursor in memcache, which is not guaranteed to persist anything. If you get a cache miss halfway through your processing, you'll re-send every message again.\nSecondly, tasks will get re-tried if they fail for any reason; they're supposed to be designed to be idempotent for this reason. In the case of sending emails, of course, this is nearly impossible, since once a message is sent it can't be rolled back if your task dies for some other reason after sending it. At a minimum, I'd recommend trying to update a \"last emailed date\" field on each Subscriber entity after sending them the message. This in itself isn't foolproof, of course, since the email send could succeed and the update of the entity could fail after that. It would also add overhead to the whole process, since you'd be doing a write for each subscriber.\n" ]
[ 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002942165_google_app_engine_python.txt
Q: python intercepting communication lets say you run third party program on your computer whitch create a process named example.exe how do i determinate if this process is running and how many windows does he open? How do i intercept network communication between this windows and server? my goal is to create an app whitch will be monitoring network trafic between example.exe and its home server in order to analyze data and save to database, and finally simulate user interaction to get more relevant data A: For network sniffing, use pypcap to capture network traffic. pypcap is a Python interface to libpcap (WinPcap on Windows), which is used the popular network sniffer Wireshark (once known as Ethereal). Regarding process information, such as whether it is running and finding all of its open windows, I'm pretty sure you can do this with the Windows API. This means that you can do it in Python using the win32 library which lets you use most of the Windows API directly. So this now becomes a Windows API question, with which I can't help. Please ask just one question per, umm, question. A: You could use wireshark from wireshark.org to sniff the network traffic (or any other packet sniffer).
python intercepting communication
lets say you run third party program on your computer whitch create a process named example.exe how do i determinate if this process is running and how many windows does he open? How do i intercept network communication between this windows and server? my goal is to create an app whitch will be monitoring network trafic between example.exe and its home server in order to analyze data and save to database, and finally simulate user interaction to get more relevant data
[ "For network sniffing, use pypcap to capture network traffic. pypcap is a Python interface to libpcap (WinPcap on Windows), which is used the popular network sniffer Wireshark (once known as Ethereal).\nRegarding process information, such as whether it is running and finding all of its open windows, I'm pretty sure you can do this with the Windows API. This means that you can do it in Python using the win32 library which lets you use most of the Windows API directly. So this now becomes a Windows API question, with which I can't help.\nPlease ask just one question per, umm, question.\n", "You could use wireshark from wireshark.org to sniff the network traffic (or any other packet sniffer).\n" ]
[ 2, 0 ]
[]
[]
[ "communication", "networking", "python" ]
stackoverflow_0002945074_communication_networking_python.txt
Q: Generating a python file I'm havin issues with python (Sorry for my personal feelings before.. :P). I have a txt file, it contains a custom language and I have to translate it to a working python code. The input: import sys n = int(sys.argv[1]) ;;print "Beginning of the program!" LOOP i in range(1,n) {print "The number:";;print i} BRANCH n < 5 {print n ;;print "less than 5"} The wanted output looks exactly like this: import sys n = int(sys.argv[1]) print "Beginning of the program!" for i in range(1,n) : print "The number:" print i if n < 5 : print n print "less than 5" The name of the input file is read from parameter. The out file is out.py. In case of a wrong parameter, it gives an error message. The ;; means a new line. When I tried to do it, I made an array, I read all the lines into it, split by " ". Then I wanted to strip it from the marks I don't need. I made 2 loops, one for the lines, one for the words. So then I started to replace the things. Everything went fine until it came to the } mark. It finds it, but it can not replace or strip it. I have no more idea what to do. My code (it's messy and I don't have the write to file at the moment): f = open('test.txt', 'r') #g = open('out.py', 'w') allWords = map(lambda l: l.split(" "), f.readlines()) for i in range(len(allWords)): vanfor = -1 vanif = -1 for j in range(len(allWords[i])): a=allWords[i][j] a=a.replace(";;","\n") a=a.replace("CIKLUS","for") a=a.replace("ELAGAZAS","if") if a == "for": allWords[i][j+3] = str(allWords[i][j+3])+" :\n" if a == "if": allWords[i][j+3] = str(allWords[i][j+3])+" :\n" zarojel=a.find('}') if zarojel>-1: a=a.rstrip('}') a=a.replace("}","") a=a.replace("{","") if vanfor == -1: vanfor=a.find("for") if vanif == -1: vanif=a.find("if") if (vanfor > -1) or (vanif > -1): a=a.replace("print"," print") if j != (len(allWords[i]))-1: allWords[i][j]=a+" " print allWords[i][j], Could someone help me, please? Thanks in advance! A: If you change the very end of your program: # print allWords[i][j], print a, the output becomes: import sys n = int(sys.argv[1]) print "Beginning of the program!" for i in range(1,n) : print "The number:" print i if n < 5 : print n print "less than 5" Looks pretty close to what you want. To output to an open file object g, instead of stdout, just another tiny change at the program's very end...: # print allWords[i][j], print>>g, a, A: A quick go at the problem (if you use it for homework make sure you understand what's going on; following a good Python language tutorial may help): import sys filename = sys.argv[1] replace_dict = { ";;": "\n", "LOOP": "for", "BRANCH": "if", "{": ":{" } indent_dict = { "{": 1, "}": -1, "\n": 0 } lines = open(filename).readlines() indent, output, pop_next_newline = 0, [], False for line in lines: for key, value in replace_dict.iteritems(): line = line.replace(key, value) for char in line: if char in indent_dict: indent += indent_dict[char] if pop_next_newline and char == "\n": pop_next_newline = False else: output.append("\n%s" % (" " * indent)) if char == "}": pop_next_newline = True else: output.append(char) print ''.join(output)
Generating a python file
I'm havin issues with python (Sorry for my personal feelings before.. :P). I have a txt file, it contains a custom language and I have to translate it to a working python code. The input: import sys n = int(sys.argv[1]) ;;print "Beginning of the program!" LOOP i in range(1,n) {print "The number:";;print i} BRANCH n < 5 {print n ;;print "less than 5"} The wanted output looks exactly like this: import sys n = int(sys.argv[1]) print "Beginning of the program!" for i in range(1,n) : print "The number:" print i if n < 5 : print n print "less than 5" The name of the input file is read from parameter. The out file is out.py. In case of a wrong parameter, it gives an error message. The ;; means a new line. When I tried to do it, I made an array, I read all the lines into it, split by " ". Then I wanted to strip it from the marks I don't need. I made 2 loops, one for the lines, one for the words. So then I started to replace the things. Everything went fine until it came to the } mark. It finds it, but it can not replace or strip it. I have no more idea what to do. My code (it's messy and I don't have the write to file at the moment): f = open('test.txt', 'r') #g = open('out.py', 'w') allWords = map(lambda l: l.split(" "), f.readlines()) for i in range(len(allWords)): vanfor = -1 vanif = -1 for j in range(len(allWords[i])): a=allWords[i][j] a=a.replace(";;","\n") a=a.replace("CIKLUS","for") a=a.replace("ELAGAZAS","if") if a == "for": allWords[i][j+3] = str(allWords[i][j+3])+" :\n" if a == "if": allWords[i][j+3] = str(allWords[i][j+3])+" :\n" zarojel=a.find('}') if zarojel>-1: a=a.rstrip('}') a=a.replace("}","") a=a.replace("{","") if vanfor == -1: vanfor=a.find("for") if vanif == -1: vanif=a.find("if") if (vanfor > -1) or (vanif > -1): a=a.replace("print"," print") if j != (len(allWords[i]))-1: allWords[i][j]=a+" " print allWords[i][j], Could someone help me, please? Thanks in advance!
[ "If you change the very end of your program:\n # print allWords[i][j],\n print a,\n\nthe output becomes:\nimport sys \n\nn = int(sys.argv[1]) \nprint \"Beginning of the program!\"\n\nfor i in range(1,n) :\n print \"The number:\"\n print i\n\nif n < 5 :\n print n \n print \"less than 5\" \n\nLooks pretty close to what you want. To output to an open file object g, instead of stdout, just another tiny change at the program's very end...:\n # print allWords[i][j],\n print>>g, a,\n\n", "A quick go at the problem (if you use it for homework make sure you understand what's going on; following a good Python language tutorial may help):\nimport sys\nfilename = sys.argv[1]\n\nreplace_dict = { \";;\": \"\\n\", \"LOOP\": \"for\", \"BRANCH\": \"if\", \"{\": \":{\" }\nindent_dict = { \"{\": 1, \"}\": -1, \"\\n\": 0 }\n\nlines = open(filename).readlines()\nindent, output, pop_next_newline = 0, [], False\n\nfor line in lines:\n for key, value in replace_dict.iteritems():\n line = line.replace(key, value)\n for char in line:\n if char in indent_dict:\n indent += indent_dict[char]\n if pop_next_newline and char == \"\\n\":\n pop_next_newline = False\n else:\n output.append(\"\\n%s\" % (\" \" * indent))\n if char == \"}\": \n pop_next_newline = True\n else:\n output.append(char)\n\nprint ''.join(output) \n\n" ]
[ 3, 1 ]
[]
[]
[ "compiler_construction", "programming_languages", "python" ]
stackoverflow_0002945044_compiler_construction_programming_languages_python.txt
Q: Optimizing python link matching regular expression I have a regular expression, links = re.compile('<a(.+?)href=(?:"|\')?((?:https?://|/)[^\'"]+)(?:"|\')?(.*?)>(.+?)</a>',re.I).findall(data) to find links in some html, it is taking a long time on certain html, any optimization advice? One that it chokes on is http://freeyourmindonline.net/Blog/ A: Is there any reason you aren't using an html parser? Using something like BeautifulSoup, you can get all links without using an ugly regex like that. A: I'd suggest using BeautifulSoup for this task. A: How about more straight handling of href's? re_href = re.compile(r"""<\s*a(?:[^>]+?)href=("[^"]*(\\"[^"]*)*"|'[^']*(\\'[^']*)*'|[^\s>]*)[^>]*>""", re.I) That takes about 0.007 seconds in comparsion with your findall which takes 38.694 seconds on my computer.
Optimizing python link matching regular expression
I have a regular expression, links = re.compile('<a(.+?)href=(?:"|\')?((?:https?://|/)[^\'"]+)(?:"|\')?(.*?)>(.+?)</a>',re.I).findall(data) to find links in some html, it is taking a long time on certain html, any optimization advice? One that it chokes on is http://freeyourmindonline.net/Blog/
[ "Is there any reason you aren't using an html parser? Using something like BeautifulSoup, you can get all links without using an ugly regex like that.\n", "I'd suggest using BeautifulSoup for this task.\n", "How about more straight handling of href's?\nre_href = re.compile(r\"\"\"<\\s*a(?:[^>]+?)href=(\"[^\"]*(\\\\\"[^\"]*)*\"|'[^']*(\\\\'[^']*)*'|[^\\s>]*)[^>]*>\"\"\", re.I)\n\nThat takes about 0.007 seconds in comparsion with your findall which takes 38.694 seconds on my computer.\n" ]
[ 2, 2, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002945364_python_regex.txt
Q: Calling/selecting variables (float valued) with user input in Python I've been working on a computational physics project (plotting related rates of chemical reactants with respect to eachother to show oscillatory behavior) with a fair amount of success. However, one of my simulations involves more than two active oscillating agents (five, in fact) which would obviously be unsuitable for any single visual plot... My scheme was hence to have the user select which two reactants they wanted plotted on the x-axis and y-axis respectively. I tried (foolishly) to convert string input values into the respective variable names, but I guess I need a radically different approach if any exist? If it helps clarify any, here is part of my code: def coupledBrusselator(A, B, t_trial,display_x,display_y): t = 0 t_step = .01 X = 0 Y = 0 E = 0 U = 0 V = 0 dX = (A) - (B+1)*(X) + (X**2)*(Y) dY = (B)*(X) - (X**2)*(Y) dE = -(E)*(U) - (X) dU = (U**2)*(V) -(E+1)*(U) - (B)*(X) dV = (E)*(U) - (U**2)*(V) array_t = [0] array_X = [0] array_Y = [0] array_U = [0] array_V = [0] while t <= t_trial: X_1 = X + (dX)*(t_step/2) Y_1 = Y + (dY)*(t_step/2) E_1 = E + (dE)*(t_step/2) U_1 = U + (dU)*(t_step/2) V_1 = V + (dV)*(t_step/2) dX_1 = (A) - (B+1)*(X_1) + (X_1**2)*(Y_1) dY_1 = (B)*(X_1) - (X_1**2)*(Y_1) dE_1 = -(E_1)*(U_1) - (X_1) dU_1 = (U_1**2)*(V_1) -(E_1+1)*(U_1) - (B)*(X_1) dV_1 = (E_1)*(U_1) - (U_1**2)*(V_1) X_2 = X + (dX_1)*(t_step/2) Y_2 = Y + (dY_1)*(t_step/2) E_2 = E + (dE_1)*(t_step/2) U_2 = U + (dU_1)*(t_step/2) V_2 = V + (dV_1)*(t_step/2) dX_2 = (A) - (B+1)*(X_2) + (X_2**2)*(Y_2) dY_2 = (B)*(X_2) - (X_2**2)*(Y_2) dE_2 = -(E_2)*(U_2) - (X_2) dU_2 = (U_2**2)*(V_2) -(E_2+1)*(U_2) - (B)*(X_2) dV_2 = (E_2)*(U_2) - (U_2**2)*(V_2) X_3 = X + (dX_2)*(t_step) Y_3 = Y + (dY_2)*(t_step) E_3 = E + (dE_2)*(t_step) U_3 = U + (dU_2)*(t_step) V_3 = V + (dV_2)*(t_step) dX_3 = (A) - (B+1)*(X_3) + (X_3**2)*(Y_3) dY_3 = (B)*(X_3) - (X_3**2)*(Y_3) dE_3 = -(E_3)*(U_3) - (X_3) dU_3 = (U_3**2)*(V_3) -(E_3+1)*(U_3) - (B)*(X_3) dV_3 = (E_3)*(U_3) - (U_3**2)*(V_3) X = X + ((dX + 2*dX_1 + 2*dX_2 + dX_3)/6) * t_step Y = Y + ((dX + 2*dY_1 + 2*dY_2 + dY_3)/6) * t_step E = E + ((dE + 2*dE_1 + 2*dE_2 + dE_3)/6) * t_step U = U + ((dU + 2*dU_1 + 2*dY_2 + dE_3)/6) * t_step V = V + ((dV + 2*dV_1 + 2*dV_2 + dE_3)/6) * t_step dX = (A) - (B+1)*(X) + (X**2)*(Y) dY = (B)*(X) - (X**2)*(Y) t_step = .01 / (1 + dX**2 + dY**2) ** .5 t = t + t_step array_X.append(X) array_Y.append(Y) array_E.append(E) array_U.append(U) array_V.append(V) array_t.append(t) where previously display_x = raw_input("Choose catalyst you wish to analyze in the phase/field diagrams (X, Y, E, U, or V) ") display_y = raw_input("Choose one other catalyst from list you wish to include in phase/field diagrams ") coupledBrusselator(A, B, t_trial, display_x, display_y) Thanks! A: Once you have calculated the different arrays, you could add them to a dict that maps names to arrays. This can then be used to look up the correct arrays for display_x and display_y: named_arrays = { "X": array_X, "Y": array_Y, "E": array_E, ... } return (named_arrays[display_x], named_arrays[display_y])
Calling/selecting variables (float valued) with user input in Python
I've been working on a computational physics project (plotting related rates of chemical reactants with respect to eachother to show oscillatory behavior) with a fair amount of success. However, one of my simulations involves more than two active oscillating agents (five, in fact) which would obviously be unsuitable for any single visual plot... My scheme was hence to have the user select which two reactants they wanted plotted on the x-axis and y-axis respectively. I tried (foolishly) to convert string input values into the respective variable names, but I guess I need a radically different approach if any exist? If it helps clarify any, here is part of my code: def coupledBrusselator(A, B, t_trial,display_x,display_y): t = 0 t_step = .01 X = 0 Y = 0 E = 0 U = 0 V = 0 dX = (A) - (B+1)*(X) + (X**2)*(Y) dY = (B)*(X) - (X**2)*(Y) dE = -(E)*(U) - (X) dU = (U**2)*(V) -(E+1)*(U) - (B)*(X) dV = (E)*(U) - (U**2)*(V) array_t = [0] array_X = [0] array_Y = [0] array_U = [0] array_V = [0] while t <= t_trial: X_1 = X + (dX)*(t_step/2) Y_1 = Y + (dY)*(t_step/2) E_1 = E + (dE)*(t_step/2) U_1 = U + (dU)*(t_step/2) V_1 = V + (dV)*(t_step/2) dX_1 = (A) - (B+1)*(X_1) + (X_1**2)*(Y_1) dY_1 = (B)*(X_1) - (X_1**2)*(Y_1) dE_1 = -(E_1)*(U_1) - (X_1) dU_1 = (U_1**2)*(V_1) -(E_1+1)*(U_1) - (B)*(X_1) dV_1 = (E_1)*(U_1) - (U_1**2)*(V_1) X_2 = X + (dX_1)*(t_step/2) Y_2 = Y + (dY_1)*(t_step/2) E_2 = E + (dE_1)*(t_step/2) U_2 = U + (dU_1)*(t_step/2) V_2 = V + (dV_1)*(t_step/2) dX_2 = (A) - (B+1)*(X_2) + (X_2**2)*(Y_2) dY_2 = (B)*(X_2) - (X_2**2)*(Y_2) dE_2 = -(E_2)*(U_2) - (X_2) dU_2 = (U_2**2)*(V_2) -(E_2+1)*(U_2) - (B)*(X_2) dV_2 = (E_2)*(U_2) - (U_2**2)*(V_2) X_3 = X + (dX_2)*(t_step) Y_3 = Y + (dY_2)*(t_step) E_3 = E + (dE_2)*(t_step) U_3 = U + (dU_2)*(t_step) V_3 = V + (dV_2)*(t_step) dX_3 = (A) - (B+1)*(X_3) + (X_3**2)*(Y_3) dY_3 = (B)*(X_3) - (X_3**2)*(Y_3) dE_3 = -(E_3)*(U_3) - (X_3) dU_3 = (U_3**2)*(V_3) -(E_3+1)*(U_3) - (B)*(X_3) dV_3 = (E_3)*(U_3) - (U_3**2)*(V_3) X = X + ((dX + 2*dX_1 + 2*dX_2 + dX_3)/6) * t_step Y = Y + ((dX + 2*dY_1 + 2*dY_2 + dY_3)/6) * t_step E = E + ((dE + 2*dE_1 + 2*dE_2 + dE_3)/6) * t_step U = U + ((dU + 2*dU_1 + 2*dY_2 + dE_3)/6) * t_step V = V + ((dV + 2*dV_1 + 2*dV_2 + dE_3)/6) * t_step dX = (A) - (B+1)*(X) + (X**2)*(Y) dY = (B)*(X) - (X**2)*(Y) t_step = .01 / (1 + dX**2 + dY**2) ** .5 t = t + t_step array_X.append(X) array_Y.append(Y) array_E.append(E) array_U.append(U) array_V.append(V) array_t.append(t) where previously display_x = raw_input("Choose catalyst you wish to analyze in the phase/field diagrams (X, Y, E, U, or V) ") display_y = raw_input("Choose one other catalyst from list you wish to include in phase/field diagrams ") coupledBrusselator(A, B, t_trial, display_x, display_y) Thanks!
[ "Once you have calculated the different arrays, you could add them to a dict that maps names to arrays. This can then be used to look up the correct arrays for display_x and display_y:\nnamed_arrays = {\n \"X\": array_X,\n \"Y\": array_Y,\n \"E\": array_E,\n ...\n}\n\nreturn (named_arrays[display_x], named_arrays[display_y])\n\n" ]
[ 1 ]
[]
[]
[ "floating_point", "input", "python", "raw_input", "variables" ]
stackoverflow_0002945486_floating_point_input_python_raw_input_variables.txt
Q: Can the Django urls.py system be turned into Pylon's Routes? Can the Django urls.py system be turned into Pylon's Routes? A: Could you be more specific? If you want to adapt a django urlconf to routes at runtime it would be really tricky if not impossible and would require having a django settings.py present and an env variable pointing to it. Otherwise translating a django urlconf to routes manually is doable. Routes is as flexible as django urlconfs when it comes to defining urlpatterns.
Can the Django urls.py system be turned into Pylon's Routes?
Can the Django urls.py system be turned into Pylon's Routes?
[ "Could you be more specific? \nIf you want to adapt a django urlconf to routes at runtime it would be really tricky if not impossible and would require having a django settings.py present and an env variable pointing to it.\nOtherwise translating a django urlconf to routes manually is doable. Routes is as flexible as django urlconfs when it comes to defining urlpatterns.\n" ]
[ 0 ]
[]
[]
[ "django", "pylons", "python", "routes" ]
stackoverflow_0002945615_django_pylons_python_routes.txt
Q: How do I fix this unicode/cPickle error in Python? ids = cPickle.loads(gem.value) loads() argument 1 must be string, not unicode A: cPickle.loads wants a byte string (which is exactly what cPickle.dumps outputs) and you're feeding it a unicode string instead. You'll need to "encode" that Unicode string to get back the byte string that dumps had originally given you, but it's hard to guess what encoding you accidentally imposed on it -- maybe latin-1 or utf-8 (if ascii don't worry, either of those two will decode it just great), maybe utf-16...? It's hard to guess without knowing what gem is and how you originally set its value from the output of a cPickle.dumps...! A: The result of cPickle.dumps() is a str object, not a unicode object. You need to find the step in your code where you are decoding the pickled str object, and omit that step. DON'T try to convert your unicode object to a str object. Two wrongs don't make a right. Example (Python 2.6): >>> import cPickle >>> ps = cPickle.dumps([1,2,3], -1) >>> ps '\x80\x02]q\x01(K\x01K\x02K\x03e.' >>> ups = ps.decode('latin1') >>> str(ups) Traceback (most recent call last): File "<stdin>", line 1, in <module> UnicodeEncodeError: 'ascii' codec can't encode character u'\x80' in position 0: ordinal not in range(128) >>> You may well be using the default (and inefficient) Protocol 0 which produces "human readable" output: >>> ps = cPickle.dumps([1,2,3]) >>> ps '(lp1\nI1\naI2\naI3\na.' >>> which is presumably ASCII (but not documented to be so) so the str(gem.value) kludge may well """work""": >>> ps == str(unicode(ps)) True >>>
How do I fix this unicode/cPickle error in Python?
ids = cPickle.loads(gem.value) loads() argument 1 must be string, not unicode
[ "cPickle.loads wants a byte string (which is exactly what cPickle.dumps outputs) and you're feeding it a unicode string instead. You'll need to \"encode\" that Unicode string to get back the byte string that dumps had originally given you, but it's hard to guess what encoding you accidentally imposed on it -- maybe latin-1 or utf-8 (if ascii don't worry, either of those two will decode it just great), maybe utf-16...? It's hard to guess without knowing what gem is and how you originally set its value from the output of a cPickle.dumps...!\n", "The result of cPickle.dumps() is a str object, not a unicode object. You need to find the step in your code where you are decoding the pickled str object, and omit that step.\nDON'T try to convert your unicode object to a str object. Two wrongs don't make a right. Example (Python 2.6):\n>>> import cPickle\n>>> ps = cPickle.dumps([1,2,3], -1)\n>>> ps\n'\\x80\\x02]q\\x01(K\\x01K\\x02K\\x03e.'\n>>> ups = ps.decode('latin1')\n>>> str(ups)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nUnicodeEncodeError: 'ascii' codec can't encode character u'\\x80' in position 0: ordinal not in range(128)\n>>>\n\nYou may well be using the default (and inefficient) Protocol 0 which produces \"human readable\" output:\n>>> ps = cPickle.dumps([1,2,3])\n>>> ps\n'(lp1\\nI1\\naI2\\naI3\\na.'\n>>>\n\nwhich is presumably ASCII (but not documented to be so) so the str(gem.value) kludge may well \"\"\"work\"\"\":\n>>> ps == str(unicode(ps))\nTrue\n>>>\n\n" ]
[ 8, 1 ]
[ "You can fix it by making gem.value a string, not unicode.\nUse str(gem.value)\n" ]
[ -1 ]
[ "pickle", "python", "unicode" ]
stackoverflow_0002946068_pickle_python_unicode.txt
Q: django 1.2.1: Override model name in admin interface? I have a model called "Activity" in my django app. in the admin interface, it appears on the screen as "Activitys". how can I override the label on the admin page to make it "Activities" instead? I see in the archives how to do this for a field, but not for a model itself. thanks! A: class MyModel(models.Model): # your fields.... class Meta: verbose_name = 'Activity' verbose_name_plural = 'Activities'
django 1.2.1: Override model name in admin interface?
I have a model called "Activity" in my django app. in the admin interface, it appears on the screen as "Activitys". how can I override the label on the admin page to make it "Activities" instead? I see in the archives how to do this for a field, but not for a model itself. thanks!
[ "class MyModel(models.Model):\n\n # your fields....\n\n class Meta:\n verbose_name = 'Activity'\n verbose_name_plural = 'Activities'\n\n" ]
[ 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002946466_django_python.txt
Q: WN server filter won't work WN servers have an alternative to cgi programs called filters. I have been trying to get one to work, but I have had no luck. I am writing in python. It looks like the server is not receiving any output from the program but is parsing nothing and wrapping this nothing in my standard header and footer. I have chmod 755 the program and my index.wn file reads: Default-Attributes=parse Default-Wrappers=templates/template1.inc File=includeTests.html File=index.html File=archives.html File=contact.html File=style.css File=testProgram.py #here is the stuff about the filter File=testFilter.html Content-type=text/html Filter=testProgram.py Attributes=parse, cgi here is what is in the filter called testProgram.py: #!/usr/bin/python print "Content-Type: text/html\n\n" print "hi" testProgram.py works perfectly if it is shoved into a cgi-bin folder and chmoded. I suppose my problem may lay with the fact that I have never ever seen a filter program in python. I'm not sure I have even seen a filter program at all. Does anyone out there have any experience with wn servers and filters? Any ideas? A: I have no real-world WN experience, but I've read its docs and it seems to me there's something wrong with your code -- quoting, no headers should be supplied by the program as WN will automatically provide them. For example, while a CGI/1.1 program typically starts with printing "Content-type: text/html" followed by a blank line, this should not be done for "someprogram" in the index.wn entry above, because WN will automatically provide the appropriate HTTP/1.1 headers based on the "Content-type=text/html" line in the index.wn file. while you do seem to be supplying a header in your code. Second, you sure you want parsing, as you're requesting? I don't see why either of these issues should just "swallow" your program's output, though, so this is hardly a complete answer... but maybe it could be a start. BTW, since you say I'm not sure I have even seen a filter program at all the one example of filter I see in the docs is zcat -- at least this does make clear that a filter is a program that takes the given file as its standard input (but doesn't have to read it, the docs say... but that file, even if ignored as in your example code, must exist -- could that perhaps be the problem...?) and gives the contents (not headers) to send back on its standard output.
WN server filter won't work
WN servers have an alternative to cgi programs called filters. I have been trying to get one to work, but I have had no luck. I am writing in python. It looks like the server is not receiving any output from the program but is parsing nothing and wrapping this nothing in my standard header and footer. I have chmod 755 the program and my index.wn file reads: Default-Attributes=parse Default-Wrappers=templates/template1.inc File=includeTests.html File=index.html File=archives.html File=contact.html File=style.css File=testProgram.py #here is the stuff about the filter File=testFilter.html Content-type=text/html Filter=testProgram.py Attributes=parse, cgi here is what is in the filter called testProgram.py: #!/usr/bin/python print "Content-Type: text/html\n\n" print "hi" testProgram.py works perfectly if it is shoved into a cgi-bin folder and chmoded. I suppose my problem may lay with the fact that I have never ever seen a filter program in python. I'm not sure I have even seen a filter program at all. Does anyone out there have any experience with wn servers and filters? Any ideas?
[ "I have no real-world WN experience, but I've read its docs and it seems to me there's something wrong with your code -- quoting,\n\nno headers should be supplied by the\n program as WN will automatically\n provide them. For example, while a\n CGI/1.1 program typically starts with\n printing \"Content-type: text/html\"\n followed by a blank line, this should\n not be done for \"someprogram\" in the\n index.wn entry above, because WN will\n automatically provide the appropriate\n HTTP/1.1 headers based on the\n \"Content-type=text/html\" line in the\n index.wn file.\n\nwhile you do seem to be supplying a header in your code. Second, you sure you want parsing, as you're requesting?\nI don't see why either of these issues should just \"swallow\" your program's output, though, so this is hardly a complete answer... but maybe it could be a start.\nBTW, since you say\n\nI'm not sure I have even seen a filter\n program at all\n\nthe one example of filter I see in the docs is zcat -- at least this does make clear that a filter is a program that takes the given file as its standard input (but doesn't have to read it, the docs say... but that file, even if ignored as in your example code, must exist -- could that perhaps be the problem...?) and gives the contents (not headers) to send back on its standard output.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0002946299_python.txt
Q: Recursion function not working properly I'm having quite a hard time figuring out what's going wrong here: class iterate(): def __init__(self): self.length=1 def iterated(self, n): if n==1: return self.length elif n%2==0: self.length+=1 self.iterated(n/2) elif n!=1: self.length+=1 self.iterated(3*n+1) For example, x=iterate() x.iterated(5) outputs None. It should output 6 because the length would look like this: 5 --> 16 --> 8 --> 4 --> 2 --> 1 After doing some debugging, I see that the self.length is returned properly but something goes wrong in the recursion. I'm not really sure. Thanks for any help. A: In the two elif blocks, you don't return a value after making the recursive call. You need a return before the recursive calls to iterated (e.g. return self.iterated(n/2)). If you don't explicitly return, the function will return None. That will fix this issue, but there is a way to make your code simpler: You don't actually need the member length. Instead, you can add 1 to the result of the recursive call: def iterated(n): if n==1: return 1 elif n%2==0: return 1 + iterated(n/2) else: return 1 + iterated(3*n+1) print(iterated(5)) This doesn't need to be in a class, since there is no need for any members. A: You're missing the return statements: class iterate(): def init(self): self.length=1 def iterated(self, n): if n==1: return self.length elif n%2==0: self.length+=1 **return** self.iterated(n/2) elif n!=1: self.length+=1 **return** self.iterated(3*n+1) A: You are only returning a value from the deepest level of recursion, then ignoring it on the second-deepest level. All of the self.iterated(...) lines should read return self.iterated(...) A: You should finish each elif branch with return self.iterated(...) rather than just self.iterated(...)
Recursion function not working properly
I'm having quite a hard time figuring out what's going wrong here: class iterate(): def __init__(self): self.length=1 def iterated(self, n): if n==1: return self.length elif n%2==0: self.length+=1 self.iterated(n/2) elif n!=1: self.length+=1 self.iterated(3*n+1) For example, x=iterate() x.iterated(5) outputs None. It should output 6 because the length would look like this: 5 --> 16 --> 8 --> 4 --> 2 --> 1 After doing some debugging, I see that the self.length is returned properly but something goes wrong in the recursion. I'm not really sure. Thanks for any help.
[ "In the two elif blocks, you don't return a value after making the recursive call. You need a return before the recursive calls to iterated (e.g. return self.iterated(n/2)). If you don't explicitly return, the function will return None.\nThat will fix this issue, but there is a way to make your code simpler: You don't actually need the member length. Instead, you can add 1 to the result of the recursive call:\ndef iterated(n):\n if n==1:\n return 1\n elif n%2==0:\n return 1 + iterated(n/2)\n else:\n return 1 + iterated(3*n+1)\n\nprint(iterated(5))\n\nThis doesn't need to be in a class, since there is no need for any members.\n", "You're missing the return statements:\nclass iterate():\n def init(self):\n self.length=1\n def iterated(self, n):\n if n==1:\n return self.length\n elif n%2==0:\n self.length+=1\n **return** self.iterated(n/2)\n elif n!=1:\n self.length+=1\n **return** self.iterated(3*n+1)\n\n", "You are only returning a value from the deepest level of recursion, then ignoring it on the second-deepest level.\nAll of the self.iterated(...) lines should read return self.iterated(...)\n", "You should finish each elif branch with return self.iterated(...) rather than just self.iterated(...)\n" ]
[ 5, 3, 2, 2 ]
[]
[]
[ "python", "recursion" ]
stackoverflow_0002946631_python_recursion.txt
Q: CSS file pathing problem When designing a HTML template in my favorite editor (TextPad at the moment) I can view my code in a browser by pressing F11 or the appropriate toolbar button. I have my common css rules in a separate file so my HTML contains the code: <link rel="stylesheet" href="commoncss.css" type="text/css"> This works when the .css file is in the same folder as the .html file, or if I fully path the .css file in the href property, eg. ///c:/mycssfolder/commoncss.css However, in a 'live' situation I want the .css file to reside in a common folder which is accessible from a number of .html files (eg. href='css/commoncss.css', where the css folder is configured at web-server level). How can I achieve this design vs. live dilemma without copying css file to all .html folders (and all the maintenance headaches that comes with it)? I am using Python 3.1 with Jinja2, but I guess this problem is applicable across any language and template-engine. Any help would be appreciated. Alan A: If you put your CSS files in a top-level "/css" directory, then your HTML files can just refer to that. <link rel='stylesheet' href='/css/style_file1.css'> I don't know much about your framework; sometimes there's an additional layer under the server root to identify an "application" or something. If that's the case, it'd be "/appname/css/filename.css". A: <link rel='stylesheet' href='../css/stylesheet.css'> This will move down a level, then up a level to /CSS/.
CSS file pathing problem
When designing a HTML template in my favorite editor (TextPad at the moment) I can view my code in a browser by pressing F11 or the appropriate toolbar button. I have my common css rules in a separate file so my HTML contains the code: <link rel="stylesheet" href="commoncss.css" type="text/css"> This works when the .css file is in the same folder as the .html file, or if I fully path the .css file in the href property, eg. ///c:/mycssfolder/commoncss.css However, in a 'live' situation I want the .css file to reside in a common folder which is accessible from a number of .html files (eg. href='css/commoncss.css', where the css folder is configured at web-server level). How can I achieve this design vs. live dilemma without copying css file to all .html folders (and all the maintenance headaches that comes with it)? I am using Python 3.1 with Jinja2, but I guess this problem is applicable across any language and template-engine. Any help would be appreciated. Alan
[ "If you put your CSS files in a top-level \"/css\" directory, then your HTML files can just refer to that.\n<link rel='stylesheet' href='/css/style_file1.css'>\n\nI don't know much about your framework; sometimes there's an additional layer under the server root to identify an \"application\" or something. If that's the case, it'd be \"/appname/css/filename.css\".\n", "<link rel='stylesheet' href='../css/stylesheet.css'>\n\nThis will move down a level, then up a level to /CSS/.\n" ]
[ 3, 2 ]
[]
[]
[ "css", "jinja2", "path", "python", "templates" ]
stackoverflow_0002946404_css_jinja2_path_python_templates.txt
Q: python simpleJSONDecoder and complex JSON issue In a unit test case that I am running, I get a KeyError exception on the 4th json object in the json text below because the piece of code responsible for decoding is looking for an object that isn't there, but should be. I went through the sub-objects and found that it was the "cpuid" object that causes the problem. When I remove it and run the test, it works fine. def _make_report_entry(record): response = self.app.post( '/machinestats', params = dict(record = self.json_encode([{ "type": "crash", "instance_id": "xxx", "version": "0.2.0", "build_id": "unknown", "crash_text": "Gah!" }, { "type": "machine_info", "machine_info": "I'm awesome.", "version": "0.2.0", "build_id": "unknown", "instance_id": "yyy" }, { "machine_info": "Soup", "crash_text": "boom!", "version": "0.2.0", "build_id": "unknown", "instance_id": "zzz", "type": "crash" }, { "build_id": "unknown", "cpu_brand": "intel", "cpu_count": 4, "cpuid": { "00000000": { "eax": 123, "ebx": 456, "ecx": 789, "edx": 321 }, "00000001": { "eax": 123, "ebx": 456, "ecx": 789, "edx": 321 } }, "driver_installed": True, "instance_id": "yyy", "version": "0.2.0", "machine_info": "I'm awesome.", "os_version": "linux", "physical_memory_mib": 1024, "product_loaded": True, "type": "machine_info", "virtualization_advertised": True } ]))) In the piece of code being tested, I use simplejson.JSONDecoder from django.utils to decode the JSON. When I log the decoded output for the above JSON that gets passed to my decoding function, I get this: root: INFO: {u'instance_id': u'xxx', u'type': u'crash', u'crash_text': u'Gah!', u'version': u'0.2.0', u'build_id': u'unknown'} root: INFO: {u'build_id': u'unknown', u'instance_id': u'yyy', u'version': u'0.2.0', u'machine_info': u"I'm awesome.", u'type': u'machine_info'} root: INFO: {u'build_id': u'unknown', u'machine_info': u'Soup', u'version': u'0.2.0', u'instance_id': u'zzz', u'crash_text': u'boom!', u'type': u'crash'} root: INFO: {u'eax': 123, u'edx': 321, u'ebx': 456, u'ecx': 789} On the last JSON object, only the object within the JSON cpuid object is being passed to my decoding function. Because my decoding function is expecting the the other objects (e.g., 'type', 'instance_id', etc.), I get a KeyError exception. [Sorry for the earlier unnecessarily long post, I hope that this will narrow it down a bit more] A: Copying and pasting what you're passing to self.json_encode, and using it as an argument of json.dumps (after an import json in Python 2.6), works just fine. So it seems the bug may be in the json_encode method you're not showing us: what else does it do, besides just calling json.dumps...? (or simplejson.dumps if you're using a Python < 2.6, of course). Edit: using json_encode = json.JSONEncoder().encode (as the OP just posted, except that's using the older simplejson as I had mentioned as a possibility) also works fine. The incomplete stack-trace also posted as part of the Q's large edit suggests that the error comes in the decoding part, perhaps through misuse of some model (can't tell, as we don't see the models) -- as the OP mentioned he's now posted a lot more info, and yet it's still not enough to debug the problem. This strongly suggests that it would be worthwhile for the OP to try and simplify the problem a little at a time until the last incremental simplification makes the bug disappear -- that usually strongly hints at what the bug may be, but even if it doesn't, posting the tiniest way to reproduce the bug plus the info that the bug will disappear if a miniscule epsilon of code is further removes, may help "third party observers" like us all assist in the debugging. SO is not really a platform designed for collective debugging (works better for questions and answers, what it was designed for) but I don't think it breaks SO's rules to try and use it for this different purpose. A: Last 2 lines in traceback: File "...j_report/src/jreport/machinestats.py", line 77, in _make_report_entry entry_type=record['type'] You have now TWO versions of def _make_report_entry(record): Note that the first few lines of the traceback are muttering about decode, not encode. What has the first/original version to do with the problem? You now say "Because my decoding function is expecting the the other objects (e.g., 'type', 'instance_id', etc.), I get a KeyError exception." So perhaps your decoding function is being called recursively and is expected by the caller to be able to handle ANY structure, not just ones with 'type' etc.
python simpleJSONDecoder and complex JSON issue
In a unit test case that I am running, I get a KeyError exception on the 4th json object in the json text below because the piece of code responsible for decoding is looking for an object that isn't there, but should be. I went through the sub-objects and found that it was the "cpuid" object that causes the problem. When I remove it and run the test, it works fine. def _make_report_entry(record): response = self.app.post( '/machinestats', params = dict(record = self.json_encode([{ "type": "crash", "instance_id": "xxx", "version": "0.2.0", "build_id": "unknown", "crash_text": "Gah!" }, { "type": "machine_info", "machine_info": "I'm awesome.", "version": "0.2.0", "build_id": "unknown", "instance_id": "yyy" }, { "machine_info": "Soup", "crash_text": "boom!", "version": "0.2.0", "build_id": "unknown", "instance_id": "zzz", "type": "crash" }, { "build_id": "unknown", "cpu_brand": "intel", "cpu_count": 4, "cpuid": { "00000000": { "eax": 123, "ebx": 456, "ecx": 789, "edx": 321 }, "00000001": { "eax": 123, "ebx": 456, "ecx": 789, "edx": 321 } }, "driver_installed": True, "instance_id": "yyy", "version": "0.2.0", "machine_info": "I'm awesome.", "os_version": "linux", "physical_memory_mib": 1024, "product_loaded": True, "type": "machine_info", "virtualization_advertised": True } ]))) In the piece of code being tested, I use simplejson.JSONDecoder from django.utils to decode the JSON. When I log the decoded output for the above JSON that gets passed to my decoding function, I get this: root: INFO: {u'instance_id': u'xxx', u'type': u'crash', u'crash_text': u'Gah!', u'version': u'0.2.0', u'build_id': u'unknown'} root: INFO: {u'build_id': u'unknown', u'instance_id': u'yyy', u'version': u'0.2.0', u'machine_info': u"I'm awesome.", u'type': u'machine_info'} root: INFO: {u'build_id': u'unknown', u'machine_info': u'Soup', u'version': u'0.2.0', u'instance_id': u'zzz', u'crash_text': u'boom!', u'type': u'crash'} root: INFO: {u'eax': 123, u'edx': 321, u'ebx': 456, u'ecx': 789} On the last JSON object, only the object within the JSON cpuid object is being passed to my decoding function. Because my decoding function is expecting the the other objects (e.g., 'type', 'instance_id', etc.), I get a KeyError exception. [Sorry for the earlier unnecessarily long post, I hope that this will narrow it down a bit more]
[ "Copying and pasting what you're passing to self.json_encode, and using it as an argument of json.dumps (after an import json in Python 2.6), works just fine. So it seems the bug may be in the json_encode method you're not showing us: what else does it do, besides just calling json.dumps...? (or simplejson.dumps if you're using a Python < 2.6, of course).\nEdit: using json_encode = json.JSONEncoder().encode (as the OP just posted, except that's using the older simplejson as I had mentioned as a possibility) also works fine. The incomplete stack-trace also posted as part of the Q's large edit suggests that the error comes in the decoding part, perhaps through misuse of some model (can't tell, as we don't see the models) -- as the OP mentioned he's now posted a lot more info, and yet it's still not enough to debug the problem.\nThis strongly suggests that it would be worthwhile for the OP to try and simplify the problem a little at a time until the last incremental simplification makes the bug disappear -- that usually strongly hints at what the bug may be, but even if it doesn't, posting the tiniest way to reproduce the bug plus the info that the bug will disappear if a miniscule epsilon of code is further removes, may help \"third party observers\" like us all assist in the debugging. SO is not really a platform designed for collective debugging (works better for questions and answers, what it was designed for) but I don't think it breaks SO's rules to try and use it for this different purpose.\n", "Last 2 lines in traceback:\nFile \"...j_report/src/jreport/machinestats.py\", line 77, in _make_report_entry\nentry_type=record['type']\n\nYou have now TWO versions of def _make_report_entry(record):\nNote that the first few lines of the traceback are muttering about decode, not encode.\nWhat has the first/original version to do with the problem?\nYou now say \"Because my decoding function is expecting the the other objects (e.g., 'type', 'instance_id', etc.), I get a KeyError exception.\"\nSo perhaps your decoding function is being called recursively and is expected by the caller to be able to handle ANY structure, not just ones with 'type' etc.\n" ]
[ 1, 0 ]
[]
[]
[ "json", "python", "simplejson" ]
stackoverflow_0002946768_json_python_simplejson.txt
Q: Index of nth biggest item in Python list I can't edit or sort the list. How can I get that index? A: The heapq module provides a nlargest function that efficiently finds the n largest elements of a list: >>> from heapq import nlargest >>> items = [100, 300, 200, 400] >>> indexes = [0, 1, 2, 3] >>> nlargest(2, indexes, key=lambda i: items[i]) [3, 1] A: What you've got is already O(n) in complexity (max is O(n), as is index(), IIRC). So while you could technically just remove the largest if it's not appropriate and try again, you're starting to get into bubblesort territory in terms of big-O. How many items are typically on the list? One option is QuickSelect, which is basically a reduced QuickSort, but honestly just sorting the list up front is not going to be much slower than what you've got already. You can use the sorted() function to return a new sorted list if you don't want to change the ordering of the original list.
Index of nth biggest item in Python list
I can't edit or sort the list. How can I get that index?
[ "The heapq module provides a nlargest function that efficiently finds the n largest elements of a list:\n>>> from heapq import nlargest\n>>> items = [100, 300, 200, 400]\n>>> indexes = [0, 1, 2, 3]\n>>> nlargest(2, indexes, key=lambda i: items[i])\n[3, 1]\n\n", "What you've got is already O(n) in complexity (max is O(n), as is index(), IIRC). So while you could technically just remove the largest if it's not appropriate and try again, you're starting to get into bubblesort territory in terms of big-O. How many items are typically on the list?\nOne option is QuickSelect, which is basically a reduced QuickSort, but honestly just sorting the list up front is not going to be much slower than what you've got already.\nYou can use the sorted() function to return a new sorted list if you don't want to change the ordering of the original list.\n" ]
[ 6, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0002946861_list_python.txt
Q: Transitioning from php to python/pylons/SQLAlchemy -- Are ORMs the standard now? Should I invest a lot of time trying to figure out an ORM style implementation, or is it still common to just stick with standard SQL queries in python/pylons/sqlalchemy? A: ORMs are very popular, for several reasons -- e.g.: some people would rather not learn SQL, ORMs can ease porting among different SQL dialects, they may fit in more smoothly with the mostly-OOP style of applications, indeed might even ease some porting to non-SQL implementations (e.g, moving a Django app to Google App Engine would be much more work if the storage access layer relied on SQL statements -- as it relies on the ORM, that reduces, a bit, the needed porting work). SQLAlchemy is the most powerful ORM I know of for Python -- it lets you work at several possible levels, from a pretty abstract declarative one all the way down to injecting actual SQL in some queries where your profiling work has determined it makes a big difference (I think most people use it mostly at the intermediate level where it essentially mediates between OOP and relational styles, just like other ORMs). You haven't asked for my personal opinion in the matter, which is somewhat athwart of the popular one I summarized above -- I've never really liked "code generators" of any kind (they increase your productivity a bit when everything goes smoothly... but you can pay that back with interest when you find yourself debugging problems [[including performance bottlenecks]] due to issues occurring below the abstraction levels that generators strive to provide). When I get a chance to use a good relational engine, such as PostgreSQL, I believe I'm overall more productive than I would be with any ORM in between (incuding SQLAlchemy, despite its many admirable qualities). However, I have to admit that the case is different when the relational engine is not all that good (e.g., I've never liked MySQL), or when porting to non-relational deployments is an important consideration. So, back to your actual question, I do think that, overall, investing time in mastering SQLAlchemy is a good idea, and time well-spent. A: If you have never use an ORM like SqlAlchemy before, I would suggest that you learn it - as long as you are learning the Python way. If nothing else, you will be better able to decide where/when to use it vs plain SQL. I don't think you should have to invest a lot of time on it. Documentation for SQLAlchemy is decent, and you can always ask for help if you get stuck.
Transitioning from php to python/pylons/SQLAlchemy -- Are ORMs the standard now?
Should I invest a lot of time trying to figure out an ORM style implementation, or is it still common to just stick with standard SQL queries in python/pylons/sqlalchemy?
[ "ORMs are very popular, for several reasons -- e.g.: some people would rather not learn SQL, ORMs can ease porting among different SQL dialects, they may fit in more smoothly with the mostly-OOP style of applications, indeed might even ease some porting to non-SQL implementations (e.g, moving a Django app to Google App Engine would be much more work if the storage access layer relied on SQL statements -- as it relies on the ORM, that reduces, a bit, the needed porting work).\nSQLAlchemy is the most powerful ORM I know of for Python -- it lets you work at several possible levels, from a pretty abstract declarative one all the way down to injecting actual SQL in some queries where your profiling work has determined it makes a big difference (I think most people use it mostly at the intermediate level where it essentially mediates between OOP and relational styles, just like other ORMs).\nYou haven't asked for my personal opinion in the matter, which is somewhat athwart of the popular one I summarized above -- I've never really liked \"code generators\" of any kind (they increase your productivity a bit when everything goes smoothly... but you can pay that back with interest when you find yourself debugging problems [[including performance bottlenecks]] due to issues occurring below the abstraction levels that generators strive to provide).\nWhen I get a chance to use a good relational engine, such as PostgreSQL, I believe I'm overall more productive than I would be with any ORM in between (incuding SQLAlchemy, despite its many admirable qualities). However, I have to admit that the case is different when the relational engine is not all that good (e.g., I've never liked MySQL), or when porting to non-relational deployments is an important consideration.\nSo, back to your actual question, I do think that, overall, investing time in mastering SQLAlchemy is a good idea, and time well-spent.\n", "If you have never use an ORM like SqlAlchemy before, I would suggest that you learn it - as long as you are learning the Python way. If nothing else, you will be better able to decide where/when to use it vs plain SQL. I don't think you should have to invest a lot of time on it. Documentation for SQLAlchemy is decent, and you can always ask for help if you get stuck.\n" ]
[ 8, 1 ]
[]
[]
[ "orm", "python", "sql", "sqlalchemy" ]
stackoverflow_0002947172_orm_python_sql_sqlalchemy.txt
Q: Python vs all the major professional languages I've been reading up a lot lately on comparisons between Python and a bunch of the more traditional professional languages - C, C++, Java, etc, mainly trying to find out if its as good as those would be for my own purposes. I can't get this thought out of my head that it isn't good for 'real' programming tasks beyond automation and macros. Anyway, the general idea I got from about two hundred forum threads and blog posts is that for general, non-professional-level progs, scripts, and apps, and as long as it's a single programmer (you) writing it, a given program can be written quicker and more efficiently with Python than it could be with pretty much any other language. But once its big enough to require multiple programmers or more complex than a regular person (read: non-professional) would have any business making, it pretty much becomes instantly inferior to a million other languages. Is this idea more or less accurate? (I'm learning Python for my first language and want to be able to make any small app that I want, but I plan on learning C eventually too, because I want to get into driver writing eventually. So I've been trying to research each ones strengths and weaknesses as much as I can.) Anyway, thanks for any input A: An open source project I work on for VCS integration (RabbitVCS) is written entirely in Python/PyGTK and includes: Two file browser extensions A text editor extension A backend VCS status cache running asynchronously, using DBUS for the interface A fairly comprehensive set of dialogs, including VCS log browsers, a repository browser and a merge wizard (maybe that one isn't such a selling point). There's no standalone app, but we're thinking about it. Because we're always adding new features, and currently trying to adapt to new VCS', Python is ideal for the ability to quickly refactor entire layers of code without breaking our mental flow. I've also found that the syntax itself makes a real difference with complicated merging of version controlled branches, but that might come with the ability to read it quickly. Recently we've begun adding support for a new VCS, requiring: refactoring current code to separate VCS specific actions and information from common/generic information refactoring the UI layer to accomodate the new functionality Most of what we've achieved has been possible because of the availability of C/Python bindings (eg. PySVN, Nautilus-Python, etc). But when it hasn't been available... well, it's not that hard to roll your own (as a developer did for the new VCS). When the bindings lack functionality... it's not that hard to add it. The real drawbacks so far have been: Threading mishaps. Lesson learnt: forget about threads, use multiple processes where possible or your toolkit's threading method (eg. PyGTK, wxPython and Twisted all have their own ways of dealing with concurrency) (C) Extensions. Cause threading mishaps (they almost invariably lock the GIL, preventing threading). See above. Needing to hack on C bindings when certain functionality is unavailable. Profiling can be tricky when you're not just doing something based on a single function call. If you want to know about more specific aspects, ask away in the comments :)
Python vs all the major professional languages
I've been reading up a lot lately on comparisons between Python and a bunch of the more traditional professional languages - C, C++, Java, etc, mainly trying to find out if its as good as those would be for my own purposes. I can't get this thought out of my head that it isn't good for 'real' programming tasks beyond automation and macros. Anyway, the general idea I got from about two hundred forum threads and blog posts is that for general, non-professional-level progs, scripts, and apps, and as long as it's a single programmer (you) writing it, a given program can be written quicker and more efficiently with Python than it could be with pretty much any other language. But once its big enough to require multiple programmers or more complex than a regular person (read: non-professional) would have any business making, it pretty much becomes instantly inferior to a million other languages. Is this idea more or less accurate? (I'm learning Python for my first language and want to be able to make any small app that I want, but I plan on learning C eventually too, because I want to get into driver writing eventually. So I've been trying to research each ones strengths and weaknesses as much as I can.) Anyway, thanks for any input
[ "An open source project I work on for VCS integration (RabbitVCS) is written entirely in Python/PyGTK and includes:\n\nTwo file browser extensions\nA text editor extension\nA backend VCS status cache running asynchronously, using DBUS for the interface\nA fairly comprehensive set of dialogs, including VCS log browsers, a repository browser and a merge wizard (maybe that one isn't such a selling point).\n\nThere's no standalone app, but we're thinking about it.\nBecause we're always adding new features, and currently trying to adapt to new VCS', Python is ideal for the ability to quickly refactor entire layers of code without breaking our mental flow. I've also found that the syntax itself makes a real difference with complicated merging of version controlled branches, but that might come with the ability to read it quickly.\nRecently we've begun adding support for a new VCS, requiring:\n\nrefactoring current code to separate VCS specific actions and information from common/generic information\nrefactoring the UI layer to accomodate the new functionality\n\nMost of what we've achieved has been possible because of the availability of C/Python bindings (eg. PySVN, Nautilus-Python, etc). But when it hasn't been available... well, it's not that hard to roll your own (as a developer did for the new VCS). When the bindings lack functionality... it's not that hard to add it.\nThe real drawbacks so far have been:\n\nThreading mishaps. Lesson learnt: forget about threads, use multiple processes where possible or your toolkit's threading method (eg. PyGTK, wxPython and Twisted all have their own ways of dealing with concurrency)\n(C) Extensions. Cause threading mishaps (they almost invariably lock the GIL, preventing threading). See above.\nNeeding to hack on C bindings when certain functionality is unavailable.\nProfiling can be tricky when you're not just doing something based on a single function call.\n\nIf you want to know about more specific aspects, ask away in the comments :)\n" ]
[ 5 ]
[]
[]
[ "c", "comparison", "python" ]
stackoverflow_0002947341_c_comparison_python.txt
Q: Efficient job progress update in web application Creating a web application (Django in my case, but I think the question is more general) that is administrating a cluster of workers doing queued jobs, there is a need to track each jobs progress. When I've done it using database UPDATE (PostgreSQL in this case), it severely hits the database performance, because each UPDATE creates a new row in a table, and in my case only vacuuming DB removes obsolete rows. Having 30 jobs running and reporting progress every 1 minute DB may require vacuuming (and it means huge slow downs on a front end side for all the employees working with the system) every 10 days. Because the progress information isn't critical, ie. it doesn't have to be persistent, how would you do the progress updates from jobs without using an overhead database implies? There are 30 worker servers, each doing 1 or 2 jobs simultaneously, 1 front end server which serves a web application to users, and 1 database server. A: There is a package called memcached which sets up a fast server for key-value retrieval. It's used by big clustered sites like wikipedia. It lets you share frequent-changed data around your cluster without DB overhead. A: If you are doing the inserts/updates/retreives based on keys (for example you are accessing the rows by ID every time) you can use the Django caching framework with any of the cache backends that can be shared between servers. amwinter suggested memcached. There's a memcached cache backend in the django distribution. But memecached doesn't guarantee it won't loose your data. For example you might be trying to store large amounts of data and memcached will start loosing your data when it hits a certain memory limit. So keep that in mind. There's an extension for memcached that can make it persist data (forgot what it was called). You may also consider redis as a cache backend or MongoDB
Efficient job progress update in web application
Creating a web application (Django in my case, but I think the question is more general) that is administrating a cluster of workers doing queued jobs, there is a need to track each jobs progress. When I've done it using database UPDATE (PostgreSQL in this case), it severely hits the database performance, because each UPDATE creates a new row in a table, and in my case only vacuuming DB removes obsolete rows. Having 30 jobs running and reporting progress every 1 minute DB may require vacuuming (and it means huge slow downs on a front end side for all the employees working with the system) every 10 days. Because the progress information isn't critical, ie. it doesn't have to be persistent, how would you do the progress updates from jobs without using an overhead database implies? There are 30 worker servers, each doing 1 or 2 jobs simultaneously, 1 front end server which serves a web application to users, and 1 database server.
[ "There is a package called memcached which sets up a fast server for key-value retrieval. It's used by big clustered sites like wikipedia.\nIt lets you share frequent-changed data around your cluster without DB overhead.\n", "If you are doing the inserts/updates/retreives based on keys (for example you are accessing the rows by ID every time) you can use the Django caching framework with any of the cache backends that can be shared between servers. amwinter suggested memcached. There's a memcached cache backend in the django distribution. But memecached doesn't guarantee it won't loose your data. For example you might be trying to store large amounts of data and memcached will start loosing your data when it hits a certain memory limit. So keep that in mind. There's an extension for memcached that can make it persist data (forgot what it was called).\nYou may also consider redis as a cache backend or MongoDB\n" ]
[ 1, 1 ]
[]
[]
[ "database", "django", "postgresql", "python", "web_applications" ]
stackoverflow_0002855277_database_django_postgresql_python_web_applications.txt
Q: optparse: No option string I am trying to use optparse but I am having a problem. My script usage would be: script <filename> I don't intend to add any option string, such as: script -f <filename> or script --file <filename> Is there any way I can choose not to pass an argument string? Or is there any way I can allow the user to do this: script -f <filename> script --filename <filename> script <filename> All of the above with the same consequence? I know that I can easily do with this with using argv[1] but the thing is that I might need to add command line support later in the project and add that time I would not want to add optparse support all over. That is the reason I want to use optparse. A: import optparse parser = optparse.OptionParser() parser.add_option("-f", "--filename", metavar="FILE", dest="input_file", action="append") options, args = parser.parse_args() if options.input_file: args.extend(options.input_file) for arg in args: process_file(arg) This will simply use args as a list of input files, but it will append the file names passed as -f or --filename arguments to args so you will get all of them.
optparse: No option string
I am trying to use optparse but I am having a problem. My script usage would be: script <filename> I don't intend to add any option string, such as: script -f <filename> or script --file <filename> Is there any way I can choose not to pass an argument string? Or is there any way I can allow the user to do this: script -f <filename> script --filename <filename> script <filename> All of the above with the same consequence? I know that I can easily do with this with using argv[1] but the thing is that I might need to add command line support later in the project and add that time I would not want to add optparse support all over. That is the reason I want to use optparse.
[ "import optparse\n\nparser = optparse.OptionParser()\nparser.add_option(\"-f\", \"--filename\", metavar=\"FILE\", dest=\"input_file\", action=\"append\")\noptions, args = parser.parse_args()\nif options.input_file:\n args.extend(options.input_file)\n\nfor arg in args:\n process_file(arg)\n\nThis will simply use args as a list of input files, but it will append the file names passed as -f or --filename arguments to args so you will get all of them.\n" ]
[ 1 ]
[]
[]
[ "optparse", "python" ]
stackoverflow_0002947993_optparse_python.txt
Q: Problems parsing a xml file I am editing a xml file that is originally like that: <SequencerLoopCommand id="1073" IterationCount="2" CommandList="1241 1242" Name="Loop Stream IDU64ToIDU63"> <IterateLoadSizeCommand id="1241" LoadType="STEP" LoadUnits="KILOBITS_PER_SECOND" LoadStart="100" LoadEnd="200" LoadStep="100" CustomLoadList="" StreamBlockList="1543" Name="Iterate Stream IDU64ToIDU63"> </IterateLoadSizeCommand> <WaitCommand id="1242" WaitTime="5" Name="Stream IDU64ToIDU63"> </WaitCommand> </SequencerLoopCommand> With the following code... doc = minidom.parse("directory") #processing fh = open(os.path.join(self.__dirname,self.__xmlfile),"w") doc.writexml(fh) fh.close() doc.unlink() after that, my new xml is something like: <SequencerLoopCommand CommandList="1241 1242" IterationCount="2" Name="Loop Stream IDU64ToIDU63" id="1073"> <IterateLoadSizeCommand CustomLoadList="" LoadEnd="200" LoadStart="100" LoadStep="100" LoadType="STEP" LoadUnits="KILOBITS_PER_SECOND" Name="Iterate Stream IDU64ToIDU63" StreamBlockList="1543" id="1241"> </IterateLoadSizeCommand> <WaitCommand Name="Stream IDU64ToIDU63" WaitTime="5" id="1242"> </WaitCommand> </SequencerLoopCommand> I need that the new file to have the same structure as the old one. Any tip? Thank you A: I guess it's not easy by default as both XMLs are identical (from parser POV). However, You can write custom SAX serializer that will break & ident attributes. See http://docs.python.org/library/xml.sax.handler.html#module-xml.sax.handler , but I'd say it's not worth the effort.
Problems parsing a xml file
I am editing a xml file that is originally like that: <SequencerLoopCommand id="1073" IterationCount="2" CommandList="1241 1242" Name="Loop Stream IDU64ToIDU63"> <IterateLoadSizeCommand id="1241" LoadType="STEP" LoadUnits="KILOBITS_PER_SECOND" LoadStart="100" LoadEnd="200" LoadStep="100" CustomLoadList="" StreamBlockList="1543" Name="Iterate Stream IDU64ToIDU63"> </IterateLoadSizeCommand> <WaitCommand id="1242" WaitTime="5" Name="Stream IDU64ToIDU63"> </WaitCommand> </SequencerLoopCommand> With the following code... doc = minidom.parse("directory") #processing fh = open(os.path.join(self.__dirname,self.__xmlfile),"w") doc.writexml(fh) fh.close() doc.unlink() after that, my new xml is something like: <SequencerLoopCommand CommandList="1241 1242" IterationCount="2" Name="Loop Stream IDU64ToIDU63" id="1073"> <IterateLoadSizeCommand CustomLoadList="" LoadEnd="200" LoadStart="100" LoadStep="100" LoadType="STEP" LoadUnits="KILOBITS_PER_SECOND" Name="Iterate Stream IDU64ToIDU63" StreamBlockList="1543" id="1241"> </IterateLoadSizeCommand> <WaitCommand Name="Stream IDU64ToIDU63" WaitTime="5" id="1242"> </WaitCommand> </SequencerLoopCommand> I need that the new file to have the same structure as the old one. Any tip? Thank you
[ "I guess it's not easy by default as both XMLs are identical (from parser POV).\nHowever, You can write custom SAX serializer that will break & ident attributes. See http://docs.python.org/library/xml.sax.handler.html#module-xml.sax.handler , but I'd say it's not worth the effort. \n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0002948386_python.txt
Q: Why can't my function access a variable in an enclosing function? I know about the LEGB rule. But a simple test of whether a function has read access to variables defined in an enclosing function doesn't seem to actually work. Ie: #!/usr/bin/env python2.4 '''Simple test of Python scoping rules''' def myfunction(): print 'Hope this works: '+myvariable def enclosing(): myvariable = 'ooh this worked' myfunction() if __name__ == '__main__': enclosing() Returns: NameError: global name 'myvariable' is not defined Am I doing something wrong? Is there more to it than the LEGB resolution order? A: you can... if you did it like this: #!/usr/bin/env python2.4 '''Simple test of Python scoping rules''' def enclosing(): myvariable = 'ooh this worked' def myfunction(): print 'Hope this works: ' + myvariable myfunction() if __name__ == '__main__': enclosing() ...otherwise your function doesn't know where to look (well it does, but it looks at the global variables, which is why you are getting the error you are getting) (pass it as a parameter if you can't define the function as a nested function)
Why can't my function access a variable in an enclosing function?
I know about the LEGB rule. But a simple test of whether a function has read access to variables defined in an enclosing function doesn't seem to actually work. Ie: #!/usr/bin/env python2.4 '''Simple test of Python scoping rules''' def myfunction(): print 'Hope this works: '+myvariable def enclosing(): myvariable = 'ooh this worked' myfunction() if __name__ == '__main__': enclosing() Returns: NameError: global name 'myvariable' is not defined Am I doing something wrong? Is there more to it than the LEGB resolution order?
[ "you can...\nif you did it like this:\n#!/usr/bin/env python2.4\n'''Simple test of Python scoping rules'''\n\ndef enclosing():\n myvariable = 'ooh this worked'\n\n def myfunction():\n print 'Hope this works: ' + myvariable\n\n myfunction()\n\nif __name__ == '__main__':\n enclosing()\n\n...otherwise your function doesn't know where to look (well it does, but it looks at the global variables, which is why you are getting the error you are getting) (pass it as a parameter if you can't define the function as a nested function)\n" ]
[ 2 ]
[]
[]
[ "python", "scope" ]
stackoverflow_0002948526_python_scope.txt
Q: How do I create a Django ModelForm, so that it's fields are sometimes required, sometimes not? Ok, here is the question. Imagine I have a ModelForm which have only two fields. like this one: class ColorForm(forms.Form): color_by_name = forms.CharField() color = forms.IntegerField(widget = forms.Select(choices=COLOR_CHOICES)) So a user can either input a color name, a choose it from a list. Color is required, but that doesn't mean, that user should enter it manually. There do I put validation, so that my code checks if user selected color in dropdownlist and if not then he should write it manually? A: Make them both required=False, but write a clean() method which checks for one or the other. See the validation documentation for an example.
How do I create a Django ModelForm, so that it's fields are sometimes required, sometimes not?
Ok, here is the question. Imagine I have a ModelForm which have only two fields. like this one: class ColorForm(forms.Form): color_by_name = forms.CharField() color = forms.IntegerField(widget = forms.Select(choices=COLOR_CHOICES)) So a user can either input a color name, a choose it from a list. Color is required, but that doesn't mean, that user should enter it manually. There do I put validation, so that my code checks if user selected color in dropdownlist and if not then he should write it manually?
[ "Make them both required=False, but write a clean() method which checks for one or the other. See the validation documentation for an example.\n" ]
[ 7 ]
[]
[]
[ "django", "modelform", "python" ]
stackoverflow_0002948626_django_modelform_python.txt
Q: Equivalent of alarm(3600) in Python Starting a Perl script with alarm(3600) will make the script abort if it is still running after one hour (3600 seconds). Assume I want to set an upper bound on the running time of a Python script, what is the easiest way to achieve that? A: on Unix you could use signal.alarm. A: Just for your information: this is much self-descriptive to use multiplication when you set up timers, for example alarm(24 * 60 * 60) for 24 hours, instead of alarm(86400) for the same period. Hope this will help keep your code clean and easy-maintainable :)
Equivalent of alarm(3600) in Python
Starting a Perl script with alarm(3600) will make the script abort if it is still running after one hour (3600 seconds). Assume I want to set an upper bound on the running time of a Python script, what is the easiest way to achieve that?
[ "on Unix you could use signal.alarm.\n", "Just for your information: this is much self-descriptive to use multiplication when you set up timers, for example alarm(24 * 60 * 60) for 24 hours, instead of alarm(86400) for the same period. Hope this will help keep your code clean and easy-maintainable :)\n" ]
[ 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0002948455_python.txt
Q: What would the jvm have to sacrifice in order to implement tail call optimisation? People say that the clojure implementation is excellent apart from the limitation of having no tail call optimisation - a limitation of the jvm not the clojure implementation. http://lambda-the-ultimate.org/node/2547 It has been said that to implement TCO into Python would sacrifice stack-trace dumps, and debugging regularity. Explain to me what the big deal with tail call optimization is and why Python needs it Would the same sacrifices have to be made for a jvm implementation of TCO? Would anything else have to be sacrificed? A: Whilst different (in that the il instructions existed already) it's worth noting the additional effort the .Net 64 bit JIT team had to go through to respect all tail calls. I call out in particular the comment: The down side of course is that if you have to debug or profile optimized code, be prepared to deal with call stacks that look like they’re missing a few frames. I would think it highly unlikely the JVM could avoid this either. Given that, in circumstances where a tail call optimization was requested, the JIT should assume that it is required to avoid a stack overflow this is not something that can just be switched off in Debug builds. They aren't much use for debugging if they crash before you get to the interesting part. The 'optimization' is in fact is a permanent feature and an issue for stack traces affected by it. It is worth pointing out that any optimization which avoids creating a real stack frame when doing an operation which the programmer conceptually describes/understands as being a stack operation (calling a function for example) will inherently cause a disconnect between what is presented to the user when debugging/providing the stack trace and reality. This is unavoidable as the code that describes the operation becomes further and further separated from the mechanics of the state machine performing the operation. A: Work is underway now to add tail calls to the JVM. There's a wiki page talking about some details. A: Yes it is generally the case that implementing TCO will prevent you from getting full stack traces. This is inevitable because the whole point of TCO is to avoid creating additional stack frames. It's also worth interesting to note that Clojure has an non-stack-consuming "recur" feature to get around this constraint on current JVM versions. Example: (defn triangle [n accumulator] (if (<= n 0) accumulator (recur (dec n) (+ n accumulator)))) (triangle 1000000 0) => 500000500000 (note stack does not explode here!)
What would the jvm have to sacrifice in order to implement tail call optimisation?
People say that the clojure implementation is excellent apart from the limitation of having no tail call optimisation - a limitation of the jvm not the clojure implementation. http://lambda-the-ultimate.org/node/2547 It has been said that to implement TCO into Python would sacrifice stack-trace dumps, and debugging regularity. Explain to me what the big deal with tail call optimization is and why Python needs it Would the same sacrifices have to be made for a jvm implementation of TCO? Would anything else have to be sacrificed?
[ "Whilst different (in that the il instructions existed already) it's worth noting the additional effort the .Net 64 bit JIT team had to go through to respect all tail calls.\nI call out in particular the comment:\n\nThe down side of course is that if you have to debug or profile optimized code, be prepared to deal with call stacks that look like they’re missing a few frames.\n\nI would think it highly unlikely the JVM could avoid this either.\nGiven that, in circumstances where a tail call optimization was requested, the JIT should assume that it is required to avoid a stack overflow this is not something that can just be switched off in Debug builds. They aren't much use for debugging if they crash before you get to the interesting part. The 'optimization' is in fact is a permanent feature and an issue for stack traces affected by it.\nIt is worth pointing out that any optimization which avoids creating a real stack frame when doing an operation which the programmer conceptually describes/understands as being a stack operation (calling a function for example) will inherently cause a disconnect between what is presented to the user when debugging/providing the stack trace and reality.\nThis is unavoidable as the code that describes the operation becomes further and further separated from the mechanics of the state machine performing the operation.\n", "Work is underway now to add tail calls to the JVM. There's a wiki page talking about some details.\n", "Yes it is generally the case that implementing TCO will prevent you from getting full stack traces. This is inevitable because the whole point of TCO is to avoid creating additional stack frames.\nIt's also worth interesting to note that Clojure has an non-stack-consuming \"recur\" feature to get around this constraint on current JVM versions.\nExample:\n(defn triangle [n accumulator] \n (if \n (<= n 0) \n accumulator\n (recur (dec n) (+ n accumulator))))\n\n(triangle 1000000 0)\n\n=> 500000500000 (note stack does not explode here!)\n\n" ]
[ 6, 2, 0 ]
[]
[]
[ "clojure", "jvm", "python", "stack_trace", "tail_call_optimization" ]
stackoverflow_0001006596_clojure_jvm_python_stack_trace_tail_call_optimization.txt
Q: python win32gui finding child windows for example at first you have to find hwnd of skype hwnd = win32gui.FindWindow(None, 'skype') and than all his child windows and their titles child = ??? any idea? A: This code shows hwnd of EditPlus child windows that has WindowsText of some length: EDIT You will have to find hwnd of your application, and then use this handle with EnumChildWindows. I extended example code with it. Once you get application hwnd you can enumerate only its windows. When you give 0 as hwnd to EnumChildWindows you will get handles of all runing windows. Add some prints to my code and check it! Extended code: import win32gui MAIN_HWND = 0 def is_win_ok(hwnd, starttext): s = win32gui.GetWindowText(hwnd) if s.startswith(starttext): print s global MAIN_HWND MAIN_HWND = hwnd return None return 1 def find_main_window(starttxt): global MAIN_HWND win32gui.EnumChildWindows(0, is_win_ok, starttxt) return MAIN_HWND def winfun(hwnd, lparam): s = win32gui.GetWindowText(hwnd) if len(s) > 3: print("winfun, child_hwnd: %d txt: %s" % (hwnd, s)) return 1 def main(): main_app = 'EditPlus' hwnd = win32gui.FindWindow(None, main_app) print hwnd if hwnd < 1: hwnd = find_main_window(main_app) print hwnd if hwnd: win32gui.EnumChildWindows(hwnd, winfun, None) main()
python win32gui finding child windows
for example at first you have to find hwnd of skype hwnd = win32gui.FindWindow(None, 'skype') and than all his child windows and their titles child = ??? any idea?
[ "This code shows hwnd of EditPlus child windows that has WindowsText of some length:\nEDIT\nYou will have to find hwnd of your application, and then use this handle with EnumChildWindows. I extended example code with it. Once you get application hwnd you can enumerate only its windows. When you give 0 as hwnd to EnumChildWindows you will get handles of all runing windows. Add some prints to my code and check it!\nExtended code:\nimport win32gui\n\nMAIN_HWND = 0\n\ndef is_win_ok(hwnd, starttext):\n s = win32gui.GetWindowText(hwnd)\n if s.startswith(starttext):\n print s\n global MAIN_HWND\n MAIN_HWND = hwnd\n return None\n return 1\n\n\ndef find_main_window(starttxt):\n global MAIN_HWND\n win32gui.EnumChildWindows(0, is_win_ok, starttxt)\n return MAIN_HWND\n\n\ndef winfun(hwnd, lparam):\n s = win32gui.GetWindowText(hwnd)\n if len(s) > 3:\n print(\"winfun, child_hwnd: %d txt: %s\" % (hwnd, s))\n return 1\n\ndef main():\n main_app = 'EditPlus'\n hwnd = win32gui.FindWindow(None, main_app)\n print hwnd\n if hwnd < 1:\n hwnd = find_main_window(main_app)\n print hwnd\n if hwnd:\n win32gui.EnumChildWindows(hwnd, winfun, None)\n\nmain()\n\n" ]
[ 8 ]
[]
[]
[ "python", "win32gui" ]
stackoverflow_0002948964_python_win32gui.txt
Q: UDP packages appear in wireshark, but are not received by program I am trying to read UDP packages sent by an FPGA with my computer. They are sent to port 21844 and to the IP 192.168.1.2 (which is my computer's IP). I can see the package in wireshark, they have no errors. When I run however this little python script, then only a very very small fraction of all packages are received by it, also depending if wireshark is running or not. import socket import sys HOST, PORT = "192.168.1.2", 21844 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind((HOST,PORT)) received ,address= sock.recvfrom(2048) print address I use windows 7 with Norton Internet Security, where I allow all traffic in the firewall for the FPGA IP and also for python. The same program on a Windows XP computer does not receive anything either... Thanks for any help! A: The TCP/IP stack of your OS doesn't hold those packets for you for eternity. Your script looks like something that very much depends on when it is run. Try to recvfrom in a loop, and run the script in the background. Then, start sending packets from your FPGA. For extra convenience, explore the SocketServer module from Python's stdlib. A: Ok, I found the problem: The UDP checksum in the FPGA was computed wrongly. Wireshark shows every package, but by default it does not check if the checksum is correct. When I set the checksum to 0x0000, then the packages arrive in python! Thanks for your help again!
UDP packages appear in wireshark, but are not received by program
I am trying to read UDP packages sent by an FPGA with my computer. They are sent to port 21844 and to the IP 192.168.1.2 (which is my computer's IP). I can see the package in wireshark, they have no errors. When I run however this little python script, then only a very very small fraction of all packages are received by it, also depending if wireshark is running or not. import socket import sys HOST, PORT = "192.168.1.2", 21844 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind((HOST,PORT)) received ,address= sock.recvfrom(2048) print address I use windows 7 with Norton Internet Security, where I allow all traffic in the firewall for the FPGA IP and also for python. The same program on a Windows XP computer does not receive anything either... Thanks for any help!
[ "The TCP/IP stack of your OS doesn't hold those packets for you for eternity. Your script looks like something that very much depends on when it is run. Try to recvfrom in a loop, and run the script in the background. Then, start sending packets from your FPGA. \nFor extra convenience, explore the SocketServer module from Python's stdlib.\n", "Ok, I found the problem: The UDP checksum in the FPGA was computed wrongly. Wireshark shows every package, but by default it does not check if the checksum is correct. When I set the checksum to 0x0000, then the packages arrive in python! Thanks for your help again!\n" ]
[ 3, 3 ]
[]
[]
[ "python", "udp", "wireshark" ]
stackoverflow_0002928507_python_udp_wireshark.txt
Q: Error in unzipping a file from a python script running as daemon I am getting an error whenever i try to run following unzip command from a python script which is running as a daemon Command : unzip abcd.zip > /dev/null Error End-of-central-directory signature not found$ a zip file, or it constitutes one disk of a multi-part archive. In the latter case the central directory and zipfile comment will be found on the last disk(s) of this archive unzip: cannot find zipfile directory in one of abcd.zip$ abcd.zip.zip, and cannot find abcd.zip.ZIP, period. Could anyone help me in this regard? Thanks in advance. A: Usually that would mean exactly what it says: that the file abcd.zip is not a valid ZIP file. Are you able to unzip abcd.zip as a normal user? If not, it would seem to have become corrupted. How did you get hold of it? Check for newline-mangling operations like ASCII-mode FTP. Can you read the file with the built-in Python zipfile module? Handling files directly in Python is generally preferable to kicking it out onto the command line. A: Validate the file first. This looks like a corrupted/invalid zip file.
Error in unzipping a file from a python script running as daemon
I am getting an error whenever i try to run following unzip command from a python script which is running as a daemon Command : unzip abcd.zip > /dev/null Error End-of-central-directory signature not found$ a zip file, or it constitutes one disk of a multi-part archive. In the latter case the central directory and zipfile comment will be found on the last disk(s) of this archive unzip: cannot find zipfile directory in one of abcd.zip$ abcd.zip.zip, and cannot find abcd.zip.ZIP, period. Could anyone help me in this regard? Thanks in advance.
[ "Usually that would mean exactly what it says: that the file abcd.zip is not a valid ZIP file. Are you able to unzip abcd.zip as a normal user? If not, it would seem to have become corrupted. How did you get hold of it? Check for newline-mangling operations like ASCII-mode FTP.\nCan you read the file with the built-in Python zipfile module? Handling files directly in Python is generally preferable to kicking it out onto the command line.\n", "Validate the file first. This looks like a corrupted/invalid zip file. \n" ]
[ 1, 0 ]
[]
[]
[ "linux", "python", "unzip" ]
stackoverflow_0002949429_linux_python_unzip.txt
Q: Unable to write to a text file I am running some tests and need to write to a file. When I run the test's the open = (file, 'r+') does not write to the file. The test script is below: class GetDetailsIP(TestGet): def runTest(self): self.category = ['PTZ'] try: # This run's and return's a value result = self.client.service.Get(self.category) mylogfile = open("test.txt", "r+") print >>mylogfile, result result = ("".join(mylogfile.readlines()[2])) result = str(result.split(':')[1].lstrip("//").split("/")[0]) mylogfile.close() except suds.WebFault, e: assert False except Exception, e: pass finally: if 'result' in locals(): self.assertEquals(result, self.camera_ip) else: assert False When this test run's, no value has been entered into the text file and a value is returned in the variable result. I havw also tried mylogfile.write(result). If the file does not exist is claim's the file does not exist and doesn't create one. Could this be a permission problem where python is not allowed to create a file? I have made sure that all other read's to this file are closed so I the file should not be locked. Can anyone offer any suggestion why this is happening? Thanks A: After writing, your cursor is at the end of the file. If you want to read the text you have to move to the beginning: >>> mylogfile = open("test10.txt", "w+") >>> print >> mylogfile, 'hola' >>> mylogfile.flush() #just in case >>> print mylogfile.read() #nothing because I'am at the end of the file >>> mylogfile.seek(0) >>> print mylogfile.read() hola Alternatively, it also works if you close your file before reading (but maybe this is not the more efficient method for your case). >>> mylogfile = open("test.txt", "w") >>> print >> mylogfile, 'hola' >>> mylogfile.close() >>> mylogfile = open("test.txt", "r") >>> print mylogfile.read() hola
Unable to write to a text file
I am running some tests and need to write to a file. When I run the test's the open = (file, 'r+') does not write to the file. The test script is below: class GetDetailsIP(TestGet): def runTest(self): self.category = ['PTZ'] try: # This run's and return's a value result = self.client.service.Get(self.category) mylogfile = open("test.txt", "r+") print >>mylogfile, result result = ("".join(mylogfile.readlines()[2])) result = str(result.split(':')[1].lstrip("//").split("/")[0]) mylogfile.close() except suds.WebFault, e: assert False except Exception, e: pass finally: if 'result' in locals(): self.assertEquals(result, self.camera_ip) else: assert False When this test run's, no value has been entered into the text file and a value is returned in the variable result. I havw also tried mylogfile.write(result). If the file does not exist is claim's the file does not exist and doesn't create one. Could this be a permission problem where python is not allowed to create a file? I have made sure that all other read's to this file are closed so I the file should not be locked. Can anyone offer any suggestion why this is happening? Thanks
[ "After writing, your cursor is at the end of the file. If you want to read the text you have to move to the beginning:\n>>> mylogfile = open(\"test10.txt\", \"w+\")\n>>> print >> mylogfile, 'hola'\n>>> mylogfile.flush() #just in case\n>>> print mylogfile.read()\n #nothing because I'am at the end of the file\n>>> mylogfile.seek(0)\n>>> print mylogfile.read()\nhola\n\nAlternatively, it also works if you close your file before reading (but maybe this is not the more efficient method for your case).\n>>> mylogfile = open(\"test.txt\", \"w\")\n>>> print >> mylogfile, 'hola' \n>>> mylogfile.close()\n>>> mylogfile = open(\"test.txt\", \"r\")\n>>> print mylogfile.read()\nhola\n\n" ]
[ 5 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0002949581_file_io_python.txt
Q: Python: Networked IDLE/Redo IDLE front-end while using the same back-end? Is there any existing web app that lets multiple users work with an interactive IDLE type session at once? Something like: IDLE 2.6.4 Morgan: >>> letters = list("abcdefg") Morgan: >>> # now, how would you iterate over letters? Jack: >>> for char in letters: print "char %s" % char char a char b char c char d char e char f char g Morgan: >>> # nice nice If not, I would like to create one. Is there some module I can use that simulates an interactive session? I'd want an interface like this: def class InteractiveSession(): ''' An interactive Python session ''' def putLine(line): ''' Evaluates line ''' pass def outputLines(): ''' A list of all lines that have been output by the session ''' pass def currentVars(): ''' A dictionary of currently defined variables and their values ''' pass (Although that last function would be more of an extra feature.) To formulate my problem another way: I'd like to create a new front end for IDLE. How can I do this? UPDATE: Or maybe I can simulate IDLE through eval()? UPDATE 2: What if I did something like this: I already have a simple GAE Python chat app set up, that allows users to sign in, make chat rooms, and chat with each other. Instead of just saving incoming messages to the datastore, I could do something like this: def putLine(line, user, chat_room): ''' Evaluates line for the session used by chat_room ''' # get the interactive session for this chat room curr_vars = InteractiveSession.objects.where("chatRoom = %s" % chat_room).get() result = eval(prepared_line, curr_vars.state, {}) curr_vars.state = curr_globals curr_vars.lines.append((user, line)) if result: curr_vars.lines.append(('SELF', result.__str__())) curr_vars.put() The InteractiveSession model: def class InteractiveSession(db.Model): # a dictionary mapping variables to values # it looks like GAE doesn't actually have a dictionary field, so what would be best to use here? state = db.DictionaryProperty() # a transcript of the session # # a list of tuples of the form (user, line_entered) # # looks something like: # # [('Morgan', '# hello'), # ('Jack', 'x = []'), # ('Morgan', 'x.append(1)'), # ('Jack', 'x'), # ('SELF', '[1]')] lines = db.ListProperty() Could this work, or am I way off/this approach is infeasible/I'm duplicating work when I should use something already built? UPDATE 3: Also, assuming I get everything else working, I'd like syntax highlighting. Ideally, I'd have some API or service I could use that would parse the code and style it appropriately. for c in "characters": would become: <span class="keyword">for</span> <span class="var">c</span> <span class="keyword">in</span> <span class="string>"characters"</span><span class="punctuation">:</span> Is there a good existing Python tool to do this? A: I could implement something like this pretty quickly in Nevow. Obviously, access would need to be pretty restricted since doing something like this involves allowing access to a Python console to someone via HTTP. What I'd do is create an Athena widget for the console, that used an instance of a custom subclass of code.InteractiveInterpreter that is common to all users logged in. UPDATE: Okay, so you have something chat-like in GAE. If you just submit lines to a code.InteractiveInterpreter subclass that looks like this, it should work for you. Note that the interface is pretty similar to the InteractiveSession class you describe: class SharedConsole(code.InteractiveInterpreter): def __init__(self): self.users = [] def write(self, data): # broadcast output to connected clients here for user in self.users: user.addOutput(data) class ConnectedUser(object): def __init__(self, sharedConsole): self.sharedConsole = sharedConsole sharedConsole.users.append(self) # reference look, should use weak refs def addOutput(self, data): pass # do GAE magic to send data to connected client # this is a hook for submitted code lines; call it from GAE when a user submits code def gotCommand(self, command): needsMore = self.sharedConsole.runsource(command) if needsMore: pass # tell the client to change the command line to a textarea # or otherwise add more lines of code to complete the statement A: The closest Python interpreter I know of to what you are looking for, in terms of interface, is DreamPie. It has separate input and output areas, much like a chat interface. Also, DreamPie runs all of the code in a subprocess. DreamPie also does completion and syntax coloring, much like IDLE, which means it doesn't just pipe input and output to/from the subprocess -- it has implemented the abstractions which you are looking for. If you wish to develop a desktop application (not a web-app), I recommend basing your work on DreamPie and just adding the multiple-frontend functionality. Update: For syntax highlighting (including HTML) see the Pygments project. But that is a completely different question; please ask one question at a time here. A: As a proof of concept, you may be able to put something together using sockets and a command-line session.
Python: Networked IDLE/Redo IDLE front-end while using the same back-end?
Is there any existing web app that lets multiple users work with an interactive IDLE type session at once? Something like: IDLE 2.6.4 Morgan: >>> letters = list("abcdefg") Morgan: >>> # now, how would you iterate over letters? Jack: >>> for char in letters: print "char %s" % char char a char b char c char d char e char f char g Morgan: >>> # nice nice If not, I would like to create one. Is there some module I can use that simulates an interactive session? I'd want an interface like this: def class InteractiveSession(): ''' An interactive Python session ''' def putLine(line): ''' Evaluates line ''' pass def outputLines(): ''' A list of all lines that have been output by the session ''' pass def currentVars(): ''' A dictionary of currently defined variables and their values ''' pass (Although that last function would be more of an extra feature.) To formulate my problem another way: I'd like to create a new front end for IDLE. How can I do this? UPDATE: Or maybe I can simulate IDLE through eval()? UPDATE 2: What if I did something like this: I already have a simple GAE Python chat app set up, that allows users to sign in, make chat rooms, and chat with each other. Instead of just saving incoming messages to the datastore, I could do something like this: def putLine(line, user, chat_room): ''' Evaluates line for the session used by chat_room ''' # get the interactive session for this chat room curr_vars = InteractiveSession.objects.where("chatRoom = %s" % chat_room).get() result = eval(prepared_line, curr_vars.state, {}) curr_vars.state = curr_globals curr_vars.lines.append((user, line)) if result: curr_vars.lines.append(('SELF', result.__str__())) curr_vars.put() The InteractiveSession model: def class InteractiveSession(db.Model): # a dictionary mapping variables to values # it looks like GAE doesn't actually have a dictionary field, so what would be best to use here? state = db.DictionaryProperty() # a transcript of the session # # a list of tuples of the form (user, line_entered) # # looks something like: # # [('Morgan', '# hello'), # ('Jack', 'x = []'), # ('Morgan', 'x.append(1)'), # ('Jack', 'x'), # ('SELF', '[1]')] lines = db.ListProperty() Could this work, or am I way off/this approach is infeasible/I'm duplicating work when I should use something already built? UPDATE 3: Also, assuming I get everything else working, I'd like syntax highlighting. Ideally, I'd have some API or service I could use that would parse the code and style it appropriately. for c in "characters": would become: <span class="keyword">for</span> <span class="var">c</span> <span class="keyword">in</span> <span class="string>"characters"</span><span class="punctuation">:</span> Is there a good existing Python tool to do this?
[ "I could implement something like this pretty quickly in Nevow. Obviously, access would need to be pretty restricted since doing something like this involves allowing access to a Python console to someone via HTTP.\nWhat I'd do is create an Athena widget for the console, that used an instance of a custom subclass of code.InteractiveInterpreter that is common to all users logged in.\nUPDATE: Okay, so you have something chat-like in GAE. If you just submit lines to a code.InteractiveInterpreter subclass that looks like this, it should work for you. Note that the interface is pretty similar to the InteractiveSession class you describe:\nclass SharedConsole(code.InteractiveInterpreter):\n def __init__(self):\n self.users = []\n\n def write(self, data):\n # broadcast output to connected clients here\n for user in self.users:\n user.addOutput(data)\n\nclass ConnectedUser(object):\n def __init__(self, sharedConsole):\n self.sharedConsole = sharedConsole\n sharedConsole.users.append(self) # reference look, should use weak refs\n\n def addOutput(self, data):\n pass # do GAE magic to send data to connected client\n\n # this is a hook for submitted code lines; call it from GAE when a user submits code\n def gotCommand(self, command):\n needsMore = self.sharedConsole.runsource(command)\n if needsMore:\n pass # tell the client to change the command line to a textarea\n # or otherwise add more lines of code to complete the statement\n\n", "The closest Python interpreter I know of to what you are looking for, in terms of interface, is DreamPie. It has separate input and output areas, much like a chat interface. Also, DreamPie runs all of the code in a subprocess. DreamPie also does completion and syntax coloring, much like IDLE, which means it doesn't just pipe input and output to/from the subprocess -- it has implemented the abstractions which you are looking for.\nIf you wish to develop a desktop application (not a web-app), I recommend basing your work on DreamPie and just adding the multiple-frontend functionality.\nUpdate: For syntax highlighting (including HTML) see the Pygments project. But that is a completely different question; please ask one question at a time here.\n", "As a proof of concept, you may be able to put something together using sockets and a command-line session.\n" ]
[ 1, 1, 0 ]
[ "this is likely possible with the upcoming implimentation of IPython using a 0MQ backend.\n", "I would use ipython and screen. With this method, you would have to create a shared login, but you could both connect to the shared screen session. One downside would be that you would both appear as the same user.\n" ]
[ -1, -1 ]
[ "python", "python_idle", "user_interface" ]
stackoverflow_0002893401_python_python_idle_user_interface.txt
Q: Where to store a datastore cursor, in memcache or in the datastore? In the google documentation it shows storing cursors in memcache, however as pointed out in an answer to this question memcache retention isn't guaranteed. So I was wondering how other people store cursors and what strategies you use for handling missing cursors? A: In the case of task queue chaining, as in the linked question, it may be best to just send the cursor in the payload for the next task (which is also mentioned in the documentation.) Memcache is fine if occasionally losing your place and starting over is acceptable. In theory if you're storing a small bit of data in memcache and using it soon afterwards it's unlikely to be evicted, although of course you should do some testing to see that you get an acceptably low rate of cache misses and watch out for situations where the memcache service being unavailable will do something really bad. A: The short answer is both. Write the value to the datastore. When a read request comes in, check to see if it exists in memcache. If so, return it. If not, read it into memcache from the datastore first. This gives you the guaranteed durability of the datastore and the speed of memcache. A: Of course memcache doesn`t guarantee that you will have your cursor when you call it so using datastore is better. But you must know that you have to "reset" them if you add/delete/modify entities from their kind. You must have in mind how slow this will be with memcache and datastore.
Where to store a datastore cursor, in memcache or in the datastore?
In the google documentation it shows storing cursors in memcache, however as pointed out in an answer to this question memcache retention isn't guaranteed. So I was wondering how other people store cursors and what strategies you use for handling missing cursors?
[ "In the case of task queue chaining, as in the linked question, it may be best to just send the cursor in the payload for the next task (which is also mentioned in the documentation.) Memcache is fine if occasionally losing your place and starting over is acceptable. In theory if you're storing a small bit of data in memcache and using it soon afterwards it's unlikely to be evicted, although of course you should do some testing to see that you get an acceptably low rate of cache misses and watch out for situations where the memcache service being unavailable will do something really bad.\n", "The short answer is both. Write the value to the datastore. When a read request comes in, check to see if it exists in memcache. If so, return it. If not, read it into memcache from the datastore first. This gives you the guaranteed durability of the datastore and the speed of memcache.\n", "Of course memcache doesn`t guarantee that you will have your cursor when you call it so using datastore is better. But you must know that you have to \"reset\" them if you add/delete/modify entities from their kind. You must have in mind how slow this will be with memcache and datastore.\n" ]
[ 3, 2, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002948728_google_app_engine_python.txt
Q: how to get selected item in pyqt Qmenu is there any way to get the selected item in a qmenu ? i want to bind all items in that list to one function and get the item once user click it . i've been looking for a way to get the item's label or index for 3 days , but couldn't find it . any ideas ? thanks in advance A: You can achieve this with signals. Connect all triggered slots of your menu items to your function. Then, in this function, use the static function QObject::sender to retrieve the menu item which has sent the signal.
how to get selected item in pyqt Qmenu
is there any way to get the selected item in a qmenu ? i want to bind all items in that list to one function and get the item once user click it . i've been looking for a way to get the item's label or index for 3 days , but couldn't find it . any ideas ? thanks in advance
[ "You can achieve this with signals.\nConnect all triggered slots of your menu items to your function. Then, in this function, use the static function QObject::sender to retrieve the menu item which has sent the signal.\n" ]
[ 3 ]
[]
[]
[ "pyqt", "pyqt4", "python", "qt", "qt4" ]
stackoverflow_0002948411_pyqt_pyqt4_python_qt_qt4.txt
Q: How to exit a program: sys.stderr.write() or print I am writing a small app and I need to quit the program multiple number of times. Should I use: sys.stderr.write('Ok quitting')sys.exit(1) Or should I just do a: print 'Error!'sys.exit(1) Which is better and why? Note that I need to do this a lot. The program should completely quit. A: sys.exit('Error!') Note from the docs: If another type of object is passed, None is equivalent to passing zero, and any other object is printed to sys.stderr and results in an exit code of 1. In particular, sys.exit("some error message") is a quick way to exit a program when an error occurs. A: They're two different ways of showing messages. print generally goes to sys.stdout and you know where sys.stderr is going. It's worth knowing the difference between stdin, stdout, and stderr. stdout should be used for normal program output, whereas stderr should be reserved only for error messages (abnormal program execution). There are utilities for splitting these streams, which allows users of your code to differentiate between normal output and errors. print can print on any file-like object, including sys.stderr: print >> sys.stderr, 'My error message' The advantages of using sys.stderr for errors instead of sys.stdout are: If the user redirected stdout to a file, they still see errors on the screen. It's unbuffered, so if sys.stderr is redirected to a log file there is less chance that the program will crash before the error was logged. It's worth noting that there's a third way you can provide a closing message: sys.exit('My error message') This will send a message to stderr and exit. A: If it's an error message, it should normally go to stderr - but whether this is necessary depends on your use case. If you expect users to redirect stdin, stderr and stdout, for example when running your program from a different tool, then you should make sure that status information and error messages are separated cleanly. If it's just you using the program, you probably don't need to bother. In that case, you might as well just raise an exception, and the program will terminate on its own. By the way, you can do print >>sys.stderr, "fatal error" # Python 2.x print("fatal error", file=sys.stderr) # Python 3.x
How to exit a program: sys.stderr.write() or print
I am writing a small app and I need to quit the program multiple number of times. Should I use: sys.stderr.write('Ok quitting')sys.exit(1) Or should I just do a: print 'Error!'sys.exit(1) Which is better and why? Note that I need to do this a lot. The program should completely quit.
[ "sys.exit('Error!')\n\nNote from the docs:\n\nIf another type of object is passed,\n None is equivalent to passing zero,\n and any other object is printed to\n sys.stderr and results in an exit code\n of 1. In particular, sys.exit(\"some\n error message\") is a quick way to exit\n a program when an error occurs.\n\n", "They're two different ways of showing messages.\nprint generally goes to sys.stdout and you know where sys.stderr is going. It's worth knowing the difference between stdin, stdout, and stderr.\nstdout should be used for normal program output, whereas stderr should be reserved only for error messages (abnormal program execution). There are utilities for splitting these streams, which allows users of your code to differentiate between normal output and errors.\nprint can print on any file-like object, including sys.stderr:\nprint >> sys.stderr, 'My error message'\n\nThe advantages of using sys.stderr for errors instead of sys.stdout are:\n\nIf the user redirected stdout to a file, they still see errors on the screen.\nIt's unbuffered, so if sys.stderr is redirected to a log file there is less chance that the program will crash before the error was logged.\n\nIt's worth noting that there's a third way you can provide a closing message:\nsys.exit('My error message')\n\nThis will send a message to stderr and exit.\n", "If it's an error message, it should normally go to stderr - but whether this is necessary depends on your use case. If you expect users to redirect stdin, stderr and stdout, for example when running your program from a different tool, then you should make sure that status information and error messages are separated cleanly.\nIf it's just you using the program, you probably don't need to bother. In that case, you might as well just raise an exception, and the program will terminate on its own.\nBy the way, you can do\nprint >>sys.stderr, \"fatal error\" # Python 2.x\nprint(\"fatal error\", file=sys.stderr) # Python 3.x\n\n" ]
[ 124, 17, 10 ]
[]
[]
[ "error_handling", "python" ]
stackoverflow_0002949974_error_handling_python.txt
Q: Update a gallery webpage via Dropbox? I'd like to know if the following situation and scripts are at all possible: I'm looking to have a photo-gallery (Javascript) webpage that will display in order of the latest added to the Dropbox folder (PHP or Python?). That is, when someone adds a picture to the Dropbox folder, there is a script on the webpage that will check the Dropbox folder and then embed those images onto the webpage via the newest added and the webpage will automatically be updated. Is it at all possible to link to a Dropbox folder via a webpage? If so, how would I best go about using scripts to automate the process of updating the webpage with new content? Any and all help is very appreciated, thanks! A: If you can install the DropBox client on the webserver then it would be simple to let it sync your folder and then iterate over the contents of the folder with a programming language (PHP, Python, .NET etc) and produce the gallery page. This could be done every time the page is requested or as a scheduled job which recreayes a static page. This is all dependent on you having access to install the client on your server. A: You can try this : http://forums.dropbox.com/topic.php?id=15885 A: You can use the (alpha) tool autodrop, wich is just that: a simple gallery frontend that uses images in Dropbox. As said: alpha. I am still developing it, rewriting it and making it a little prettier and nicer. Written in Ruby, using dropbox, sinatra and HAML gems. So you will need a host that supports Ruby apps.
Update a gallery webpage via Dropbox?
I'd like to know if the following situation and scripts are at all possible: I'm looking to have a photo-gallery (Javascript) webpage that will display in order of the latest added to the Dropbox folder (PHP or Python?). That is, when someone adds a picture to the Dropbox folder, there is a script on the webpage that will check the Dropbox folder and then embed those images onto the webpage via the newest added and the webpage will automatically be updated. Is it at all possible to link to a Dropbox folder via a webpage? If so, how would I best go about using scripts to automate the process of updating the webpage with new content? Any and all help is very appreciated, thanks!
[ "If you can install the DropBox client on the webserver then it would be simple to let it sync your folder and then iterate over the contents of the folder with a programming language (PHP, Python, .NET etc) and produce the gallery page. This could be done every time the page is requested or as a scheduled job which recreayes a static page. This is all dependent on you having access to install the client on your server.\n", "You can try this : http://forums.dropbox.com/topic.php?id=15885\n", "You can use the (alpha) tool autodrop, wich is just that: a simple gallery frontend that uses images in Dropbox.\nAs said: alpha. I am still developing it, rewriting it and making it a little prettier and nicer. \nWritten in Ruby, using dropbox, sinatra and HAML gems. So you will need a host that supports Ruby apps. \n" ]
[ 2, 1, 0 ]
[]
[]
[ "dropbox", "html", "php", "python" ]
stackoverflow_0001522951_dropbox_html_php_python.txt
Q: strange(?) module import syntax I've come across the following code in a Python script from pprint import pprint why not simply import pprint? Unless the module pprint contains a function called pprint which is being aliased as pprint (surely, this must be the definition of madness?) A: It does contain a function pprint, and that is exactly what's going on. I much prefer typing pprint, not pprint.pprint, or decimal.Decimal, or datetime.datetime.now() - wouldn't you? A: Yes, the syntax is from module import functions, so the first pprint is the module name and the second the function name. A: Your belief is correct, but it is not "aliased" in any way. It is simply named pprint, which is no violation of any Python style guide.
strange(?) module import syntax
I've come across the following code in a Python script from pprint import pprint why not simply import pprint? Unless the module pprint contains a function called pprint which is being aliased as pprint (surely, this must be the definition of madness?)
[ "It does contain a function pprint, and that is exactly what's going on. I much prefer typing pprint, not pprint.pprint, or decimal.Decimal, or datetime.datetime.now() - wouldn't you?\n", "Yes, the syntax is from module import functions, so the first pprint is the module name and the second the function name.\n", "Your belief is correct, but it is not \"aliased\" in any way. It is simply named pprint, which is no violation of any Python style guide.\n" ]
[ 3, 1, 0 ]
[]
[]
[ "import", "python" ]
stackoverflow_0002950275_import_python.txt
Q: Django - Expression based model constraints Is it possible to set an expression based constraint on a django model object, e.g. If I want to impose a constraint where an owner can have only one widget of a given type that is not in an expired state, but can have as many others as long as they are expired. Obviously I can do this by overriding the save method, but I am wondering if it can be done by setting constraints, e.g. some derivative of the unique_together constraint WIDGET_STATE_CHOICES = ( ('NEW', 'NEW'), ('ACTIVE', 'ACTIVE'), ('EXPIRED', 'EXPIRED') ) class MyWidget(models.Model): owner = models.CharField(max_length=64) widget_type = models.CharField(max_length = 10) widget_state = models.CharField(max_length = 10, choices = WIDGET_STATE_CHOICES) #I'd like to be able to do something like class Meta: unique_together = (("owner","widget_type","widget_state" != 'EXPIRED') A: This sounds like a job for the new model validation support in Django 1.2. A: No, I don't think this will fly. The model's expecting a tuple of tuples and then the modelform base that checks it seems to grab and compare values, not run expressions. Still, you can do it in save(), as you say - or using model validation, as DR points out A: This is what model-based form validation is all about. Define a form with a clean method that implements these additional rules. Always use the form's save method to create new model objects that pass the validation rules. http://docs.djangoproject.com/en/1.2/ref/forms/validation/#ref-forms-validation http://docs.djangoproject.com/en/1.2/topics/forms/modelforms/#the-save-method
Django - Expression based model constraints
Is it possible to set an expression based constraint on a django model object, e.g. If I want to impose a constraint where an owner can have only one widget of a given type that is not in an expired state, but can have as many others as long as they are expired. Obviously I can do this by overriding the save method, but I am wondering if it can be done by setting constraints, e.g. some derivative of the unique_together constraint WIDGET_STATE_CHOICES = ( ('NEW', 'NEW'), ('ACTIVE', 'ACTIVE'), ('EXPIRED', 'EXPIRED') ) class MyWidget(models.Model): owner = models.CharField(max_length=64) widget_type = models.CharField(max_length = 10) widget_state = models.CharField(max_length = 10, choices = WIDGET_STATE_CHOICES) #I'd like to be able to do something like class Meta: unique_together = (("owner","widget_type","widget_state" != 'EXPIRED')
[ "This sounds like a job for the new model validation support in Django 1.2. \n", "No, I don't think this will fly. The model's expecting a tuple of tuples and then the modelform base that checks it seems to grab and compare values, not run expressions.\nStill, you can do it in save(), as you say - or using model validation, as DR points out \n", "This is what model-based form validation is all about.\nDefine a form with a clean method that implements these additional rules.\nAlways use the form's save method to create new model objects that pass the validation rules.\nhttp://docs.djangoproject.com/en/1.2/ref/forms/validation/#ref-forms-validation\nhttp://docs.djangoproject.com/en/1.2/topics/forms/modelforms/#the-save-method\n" ]
[ 2, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002948813_django_python.txt
Q: App Engine Transaction Entity group problem I have an issue with creating a transaction. I get an error back that the objects are not in the same entity group. I have a type called Relationship and I need to create a two way relationship between two parties. def _transaction(): relationship1 = Relationship(firstParty = party1, secondParty = party2) relationship2 = Relationship(firstParty = party2, secondParty = party1) db.put([relationship1 , relationship2 ]) db.run_in_transaction(_transaction) Both of the party objects are the same type. The business rule dictates both records need to be persisted or it needs to fail. The error comes from the party objects. the properties firstParty and secondParty are Reference Properties. How can i perform a transaction on this business rule? A: You need to understand entity groups before you can effectively work with transactions in app engine. Start here. In short, only entities (what you call records) in the same entity group can be involved in a transaction. By default, entities are created in their own group, so you will not be able to perform a transaction on them.
App Engine Transaction Entity group problem
I have an issue with creating a transaction. I get an error back that the objects are not in the same entity group. I have a type called Relationship and I need to create a two way relationship between two parties. def _transaction(): relationship1 = Relationship(firstParty = party1, secondParty = party2) relationship2 = Relationship(firstParty = party2, secondParty = party1) db.put([relationship1 , relationship2 ]) db.run_in_transaction(_transaction) Both of the party objects are the same type. The business rule dictates both records need to be persisted or it needs to fail. The error comes from the party objects. the properties firstParty and secondParty are Reference Properties. How can i perform a transaction on this business rule?
[ "You need to understand entity groups before you can effectively work with transactions in app engine. Start here. In short, only entities (what you call records) in the same entity group can be involved in a transaction. By default, entities are created in their own group, so you will not be able to perform a transaction on them.\n" ]
[ 3 ]
[]
[]
[ "google_app_engine", "python", "transactions" ]
stackoverflow_0002950360_google_app_engine_python_transactions.txt
Q: Several modules in a package importing one common module I am writing a python package. I am using the concept of plugins - where each plugin is a specialization of a Worker class. Each plugin is written as a module (script?) and spawned in a separate process. Because of the base commonality between the plugins (e.g. all extend a base class 'Worker'), The plugin module generally looks like this: import commonfuncs def do_work(data): # do customised work for the plugin print 'child1 does work with %s' % data In C/C++, we have include guards, which prevent a header from being included more than once. Do I need something like that in Python, and if yes, how may I make sure that commonfuncs is not 'included' more than once? A: No worry: only the first import of a module in the course of a program's execution causes it to be loaded. Every further import after that first one just fetches the module object from a "cache" dictionary (sys.modules, indexed by module name strings) and therefore it's both very fast and bereft of side effects. Therefore, no guard is necessary.
Several modules in a package importing one common module
I am writing a python package. I am using the concept of plugins - where each plugin is a specialization of a Worker class. Each plugin is written as a module (script?) and spawned in a separate process. Because of the base commonality between the plugins (e.g. all extend a base class 'Worker'), The plugin module generally looks like this: import commonfuncs def do_work(data): # do customised work for the plugin print 'child1 does work with %s' % data In C/C++, we have include guards, which prevent a header from being included more than once. Do I need something like that in Python, and if yes, how may I make sure that commonfuncs is not 'included' more than once?
[ "No worry: only the first import of a module in the course of a program's execution causes it to be loaded. Every further import after that first one just fetches the module object from a \"cache\" dictionary (sys.modules, indexed by module name strings) and therefore it's both very fast and bereft of side effects. Therefore, no guard is necessary.\n" ]
[ 26 ]
[]
[]
[ "python" ]
stackoverflow_0002950557_python.txt
Q: Realtime processing and callbacks with Python and C++ I need to write code to do some realtime processing that is fairly computationally complex. I would like to create some Python classes to manage all my scripting, and leave the intensive parts of the algorithm coded in C++ so that they can run as fast as possible. I would like to instantiate the objects in Python, and have the C++ algorithms chime back into the script with callbacks in python. Something like: myObject = MyObject() myObject.setCallback(myCallback) myObject.run() def myCallback(val): """Do something with the value passed back to the python script.""" pass Will this be possible? How can I run a callback in python from a loop that is running in a C++ module? Anyone have a link or a tutorial to help me do this correctly? A: Have a look at Boost.Python. Its tutorial starts here. A: I suggest using Boost.Python as suggested by ChristopheD. A gotcha would be if the C++ extension is running in it's own thread context (not created by Python). If that's the case, make sure to use the PyGILState_Ensure() and PyGILState_Release() functions when calling into Python code from C++. From the docs (http://docs.python.org/c-api/init.html#thread-state-and-the-global-interpreter-lock): Beginning with version 2.3, threads can now take advantage of the PyGILState_*() functions to do all of the above automatically. The typical idiom for calling into Python from a C thread is now: PyGILState_STATE gstate; gstate = PyGILState_Ensure(); /* Perform Python actions here. */ result = CallSomeFunction(); /* evaluate result */ /* Release the thread. No Python API allowed beyond this point. */ PyGILState_Release(gstate) I recommend making the callbacks short & sweet - to limit the need to perform exception handling in C++ code. If you're using wxPython, you could use it's robust async event system. Or the callbacks could put events on a Queue and you could have a thread devoted to asynchronously executing callback/event code. Even with Boost.Python magic, you'll have to get familiar with this portion of the Python C API when dealing with threads. (Don't forget to wrap the C++ functions with Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS to release the GIL!) A: Here is an example of how to do python callbacks using Cython. It might be worth looking at Pyrex as well. Both can make integrating C/C++ with Python rather easy. A: We do what you are doing a lot at work. We like python but it's just not fast enough sometimes. Boost and Swig are both good for doing that. You should also check out this link on Python Performance they talk a little about NumPy which may help you.
Realtime processing and callbacks with Python and C++
I need to write code to do some realtime processing that is fairly computationally complex. I would like to create some Python classes to manage all my scripting, and leave the intensive parts of the algorithm coded in C++ so that they can run as fast as possible. I would like to instantiate the objects in Python, and have the C++ algorithms chime back into the script with callbacks in python. Something like: myObject = MyObject() myObject.setCallback(myCallback) myObject.run() def myCallback(val): """Do something with the value passed back to the python script.""" pass Will this be possible? How can I run a callback in python from a loop that is running in a C++ module? Anyone have a link or a tutorial to help me do this correctly?
[ "Have a look at Boost.Python. Its tutorial starts here.\n", "I suggest using Boost.Python as suggested by ChristopheD. A gotcha would be if the C++ extension is running in it's own thread context (not created by Python). If that's the case, make sure to use the PyGILState_Ensure() and PyGILState_Release() functions when calling into Python code from C++.\nFrom the docs (http://docs.python.org/c-api/init.html#thread-state-and-the-global-interpreter-lock):\n\nBeginning with version 2.3, threads\n can now take advantage of the\n PyGILState_*() functions to do all of\n the above automatically. The typical\n idiom for calling into Python from a C\n thread is now:\nPyGILState_STATE gstate;\ngstate = PyGILState_Ensure();\n\n/* Perform Python actions here. */\nresult = CallSomeFunction();\n/* evaluate result */\n\n/* Release the thread. No Python API allowed beyond this point. */\nPyGILState_Release(gstate)\n\n\nI recommend making the callbacks short & sweet - to limit the need to perform exception handling in C++ code. If you're using wxPython, you could use it's robust async event system. Or the callbacks could put events on a Queue and you could have a thread devoted to asynchronously executing callback/event code.\nEven with Boost.Python magic, you'll have to get familiar with this portion of the Python C API when dealing with threads. (Don't forget to wrap the C++ functions with Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS to release the GIL!)\n", "Here is an example of how to do python callbacks using Cython. It might be worth looking at Pyrex as well. Both can make integrating C/C++ with Python rather easy.\n", "We do what you are doing a lot at work. We like python but it's just not fast enough sometimes.\nBoost and Swig are both good for doing that. You should also check out this link on Python Performance they talk a little about NumPy which may help you.\n" ]
[ 4, 3, 0, 0 ]
[]
[]
[ "c++", "callback", "python", "real_time" ]
stackoverflow_0002946226_c++_callback_python_real_time.txt
Q: Debugging (displaying) SQL command sent to the db by SQLAlchemy I have an ORM class called Person, which wraps around a person table: After setting up the connection to the db etc, I run the statement: people = session.query(Person).all() The person table does not contain any data (as yet), so when I print the variable people, I get an empty list. I renamed the table referred to in my ORM class People, to people_foo (which does not exist). I then run the script again. I was surprised that no exception was thrown when attempting to access a table that does not exist. I therefore have the following 2 questions: How may I setup SQLAlchemy so that it propagates db errors back to the script? How may I view (i.e. print) the SQL that is being sent to the db engine? If it helps, I am using PostgreSQL. [Edit] I am writing a package. In my __main__.py script, I have the following code (shortened here): ### __main__.py import common # imports logging and defines logging setup funcs etc logger = logging.getLogger(__name__) def main(): parser = OptionParser(usage="%prog [options] <commands>", version="%prog 1.0") commands = OptionGroup(parser, "commands") parser.add_option( "-l", "--logfile", dest="logfile", metavar="FILE", help="log to FILE. if not set, no logging will be done" ) parser.add_option( "--level", dest="loglevel", metavar="LOG LEVEL", help="Debug level. if not set, level will default to low" ) # Set defaults if not specified if not options.loglevel: loglevel = 1 else: loglevel = options.loglevel if not options.logfile: logfilename = 'datafeed.log' else: logfilename = options.logfile common.setup_logger(False, logfilename, loglevel) # and so on ... #### dbfuncs.py import logging # not sure how to 'bind' to the logger in __main__.py logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO) engine = create_engine('postgres://postgres:pwd@localhost:port/dbname', echo=True) [Edit2] Common module sets the logger up correctly, and I can use the logger in my other modules that import common. However in dbfuncs module, I am getting the following error/warning: No handlers could be found for logger "sqlalchemy.engine.base.Engine A: In addition to echo parameter of create_engine() there is a more flexible way: configuring logging to echo engine statements: import logging logging.basicConfig() logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO) See Configuring Logging section of documentation for more information. A: You can see the SQL statements being sent to the DB by passing echo=True when the engine instance is created (usually using the create_engine() or engine_from_config() call in your code). For example: engine = sqlalchemy.create_engine('postgres://foo/bar', echo=True) By default, logged statements go to stdout.
Debugging (displaying) SQL command sent to the db by SQLAlchemy
I have an ORM class called Person, which wraps around a person table: After setting up the connection to the db etc, I run the statement: people = session.query(Person).all() The person table does not contain any data (as yet), so when I print the variable people, I get an empty list. I renamed the table referred to in my ORM class People, to people_foo (which does not exist). I then run the script again. I was surprised that no exception was thrown when attempting to access a table that does not exist. I therefore have the following 2 questions: How may I setup SQLAlchemy so that it propagates db errors back to the script? How may I view (i.e. print) the SQL that is being sent to the db engine? If it helps, I am using PostgreSQL. [Edit] I am writing a package. In my __main__.py script, I have the following code (shortened here): ### __main__.py import common # imports logging and defines logging setup funcs etc logger = logging.getLogger(__name__) def main(): parser = OptionParser(usage="%prog [options] <commands>", version="%prog 1.0") commands = OptionGroup(parser, "commands") parser.add_option( "-l", "--logfile", dest="logfile", metavar="FILE", help="log to FILE. if not set, no logging will be done" ) parser.add_option( "--level", dest="loglevel", metavar="LOG LEVEL", help="Debug level. if not set, level will default to low" ) # Set defaults if not specified if not options.loglevel: loglevel = 1 else: loglevel = options.loglevel if not options.logfile: logfilename = 'datafeed.log' else: logfilename = options.logfile common.setup_logger(False, logfilename, loglevel) # and so on ... #### dbfuncs.py import logging # not sure how to 'bind' to the logger in __main__.py logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO) engine = create_engine('postgres://postgres:pwd@localhost:port/dbname', echo=True) [Edit2] Common module sets the logger up correctly, and I can use the logger in my other modules that import common. However in dbfuncs module, I am getting the following error/warning: No handlers could be found for logger "sqlalchemy.engine.base.Engine
[ "In addition to echo parameter of create_engine() there is a more flexible way: configuring logging to echo engine statements:\nimport logging\nlogging.basicConfig()\nlogging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)\n\nSee Configuring Logging section of documentation for more information.\n", "You can see the SQL statements being sent to the DB by passing echo=True when the engine instance is created (usually using the create_engine() or engine_from_config() call in your code).\nFor example:\nengine = sqlalchemy.create_engine('postgres://foo/bar', echo=True)\n\nBy default, logged statements go to stdout.\n" ]
[ 272, 119 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0002950385_python_sqlalchemy.txt
Q: python,running command line servers - they're not listening properly Im attempting to start a server app (in erlang, opens ports and listens for http requests) via the command line using pexpect (or even directly using subprocess.Popen()). the app starts fine, logs (via pexpect) to the screen fine, I can interact with it as well via command line... the issue is that the servers wont listen for incoming requests. The app listens when I start it up manually, by typing commands in the command line. using subprocess/pexpect stops the app from listening somehow... when I start it manually "netstat -tlp" displays the app as listening, when I start it via python (subprocess/pexpect) netstat does not register the app... I have a feeling it has something to do with the environemnt, the way python forks things, etc. Any ideas? thank you basic example: note: "-pz" - just ads ./ebin to the modules path for the erl VM, library search path "-run" - runs moduleName, without any parameters. command_str = "erl -pz ./ebin -run moduleName" child = pexpect.spawn(command_str) child.interact() # Give control of the child to the user all of this stuff works correctly, which is strange. I have logging inside my code and all the log messages output as they should. the server wouldnt listen even if I started up its process via a bash script, so I dont think its the python code thats causing it (thats why I have a feeling that its something regarding the way the new OS process is started). A: It could be to do with the way that command line arguments are passed to the subprocess. Without more specific code, I can't say for sure, but I had this problem working on sshsplit ( https://launchpad.net/sshsplit ) To pass arguments correctly (in this example "ssh -ND 3000"), you should use something like this: openargs = ["ssh", "-ND", "3000"] print "Launching %s" %(" ".join(openargs)) p = subprocess.Popen(openargs, stdout=subprocess.PIPE, stderr=subprocess.PIPE) This will not only allow you to see exactly what command you are launching, but should correctly pass the values to the executable. Although I can't say for sure without seeing some code, this seems the most likely cause of failure (could it also be that the program requires a specific working directory, or configuration file?).
python,running command line servers - they're not listening properly
Im attempting to start a server app (in erlang, opens ports and listens for http requests) via the command line using pexpect (or even directly using subprocess.Popen()). the app starts fine, logs (via pexpect) to the screen fine, I can interact with it as well via command line... the issue is that the servers wont listen for incoming requests. The app listens when I start it up manually, by typing commands in the command line. using subprocess/pexpect stops the app from listening somehow... when I start it manually "netstat -tlp" displays the app as listening, when I start it via python (subprocess/pexpect) netstat does not register the app... I have a feeling it has something to do with the environemnt, the way python forks things, etc. Any ideas? thank you basic example: note: "-pz" - just ads ./ebin to the modules path for the erl VM, library search path "-run" - runs moduleName, without any parameters. command_str = "erl -pz ./ebin -run moduleName" child = pexpect.spawn(command_str) child.interact() # Give control of the child to the user all of this stuff works correctly, which is strange. I have logging inside my code and all the log messages output as they should. the server wouldnt listen even if I started up its process via a bash script, so I dont think its the python code thats causing it (thats why I have a feeling that its something regarding the way the new OS process is started).
[ "It could be to do with the way that command line arguments are passed to the subprocess.\nWithout more specific code, I can't say for sure, but I had this problem working on sshsplit ( https://launchpad.net/sshsplit )\nTo pass arguments correctly (in this example \"ssh -ND 3000\"), you should use something like this:\nopenargs = [\"ssh\", \"-ND\", \"3000\"]\nprint \"Launching %s\" %(\" \".join(openargs))\np = subprocess.Popen(openargs, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\nThis will not only allow you to see exactly what command you are launching, but should correctly pass the values to the executable. Although I can't say for sure without seeing some code, this seems the most likely cause of failure (could it also be that the program requires a specific working directory, or configuration file?).\n" ]
[ 0 ]
[]
[]
[ "command_line", "pexpect", "python" ]
stackoverflow_0002947724_command_line_pexpect_python.txt