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: Basic Python While loop compound conditional evaluation In Python IDLE Shell it seems I cannot use a compound conditional expression and a while loop. I tried it within brackets too. Take these two examples: k=0 m=0 while k<10 & m<10: print k k +=1 m+=1 This doesn't evaluate the second condition. But if I write while k<10: print k k+=1 This does work. Is there a way I could achieve the first block of code with the "and" operator. I have done it in Java. Do I just need to put together "if" statements to achieve the same functionality in Python? A: & should be and. & is the bitwise AND operator.
Basic Python While loop compound conditional evaluation
In Python IDLE Shell it seems I cannot use a compound conditional expression and a while loop. I tried it within brackets too. Take these two examples: k=0 m=0 while k<10 & m<10: print k k +=1 m+=1 This doesn't evaluate the second condition. But if I write while k<10: print k k+=1 This does work. Is there a way I could achieve the first block of code with the "and" operator. I have done it in Java. Do I just need to put together "if" statements to achieve the same functionality in Python?
[ "& should be and. & is the bitwise AND operator.\n" ]
[ 7 ]
[]
[]
[ "conditional_operator", "python", "while_loop" ]
stackoverflow_0003006521_conditional_operator_python_while_loop.txt
Q: Python SUDS - problem with sending a message encoded not in UTF-8 I need to send a SOAP message (with Python SUDS) with strings encoded in 'iso-8859-2'. Does anybody know how to do it? SUDS raises the following exception when I invoke a method on a client with parameters encoded in 'iso-8859-2': File "/home/bartek/myenv/lib/python2.5/site-packages/suds/sax/text.py", line 43, in __new__ result = super(Text, cls).__new__(cls, *args, **kwargs) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 10: ordinal not in range(128) A: Text = Text.decode('iso-8859-2') might be all you need, if Text starts out as an 8-bit string that was encoded with iso-8859-2. If it needs to be sent as a UTF-8 string or something, however, then you'd probably want to use Text = Text.decode('utf-8') If neither of those, then just play around with the decode() and encode() methods and the error handling methods used with them: http://docs.python.org/release/2.5/lib/string-methods.html (Took out most of the stuff in my answer that wasn't really necessary, considering what the question states.)
Python SUDS - problem with sending a message encoded not in UTF-8
I need to send a SOAP message (with Python SUDS) with strings encoded in 'iso-8859-2'. Does anybody know how to do it? SUDS raises the following exception when I invoke a method on a client with parameters encoded in 'iso-8859-2': File "/home/bartek/myenv/lib/python2.5/site-packages/suds/sax/text.py", line 43, in __new__ result = super(Text, cls).__new__(cls, *args, **kwargs) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 10: ordinal not in range(128)
[ "Text = Text.decode('iso-8859-2')\n\nmight be all you need, if Text starts out as an 8-bit string that was encoded with iso-8859-2. If it needs to be sent as a UTF-8 string or something, however, then you'd probably want to use\nText = Text.decode('utf-8')\n\nIf neither of those, then just play around with the decode() and encode() methods and the error handling methods used with them: http://docs.python.org/release/2.5/lib/string-methods.html\n(Took out most of the stuff in my answer that wasn't really necessary, considering what the question states.)\n" ]
[ 0 ]
[]
[]
[ "django", "python", "soap", "suds", "web_services" ]
stackoverflow_0003006669_django_python_soap_suds_web_services.txt
Q: problem with python script I want to run a csh file from a python script, example, #!/usr/bin/python import os os.system("source path/to/file.csh") and I want this file to run in the same shell as I am running the python script, because the file.csh script is settings some environment variables that I need. Does anyone know how to do this in Python? A: A child process cannot affect the environment of the parent process. The best you can do is to run your csh script in a separate process, get the environment variables that it defines, then set each environment variable in your python script. Even with that, the python script won't be able to affect the shell in which you run the python script. The common way to solve this (AFAIK) is to have your script emit shell commands to set the environment, then from the main shell you run the script and eval what you get back. For more information you might want to check out this question: can a shell script set environment variables of the calling shell A: You can kludge it this way: #!/usr/bin/env python # This is kludge.py print "setenv VARNAME \"the value\"" In your case, you can have the file.sh print the setenv line. Then from csh: $ eval `./kludge.py` $ echo $VARNAME the value This isn't clean, but it is the only way to have a child process effect the environment of its parent. This is only because the parent process is explicitly letting it happen with eval.
problem with python script
I want to run a csh file from a python script, example, #!/usr/bin/python import os os.system("source path/to/file.csh") and I want this file to run in the same shell as I am running the python script, because the file.csh script is settings some environment variables that I need. Does anyone know how to do this in Python?
[ "A child process cannot affect the environment of the parent process. The best you can do is to run your csh script in a separate process, get the environment variables that it defines, then set each environment variable in your python script.\nEven with that, the python script won't be able to affect the shell in which you run the python script.\nThe common way to solve this (AFAIK) is to have your script emit shell commands to set the environment, then from the main shell you run the script and eval what you get back.\nFor more information you might want to check out this question: can a shell script set environment variables of the calling shell\n", "You can kludge it this way:\n#!/usr/bin/env python\n# This is kludge.py\n\nprint \"setenv VARNAME \\\"the value\\\"\"\n\nIn your case, you can have the file.sh print the setenv line.\nThen from csh:\n$ eval `./kludge.py`\n$ echo $VARNAME \nthe value\n\nThis isn't clean, but it is the only way to have a child process effect the environment of its parent. This is only because the parent process is explicitly letting it happen with eval.\n" ]
[ 3, 0 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0003006481_python_subprocess.txt
Q: mutliprocessing.Pool.add_sync() eating up memory I want to use multithreading to make my script faster... I'm still new to this. The Python doc assumes you already understand threading and what-not. So... I have code that looks like this from itertools import izip from multiprocessing import Pool p = Pool() for i, j in izip(hugeseta, hugesetb): p.apply_async(number_crunching, (i, j)) Which gives me great speed! However, hugeseta and hugesetb are really huge. Pool keeps all of the i s and j s in memory after they've finished their job (basically, print output to stdout). Is there any to del i, and j after they complete? A: The del statement deletes object references, so can free up memory when the garbage collector runs. from itertools import izip from multiprocessing import Pool p = Pool() for i, j in izip(hugeseta, hugesetb): p.apply_async(number_crunching, (i, j)) del i, j A: Not really an answer but I used Pool.imap()instead: for i in p.imap(do, izip(Fastitr(seqsa, filetype='fastq'), \ Fastitr(seqsb, filetype='fastq'))): pass Which works beautifully and garbage collects as expected however it feels funny having a for loop with nothing but pass actually do something useful.
mutliprocessing.Pool.add_sync() eating up memory
I want to use multithreading to make my script faster... I'm still new to this. The Python doc assumes you already understand threading and what-not. So... I have code that looks like this from itertools import izip from multiprocessing import Pool p = Pool() for i, j in izip(hugeseta, hugesetb): p.apply_async(number_crunching, (i, j)) Which gives me great speed! However, hugeseta and hugesetb are really huge. Pool keeps all of the i s and j s in memory after they've finished their job (basically, print output to stdout). Is there any to del i, and j after they complete?
[ "The del statement deletes object references, so can free up memory when the garbage collector runs.\nfrom itertools import izip\nfrom multiprocessing import Pool\n\np = Pool()\nfor i, j in izip(hugeseta, hugesetb):\n p.apply_async(number_crunching, (i, j))\n\ndel i, j\n\n", "Not really an answer but I used Pool.imap()instead:\nfor i in p.imap(do, izip(Fastitr(seqsa, filetype='fastq'), \\\n Fastitr(seqsb, filetype='fastq'))):\n pass\n\nWhich works beautifully and garbage collects as expected however it feels funny having a for loop with nothing but pass actually do something useful.\n" ]
[ 0, 0 ]
[]
[]
[ "multiprocessing", "pool", "python" ]
stackoverflow_0003001389_multiprocessing_pool_python.txt
Q: how to speed up the code? in my program i have a method which requires about 4 files to be open each time it is called,as i require to take some data.all this data from the file i have been storing in list for manupalation. I approximatily need to call this method about 10,000 times.which is making my program very slow? any method for handling this files in a better ways and is storing the whole data in list time consuming what is better alternatives for list? I can give some code,but my previous question was closed as that only confused everyone as it is a part of big program and need to be explained completely to understand,so i am not giving any code,please suggest ways thinking this as a general question... thanks in advance A: As a general strategy, it's best to keep this data in an in-memory cache if it's static, and relatively small. Then, the 10k calls will read an in-memory cache rather than a file. Much faster. If you are modifying the data, the alternative might be a database like SQLite, or embedded MS SQL Server (and there are others, too!). It's not clear what kind of data this is. Is it simple config/properties data? Sometimes you can find libraries to handle the loading/manipulation/storage of this data, and it usually has it's own internal in-memory cache, all you need to do is call one or two functions. Without more information about the files (how big are they?) and the data (how is it formatted and structured?), it's hard to say more. A: Opening, closing, and reading a file 10,000 times is always going to be slow. Can you open the file once, do 10,000 operations on the list, then close the file once? A: It might be better to load your data into a database and put some indexes on the database. Then it will be very fast to make simple queries against your data. You don't need a lot of work to set up a database. You can create an SQLite database without requiring a separate process and it doesn't have a complicated installation process. A: Call the open to the file from the calling method of the one you want to run. Pass the data as parameters to the method A: If the files are structured, kinda configuration files, it might be good to use ConfigParser library, else if you have other structural format then I think it would be better to store all this data in JSON or XML and perform any necessary operations on your data
how to speed up the code?
in my program i have a method which requires about 4 files to be open each time it is called,as i require to take some data.all this data from the file i have been storing in list for manupalation. I approximatily need to call this method about 10,000 times.which is making my program very slow? any method for handling this files in a better ways and is storing the whole data in list time consuming what is better alternatives for list? I can give some code,but my previous question was closed as that only confused everyone as it is a part of big program and need to be explained completely to understand,so i am not giving any code,please suggest ways thinking this as a general question... thanks in advance
[ "As a general strategy, it's best to keep this data in an in-memory cache if it's static, and relatively small. Then, the 10k calls will read an in-memory cache rather than a file. Much faster.\nIf you are modifying the data, the alternative might be a database like SQLite, or embedded MS SQL Server (and there are others, too!).\nIt's not clear what kind of data this is. Is it simple config/properties data? Sometimes you can find libraries to handle the loading/manipulation/storage of this data, and it usually has it's own internal in-memory cache, all you need to do is call one or two functions.\nWithout more information about the files (how big are they?) and the data (how is it formatted and structured?), it's hard to say more.\n", "Opening, closing, and reading a file 10,000 times is always going to be slow. Can you open the file once, do 10,000 operations on the list, then close the file once?\n", "It might be better to load your data into a database and put some indexes on the database. Then it will be very fast to make simple queries against your data. You don't need a lot of work to set up a database. You can create an SQLite database without requiring a separate process and it doesn't have a complicated installation process.\n", "Call the open to the file from the calling method of the one you want to run. Pass the data as parameters to the method\n", "If the files are structured, kinda configuration files, it might be good to use ConfigParser library, else if you have other structural format then I think it would be better to store all this data in JSON or XML and perform any necessary operations on your data\n" ]
[ 3, 2, 1, 0, 0 ]
[]
[]
[ "optimization", "python" ]
stackoverflow_0003006769_optimization_python.txt
Q: Error in Python's os.walk? The os.walk documentation (http://docs.python.org/library/os.html? highlight=os.walk#os.walk), says I can skip traversing unwanted directories by removing them from the dir list. The explicit example from the docs: import os from os.path import join, getsize for root, dirs, files in os.walk('python/Lib/email'): print root, "consumes", print sum(getsize(join(root, name)) for name in files), print "bytes in", len(files), "non-directory files" if 'CVS' in dirs: dirs.remove('CVS') # don't visit CVS directories I see different behavior (using ActivePython 2.6.2). Namely for the code: >>> for root,dirs,files in os.walk(baseline): ... if root.endswith(baseline): ... for d in dirs: ... print "DIR: %s" % d ... if not d.startswith("keep_"): ... print "Removing %s\\%s" % (root,d) ... dirs.remove(d) ... ... print "ROOT: %s" % root ... I get the output: DIR: two Removing: two DIR: thr33 Removing: thr33 DIR: keep_me DIR: keep_me_too DIR: keep_all_of_us ROOT: \\mach\dirs ROOT: \\mach\dirs\ONE ROOT: \\mach\dirs\ONE\FurtherRubbish ROOT: \\mach\dirs\ONE\FurtherRubbish\blah ROOT: \\mach\dirs\ONE\FurtherRubbish\blah\Extracted ROOT: \\mach\dirs\ONE\FurtherRubbish\blah2\Extracted\Stuff_1 ... WTF? Why wasn't \\mach\dirs\ONE removed? It clearly doesn't start with "keep_". A: Because you're modifying the list dirs while iterating over it. ONE was just skipped and never gets looked at. Compare: >>> a = [1, 2, 3] >>> for i in a: if i > 1: a.remove(i) >>> a [1, 3] A: You aren't removing it from the dirs list. If you were, you'd see your "Removing" print out, wouldn't you? Change for d in dirs to for d in list(dirs) to safely remove items from the dirs list while iterating over it. Or you could just write: dirs[:] = [d for d in dirs if not d.startswith("keep_")]
Error in Python's os.walk?
The os.walk documentation (http://docs.python.org/library/os.html? highlight=os.walk#os.walk), says I can skip traversing unwanted directories by removing them from the dir list. The explicit example from the docs: import os from os.path import join, getsize for root, dirs, files in os.walk('python/Lib/email'): print root, "consumes", print sum(getsize(join(root, name)) for name in files), print "bytes in", len(files), "non-directory files" if 'CVS' in dirs: dirs.remove('CVS') # don't visit CVS directories I see different behavior (using ActivePython 2.6.2). Namely for the code: >>> for root,dirs,files in os.walk(baseline): ... if root.endswith(baseline): ... for d in dirs: ... print "DIR: %s" % d ... if not d.startswith("keep_"): ... print "Removing %s\\%s" % (root,d) ... dirs.remove(d) ... ... print "ROOT: %s" % root ... I get the output: DIR: two Removing: two DIR: thr33 Removing: thr33 DIR: keep_me DIR: keep_me_too DIR: keep_all_of_us ROOT: \\mach\dirs ROOT: \\mach\dirs\ONE ROOT: \\mach\dirs\ONE\FurtherRubbish ROOT: \\mach\dirs\ONE\FurtherRubbish\blah ROOT: \\mach\dirs\ONE\FurtherRubbish\blah\Extracted ROOT: \\mach\dirs\ONE\FurtherRubbish\blah2\Extracted\Stuff_1 ... WTF? Why wasn't \\mach\dirs\ONE removed? It clearly doesn't start with "keep_".
[ "Because you're modifying the list dirs while iterating over it. ONE was just skipped and never gets looked at. Compare:\n>>> a = [1, 2, 3]\n>>> for i in a:\n if i > 1:\n a.remove(i)\n\n\n>>> a\n[1, 3]\n\n", "You aren't removing it from the dirs list. If you were, you'd see your \"Removing\" print out, wouldn't you?\nChange for d in dirs to for d in list(dirs) to safely remove items from the dirs list while iterating over it.\nOr you could just write:\ndirs[:] = [d for d in dirs if not d.startswith(\"keep_\")]\n\n" ]
[ 5, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003006911_python.txt
Q: Python module for drawing functions graphics Which python module should I use for drawing simple functions graphics? E.g f: M -> M, f(x) = x A: Matplotlib: http://matplotlib.sourceforge.net/gallery.html A: Check out the third party Gnuplot-py package. I have used it before with success. If you are familiar with gnuplot syntax, this should be relatively easy. If not, there are plenty of good gnuplot examples online. http://pypi.python.org/pypi/gnuplot-py/1.8
Python module for drawing functions graphics
Which python module should I use for drawing simple functions graphics? E.g f: M -> M, f(x) = x
[ "Matplotlib: http://matplotlib.sourceforge.net/gallery.html\n", "Check out the third party Gnuplot-py package. I have used it before with success.\nIf you are familiar with gnuplot syntax, this should be relatively easy. If not, there are plenty of good gnuplot examples online.\nhttp://pypi.python.org/pypi/gnuplot-py/1.8\n" ]
[ 5, 0 ]
[]
[]
[ "graphics", "python" ]
stackoverflow_0003006965_graphics_python.txt
Q: load a pickle file from a zipfile For some reason I cannot get cPickle.load to work on the file-type object returned by ZipFile.open(). If I call read() on the file-type object returned by ZipFile.open() I can use cPickle.loads though. Example .... import zipfile import cPickle # the data we want to store some_data = {1: 'one', 2: 'two', 3: 'three'} # # create a zipped pickle file # zf = zipfile.ZipFile('zipped_pickle.zip', 'w', zipfile.ZIP_DEFLATED) zf.writestr('data.pkl', cPickle.dumps(some_data)) zf.close() # # cPickle.loads works # zf = zipfile.ZipFile('zipped_pickle.zip', 'r') sd1 = cPickle.loads(zf.open('data.pkl').read()) zf.close() # # cPickle.load doesn't work # zf = zipfile.ZipFile('zipped_pickle.zip', 'r') sd2 = cPickle.load(zf.open('data.pkl')) zf.close() Note: I don't want to zip just the pickle file but many files of other types. This is just an example. A: It's due to an imperfection in the pseudofile object implemented by the zipfile module (for the .open method of the ZipFile class introduced in Python 2.6). Consider: >>> f = zf.open('data.pkl') >>> f.read(1) '(' >>> f.readline() 'dp1\n' >>> f.read(1) '' >>> the sequence of .read(1) -- .readline() is what .loads internally does (on a protocol-0 pickle, the default in Python 2, which is what you're using here). Unfortunately zipfile's imperfection means this particular sequence doesn't work, producing a spurious "end of file" (.read returning an empty string) right after the first read/readline pair. Not sure offhand if this bug in Python's standard library is fixed in Python 2.7 -- I'm going to check. Edit: just checked -- the bug is fixed in Python 2.7 rc1 (the release candidate that's currently the latest 2.7 version). I don't yet know whether it's fixed in the latest bug-fix release of 2.6 as well. Edit again: the bug is still there in Python 2.6.5, the latest bug-fix release of Python 2.6 -- so if you can't upgrade to 2.7 and need better-behaving pseudofile objects from ZipFile.open, a backport of the 2.7 fix seems the only viable solution. Note that it's not certain you do need better-behaving pseudofile objects; if you control the dump calls and can use the latest-and-greatest protocol, everything will be fine: >>> zf = zipfile.ZipFile('zipped_pickle.zip', 'w', zipfile.ZIP_DEFLATED) >>> zf.writestr('data.pkl', cPickle.dumps(some_data, -1)) >>> sd2 = cPickle.load(zf.open('data.pkl')) >>> it's only old crufty backwards-compatible "protocol 0" (the default) that requires proper pseudofile object behavior when mixing read and readline calls in the load (protocol 0 is also slower, and results in larger pickles, so it's definitely not recommended unless backwards compatibility with old Python versions, or the ascii-only nature of the pickles that 0 produces, are mandatory constraints in your application).
load a pickle file from a zipfile
For some reason I cannot get cPickle.load to work on the file-type object returned by ZipFile.open(). If I call read() on the file-type object returned by ZipFile.open() I can use cPickle.loads though. Example .... import zipfile import cPickle # the data we want to store some_data = {1: 'one', 2: 'two', 3: 'three'} # # create a zipped pickle file # zf = zipfile.ZipFile('zipped_pickle.zip', 'w', zipfile.ZIP_DEFLATED) zf.writestr('data.pkl', cPickle.dumps(some_data)) zf.close() # # cPickle.loads works # zf = zipfile.ZipFile('zipped_pickle.zip', 'r') sd1 = cPickle.loads(zf.open('data.pkl').read()) zf.close() # # cPickle.load doesn't work # zf = zipfile.ZipFile('zipped_pickle.zip', 'r') sd2 = cPickle.load(zf.open('data.pkl')) zf.close() Note: I don't want to zip just the pickle file but many files of other types. This is just an example.
[ "It's due to an imperfection in the pseudofile object implemented by the zipfile module (for the .open method of the ZipFile class introduced in Python 2.6). Consider:\n>>> f = zf.open('data.pkl')\n>>> f.read(1)\n'('\n>>> f.readline()\n'dp1\\n'\n>>> f.read(1)\n''\n>>> \n\nthe sequence of .read(1) -- .readline() is what .loads internally does (on a protocol-0 pickle, the default in Python 2, which is what you're using here). Unfortunately zipfile's imperfection means this particular sequence doesn't work, producing a spurious \"end of file\" (.read returning an empty string) right after the first read/readline pair.\nNot sure offhand if this bug in Python's standard library is fixed in Python 2.7 -- I'm going to check.\nEdit: just checked -- the bug is fixed in Python 2.7 rc1 (the release candidate that's currently the latest 2.7 version). I don't yet know whether it's fixed in the latest bug-fix release of 2.6 as well.\nEdit again: the bug is still there in Python 2.6.5, the latest bug-fix release of Python 2.6 -- so if you can't upgrade to 2.7 and need better-behaving pseudofile objects from ZipFile.open, a backport of the 2.7 fix seems the only viable solution.\nNote that it's not certain you do need better-behaving pseudofile objects; if you control the dump calls and can use the latest-and-greatest protocol, everything will be fine:\n>>> zf = zipfile.ZipFile('zipped_pickle.zip', 'w', zipfile.ZIP_DEFLATED)\n>>> zf.writestr('data.pkl', cPickle.dumps(some_data, -1))\n>>> sd2 = cPickle.load(zf.open('data.pkl'))\n>>> \n\nit's only old crufty backwards-compatible \"protocol 0\" (the default) that requires proper pseudofile object behavior when mixing read and readline calls in the load (protocol 0 is also slower, and results in larger pickles, so it's definitely not recommended unless backwards compatibility with old Python versions, or the ascii-only nature of the pickles that 0 produces, are mandatory constraints in your application).\n" ]
[ 8 ]
[]
[]
[ "pickle", "python", "python_zipfile" ]
stackoverflow_0003006727_pickle_python_python_zipfile.txt
Q: Django facebook integration error I'm trying to integrate facebook into my application so that users can use their FB login to login to my site. I've got everything up and running and there are no issues when I run my site using the command line python manage.py runserver But this same code refuses to run when I try and run it through Apache. I get the following error: Environment: Request Method: GET Request URL: http://helvetica/foodfolio/login Django Version: 1.1.1 Python Version: 2.6.4 Installed Applications: ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'foodfolio.app', 'foodfolio.facebookconnect'] Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'facebook.djangofb.FacebookMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'facebookconnect.middleware.FacebookConnectMiddleware') Template error: In template /home/swat/website-apps/foodfolio/facebookconnect/templates/facebook/js.html, error at line 2 Caught an exception while rendering: No module named app.models 1 : <script type="text/javascript"> 2 : FB_RequireFeatures(["XFBML"], function() {FB.Facebook.init("{{ facebook_api_key }}", " {% url facebook_xd_receiver %} ")}); 3 : 4 : function facebookConnect(loginForm) { 5 : FB.Connect.requireSession(); 6 : FB.Facebook.get_sessionState().waitUntilReady(function(){loginForm.submit();}); 7 : } 8 : function pushToFacebookFeed(data){ 9 : if(data['success']){ 10 : var template_data = data['template_data']; 11 : var template_bundle_id = data['template_bundle_id']; 12 : feedTheFacebook(template_data,template_bundle_id,function(){}); Traceback: File "/usr/lib/pymodules/python2.6/django/core/handlers/base.py" in get_response 92. response = callback(request, *callback_args, **callback_kwargs) File "/home/swat/website-apps/foodfolio/app/controller.py" in __showLogin__ 238. context_instance = RequestContext(request)) File "/usr/lib/pymodules/python2.6/django/shortcuts/__init__.py" in render_to_response 20. return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs) File "/usr/lib/pymodules/python2.6/django/template/loader.py" in render_to_string 108. return t.render(context_instance) File "/usr/lib/pymodules/python2.6/django/template/__init__.py" in render 178. return self.nodelist.render(context) File "/usr/lib/pymodules/python2.6/django/template/__init__.py" in render 779. bits.append(self.render_node(node, context)) File "/usr/lib/pymodules/python2.6/django/template/debug.py" in render_node 71. result = node.render(context) File "/usr/lib/pymodules/python2.6/django/template/__init__.py" in render 946. autoescape=context.autoescape)) File "/usr/lib/pymodules/python2.6/django/template/__init__.py" in render 779. bits.append(self.render_node(node, context)) File "/usr/lib/pymodules/python2.6/django/template/debug.py" in render_node 81. raise wrapped Exception Type: TemplateSyntaxError at /foodfolio/login Exception Value: Caught an exception while rendering: No module named app.models A: It looks as though you are referencing app.models, which tends to work fine in development but fails in production. Change it to foodfolio.app.models, and it should be fine. This seems to be somewhere in your custom template tags.
Django facebook integration error
I'm trying to integrate facebook into my application so that users can use their FB login to login to my site. I've got everything up and running and there are no issues when I run my site using the command line python manage.py runserver But this same code refuses to run when I try and run it through Apache. I get the following error: Environment: Request Method: GET Request URL: http://helvetica/foodfolio/login Django Version: 1.1.1 Python Version: 2.6.4 Installed Applications: ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'foodfolio.app', 'foodfolio.facebookconnect'] Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'facebook.djangofb.FacebookMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'facebookconnect.middleware.FacebookConnectMiddleware') Template error: In template /home/swat/website-apps/foodfolio/facebookconnect/templates/facebook/js.html, error at line 2 Caught an exception while rendering: No module named app.models 1 : <script type="text/javascript"> 2 : FB_RequireFeatures(["XFBML"], function() {FB.Facebook.init("{{ facebook_api_key }}", " {% url facebook_xd_receiver %} ")}); 3 : 4 : function facebookConnect(loginForm) { 5 : FB.Connect.requireSession(); 6 : FB.Facebook.get_sessionState().waitUntilReady(function(){loginForm.submit();}); 7 : } 8 : function pushToFacebookFeed(data){ 9 : if(data['success']){ 10 : var template_data = data['template_data']; 11 : var template_bundle_id = data['template_bundle_id']; 12 : feedTheFacebook(template_data,template_bundle_id,function(){}); Traceback: File "/usr/lib/pymodules/python2.6/django/core/handlers/base.py" in get_response 92. response = callback(request, *callback_args, **callback_kwargs) File "/home/swat/website-apps/foodfolio/app/controller.py" in __showLogin__ 238. context_instance = RequestContext(request)) File "/usr/lib/pymodules/python2.6/django/shortcuts/__init__.py" in render_to_response 20. return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs) File "/usr/lib/pymodules/python2.6/django/template/loader.py" in render_to_string 108. return t.render(context_instance) File "/usr/lib/pymodules/python2.6/django/template/__init__.py" in render 178. return self.nodelist.render(context) File "/usr/lib/pymodules/python2.6/django/template/__init__.py" in render 779. bits.append(self.render_node(node, context)) File "/usr/lib/pymodules/python2.6/django/template/debug.py" in render_node 71. result = node.render(context) File "/usr/lib/pymodules/python2.6/django/template/__init__.py" in render 946. autoescape=context.autoescape)) File "/usr/lib/pymodules/python2.6/django/template/__init__.py" in render 779. bits.append(self.render_node(node, context)) File "/usr/lib/pymodules/python2.6/django/template/debug.py" in render_node 81. raise wrapped Exception Type: TemplateSyntaxError at /foodfolio/login Exception Value: Caught an exception while rendering: No module named app.models
[ "It looks as though you are referencing app.models, which tends to work fine in development but fails in production. Change it to foodfolio.app.models, and it should be fine. This seems to be somewhere in your custom template tags.\n" ]
[ 0 ]
[]
[]
[ "django", "facebook", "python" ]
stackoverflow_0003004802_django_facebook_python.txt
Q: python `IN` module problem (FreeBSD) I'm trying to work with sockets and I have such problem In code example: setsockopt(socket.SOL_SOCKET,IN.SO_BINDTODEVICE,self.listen_address+'\0') I have error AttributeError: 'module' object has no attribute 'SO_BINDTODEVICE' On Linux machine this attribute is OK but on FreeBSD trere are no any SO_* attributes in module IN. What port should I install to resolve this problem on FreeBDS machine? Python versions on Linux tested: 2.5.4 and 2.6.4; on FreeBSD: 2.5.5 I can't find anything about this module in my book, and googling keyword IN looks like seamless ... update: I can only bind to address, not to device. >>> import socket >>> s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) >>> s.bind(("eth0",3040)) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<string>", line 1, in bind socket.gaierror: [Errno -2] Name or service not known >>> s.bind(("192.168.33.152",3040)) >>> s.close() update 2: ... but I'm working with broadcast packets. I'm trying to write daemon which acts like DHCP server. If I bind to address would I catch broadcast packets? And if I'll set promiscuous mode on? A: SO_BINDTODEVICE socket option is not standard and is not supported on FreeBSD. Why can't you just use regular bind(2) for assigning local address/interface? Edit: Take a look at the socket object docs. Here's an example. Edit 2: You didn't say what exactly you are trying to achieve, so assuming regular TCP/IP client-server. IP, being a network-layer protocol (vs. for example, Ethernet, which is a data-link protocol), is not concerned with devices, but addresses. The idea is that you don't need to bind to a device - the OS takes care of mapping addresses to devices, and maintains a routing table. The only time you need explicit relationship between a socket and a device is when working with broadcast and multicast, where mapping between addresses and interfaces is not obvious. Each network interface known to TCP/IP stack is assigned an IP address (see ifconfig(8)). Bind your socket to that IP address and you'll be all set. Hope this helps. Edit 3: Have you looked into SO_BROADCAST option? Also check out this SO question about raw sockets.
python `IN` module problem (FreeBSD)
I'm trying to work with sockets and I have such problem In code example: setsockopt(socket.SOL_SOCKET,IN.SO_BINDTODEVICE,self.listen_address+'\0') I have error AttributeError: 'module' object has no attribute 'SO_BINDTODEVICE' On Linux machine this attribute is OK but on FreeBSD trere are no any SO_* attributes in module IN. What port should I install to resolve this problem on FreeBDS machine? Python versions on Linux tested: 2.5.4 and 2.6.4; on FreeBSD: 2.5.5 I can't find anything about this module in my book, and googling keyword IN looks like seamless ... update: I can only bind to address, not to device. >>> import socket >>> s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) >>> s.bind(("eth0",3040)) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<string>", line 1, in bind socket.gaierror: [Errno -2] Name or service not known >>> s.bind(("192.168.33.152",3040)) >>> s.close() update 2: ... but I'm working with broadcast packets. I'm trying to write daemon which acts like DHCP server. If I bind to address would I catch broadcast packets? And if I'll set promiscuous mode on?
[ "SO_BINDTODEVICE socket option is not standard and is not supported on FreeBSD. Why can't you just use regular bind(2) for assigning local address/interface?\nEdit:\nTake a look at the socket object docs.\nHere's an example.\nEdit 2:\nYou didn't say what exactly you are trying to achieve, so assuming regular TCP/IP client-server.\nIP, being a network-layer protocol (vs. for example, Ethernet, which is a data-link protocol), is not concerned with devices, but addresses. The idea is that you don't need to bind to a device - the OS takes care of mapping addresses to devices, and maintains a routing table. The only time you need explicit relationship between a socket and a device is when working with broadcast and multicast, where mapping between addresses and interfaces is not obvious.\nEach network interface known to TCP/IP stack is assigned an IP address (see ifconfig(8)). Bind your socket to that IP address and you'll be all set.\nHope this helps.\nEdit 3:\nHave you looked into SO_BROADCAST option? Also check out this SO question about raw sockets.\n" ]
[ 1 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0003007084_python_sockets.txt
Q: Django: Page doesn't load images I am working on a Django project for a company. This project worked very well before today. Today I found a page can not show images (and their corrsponding links). I checked source code of THAT PAGE, I found there are images and links, I just can not find them on the page. I checked the auth of the server and I am sure I can write things to the database. In fact, I think it is not database mistake because I can find what I want in the page source code, I just can not find them on the page. Oh my Gosh, I am going to be crazy... Has anyone suffered similar problem? What kind of problem could it be? Please help me! Thank you very much! PS: I can not provide any source code of the project because some business limit...I am really sorry... A: Try exploring the site_media directory. If you're images are being served up as static content it could be related to the permissions of that folder on local disk or based on the settings. Within your urls you may have something similar to: (r'^site_media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '/path/to/media'}), OR it may reference the path in the settings file something similar to: STATIC_DOC_ROOT = '/path/to/media' If the link looks correct for the image, but the side is not rendering the image even directly your issue will be somewhere in these areas. For more information check the django docs: http://docs.djangoproject.com/en/dev/howto/static-files/
Django: Page doesn't load images
I am working on a Django project for a company. This project worked very well before today. Today I found a page can not show images (and their corrsponding links). I checked source code of THAT PAGE, I found there are images and links, I just can not find them on the page. I checked the auth of the server and I am sure I can write things to the database. In fact, I think it is not database mistake because I can find what I want in the page source code, I just can not find them on the page. Oh my Gosh, I am going to be crazy... Has anyone suffered similar problem? What kind of problem could it be? Please help me! Thank you very much! PS: I can not provide any source code of the project because some business limit...I am really sorry...
[ "Try exploring the site_media directory. If you're images are being served up as static content it could be related to the permissions of that folder on local disk or based on the settings.\nWithin your urls you may have something similar to:\n(r'^site_media/(?P<path>.*)$', 'django.views.static.serve',\n {'document_root': '/path/to/media'}),\n\nOR it may reference the path in the settings file something similar to:\nSTATIC_DOC_ROOT = '/path/to/media'\n\nIf the link looks correct for the image, but the side is not rendering the image even directly your issue will be somewhere in these areas.\nFor more information check the django docs:\nhttp://docs.djangoproject.com/en/dev/howto/static-files/\n" ]
[ 0 ]
[]
[]
[ "django", "python", "web" ]
stackoverflow_0002995648_django_python_web.txt
Q: In Python, how do I remove the "root" tag in an HTML snippet? Suppose I have an HTML snippet like this: <div> Hello <strong>There</strong> <div>I think <em>I am</em> feeing better!</div> <div>Don't you?</div> Yup! </div> What's the best/most robust way to remove the surrounding root element, so it looks like this: Hello <strong>There</strong> <div>I think <em>I am</em> feeing better!</div> <div>Don't you?</div> Yup! I've tried using lxml.html like this: lxml.html.fromstring(fragment_string).drop_tag() But that only gives me "Hello", which I guess makes sense. Any better ideas? A: This is a bit odd in lxml (or ElementTree). You'd have to do: def inner_html(el): return (el.text or '') + ''.join(tostring(child) for child in el) Note that lxml (and ElementTree) have no special way to represent a document except rooted with a single element, but .drop_tag() would work like you want if that <div> wasn't the root element. A: You can use BeautifulSoup package. For this particular html I would go like this: import BeautifulSoup html = """<div> Hello <strong>There</strong> <div>I think <em>I am</em> feeing better!</div> <div>Don't you?</div> Yup! </div>""" bs = BeautifulSoup.BeautifulSoup(html) no_root = '\n'.join(map(unicode, bs.div.contents)) BeautifulSoup has many nice features that will allow you to tweak this example for many other cases. Full documentation: http://www.crummy.com/software/BeautifulSoup/documentation.html. A: For such a simple task you can use regexp like r'<(.*?)>(.*)</\1>' and get match #2 (\2 in perl terms) from it You should also put flags like ms for correct multi-line working
In Python, how do I remove the "root" tag in an HTML snippet?
Suppose I have an HTML snippet like this: <div> Hello <strong>There</strong> <div>I think <em>I am</em> feeing better!</div> <div>Don't you?</div> Yup! </div> What's the best/most robust way to remove the surrounding root element, so it looks like this: Hello <strong>There</strong> <div>I think <em>I am</em> feeing better!</div> <div>Don't you?</div> Yup! I've tried using lxml.html like this: lxml.html.fromstring(fragment_string).drop_tag() But that only gives me "Hello", which I guess makes sense. Any better ideas?
[ "This is a bit odd in lxml (or ElementTree). You'd have to do:\ndef inner_html(el):\n return (el.text or '') + ''.join(tostring(child) for child in el)\n\nNote that lxml (and ElementTree) have no special way to represent a document except rooted with a single element, but .drop_tag() would work like you want if that <div> wasn't the root element.\n", "You can use BeautifulSoup package. For this particular html I would go like this:\nimport BeautifulSoup\n\nhtml = \"\"\"<div>\n Hello <strong>There</strong>\n <div>I think <em>I am</em> feeing better!</div>\n <div>Don't you?</div>\n Yup!\n</div>\"\"\"\n\nbs = BeautifulSoup.BeautifulSoup(html)\n\nno_root = '\\n'.join(map(unicode, bs.div.contents))\n\nBeautifulSoup has many nice features that will allow you to tweak this example for many other cases. Full documentation: http://www.crummy.com/software/BeautifulSoup/documentation.html.\n", "For such a simple task you can use regexp like\nr'<(.*?)>(.*)</\\1>' and get match #2 (\\2 in perl terms) from it\nYou should also put flags like ms for correct multi-line working\n" ]
[ 6, 1, 0 ]
[]
[]
[ "html", "python" ]
stackoverflow_0003003049_html_python.txt
Q: Using localtime in a where clause for GqlQuery I'm trying to understand how I can use the local server time to quickly filter results on google appengine. It seems to me that there should be a simple way of doing this using DATETIME(time.localtime()). For example (where 'timestamp' is of type db.DateTimeProperty)... q = db.GqlQuery("SELECT * FROM LiveData WHERE timestamp > DATETIME(:1)", time.localtime()) Is there a GqlQuery and/or python construct that lets me do this with one method call? It seems as though I need to create strings for DATETIME() parameters. A: You do not have to create strings when querying DateTimeProperty types. Try this: import datetime q = db.GqlQuery("SELECT * FROM LiveData WHERE timestamp > :1", datetime.datetime.now())
Using localtime in a where clause for GqlQuery
I'm trying to understand how I can use the local server time to quickly filter results on google appengine. It seems to me that there should be a simple way of doing this using DATETIME(time.localtime()). For example (where 'timestamp' is of type db.DateTimeProperty)... q = db.GqlQuery("SELECT * FROM LiveData WHERE timestamp > DATETIME(:1)", time.localtime()) Is there a GqlQuery and/or python construct that lets me do this with one method call? It seems as though I need to create strings for DATETIME() parameters.
[ "You do not have to create strings when querying DateTimeProperty types. Try this:\nimport datetime\nq = db.GqlQuery(\"SELECT * FROM LiveData WHERE timestamp > :1\", datetime.datetime.now())\n\n" ]
[ 3 ]
[]
[]
[ "google_app_engine", "gqlquery", "python" ]
stackoverflow_0003007512_google_app_engine_gqlquery_python.txt
Q: Are there any tools for schema migration for NoSQL databases? I'm looking a way to automate schema migration for such databases like MongoDB or CouchDB. Preferably, this instument should be written in python, but any other language is ok. A: Since a nosql database can contain huge amounts of data you can not migrate it in the regular rdbms sence. Actually you can't do it for rdbms as well as soon as your data passes some size threshold. It is impractical to bring your site down for a day to add a field to an existing table, and so with rdbms you end up doing ugly patches like adding new tables just for the field and doing joins to get to the data. In nosql world you can do several things. As others suggested you can write your code so that it will handle different 'versions' of the possible schema. this is usually simpler then it looks. Many kinds of schema changes are trivial to code around. for example if you want to add a new field to the schema, you just add it to all new records and it will be empty on the all old records (you will not get "field doesn't exist" errors or anything ;). if you need a 'default' value for the field in the old records it is too trivially done in code. Another option and actually the only sane option going forward with non-trivial schema changes like field renames and structural changes is to store schema_version in EACH record, and to have code to migrate data from any version to the next on READ. i.e. if your current schema version is 10 and you read a record from the database with the version of 7, then your db layer should call migrate_8, migrate_9, and migrate_10. This way the data that is accessed will be gradually migrated to the new version. and if it is not accessed, then who cares which version is it;) A: One of the supposed benefits of these databases is that they are schemaless, and therefore don't need schema migration tools. Instead, you write your data handling code to deal with the variety of data stored in the db. A: If your data are sufficiently big, you will probably find that you cannot EVER migrate the data, or that it is not beneficial to do so. This means that when you do a schema change, the code needs to continue to be backwards compatible with the old formats forever. Of course if your data "age" and eventually expire anyway, this can do schema migration for you - simply change the format for newly added data, then wait for all data in the old format to expire - you can then retire the backward-compatibility code. A: When a project has a need for a schema migration in regards to a NoSQL database makes me think that you are still thinking in a Relational database manner, but using a NoSQL database. If anybody is going to start working with NoSQL databases, you need to realize that most of the 'rules' for a RDBMS (i.e. MySQL) need to go out the window too. Things like strict schemas, normalization, using many relationships between objects. NoSQL exists to solve problems that don't need all the extra 'features' provided by a RDBMS. I would urge you to write your code in a manner that doesn't expect or need a hard schema for your NoSQL database - you should support an old schema and convert a document record on the fly when you access if if you really want more schema fields on that record. Please keep in mind that NoSQL storage works best when you think and design differently compared to when using a RDBMS
Are there any tools for schema migration for NoSQL databases?
I'm looking a way to automate schema migration for such databases like MongoDB or CouchDB. Preferably, this instument should be written in python, but any other language is ok.
[ "Since a nosql database can contain huge amounts of data you can not migrate it in the regular rdbms sence. Actually you can't do it for rdbms as well as soon as your data passes some size threshold. It is impractical to bring your site down for a day to add a field to an existing table, and so with rdbms you end up doing ugly patches like adding new tables just for the field and doing joins to get to the data.\nIn nosql world you can do several things.\n\nAs others suggested you can write your code so that it will handle different 'versions' of the possible schema. this is usually simpler then it looks. Many kinds of schema changes are trivial to code around. for example if you want to add a new field to the schema, you just add it to all new records and it will be empty on the all old records (you will not get \"field doesn't exist\" errors or anything ;). if you need a 'default' value for the field in the old records it is too trivially done in code.\nAnother option and actually the only sane option going forward with non-trivial schema changes like field renames and structural changes is to store schema_version in EACH record, and to have code to migrate data from any version to the next on READ. i.e. if your current schema version is 10 and you read a record from the database with the version of 7, then your db layer should call migrate_8, migrate_9, and migrate_10. This way the data that is accessed will be gradually migrated to the new version. and if it is not accessed, then who cares which version is it;)\n\n", "One of the supposed benefits of these databases is that they are schemaless, and therefore don't need schema migration tools. Instead, you write your data handling code to deal with the variety of data stored in the db.\n", "If your data are sufficiently big, you will probably find that you cannot EVER migrate the data, or that it is not beneficial to do so. This means that when you do a schema change, the code needs to continue to be backwards compatible with the old formats forever.\nOf course if your data \"age\" and eventually expire anyway, this can do schema migration for you - simply change the format for newly added data, then wait for all data in the old format to expire - you can then retire the backward-compatibility code.\n", "When a project has a need for a schema migration in regards to a NoSQL database makes me think that you are still thinking in a Relational database manner, but using a NoSQL database.\nIf anybody is going to start working with NoSQL databases, you need to realize that most of the 'rules' for a RDBMS (i.e. MySQL) need to go out the window too. Things like strict schemas, normalization, using many relationships between objects. NoSQL exists to solve problems that don't need all the extra 'features' provided by a RDBMS.\nI would urge you to write your code in a manner that doesn't expect or need a hard schema for your NoSQL database - you should support an old schema and convert a document record on the fly when you access if if you really want more schema fields on that record.\nPlease keep in mind that NoSQL storage works best when you think and design differently compared to when using a RDBMS\n" ]
[ 19, 2, 2, 1 ]
[]
[]
[ "couchdb", "database", "mongodb", "nosql", "python" ]
stackoverflow_0001961013_couchdb_database_mongodb_nosql_python.txt
Q: Is there a way to programatically access a bazaar repository? I would like to access a bazaar repository and pull code from it with either a Python or PHP script. How is this done? Is there a Python module / PEAR library that makes this easy? If it helps, the repository is on Launchpad. Edit: As mentioned below, running the bazaar commands directly is not an option. Also, an example would be much appreciated. A: There is bzrlib. Depending on your circumstance you could also just execute the command lines to do this. Based on the Integrating with BZR page you might do something like the following to checkout code. You can also Export code which might be more appropriate: from bzrlib.bzrdir BzrDir accelerator_tree, source = BzrDir.open_tree_or_branch('http:URL') source.create_checkout('/tmp/newBzrCheckout', None, True, accelerator_tree)
Is there a way to programatically access a bazaar repository?
I would like to access a bazaar repository and pull code from it with either a Python or PHP script. How is this done? Is there a Python module / PEAR library that makes this easy? If it helps, the repository is on Launchpad. Edit: As mentioned below, running the bazaar commands directly is not an option. Also, an example would be much appreciated.
[ "There is bzrlib. Depending on your circumstance you could also just execute the command lines to do this.\nBased on the Integrating with BZR page you might do something like the following to checkout code. You can also Export code which might be more appropriate:\nfrom bzrlib.bzrdir BzrDir\n\naccelerator_tree, source = BzrDir.open_tree_or_branch('http:URL')\nsource.create_checkout('/tmp/newBzrCheckout', None, True, accelerator_tree)\n\n" ]
[ 4 ]
[]
[]
[ "bazaar", "php", "python" ]
stackoverflow_0003008054_bazaar_php_python.txt
Q: Python logging is outputting with the time 4 hours ahead of system My system is set to EDT in Linux, and I can confirm this in Python with datetime.now(). However the logger is outputting 4 hours ahead. What could be the cause of this? EDIT: Logging config looks like this: logging.basicConfig(level=logging.DEBUG) lf = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") mylogger = logging.getLogger('mylogger') mylogger .setLevel(logging.DEBUG) lsh = logging.StreamHandler() lsh.setLevel(logging.DEBUG) lsh.setFormatter(lf) mylogger.addHandler(lsh) A: Your logger is using UTC time. If you show us your code it would be possible to say exactly why. A: I think it is significant that 4 hours ahead is GMT for you. Poking around logging's code - it seems that it uses time rather than datetime. Apparently they work differently in figuring out the localtime. What does the following output?: import time print time.tzname AFAIK, that controls the offset used by logging. According to the documentation, you want to tweak your "system's zoneinfo database to specify the timezone rules" (man tzfile).
Python logging is outputting with the time 4 hours ahead of system
My system is set to EDT in Linux, and I can confirm this in Python with datetime.now(). However the logger is outputting 4 hours ahead. What could be the cause of this? EDIT: Logging config looks like this: logging.basicConfig(level=logging.DEBUG) lf = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") mylogger = logging.getLogger('mylogger') mylogger .setLevel(logging.DEBUG) lsh = logging.StreamHandler() lsh.setLevel(logging.DEBUG) lsh.setFormatter(lf) mylogger.addHandler(lsh)
[ "Your logger is using UTC time. If you show us your code it would be possible to say exactly why.\n", "I think it is significant that 4 hours ahead is GMT for you. Poking around logging's code - it seems that it uses time rather than datetime. Apparently they work differently in figuring out the localtime.\nWhat does the following output?:\nimport time\nprint time.tzname\n\nAFAIK, that controls the offset used by logging. According to the documentation, you want to tweak your \"system's zoneinfo database to specify the timezone rules\" (man tzfile).\n" ]
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003005530_python.txt
Q: I need powerful interactive packet manipulation program like scapy I need powerful interactive packet manipulation program like Scapy for Ruby A: Did you try Scruby ? http://www.rubyinside.com/scruby-a-ruby-shell-for-packet-sending-and-sniffing-460.html A: http://github.com/ahobson/ruby-pcap here's one. Don't know how powerful it when compared to Scapy, but it was enough for my needs.
I need powerful interactive packet manipulation program like scapy
I need powerful interactive packet manipulation program like Scapy for Ruby
[ "Did you try Scruby ? http://www.rubyinside.com/scruby-a-ruby-shell-for-packet-sending-and-sniffing-460.html\n", "http://github.com/ahobson/ruby-pcap\nhere's one. Don't know how powerful it when compared to Scapy, but it was enough for my needs.\n" ]
[ 0, 0 ]
[]
[]
[ "packet", "python", "ruby", "scapy" ]
stackoverflow_0003008246_packet_python_ruby_scapy.txt
Q: In Python, how do I search a flat file for the closest match to a particular numeric value? have file data of format 3.343445 1 3.54564 1 4.345535 1 2.453454 1 and so on upto 1000 lines and i have number given such as a=2.44443 for the given file i need to find the row number of the numbers in file which is most close to the given number "a" how can i do this i am presently doing by loading whole file into list and comparing each element and finding the closest one any other better faster method? my code:i need to ru this for different file each time around 20000 times so want a fast method p=os.path.join("c:/begpython/wavnk/",str(str(str(save_a[1]).replace('phone','text'))+'.pm')) x=open(p , 'r') for i in range(6): x.readline() j=0 o=[] for line in x: oj=str(str(line).rstrip('\n')).split(' ') o=o+[oj] j=j+1 temp=long(1232332) end_time=save_a[4] for i in range((j-1)): diff=float(o[i][0])-float(end_time) if diff<0: diff=diff*(-1) if temp>diff: temp=diff pm_row=i A: >>> gen = (float(line.partition(' ')[0]) for line in open(fname)) >>> min(enumerate(gen), key=lambda x: abs(x[1] - a)) (3, 2.453454) A: If the file isn't sorted, no, there is no faster method. Actually, let me rephrase: the fastest algorithm is to go through the file line by line and compare the first number on each line with your "target value," and save the line number where the difference is smallest. But from your description, it sounds like your implementation is inefficient. You don't need to load the whole file into memory, Python allows you to iterate through it loading a line at a time. Like so: a = 2.44443 min_line = 0 min_diff = Infinity with open('file.txt', 'r') as f: for i, line in enumerate(f): diff = abs(float(line.split()[0]) - a) if diff < min_diff: min_line = i min_diff = diff EDIT: This assumes that you're only going to be searching the file for one value of a. If you're going to be repeatedly searching for several different values of a, then sorting the file and doing a binary search as other answers suggest becomes quicker. A: Retrieve all the numbers and use bisect.insort to store them in a sorted list (or just throw them in any order and sort yourself); then use bisect to easily find the next higher and next lower number, and take the closer of the two. This approach (that depends on an already-sorted list) is algorithmically much more efficient than iterating over the entire unsorted list each time you need to find a "close" number. A: Here's one suggestion. After loading the data into a list, sort it in ascending order. Check the value against the last item in the list, then you know it's not in the list if greater than the last. Then start checking against each value if in the list. Stop checking once you get to a value higher then the "a" value. Then you can compare "a" to those two last values to see which was closer. Be sure to store the row number in your list when you originally scan in the data. That preserves it for you to retrieve it after the sort. A: a=2.44443 closest = None f = open('somefile.txt','r') theLines = f.readlines() #or for really large files theLines = f.xreadlines() #VALIDATE: I'm asumming at least one file closest = float(theLines.iter().next().split()[0]) for line in theLines: b, c = line.split(); b = float(b) if (abs(a - b) < abs(a - closest)): closest = b f.close() print "The closest is ", b
In Python, how do I search a flat file for the closest match to a particular numeric value?
have file data of format 3.343445 1 3.54564 1 4.345535 1 2.453454 1 and so on upto 1000 lines and i have number given such as a=2.44443 for the given file i need to find the row number of the numbers in file which is most close to the given number "a" how can i do this i am presently doing by loading whole file into list and comparing each element and finding the closest one any other better faster method? my code:i need to ru this for different file each time around 20000 times so want a fast method p=os.path.join("c:/begpython/wavnk/",str(str(str(save_a[1]).replace('phone','text'))+'.pm')) x=open(p , 'r') for i in range(6): x.readline() j=0 o=[] for line in x: oj=str(str(line).rstrip('\n')).split(' ') o=o+[oj] j=j+1 temp=long(1232332) end_time=save_a[4] for i in range((j-1)): diff=float(o[i][0])-float(end_time) if diff<0: diff=diff*(-1) if temp>diff: temp=diff pm_row=i
[ ">>> gen = (float(line.partition(' ')[0]) for line in open(fname))\n>>> min(enumerate(gen), key=lambda x: abs(x[1] - a))\n(3, 2.453454)\n\n", "If the file isn't sorted, no, there is no faster method.\nActually, let me rephrase: the fastest algorithm is to go through the file line by line and compare the first number on each line with your \"target value,\" and save the line number where the difference is smallest. But from your description, it sounds like your implementation is inefficient. You don't need to load the whole file into memory, Python allows you to iterate through it loading a line at a time. Like so:\na = 2.44443\nmin_line = 0\nmin_diff = Infinity\nwith open('file.txt', 'r') as f:\n for i, line in enumerate(f):\n diff = abs(float(line.split()[0]) - a)\n if diff < min_diff:\n min_line = i\n min_diff = diff\n\nEDIT: This assumes that you're only going to be searching the file for one value of a. If you're going to be repeatedly searching for several different values of a, then sorting the file and doing a binary search as other answers suggest becomes quicker.\n", "Retrieve all the numbers and use bisect.insort to store them in a sorted list (or just throw them in any order and sort yourself); then use bisect to easily find the next higher and next lower number, and take the closer of the two.\nThis approach (that depends on an already-sorted list) is algorithmically much more efficient than iterating over the entire unsorted list each time you need to find a \"close\" number.\n", "Here's one suggestion. After loading the data into a list, sort it in ascending order. Check the value against the last item in the list, then you know it's not in the list if greater than the last. Then start checking against each value if in the list. Stop checking once you get to a value higher then the \"a\" value. Then you can compare \"a\" to those two last values to see which was closer.\nBe sure to store the row number in your list when you originally scan in the data. That preserves it for you to retrieve it after the sort.\n", "a=2.44443\nclosest = None\nf = open('somefile.txt','r')\ntheLines = f.readlines() #or for really large files theLines = f.xreadlines() \n#VALIDATE: I'm asumming at least one file\nclosest = float(theLines.iter().next().split()[0])\nfor line in theLines:\n b, c = line.split();\n b = float(b)\n if (abs(a - b) < abs(a - closest)):\n closest = b\nf.close()\nprint \"The closest is \", b\n\n" ]
[ 8, 2, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003008212_python.txt
Q: Python Library installation I have two questions regarding python libraries: I would like to know if there is something like a "super" python library which lets me install ALL or at least all scientific useful python libraries, which I can install once and then I have all I need. There is a number of annoying problems when installing different libraries (pythonpath, cant import because it is not installed BUT it is installed). Is there any good documentation about common installation errors and how to avoid them. If there is no total solution I would be interested in numpy, scipy, matplotlib, PIL Thanks a lot for the attention and help Best Z A: In Windows enviroments, pythonXY is what your are looking for. A: Enthought Python Distribution A: Several options are listed at http://new.scipy.org/download.html#software-distributions-that-include-numpy-scipy
Python Library installation
I have two questions regarding python libraries: I would like to know if there is something like a "super" python library which lets me install ALL or at least all scientific useful python libraries, which I can install once and then I have all I need. There is a number of annoying problems when installing different libraries (pythonpath, cant import because it is not installed BUT it is installed). Is there any good documentation about common installation errors and how to avoid them. If there is no total solution I would be interested in numpy, scipy, matplotlib, PIL Thanks a lot for the attention and help Best Z
[ "In Windows enviroments, pythonXY is what your are looking for.\n", "Enthought Python Distribution\n", "Several options are listed at http://new.scipy.org/download.html#software-distributions-that-include-numpy-scipy\n" ]
[ 5, 4, 3 ]
[]
[]
[ "matplotlib", "numpy", "python", "python_imaging_library" ]
stackoverflow_0003006844_matplotlib_numpy_python_python_imaging_library.txt
Q: Matplotlib autodatelocator custom date formatting? I'm using Matplotlib to dynamically generate .png charts from a database. The user may set as the x-axis any given range of datetimes, and I need to account for all of it. While Matplotlib has the dates.AutoDateLocator(), I want the datetime format printed on the chart to be context-specific - e.g. if the user is charting from 3 p.m. to 5 p.m., the year/month/day information doesn't need to be displayed. Right now, I'm manually creating Locator and Formatter objects thusly: def get_ticks(start, end): from datetime import timedelta as td delta = end - start if delta <= td(minutes=10): loc = mdates.MinuteLocator() fmt = mdates.DateFormatter('%I:%M %p') elif delta <= td(minutes=30): loc = mdates.MinuteLocator(byminute=range(0,60,5)) fmt = mdates.DateFormatter('%I:%M %p') elif delta <= td(hours=1): loc = mdates.MinuteLocator(byminute=range(0,60,15)) fmt = mdates.DateFormatter('%I:%M %p') elif delta <= td(hours=6): loc = mdates.HourLocator() fmt = mdates.DateFormatter('%I:%M %p') elif delta <= td(days=1): loc = mdates.HourLocator(byhour=range(0,24,3)) fmt = mdates.DateFormatter('%I:%M %p') elif delta <= td(days=3): loc = mdates.HourLocator(byhour=range(0,24,6)) fmt = mdates.DateFormatter('%I:%M %p') elif delta <= td(weeks=2): loc = mdates.DayLocator() fmt = mdates.DateFormatter('%b %d') elif delta <= td(weeks=12): loc = mdates.WeekdayLocator() fmt = mdates.DateFormatter('%b %d') elif delta <= td(weeks=52): loc = mdates.MonthLocator() fmt = mdates.DateFormatter('%b') else: loc = mdates.MonthLocator(interval=3) fmt = mdates.DateFormatter('%b %Y') return loc,fmt Is there a better way of doing this? A: Does AutoDateFormatter do what you want? Even if it doesn't, you may want to take a look at its source code for a somewhat more compact way of implementing the choice of format string. In the released version, you cannot customize the per-level formats, but in the development code you can. You could probably just copy the version from the trunk into your own code.
Matplotlib autodatelocator custom date formatting?
I'm using Matplotlib to dynamically generate .png charts from a database. The user may set as the x-axis any given range of datetimes, and I need to account for all of it. While Matplotlib has the dates.AutoDateLocator(), I want the datetime format printed on the chart to be context-specific - e.g. if the user is charting from 3 p.m. to 5 p.m., the year/month/day information doesn't need to be displayed. Right now, I'm manually creating Locator and Formatter objects thusly: def get_ticks(start, end): from datetime import timedelta as td delta = end - start if delta <= td(minutes=10): loc = mdates.MinuteLocator() fmt = mdates.DateFormatter('%I:%M %p') elif delta <= td(minutes=30): loc = mdates.MinuteLocator(byminute=range(0,60,5)) fmt = mdates.DateFormatter('%I:%M %p') elif delta <= td(hours=1): loc = mdates.MinuteLocator(byminute=range(0,60,15)) fmt = mdates.DateFormatter('%I:%M %p') elif delta <= td(hours=6): loc = mdates.HourLocator() fmt = mdates.DateFormatter('%I:%M %p') elif delta <= td(days=1): loc = mdates.HourLocator(byhour=range(0,24,3)) fmt = mdates.DateFormatter('%I:%M %p') elif delta <= td(days=3): loc = mdates.HourLocator(byhour=range(0,24,6)) fmt = mdates.DateFormatter('%I:%M %p') elif delta <= td(weeks=2): loc = mdates.DayLocator() fmt = mdates.DateFormatter('%b %d') elif delta <= td(weeks=12): loc = mdates.WeekdayLocator() fmt = mdates.DateFormatter('%b %d') elif delta <= td(weeks=52): loc = mdates.MonthLocator() fmt = mdates.DateFormatter('%b') else: loc = mdates.MonthLocator(interval=3) fmt = mdates.DateFormatter('%b %Y') return loc,fmt Is there a better way of doing this?
[ "Does AutoDateFormatter do what you want? Even if it doesn't, you may want to take a look at its source code for a somewhat more compact way of implementing the choice of format string.\nIn the released version, you cannot customize the per-level formats, but in the development code you can. You could probably just copy the version from the trunk into your own code.\n" ]
[ 2 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0003002155_matplotlib_python.txt
Q: How to write a copyright message using matplotlib I am creating some graphs using matplotlib, and I want to be able to write a copyright message and my website address at the bottom of the image. Something like: © ACME Corp www.example.com Does anyone know how I may do this? A: To write text in the figure outside the axis area, use figtext. A: Not sure if this answer your question but you can put any text in a figure with text(x, y, s, fontdict=None, **kwargs) some examples of fonts are in here
How to write a copyright message using matplotlib
I am creating some graphs using matplotlib, and I want to be able to write a copyright message and my website address at the bottom of the image. Something like: © ACME Corp www.example.com Does anyone know how I may do this?
[ "To write text in the figure outside the axis area, use figtext. \n", "Not sure if this answer your question but you can put any text in a figure with\n text(x, y, s, fontdict=None, **kwargs)\n\nsome examples of fonts are in here\n" ]
[ 3, 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0002964009_matplotlib_python.txt
Q: Manipulating Directory Paths in Python Basically I've got this current url and this other key that I want to merge into a new url, but there are three different cases. Suppose the current url is localhost:32401/A/B/foo if key is bar then I want to return localhost:32401/A/B/bar if key starts with a slash and is /A/bar then I want to return localhost:32401/A/bar finally if key is its own independent url then I just want to return that key = http://foo.com/bar -> http://foo.com/bar I assume there is a way to do at least the first two cases without manipulating the strings manually, but nothing jumped out at me immediately in the os.path module. A: Have you checked out the urlparse module? From the docs, from urlparse import urljoin urljoin('http://www.cwi.nl/%7Eguido/Python.html', 'FAQ.html') Should help with your first case. Obviously, you can always do basic string manipulation for the rest. A: String objects in Python all have startswith and endswith methods that should be able to get you there. Something like this perhaps? def merge(current, key): if key.startswith('http'): return key if key.startswith('/'): parts = current.partition('/') return '/'.join(parts[0], key) parts = current.rpartition('/') return '/'.join(parts[0], key) A: I assume there is a way to do at least the first two cases without manipulating the strings manually, but nothing jumped out at me immediately in the os.path module. That's because you want to use urllib.parse (for Python 3.x) or urlparse (for Python 2.x) instead. I don't have much experience with it, though, so here's a snippet using str.split() and str.join(). urlparts = url.split('/') if key.startswith('http://'): return key elif key.startswith('/'): return '/'.join(urlparts[:2], key[1:]) else: urlparts[len(urlparts) - 1] = key return '/'.join(urlparts)
Manipulating Directory Paths in Python
Basically I've got this current url and this other key that I want to merge into a new url, but there are three different cases. Suppose the current url is localhost:32401/A/B/foo if key is bar then I want to return localhost:32401/A/B/bar if key starts with a slash and is /A/bar then I want to return localhost:32401/A/bar finally if key is its own independent url then I just want to return that key = http://foo.com/bar -> http://foo.com/bar I assume there is a way to do at least the first two cases without manipulating the strings manually, but nothing jumped out at me immediately in the os.path module.
[ "Have you checked out the urlparse module?\nFrom the docs,\nfrom urlparse import urljoin\nurljoin('http://www.cwi.nl/%7Eguido/Python.html', 'FAQ.html')\n\nShould help with your first case.\nObviously, you can always do basic string manipulation for the rest.\n", "String objects in Python all have startswith and endswith methods that should be able to get you there. Something like this perhaps?\ndef merge(current, key):\n if key.startswith('http'):\n return key\n if key.startswith('/'):\n parts = current.partition('/')\n return '/'.join(parts[0], key)\n parts = current.rpartition('/')\n return '/'.join(parts[0], key)\n\n", "\nI assume there is a way to do at least the first two cases without manipulating the strings manually, but nothing jumped out at me immediately in the os.path module.\n\nThat's because you want to use urllib.parse (for Python 3.x) or urlparse (for Python 2.x) instead.\nI don't have much experience with it, though, so here's a snippet using str.split() and str.join().\nurlparts = url.split('/')\n\nif key.startswith('http://'):\n return key\nelif key.startswith('/'):\n return '/'.join(urlparts[:2], key[1:])\nelse:\n urlparts[len(urlparts) - 1] = key\n return '/'.join(urlparts)\n\n" ]
[ 1, 0, 0 ]
[]
[]
[ "absolute_path", "directory", "python", "relative_path" ]
stackoverflow_0003008756_absolute_path_directory_python_relative_path.txt
Q: How to hide Windows console with python Tkinter? I tried renaming my .py file to .pyw. But compiling with py2exe does not make a difference. I tried using root.withdraw() but all it does is freeze the application, prevent the initial canvas from popping up, and fail to remove the command prompt window anyways. Does anyone have a solution? My root is: root = Tk() A: I ended up finding the solution on http://ubuntuforums.org/showthread.php?t=728170 In short, the solution is to change the line setup(console=["yourapp.py"]) to setup(windows=["yourapp.py"]), otherwise, it is the same code as the rest of the py2exe tutorial.
How to hide Windows console with python Tkinter?
I tried renaming my .py file to .pyw. But compiling with py2exe does not make a difference. I tried using root.withdraw() but all it does is freeze the application, prevent the initial canvas from popping up, and fail to remove the command prompt window anyways. Does anyone have a solution? My root is: root = Tk()
[ "I ended up finding the solution on http://ubuntuforums.org/showthread.php?t=728170\nIn short, the solution is to change the line setup(console=[\"yourapp.py\"]) to setup(windows=[\"yourapp.py\"]), otherwise, it is the same code as the rest of the py2exe tutorial.\n" ]
[ 5 ]
[]
[]
[ "console", "hide", "python", "tkinter", "windows" ]
stackoverflow_0003008731_console_hide_python_tkinter_windows.txt
Q: how to speed up code? i want to speed my code compilation..I have searched the internet and heard that psyco is a very tool to improve the speed.i have searched but could get a site for download. i have installed any additional libraries or modules till date in my python.. can psyco user,tell where we can download the psyco and its installation and using procedures?? i use windows vista and python 2.6 does this work on this ?? A: I suggest to not rely on this tools, anyway psycho is being replaced by the new python implementations as PyPy and unladen swallow. To speed up "for free" you can use Cython and Shedskin. Anyway this is not the right way to speedup the code in my opinion. If you are looking for speed here are some hints: Profiling Profiling Profiling You should use the cProfile module and find the bottlenecks, then proceed with the optimization. If the optimization in python isn't enough, rewrite the relevant parts in Cython and you're ok. A: Psyco does not speed up compilation (in fact, it would slow it down). However, if your problem is compilation speed in Python, there are some serious problems with your code. If you are trying to improve runtime performance, Psyco does work with 32bit operating systems and Python version 2.5. The latest version is the first Google result for Psyco: http://psyco.sourceforge.net/ Psyco is no longer an "interesting" project as Python 3.x has gained Unladen Swallow, and most of the developer attention is divided between that and PyPy. There are other ways of improving performance, not limited to Cython and Shed Skin A: So it seems you don't want to speed up the compile but want to speed up the execution. If that is the case, my mantra is "do less." Save off results and keep them around, don't re-read the same file(s) over and over again. Read a lot of data out of the file at once and work with it. On files specifically, your performance will be pretty miserable if you're reading a little bit of data out of each file and switching between a number of files while doing it. Just read in each file in completion, one at a time, and then work with them. A: Use the appropriate data structures. If you see that you are doing a lot if element in list #or list.index(element) then you might be better off with sets and dictionaries. Don't create a list only to iterate over it, use generators or the itertools module. Read Python Performance Tips As already mentioned, do profiling.
how to speed up code?
i want to speed my code compilation..I have searched the internet and heard that psyco is a very tool to improve the speed.i have searched but could get a site for download. i have installed any additional libraries or modules till date in my python.. can psyco user,tell where we can download the psyco and its installation and using procedures?? i use windows vista and python 2.6 does this work on this ??
[ "I suggest to not rely on this tools, anyway psycho is being replaced by the new python implementations as PyPy and unladen swallow. To speed up \"for free\" you can use Cython and Shedskin. Anyway this is not the right way to speedup the code in my opinion.\nIf you are looking for speed here are some hints:\n\nProfiling\nProfiling\nProfiling\n\nYou should use the cProfile module and find the bottlenecks, then proceed with the optimization.\nIf the optimization in python isn't enough, rewrite the relevant parts in Cython and you're ok.\n", "Psyco does not speed up compilation (in fact, it would slow it down). However, if your problem is compilation speed in Python, there are some serious problems with your code.\nIf you are trying to improve runtime performance, Psyco does work with 32bit operating systems and Python version 2.5. The latest version is the first Google result for Psyco: http://psyco.sourceforge.net/\nPsyco is no longer an \"interesting\" project as Python 3.x has gained Unladen Swallow, and most of the developer attention is divided between that and PyPy.\nThere are other ways of improving performance, not limited to Cython and Shed Skin\n", "So it seems you don't want to speed up the compile but want to speed up the execution.\nIf that is the case, my mantra is \"do less.\" Save off results and keep them around, don't re-read the same file(s) over and over again. Read a lot of data out of the file at once and work with it.\nOn files specifically, your performance will be pretty miserable if you're reading a little bit of data out of each file and switching between a number of files while doing it. Just read in each file in completion, one at a time, and then work with them.\n", "\nUse the appropriate data structures. If you see that you are doing a lot \nif element in list\n#or \nlist.index(element) \n\nthen you might be better off with sets and dictionaries.\nDon't create a list only to iterate over it, use generators or the itertools module.\nRead Python Performance Tips\nAs already mentioned, do profiling.\n\n" ]
[ 11, 3, 2, 2 ]
[]
[]
[ "optimization", "python" ]
stackoverflow_0003007678_optimization_python.txt
Q: downloading full page text from a web domain First time here -- thought I'd field a question on behalf of a coworker. Somebody in my lab is doing a content analysis (e.g. reading an article or transcript line by line and identifying relevant themes) of the web presences of various privatized neuroimaging centers (e.g. http://www.canmagnetic.com/). She's been c/ping entire site maps by hand, and I know I could slap something together with Python to follow links and dump full text (with line numbers) for her, but I've never actually done anything quite like this. Any ideas for how I'd get started? Cheers, -alex A: Here is pretty much everything you need to get started. Read the section "Listing 7. Simple Python Web site crawler". The examples are even written in python. http://www.ibm.com/developerworks/linux/library/l-spider/ Good luck! A: A popular web scraping module for Python is Scrapy. Go ahead and take a look at the tutorial link at the bottom for instance. A: you're looking for "web scraping". you can Google around to find quite a bit of different techniques and utilities such as this one http://www.webscrape.com/ more info http://blogs.computerworld.com/node/324 A: Is it necessary to do it in Python? If not, HTTrack could be the perfect solution for you. This can copy entire sites into a hierarchy of HTML files. If you are looking for a Python solution, try Scrapy. A: You could use wget with the --spider option. A: Last time I had to do something like this, I started something like this: from BeautifulSoup import BeautifulSoup import urllib html = urllib.urlopen("http://www.someurl.com") html = html.read() soup = BeautifulSoup(html) Here is the documentation for Beautiful Soup (http://www.crummy.com/software/BeautifulSoup/documentation.html) and while it may be overkill for your purposes, it is handy to know in my opinion.
downloading full page text from a web domain
First time here -- thought I'd field a question on behalf of a coworker. Somebody in my lab is doing a content analysis (e.g. reading an article or transcript line by line and identifying relevant themes) of the web presences of various privatized neuroimaging centers (e.g. http://www.canmagnetic.com/). She's been c/ping entire site maps by hand, and I know I could slap something together with Python to follow links and dump full text (with line numbers) for her, but I've never actually done anything quite like this. Any ideas for how I'd get started? Cheers, -alex
[ "Here is pretty much everything you need to get started. Read the section \"Listing 7. Simple Python Web site crawler\". The examples are even written in python.\nhttp://www.ibm.com/developerworks/linux/library/l-spider/\nGood luck!\n", "A popular web scraping module for Python is Scrapy. Go ahead and take a look at the tutorial link at the bottom for instance.\n", "you're looking for \"web scraping\". \nyou can Google around to find quite a bit of different techniques and utilities such as this one\nhttp://www.webscrape.com/\nmore info \nhttp://blogs.computerworld.com/node/324\n", "Is it necessary to do it in Python? If not, HTTrack could be the perfect solution for you. This can copy entire sites into a hierarchy of HTML files. If you are looking for a Python solution, try Scrapy.\n", "You could use wget with the --spider option.\n", "Last time I had to do something like this, I started something like this:\nfrom BeautifulSoup import BeautifulSoup\nimport urllib\nhtml = urllib.urlopen(\"http://www.someurl.com\")\nhtml = html.read()\nsoup = BeautifulSoup(html)\n\nHere is the documentation for Beautiful Soup (http://www.crummy.com/software/BeautifulSoup/documentation.html) and while it may be overkill for your purposes, it is handy to know in my opinion.\n" ]
[ 1, 1, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003009253_python.txt
Q: More elegant way to initialize list of duplicated items in Python If I want a list initialized to 5 zeroes, that's very nice and easy: [0] * 5 However if I change my code to put a more complicated data structure, like a list of zeroes: [[0]] * 5 will not work as intended, since it'll be 10 copies of the same list. I have to do: [[0] for i in xrange(5)] that feels bulky and uses a variable so sometimes I even do: [[0] for _ in " "] But then if i want a list of lists of zeros it gets uglier: [[[0] for _ in " "] for _ in " "] all this instead of what I want to do: [[[0]]*5]*5 Has anyone found an elegant way to deal with this "problem"? A: After thinking a bit about it, I came up with this solution: (7 lines without import) # helper def cl(n, func): # return a lambda, that returns a list, where func(tion) is called return (lambda: [func() for _ in range(n)]) def matrix(base, *ns): # the grid lambda (at the start it returns the base-element) grid = lambda: base # traverse reversed, to handle the midmost values first for n in reversed(ns): # assign a new lambda with the last grid within (and call it) grid = cl(n, grid) return grid() # call the full grid (but the matrix calls you ^^) The tests give the following results: >>> from pprint import pprint as pp >>> >>> matrix(None, 2,3) [[None, None, None], [None, None, None]] >>> >>> matrix(None, 4,3) [[None, None, None], [None, None, None], [None, None, None], [None, None, None]] >>> >>> x = matrix(None, 3,5,2) >>> pp(x) [[[None, None], [None, None], [None, None], [None, None], [None, None]], [[None, None], [None, None], [None, None], [None, None], [None, None]], [[None, None], [None, None], [None, None], [None, None], [None, None]]] >>> x[1][3][0] = "test" >>> pp(x) [[[None, None], [None, None], [None, None], [None, None], [None, None]], [[None, None], [None, None], [None, None], ['test', None], [None, None]], [[None, None], [None, None], [None, None], [None, None], [None, None]]] Another solution, which has the advantage of using the "[[[0]]*5]*5"-syntax: def uniq(base, l): # function used to replace all values with the base nl = [] for i in l: if type(i) is list: nl.append(uniq(base, i)) # recursion for deep lists else: nl.append(base) return nl Test: # first arg is the base, the 0 inside the [] is just a dummy # (for what None is the best choice usually) >>> x = uniq(0, [[[0]]*5]*5) >>> x[0][3][0] = 5 >>> pp(x) [[[0], [0], [0], [5], [0]], [[0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0]]] btw. the numpy library has a np.zeros(s)-function, where s is a shape like (3,4,5) >>> s = (2,2) >>> np.zeros(s) array([[ 0., 0.], [ 0., 0.]]) Finally a performance test: # functions are already defined ... import timeit >>> # Alex Martelli's Code >>> t1 = timeit.Timer( lambda: multi_dimension_list(None, 3,4,5) ) >>> # the two mentioned above >>> t2 = timeit.Timer( lambda: matrix(None, 3,4,5) ) >>> t3 = timeit.Timer( lambda: uniq(None, [[[None]*5]*4]*3) ) >>> >>> t1.timeit(10000) 2.1910018920898438 >>> t2.timeit(10000) 0.44953203201293945 >>> t3.timeit(10000) 0.48807907104492188 I found it really interesting to discover this problem. So, thanks for the question :) A: If I had a frequent requirement for lists of lists of lists of ... I'd simply package the building thereof into a small factory function, such as: import copy def multi_dimension_list(baseitem, *dimensions): dimensions = list(dimensions) result = [baseitem] * dimensions.pop(-1) for d in reversed(dimensions): result = [copy.deepcopy(result) for _ in range(d)] return result eg = multi_dimension_list(0, 3, 4, 5) print(eg) # and just to prove the parts are independent...: eg[1][1][1] = 23 print(eg) In practice, I don't even bother, because my uses of multi-dimensional lists of this kind are few and far between, so that inline list comprehensions are just fine. However, the general idea of building up your own module of little utility functions for simple tasks that you do need to perform often and (in your opinion) aren't done elegantly by inline idioms, is really the only way to go!-) A: Another is to extend the list class: import copy class mlist(list): def __mul__(self, n): res = mlist() for _ in xrange(n): for l in self: res.append(copy.deepcopy(l)) return res then: >>> hey = mlist([mlist([0])]) >>> hey [[0]] >>> hey * 4 [[0], [0], [0], [0]] >>> blah = hey * 4 >>> blah[0][0] = 9 >>> blah [[9], [0], [0], [0]] but initializing the mlist is annoying. A: One solution is to have a helper function: import copy def r(i,n): return [copy.deepcopy(i) for _ in xrange(n)] then: r([0],5) r(r([0],5),5) But this syntax is ugly.
More elegant way to initialize list of duplicated items in Python
If I want a list initialized to 5 zeroes, that's very nice and easy: [0] * 5 However if I change my code to put a more complicated data structure, like a list of zeroes: [[0]] * 5 will not work as intended, since it'll be 10 copies of the same list. I have to do: [[0] for i in xrange(5)] that feels bulky and uses a variable so sometimes I even do: [[0] for _ in " "] But then if i want a list of lists of zeros it gets uglier: [[[0] for _ in " "] for _ in " "] all this instead of what I want to do: [[[0]]*5]*5 Has anyone found an elegant way to deal with this "problem"?
[ "After thinking a bit about it, I came up with this solution: (7 lines without import)\n# helper\ndef cl(n, func):\n # return a lambda, that returns a list, where func(tion) is called\n return (lambda: [func() for _ in range(n)])\n\ndef matrix(base, *ns):\n # the grid lambda (at the start it returns the base-element)\n grid = lambda: base\n\n # traverse reversed, to handle the midmost values first\n for n in reversed(ns):\n # assign a new lambda with the last grid within (and call it)\n grid = cl(n, grid)\n\n return grid() # call the full grid (but the matrix calls you ^^)\n\nThe tests give the following results:\n>>> from pprint import pprint as pp\n>>> \n>>> matrix(None, 2,3)\n[[None, None, None], [None, None, None]]\n>>> \n>>> matrix(None, 4,3)\n[[None, None, None], [None, None, None], [None, None, None], [None, None, None]]\n>>> \n>>> x = matrix(None, 3,5,2)\n>>> pp(x)\n[[[None, None], [None, None], [None, None], [None, None], [None, None]],\n [[None, None], [None, None], [None, None], [None, None], [None, None]],\n [[None, None], [None, None], [None, None], [None, None], [None, None]]]\n>>> x[1][3][0] = \"test\"\n>>> pp(x)\n[[[None, None], [None, None], [None, None], [None, None], [None, None]],\n [[None, None], [None, None], [None, None], ['test', None], [None, None]],\n [[None, None], [None, None], [None, None], [None, None], [None, None]]]\n\n\nAnother solution, which has the advantage of using the \"[[[0]]*5]*5\"-syntax:\ndef uniq(base, l):\n # function used to replace all values with the base\n nl = []\n for i in l:\n if type(i) is list:\n nl.append(uniq(base, i)) # recursion for deep lists\n else:\n nl.append(base)\n return nl\n\nTest:\n# first arg is the base, the 0 inside the [] is just a dummy\n# (for what None is the best choice usually)\n>>> x = uniq(0, [[[0]]*5]*5)\n>>> x[0][3][0] = 5\n>>> pp(x)\n[[[0], [0], [0], [5], [0]],\n [[0], [0], [0], [0], [0]],\n [[0], [0], [0], [0], [0]],\n [[0], [0], [0], [0], [0]],\n [[0], [0], [0], [0], [0]]]\n\n\nbtw. the numpy library has a np.zeros(s)-function, where s is a shape like (3,4,5)\n>>> s = (2,2)\n>>> np.zeros(s)\narray([[ 0., 0.],\n [ 0., 0.]])\n\n\nFinally a performance test:\n# functions are already defined ...\nimport timeit\n>>> # Alex Martelli's Code\n>>> t1 = timeit.Timer( lambda: multi_dimension_list(None, 3,4,5) )\n>>> # the two mentioned above\n>>> t2 = timeit.Timer( lambda: matrix(None, 3,4,5) )\n>>> t3 = timeit.Timer( lambda: uniq(None, [[[None]*5]*4]*3) )\n>>> \n>>> t1.timeit(10000)\n2.1910018920898438\n>>> t2.timeit(10000)\n0.44953203201293945\n>>> t3.timeit(10000)\n0.48807907104492188\n\nI found it really interesting to discover this problem. So, thanks for the question :)\n", "If I had a frequent requirement for lists of lists of lists of ... I'd simply package the building thereof into a small factory function, such as:\nimport copy\n\ndef multi_dimension_list(baseitem, *dimensions):\n dimensions = list(dimensions)\n result = [baseitem] * dimensions.pop(-1)\n for d in reversed(dimensions):\n result = [copy.deepcopy(result) for _ in range(d)]\n return result\n\neg = multi_dimension_list(0, 3, 4, 5)\nprint(eg)\n# and just to prove the parts are independent...:\neg[1][1][1] = 23\nprint(eg)\n\nIn practice, I don't even bother, because my uses of multi-dimensional lists of this kind are few and far between, so that inline list comprehensions are just fine. However, the general idea of building up your own module of little utility functions for simple tasks that you do need to perform often and (in your opinion) aren't done elegantly by inline idioms, is really the only way to go!-)\n", "Another is to extend the list class:\nimport copy\nclass mlist(list):\n def __mul__(self, n):\n res = mlist()\n for _ in xrange(n):\n for l in self:\n res.append(copy.deepcopy(l))\n return res\n\nthen:\n>>> hey = mlist([mlist([0])])\n>>> hey\n[[0]]\n>>> hey * 4\n[[0], [0], [0], [0]]\n>>> blah = hey * 4\n>>> blah[0][0] = 9\n>>> blah\n[[9], [0], [0], [0]]\n\nbut initializing the mlist is annoying.\n", "One solution is to have a helper function:\nimport copy\ndef r(i,n):\n return [copy.deepcopy(i) for _ in xrange(n)]\n\nthen:\nr([0],5)\nr(r([0],5),5)\n\nBut this syntax is ugly.\n" ]
[ 9, 5, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003009091_python.txt
Q: Use Python to search one .txt file for a list of words or phrases (and show the context) Basically as the question states. I am fairly new to Python and like to learn by seeing and doing. I would like to create a script that searches through a text document (say the text copied and pasted from a news article for example) for certain words or phrases. Ideally, the list of words and phrases would be stored in a separate file. When getting the results, it would be great to get the context of the results. So maybe it could print out the 50 characters in the text file before and after each search term that has been found. It'd be cool if it also showed what line the search term was found on. Any pointers on how to code this, or even code examples would be much appreciated. A: Despite the frequently expressed antipathy for Regular Expressions on the part of many in the Python community, they're really a precious tool for the appropriate use cases -- which definitely include identifying words and phrases (thanks to the \b "word boundary" element in regular expression patterns -- string-processing based alternatives are much more of a problem, e.g., .split() uses whitespace as the separator and thus annoyingly leave punctuation attached to words adjacent to it, etc, etc). If RE's are OK, I would recommend something like: import re import sys def main(): if len(sys.argv) != 3: print("Usage: %s fileofstufftofind filetofinditin" % sys.argv[0]) sys.exit(1) with open(sys.argv[1]) as f: patterns = [r'\b%s\b' % re.escape(s.strip()) for s in f] there = re.compile('|'.join(patterns)) with open(sys.argv[2]) as f: for i, s in enumerate(f): if there.search(s): print("Line %s: %r" % (i, s)) main() the first argument being (the path of) a text file with words or phrases to find, one per line, and the second argument (the path of) a text file in which to find them. It's easy, if desired, to make the case search-insensitive (perhaps just optionally based on a command line option switch), etc, etc. Some explanation for readers that are not familiar with REs...: The \b item in the patterns items ensures that there will be no accidental matches (if you're searching for "cat" or "dog", you won't see an accidental hit with "catalog" or "underdog"; and you won't miss a hit in "The cat, smiling, ran away" by some splitting thinking that the word there is "cat," including the comma;-). The | item means or, so e.g. from a text file with contents (two lines) cat dog this will form the pattern '\bcat\b|\bdog\b' which will locate either "cat" or "dog" (as stand-alone words, ignoring punctuation, but rejecting hits within longer words). The re.escape escapes punctuation so it's matched literally, not with special meaning as it would normally have in a RE pattern. A: Start with something like this. This code is not an exact solution for the specification you have, but it is a good starting point. import sys words = "foo bar baz frob" word_set = set(words.split()) for line_number, line in enumerate(open(sys.argv[1])): if words_set.intersection(line.split()): print "%d:%s" % (line_number, line.strip()) Some explanations below: The words being sought are stored in a string initially (in line 3). I split this wordlist along whitespaces and create a set out of it so it is easier to check whether any of the words in the current line are to be found in the wordlist. (Membership check on a set is O(1), while it is O(n) on a list). In the main for loop, I open the input file (which is passed as a command line argument) and use the enumerate built-in method to get a line number counter as well as the actual line. sys.argv is an array storing the command line arguments; sys.argv[0] is always the name of the Python script. In the loop itself, I take the current line, split it to individual words and create a set out of the words again. Then I can quickly take the intersection of the wordset in the current line with the set of words I am looking for. If the intersection has a logical True value (i.e. if it is not empty), I print the line number as well as the line. Things that are not solved yet (and left up to you): The list of words are now hard-coded in the source, but it should not be too hard to open an extra file (whose name is passed in, say, sys.argv[2]), read its words one by one and store them in a set. Note that you can extend sets by their add and update methods (instead of append and extend which work for lists). Obviously the above method does not work if you have phrases instead of words (as pointed out in one of the comments). As I assume that you want to learn and you don't need an exact solution, I will only say that if you have phrases in a set, you can check whether any of the set elements is in a line by saying any(phrase in line for phrase in set_of_phrases). This can be used in place of the set intersection (and of course don't split your line into words in this case). If you want to print the context of the hits, you can use two extra variables (say, prev_line and next_line) that stores the previous line and the next line. In the for loop, you will actually be reading next_line instead of line, and at the end of the for loop, you should take care of copying line into prev_line and next_line into line. An even more Pythonic way of keeping track of the previous and the next line as well is to create a Python generator function that yields a tuple consisting of item i-1, item i and item i+1 for each i given an iterable (like a file). This is more advanced stuff, though, and as you are fairly new to Python, I think it's best to leave it for later. However, if you are curious, a generator function doing this task might look like this: def context_generator(iterable): prev, current, next = None, None, None for element in iterable: prev, current, next = current, next, element if current is not None: yield prev, current, next if next is not None: yield current, next, None
Use Python to search one .txt file for a list of words or phrases (and show the context)
Basically as the question states. I am fairly new to Python and like to learn by seeing and doing. I would like to create a script that searches through a text document (say the text copied and pasted from a news article for example) for certain words or phrases. Ideally, the list of words and phrases would be stored in a separate file. When getting the results, it would be great to get the context of the results. So maybe it could print out the 50 characters in the text file before and after each search term that has been found. It'd be cool if it also showed what line the search term was found on. Any pointers on how to code this, or even code examples would be much appreciated.
[ "Despite the frequently expressed antipathy for Regular Expressions on the part of many in the Python community, they're really a precious tool for the appropriate use cases -- which definitely include identifying words and phrases (thanks to the \\b \"word boundary\" element in regular expression patterns -- string-processing based alternatives are much more of a problem, e.g., .split() uses whitespace as the separator and thus annoyingly leave punctuation attached to words adjacent to it, etc, etc).\nIf RE's are OK, I would recommend something like:\nimport re\nimport sys\n\ndef main():\n if len(sys.argv) != 3:\n print(\"Usage: %s fileofstufftofind filetofinditin\" % sys.argv[0])\n sys.exit(1)\n\n with open(sys.argv[1]) as f:\n patterns = [r'\\b%s\\b' % re.escape(s.strip()) for s in f]\n there = re.compile('|'.join(patterns))\n\n with open(sys.argv[2]) as f:\n for i, s in enumerate(f):\n if there.search(s):\n print(\"Line %s: %r\" % (i, s))\n\nmain()\n\nthe first argument being (the path of) a text file with words or phrases to find, one per line, and the second argument (the path of) a text file in which to find them. It's easy, if desired, to make the case search-insensitive (perhaps just optionally based on a command line option switch), etc, etc.\nSome explanation for readers that are not familiar with REs...:\nThe \\b item in the patterns items ensures that there will be no accidental matches (if you're searching for \"cat\" or \"dog\", you won't see an accidental hit with \"catalog\" or \"underdog\"; and you won't miss a hit in \"The cat, smiling, ran away\" by some splitting thinking that the word there is \"cat,\" including the comma;-).\nThe | item means or, so e.g. from a text file with contents (two lines)\ncat\ndog\n\nthis will form the pattern '\\bcat\\b|\\bdog\\b' which will locate either \"cat\" or \"dog\" (as stand-alone words, ignoring punctuation, but rejecting hits within longer words).\nThe re.escape escapes punctuation so it's matched literally, not with special meaning as it would normally have in a RE pattern.\n", "Start with something like this. This code is not an exact solution for the specification you have, but it is a good starting point.\nimport sys\n\nwords = \"foo bar baz frob\"\n\nword_set = set(words.split())\nfor line_number, line in enumerate(open(sys.argv[1])):\n if words_set.intersection(line.split()):\n print \"%d:%s\" % (line_number, line.strip())\n\nSome explanations below:\n\nThe words being sought are stored in a string initially (in line 3). I split this wordlist along whitespaces and create a set out of it so it is easier to check whether any of the words in the current line are to be found in the wordlist. (Membership check on a set is O(1), while it is O(n) on a list).\nIn the main for loop, I open the input file (which is passed as a command line argument) and use the enumerate built-in method to get a line number counter as well as the actual line. sys.argv is an array storing the command line arguments; sys.argv[0] is always the name of the Python script.\nIn the loop itself, I take the current line, split it to individual words and create a set out of the words again. Then I can quickly take the intersection of the wordset in the current line with the set of words I am looking for. If the intersection has a logical True value (i.e. if it is not empty), I print the line number as well as the line.\n\nThings that are not solved yet (and left up to you):\n\nThe list of words are now hard-coded in the source, but it should not be too hard to open an extra file (whose name is passed in, say, sys.argv[2]), read its words one by one and store them in a set. Note that you can extend sets by their add and update methods (instead of append and extend which work for lists).\nObviously the above method does not work if you have phrases instead of words (as pointed out in one of the comments). As I assume that you want to learn and you don't need an exact solution, I will only say that if you have phrases in a set, you can check whether any of the set elements is in a line by saying any(phrase in line for phrase in set_of_phrases). This can be used in place of the set intersection (and of course don't split your line into words in this case).\nIf you want to print the context of the hits, you can use two extra variables (say, prev_line and next_line) that stores the previous line and the next line. In the for loop, you will actually be reading next_line instead of line, and at the end of the for loop, you should take care of copying line into prev_line and next_line into line.\nAn even more Pythonic way of keeping track of the previous and the next line as well is to create a Python generator function that yields a tuple consisting of item i-1, item i and item i+1 for each i given an iterable (like a file). This is more advanced stuff, though, and as you are fairly new to Python, I think it's best to leave it for later. However, if you are curious, a generator function doing this task might look like this:\ndef context_generator(iterable):\n prev, current, next = None, None, None\n for element in iterable:\n prev, current, next = current, next, element\n if current is not None:\n yield prev, current, next\n if next is not None:\n yield current, next, None\n\n\n" ]
[ 7, 3 ]
[]
[]
[ "python", "search", "text" ]
stackoverflow_0003007889_python_search_text.txt
Q: Compute the total RAM used by Python dict or list My problem: I am writing a simple Python tool to help me visualize my data as a function of many parameters. Each change in parameters involves a non-trivial amount of time, so I would like to cache each step's resulting imagery and supporting data in a dictionary. But then I worry that this dictionary could grow too large over time. Most of my data is in the form of Numpy arrays. My question: How would one go about computing the total number of bytes used by a Python dictionary. The dictionary itself may contain lists and other dictionaries, each of which contain data stored in Numpy arrays. Ideas? A: Use a memory profiler such as PySizer or Heapy.
Compute the total RAM used by Python dict or list
My problem: I am writing a simple Python tool to help me visualize my data as a function of many parameters. Each change in parameters involves a non-trivial amount of time, so I would like to cache each step's resulting imagery and supporting data in a dictionary. But then I worry that this dictionary could grow too large over time. Most of my data is in the form of Numpy arrays. My question: How would one go about computing the total number of bytes used by a Python dictionary. The dictionary itself may contain lists and other dictionaries, each of which contain data stored in Numpy arrays. Ideas?
[ "Use a memory profiler such as PySizer or Heapy.\n" ]
[ 3 ]
[]
[]
[ "dictionary", "memory", "python" ]
stackoverflow_0003009686_dictionary_memory_python.txt
Q: Boost.Python tutorial in Ubuntu 10.04 I downloaded the latest version of Boost and I'm trying to get the Boost.python tutorial up and running on Ubuntu 10.04: http://www.boost.org/doc/libs/1_43_0/libs/python/doc/tutorial/doc/html/python/hello.html I navigated to the correct directory, ran "bjam" and it compiled using default settings. I did not yet create a bjam config file. The compilation appears to have worked, but now I have no idea how to include the files in my python script. When I try to run the python hello world script, it gives me this error: Traceback (most recent call last): File "./hello.py", line 6, in <module> import hello_ext ImportError: libboost_python.so.1.43.0: cannot open shared object file: No such file or directory Anyone know what is going on? A: How did you install boost ? Assuming you have use the following: http://www.boost.org/doc/libs/1_43_0/more/getting_started/unix-variants.html#easy-build-and-install liboost_python shard library will be install in /usr/local/lib To run the hello.py example, try the following: LD_LIBRARY_PATH=/usr/local/lib python ./hello.py A: I have no experience with the the Boost Python libraries but as the error states, it is unable to find the libboost_python shared object. You have several options here (there may be more): Place the .so in /usr/local/lib. Place the .so in /usr/lib. This is probably a bad idea. Run export LD_LIBRARY_PATH=/path_to_so/ before execution. A: Did you install boost? Just compiling it isn't sufficient to install the libraries where they need to be to run programs.
Boost.Python tutorial in Ubuntu 10.04
I downloaded the latest version of Boost and I'm trying to get the Boost.python tutorial up and running on Ubuntu 10.04: http://www.boost.org/doc/libs/1_43_0/libs/python/doc/tutorial/doc/html/python/hello.html I navigated to the correct directory, ran "bjam" and it compiled using default settings. I did not yet create a bjam config file. The compilation appears to have worked, but now I have no idea how to include the files in my python script. When I try to run the python hello world script, it gives me this error: Traceback (most recent call last): File "./hello.py", line 6, in <module> import hello_ext ImportError: libboost_python.so.1.43.0: cannot open shared object file: No such file or directory Anyone know what is going on?
[ "How did you install boost ?\nAssuming you have use the following: http://www.boost.org/doc/libs/1_43_0/more/getting_started/unix-variants.html#easy-build-and-install\nliboost_python shard library will be install in /usr/local/lib\nTo run the hello.py example, try the following:\nLD_LIBRARY_PATH=/usr/local/lib python ./hello.py\n\n", "I have no experience with the the Boost Python libraries but as the error states, it is unable to find the libboost_python shared object.\nYou have several options here (there may be more):\n\nPlace the .so in /usr/local/lib.\nPlace the .so in /usr/lib. This is probably a bad idea.\nRun export LD_LIBRARY_PATH=/path_to_so/ before execution.\n\n", "Did you install boost? Just compiling it isn't sufficient to install the libraries where they need to be to run programs. \n" ]
[ 5, 2, 0 ]
[]
[]
[ "boost_python", "c++", "python" ]
stackoverflow_0003009533_boost_python_c++_python.txt
Q: PyGTK: how to make a clipboard monitor? How can I make a simple clipboard monitor in Python using the PyGTK GUI? I found gtk.clipboard class and but I couldn't find any solution to get the "signals" to trigger the event when the clipboard content has changed. Any ideas? A: Without a proper notification API, such as WM_DrawClipboard messages, you would probably have to resort to a polling loop. And then you will cause major conflicts with other apps that are trying to use this shared resource. Do not resort to a polling loop.
PyGTK: how to make a clipboard monitor?
How can I make a simple clipboard monitor in Python using the PyGTK GUI? I found gtk.clipboard class and but I couldn't find any solution to get the "signals" to trigger the event when the clipboard content has changed. Any ideas?
[ "Without a proper notification API, such as WM_DrawClipboard messages, you would probably have to resort to a polling loop. And then you will cause major conflicts with other apps that are trying to use this shared resource.\nDo not resort to a polling loop. \n" ]
[ 4 ]
[]
[]
[ "clipboard", "monitor", "pygtk", "python" ]
stackoverflow_0003005522_clipboard_monitor_pygtk_python.txt
Q: Django dictionary in templates: Grab key from another objects attribute I have a dictionary called number_devices I'm passing to a template, the dictionary keys are the ids of a list of objects I'm also passing to the template (called implementations). I'm iterating over the list of objects and then trying to use the object.id to get a value out of the dict like so: {% for implementation in implementations %} {{ number_devices.implementation.id }} {% endfor %} Unfortunately number_devices.implementation is evaluated first, then the result.id is evaluated obviously returning and displaying nothing. I can't use parentheses like: {{ number_devices.(implementation.id) }} because I get a parse error. How do I get around this annoyance in Django templates? Thanks for any help! A: A workaround could be using the keys from number_devices and check in the for loop if it is equal to the key provided by number_devices. {% for key in number_devices.keys %} {% for implementation in implementations %} {% ifequal key implementation.id %} you got it {% endifequal %} {% endfor %} {% endfor %} Seems a bit ugly, but should work.
Django dictionary in templates: Grab key from another objects attribute
I have a dictionary called number_devices I'm passing to a template, the dictionary keys are the ids of a list of objects I'm also passing to the template (called implementations). I'm iterating over the list of objects and then trying to use the object.id to get a value out of the dict like so: {% for implementation in implementations %} {{ number_devices.implementation.id }} {% endfor %} Unfortunately number_devices.implementation is evaluated first, then the result.id is evaluated obviously returning and displaying nothing. I can't use parentheses like: {{ number_devices.(implementation.id) }} because I get a parse error. How do I get around this annoyance in Django templates? Thanks for any help!
[ "A workaround could be using the keys from number_devices and check in the for loop if it is equal to the key provided by number_devices.\n{% for key in number_devices.keys %}\n {% for implementation in implementations %}\n {% ifequal key implementation.id %} you got it {% endifequal %}\n {% endfor %}\n{% endfor %}\n\nSeems a bit ugly, but should work.\n" ]
[ 1 ]
[]
[]
[ "dictionary", "django", "python", "templates" ]
stackoverflow_0003009760_dictionary_django_python_templates.txt
Q: Parameters with braces in python If you look at the following line of python code: bpy.ops.object.particle_system_add({"object":bpy.data.objects[2]}) you see that in the parameters there is something enclosed in braces. Can anyone tell me what the braces are for (generically anyway)? I haven't really seen this type of syntax in python and I can't find any documentation on it. Any help is greatly appreciated. Thank you. A: From the docs: Dictionaries can be created by placing a comma-separated list of key: value pairs within braces, for example: {'jack': 4098, 'sjoerd': 4127} or {4098: 'jack', 4127: 'sjoerd'}, or by the dict constructor. A: The braces create a dictionary. particle_system_add seems to be accepting a dictionary as its argument. A: It's a dictionary. A: It's just a dictionary with a single key/value pair of "object" as the key and whatever bpy.data.objects[2] evaluates to as the value.
Parameters with braces in python
If you look at the following line of python code: bpy.ops.object.particle_system_add({"object":bpy.data.objects[2]}) you see that in the parameters there is something enclosed in braces. Can anyone tell me what the braces are for (generically anyway)? I haven't really seen this type of syntax in python and I can't find any documentation on it. Any help is greatly appreciated. Thank you.
[ "From the docs:\n\nDictionaries can be created by placing a comma-separated list of key: value pairs within braces, for example: {'jack': 4098, 'sjoerd': 4127} or {4098: 'jack', 4127: 'sjoerd'}, or by the dict constructor.\n\n", "The braces create a dictionary. particle_system_add seems to be accepting a dictionary as its argument.\n", "It's a dictionary.\n", "It's just a dictionary with a single key/value pair of \"object\" as the key and whatever bpy.data.objects[2] evaluates to as the value. \n" ]
[ 6, 2, 2, 1 ]
[]
[]
[ "curly_braces", "parameters", "python", "python_3.x" ]
stackoverflow_0003010225_curly_braces_parameters_python_python_3.x.txt
Q: ldapsearch and vcard creation I'm using openldap on Mac OS X Server 10.6 and need to generate a vcard for all the users in a given group. By using the ldapsearch I can list all the memberUid's for all users in that group. I found a perl script (Advanced LDAP Search or ALS) that was written by someone that will generate the vcard easily. ALS can be found here http://www.ldapman.org/tools/als.gz So what I need to do is create a wrapper script (in python or perl) that will effectively loop through the memberUid's and run the ALS command to create the vcard and append it to the file. This command provides the memberUid's: ldapsearch -x -b 'dc=ldap,dc=server,dc=com' '(cn=testgroup)' Then running ALS gives the vcard: als -b dc=ldap,dc=server,dc=com -V uid=aaronh > vcardlist.vcf If it's easier to do this using Perl since ALS is already using it that would be fine. I've done more work in python but I'm open to suggestions. Thanks in advance, Aaron EDIT: Here is a link to the Net:LDAP code that I have to date. So far it pulls down the ldap entries with all user information. What I'm missing is how to capture just the UID for each user and then push it into ALS. http://www.queencitytech.com/net-ldap Here is an example entry (after running the code from the above link): #------------------------------- DN: uid=aaronh,cn=users,dc=ldap,dc=server,dc=com altSecurityIdentities : Kerberos:aaronh@LDAP.SERVER.COM apple-generateduid : F0F9DA73-70B3-47EB-BD25-FE4139E16942 apple-imhandle : Jabber:aaronh@ichat.server.com apple-mcxflags : <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>simultaneous_login_enabled</key> <true/> </dict> </plist> authAuthority : ;ApplePasswordServer;0x4c11231147c72b59000001f800001663,1024 35 131057002239213764263627099108547501925287731311742942286788930775556419648865483768960345576253082450228562208107642206135992876630494830143899597135936566841409094870100055573569425410665510365545238751677692308677943427807426637133913499488233527734757673201849965347880843479632671824597968768822920700439 root@ldap.server.com:192.168.1.175;Kerberosv5;0x4c11231147c72b59000001f800001663;aaronh@LDAP.SERVER.COM;LDAP.SERVER.COM;1024 35 131057002239213764263627099108547501925287731311742942286788930775556419648865483768960345576253082450228562208107642206135992876630494830143899597135936566841409094870100055573569425410665510365545238751677692308677943427807426637133913499488233527734757673201849965347880843479632671824597968768822920700439 root@ldap.server.com:192.168.1.170 cn : Aaron Hoffman gidNumber : 20 givenName : Aaron homeDirectory : 99 loginShell : /bin/bash objectClass : inetOrgPersonposixAccountshadowAccountapple-userextensibleObjectorganizationalPersontopperson sn : Hoffman uid : aaronh uidNumber : 2643 userPassword : ******** #------------------------------- A: My language of choice would be Perl - but only because I've done similar operations using Perl and LDAP. If I remember correctly, that ldapsearch command will give you the full LDIF entry for each uid in the testgroup cn. If that's the case, then you'll need to clean it up a bit before it's ready for the als part. Though it's definitely not the most elegant solution, a quick and dirty method is to use backticks and run the command's output through a grep. This will return a nice list of all the memberUids. From there it's just a simple foreach loop and you're done. Without any testing or knowing for sure what your LDAP output looks like, I'd go with something like this: #!/usr/bin/perl # should return a list of "memberUid: name" entries @uids = `ldapsearch -x -b 'cn=testgroup,cn=groups,dc=ldap,dc=server,dc=com' | grep memberUid:`; foreach (@uids) { $_ =~ s/memberUid: //; # get rid of the "uid: " part, leaving just the name chomp $_; # get rid of the pesky newline system "als -b \"dc=ldap,dc=server,dc=com\" -V uid=$_ >> vcardlist.vcf"; } As I said, I haven't tested this, and I'm not exactly sure what the output of your ldapsearch looks like, so you may have to tweak it a bit to fit your exact needs. That should be enough to get you going though. If anyone has a better idea I'd love to hear it too.
ldapsearch and vcard creation
I'm using openldap on Mac OS X Server 10.6 and need to generate a vcard for all the users in a given group. By using the ldapsearch I can list all the memberUid's for all users in that group. I found a perl script (Advanced LDAP Search or ALS) that was written by someone that will generate the vcard easily. ALS can be found here http://www.ldapman.org/tools/als.gz So what I need to do is create a wrapper script (in python or perl) that will effectively loop through the memberUid's and run the ALS command to create the vcard and append it to the file. This command provides the memberUid's: ldapsearch -x -b 'dc=ldap,dc=server,dc=com' '(cn=testgroup)' Then running ALS gives the vcard: als -b dc=ldap,dc=server,dc=com -V uid=aaronh > vcardlist.vcf If it's easier to do this using Perl since ALS is already using it that would be fine. I've done more work in python but I'm open to suggestions. Thanks in advance, Aaron EDIT: Here is a link to the Net:LDAP code that I have to date. So far it pulls down the ldap entries with all user information. What I'm missing is how to capture just the UID for each user and then push it into ALS. http://www.queencitytech.com/net-ldap Here is an example entry (after running the code from the above link): #------------------------------- DN: uid=aaronh,cn=users,dc=ldap,dc=server,dc=com altSecurityIdentities : Kerberos:aaronh@LDAP.SERVER.COM apple-generateduid : F0F9DA73-70B3-47EB-BD25-FE4139E16942 apple-imhandle : Jabber:aaronh@ichat.server.com apple-mcxflags : <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>simultaneous_login_enabled</key> <true/> </dict> </plist> authAuthority : ;ApplePasswordServer;0x4c11231147c72b59000001f800001663,1024 35 131057002239213764263627099108547501925287731311742942286788930775556419648865483768960345576253082450228562208107642206135992876630494830143899597135936566841409094870100055573569425410665510365545238751677692308677943427807426637133913499488233527734757673201849965347880843479632671824597968768822920700439 root@ldap.server.com:192.168.1.175;Kerberosv5;0x4c11231147c72b59000001f800001663;aaronh@LDAP.SERVER.COM;LDAP.SERVER.COM;1024 35 131057002239213764263627099108547501925287731311742942286788930775556419648865483768960345576253082450228562208107642206135992876630494830143899597135936566841409094870100055573569425410665510365545238751677692308677943427807426637133913499488233527734757673201849965347880843479632671824597968768822920700439 root@ldap.server.com:192.168.1.170 cn : Aaron Hoffman gidNumber : 20 givenName : Aaron homeDirectory : 99 loginShell : /bin/bash objectClass : inetOrgPersonposixAccountshadowAccountapple-userextensibleObjectorganizationalPersontopperson sn : Hoffman uid : aaronh uidNumber : 2643 userPassword : ******** #-------------------------------
[ "My language of choice would be Perl - but only because I've done similar operations using Perl and LDAP.\nIf I remember correctly, that ldapsearch command will give you the full LDIF entry for each uid in the testgroup cn. If that's the case, then you'll need to clean it up a bit before it's ready for the als part. Though it's definitely not the most elegant solution, a quick and dirty method is to use backticks and run the command's output through a grep. This will return a nice list of all the memberUids. From there it's just a simple foreach loop and you're done. Without any testing or knowing for sure what your LDAP output looks like, I'd go with something like this:\n#!/usr/bin/perl\n\n# should return a list of \"memberUid: name\" entries\n@uids = `ldapsearch -x -b 'cn=testgroup,cn=groups,dc=ldap,dc=server,dc=com' | grep memberUid:`;\n\nforeach (@uids) {\n $_ =~ s/memberUid: //; # get rid of the \"uid: \" part, leaving just the name\n chomp $_; # get rid of the pesky newline\n system \"als -b \\\"dc=ldap,dc=server,dc=com\\\" -V uid=$_ >> vcardlist.vcf\";\n}\n\nAs I said, I haven't tested this, and I'm not exactly sure what the output of your ldapsearch looks like, so you may have to tweak it a bit to fit your exact needs. That should be enough to get you going though.\nIf anyone has a better idea I'd love to hear it too.\n" ]
[ 1 ]
[]
[]
[ "ldap", "perl", "python" ]
stackoverflow_0003007739_ldap_perl_python.txt
Q: Selecting dictionary items by key efficiently in Python suppose I have a dictionary whose keys are strings. How can I efficiently make a new dictionary from that which contains only the keys present in some list? for example: # a dictionary mapping strings to stuff mydict = {'quux': ..., 'bar': ..., 'foo': ...} # list of keys to be selected from mydict keys_to_select = ['foo', 'bar', ...] The way I came up with is: filtered_mydict = [mydict[k] for k in mydict.keys() \ if k in keys_to_select] but I think this is highly inefficient because: (1) it requires enumerating the keys with keys(), (2) it requires looking up k in keys_to_select each time. at least one of these can be avoided, I would think. any ideas? I can use scipy/numpy too if needed. A: dict((k, mydict[k]) for k in keys_to_select) if you know all the keys to select are also keys in mydict; if that's not the case, dict((k, mydict[k]) for k in keys_to_select if k in mydict)
Selecting dictionary items by key efficiently in Python
suppose I have a dictionary whose keys are strings. How can I efficiently make a new dictionary from that which contains only the keys present in some list? for example: # a dictionary mapping strings to stuff mydict = {'quux': ..., 'bar': ..., 'foo': ...} # list of keys to be selected from mydict keys_to_select = ['foo', 'bar', ...] The way I came up with is: filtered_mydict = [mydict[k] for k in mydict.keys() \ if k in keys_to_select] but I think this is highly inefficient because: (1) it requires enumerating the keys with keys(), (2) it requires looking up k in keys_to_select each time. at least one of these can be avoided, I would think. any ideas? I can use scipy/numpy too if needed.
[ "dict((k, mydict[k]) for k in keys_to_select)\n\nif you know all the keys to select are also keys in mydict; if that's not the case,\ndict((k, mydict[k]) for k in keys_to_select if k in mydict)\n\n" ]
[ 15 ]
[]
[]
[ "numpy", "python", "scipy" ]
stackoverflow_0003010326_numpy_python_scipy.txt
Q: In Django, how do I filter where language column = "null"? MyTable.objects.filter(where language column = null) How can that be done? Thanks. A: MyTable.objects.filter(language__isnull=True) Link to documentation.
In Django, how do I filter where language column = "null"?
MyTable.objects.filter(where language column = null) How can that be done? Thanks.
[ "MyTable.objects.filter(language__isnull=True)\n\nLink to documentation.\n" ]
[ 3 ]
[]
[]
[ "database", "django", "mysql", "python" ]
stackoverflow_0003010492_database_django_mysql_python.txt
Q: Efficient way to store tuples in the datastore If I have a pair of floats, is it any more efficient (computationally or storage-wise) to store them as a GeoPtProperty than it would be pickle the tuple and store it as a BlobProperty? If GeoPt is doing something more clever to keep multiple values in a single property, can it be leveraged for arbitrary data? Can I store the tuple ("Johnny", 5) in a single entity property in a similarly efficient manner? A: Here are some empirical answers: GeoPtProperty uses 31B of storage space. Using BlobProperty varies based on what exactly you store: struct.pack('>2f', lat, lon) => 21B. Using pickle (v2) to packe a 2-tuple containing floats => 37B. Using pickle (v0) to packe a 2-tuple containing floats => about 30B-32B (v0 uses a variable-length ascii encoding for floats). In short, it doesn't look like GeoPt is doing anything particularly clever. If you are going to be storing a lot of these, then you could use struct to pack your floats. Packing and unpacking them with struct will probably be unnoticeably different from the CPU cost associated with serializing/deserializing GeoPt. If you plan on storing lots of floats per entity and space is really important, then you might consider leveraging the CompressedBlobProperty in aetycoon. Disclaimer: This is the minimum space required. Actual space will be slightly larger per property based on the length of the property's name. The model itself also adds overhead (for its name and key). A: GeoPt itself is limited to (-90 - 90, -180 - 180); it can't be used to store any data that won't fit this model. However, a custom tuple property shouldn't be too difficult to create yourself; take a look at how SetProperty and ArrayProperty are designed in aetycoon.
Efficient way to store tuples in the datastore
If I have a pair of floats, is it any more efficient (computationally or storage-wise) to store them as a GeoPtProperty than it would be pickle the tuple and store it as a BlobProperty? If GeoPt is doing something more clever to keep multiple values in a single property, can it be leveraged for arbitrary data? Can I store the tuple ("Johnny", 5) in a single entity property in a similarly efficient manner?
[ "Here are some empirical answers:\nGeoPtProperty uses 31B of storage space.\nUsing BlobProperty varies based on what exactly you store:\n\nstruct.pack('>2f', lat, lon) => 21B.\nUsing pickle (v2) to packe a 2-tuple containing floats => 37B.\nUsing pickle (v0) to packe a 2-tuple containing floats => about 30B-32B (v0 uses a variable-length ascii encoding for floats).\n\nIn short, it doesn't look like GeoPt is doing anything particularly clever. If you are going to be storing a lot of these, then you could use struct to pack your floats. Packing and unpacking them with struct will probably be unnoticeably different from the CPU cost associated with serializing/deserializing GeoPt.\nIf you plan on storing lots of floats per entity and space is really important, then you might consider leveraging the CompressedBlobProperty in aetycoon.\nDisclaimer: This is the minimum space required. Actual space will be slightly larger per property based on the length of the property's name. The model itself also adds overhead (for its name and key).\n", "GeoPt itself is limited to (-90 - 90, -180 - 180); it can't be used to store any data that won't fit this model. \nHowever, a custom tuple property shouldn't be too difficult to create yourself; take a look at how SetProperty and ArrayProperty are designed in aetycoon.\n" ]
[ 3, 0 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0003010375_google_app_engine_google_cloud_datastore_python.txt
Q: Can you dynamically combine multiple conditional functions into one in Python? I'm curious if it's possible to take several conditional functions and create one function that checks them all (e.g. the way a generator takes a procedure for iterating through a series and creates an iterator). The basic usage case would be when you have a large number of conditional parameters (e.g. "max_a", "min_a", "max_b", "min_b", etc.), many of which could be blank. They would all be passed to this "function creating" function, which would then return one function that checked them all. Below is an example of a naive way of doing what I'm asking: def combining_function(max_a, min_a, max_b, min_b, ...): f_array = [] if max_a is not None: f_array.append( lambda x: x.a < max_a ) if min_a is not None: f_array.append( lambda x: x.a > min_a ) ... return lambda x: all( [ f(x) for f in f_array ] ) What I'm wondering is what is the most efficient to achieve what's being done above? It seems like executing a function call for every function in f_array would create a decent amount of overhead, but perhaps I'm engaging in premature/unnecessary optimization. Regardless, I'd be interested to see if anyone else has come across usage cases like this and how they proceeded. Also, if this isn't possible in Python, is it possible in other (perhaps more functional) languages? EDIT: It looks like the consensus solution is to compose a string containing the full collection of conditions and then use exec or eval to generate a single function. @doublep suggests this is pretty hackish. Any thoughts on how bad this is? Is it plausible to check the arguments closely enough when composing the function that a solution like this could be considered safe? After all, whatever rigorous checking is required only needs to be performed once whereas the benefit from a faster combined conditional can be accrued over a large number of calls. Are people using stuff like this in deployment scenarios or is this mainly a technique to play around with? A: Based on your example, if your list of possible parameters is just a sequence of max,min,max,min,max,min,... then here's an easy way to do it: def combining_function(*args): maxs, mins = zip(*zip(*[iter(args)]*2)) minv = max(m for m in mins if m is not None) maxv = min(m for m in maxs if m is not None) return lambda x: minv < x.a < maxv But this kind of "cheats" a bit: it precomputes the smallest maximum value and the largest minimum value. If your tests can be something more complicated than just max/min testing, the code will need to be modified. A: Replacing return lambda x: all( [ f(x) for f in f_array ] ) with return lambda x: all( f(x) for f in f_array ) will give a more efficient lambda as it will stop early if any f returns a false value and doesn't need to create unnecessary list. This is only possible on Python 2.4 or 2.5 and up, though. If you need to support ancient values, do the following: def check (x): for f in f_array: if not f (x): return False return True return check Finally, if you really need to make this very efficient and are not afraid of bounding-on-hackish solutions, you could try compilation at runtime: def combining_function (max_a, min_a): constants = { } checks = [] if max_a is not None: constants['max_a'] = max_a checks.append ('x.a < max_a') if min_a is not None: constants['min_a'] = min_a checks.append ('x.a > min_a') if not checks: return lambda x: True else: func = 'def check (x): return (%s)' % ') and ('.join (checks) exec func in constants, constants return constants['check'] class X: def __init__(self, a): self.a = a check = combining_function (3, 1) print check (X (0)), check (X (2)), check (X (4)) Note that in Python 3.x exec becomes a function, so the above code is not portable. A: The combining_function() interface is horrible, but if you can't change it then you could use: def combining_function(min_a, max_a, min_b, max_b): conditions = [] for name, value in locals().items(): if value is None: continue kind, sep, attr = name.partition("_") op = {"min": ">", "max": "<"}.get(kind, None) if op is None: continue conditions.append("x.%(attr)s %(op)s %(value)r" % dict( attr=attr, op=op, value=value)) if conditions: return eval("lambda x: " + " and ".join(conditions), {}) else: return lambda x: True
Can you dynamically combine multiple conditional functions into one in Python?
I'm curious if it's possible to take several conditional functions and create one function that checks them all (e.g. the way a generator takes a procedure for iterating through a series and creates an iterator). The basic usage case would be when you have a large number of conditional parameters (e.g. "max_a", "min_a", "max_b", "min_b", etc.), many of which could be blank. They would all be passed to this "function creating" function, which would then return one function that checked them all. Below is an example of a naive way of doing what I'm asking: def combining_function(max_a, min_a, max_b, min_b, ...): f_array = [] if max_a is not None: f_array.append( lambda x: x.a < max_a ) if min_a is not None: f_array.append( lambda x: x.a > min_a ) ... return lambda x: all( [ f(x) for f in f_array ] ) What I'm wondering is what is the most efficient to achieve what's being done above? It seems like executing a function call for every function in f_array would create a decent amount of overhead, but perhaps I'm engaging in premature/unnecessary optimization. Regardless, I'd be interested to see if anyone else has come across usage cases like this and how they proceeded. Also, if this isn't possible in Python, is it possible in other (perhaps more functional) languages? EDIT: It looks like the consensus solution is to compose a string containing the full collection of conditions and then use exec or eval to generate a single function. @doublep suggests this is pretty hackish. Any thoughts on how bad this is? Is it plausible to check the arguments closely enough when composing the function that a solution like this could be considered safe? After all, whatever rigorous checking is required only needs to be performed once whereas the benefit from a faster combined conditional can be accrued over a large number of calls. Are people using stuff like this in deployment scenarios or is this mainly a technique to play around with?
[ "Based on your example, if your list of possible parameters is just a sequence of max,min,max,min,max,min,... then here's an easy way to do it:\ndef combining_function(*args):\n maxs, mins = zip(*zip(*[iter(args)]*2))\n minv = max(m for m in mins if m is not None)\n maxv = min(m for m in maxs if m is not None)\n return lambda x: minv < x.a < maxv\n\nBut this kind of \"cheats\" a bit: it precomputes the smallest maximum value and the largest minimum value. If your tests can be something more complicated than just max/min testing, the code will need to be modified.\n", "Replacing\nreturn lambda x: all( [ f(x) for f in f_array ] )\n\nwith\nreturn lambda x: all( f(x) for f in f_array )\n\nwill give a more efficient lambda as it will stop early if any f returns a false value and doesn't need to create unnecessary list. This is only possible on Python 2.4 or 2.5 and up, though. If you need to support ancient values, do the following:\ndef check (x):\n for f in f_array:\n if not f (x):\n return False\n return True\n\nreturn check\n\nFinally, if you really need to make this very efficient and are not afraid of bounding-on-hackish solutions, you could try compilation at runtime:\ndef combining_function (max_a, min_a):\n constants = { }\n checks = []\n\n if max_a is not None:\n constants['max_a'] = max_a\n checks.append ('x.a < max_a')\n\n if min_a is not None:\n constants['min_a'] = min_a\n checks.append ('x.a > min_a')\n\n if not checks:\n return lambda x: True\n else:\n func = 'def check (x): return (%s)' % ') and ('.join (checks)\n exec func in constants, constants\n return constants['check']\n\nclass X:\n def __init__(self, a):\n self.a = a\n\ncheck = combining_function (3, 1)\nprint check (X (0)), check (X (2)), check (X (4))\n\nNote that in Python 3.x exec becomes a function, so the above code is not portable.\n", "The combining_function() interface is horrible, but if you can't change it then you could use:\ndef combining_function(min_a, max_a, min_b, max_b):\n conditions = []\n for name, value in locals().items():\n if value is None:\n continue\n kind, sep, attr = name.partition(\"_\")\n op = {\"min\": \">\", \"max\": \"<\"}.get(kind, None)\n if op is None:\n continue\n conditions.append(\"x.%(attr)s %(op)s %(value)r\" % dict(\n attr=attr, op=op, value=value))\n\n if conditions:\n return eval(\"lambda x: \" + \" and \".join(conditions), {})\n else:\n return lambda x: True\n\n" ]
[ 1, 1, 1 ]
[]
[]
[ "functional_programming", "python" ]
stackoverflow_0003010381_functional_programming_python.txt
Q: Prepopulate drop-box according to another drop-box choice in Django Admin I have models like this: class User(models.Model): Switch = models.ForeignKey(Switch, related_name='SwitchUsers') Port = models.ForeignKey(Port) class Switch(models.Model): Name = models.CharField(max_length=50) class Port(models.Model): PortNum = models.PositiveIntegerField() Switch = models.ForeignKey(Switch, related_name = "Ports") When I'm in Admin interface and choose Switch from Switches available, I would like to have Port prepopulated accordingly with Ports from the related Switch. As far as I understand I need to create some JS script to prepopulate it. Unfortunately I don't have this experience, and I would like to keep things simple as it possible and don't rewrite all Django admin interface. Just add this functionality for one Field. Could you please help me with my problem? Thank you. A: You are correct that you will need some js to create this. You don't need to re-write the django admin interface. You only need to customize it. This type of a thing requires a few things. Start here: http://docs.djangoproject.com/en/1.2/ref/contrib/admin/#modeladmin-objects To include your javascript use the Media class. The django forms give all form inputs consistent ids so it is easy to manipulate them. You will need, however, to "pass" your relationship to the client. I mean, on the client you'll need to know which Ports go with which Switch. Depending on how much data you have, there are a couple of approaches for this: Encode the relationship in json and output it in a tag by customizing the admin template for your model. Use ajax. You'll need at least one extra view that takes a Switch and returns a json list (or something similar) for the Ports that go with it. The javascript maniuplation should be straight forward: you want to bind the onChange() event of the dropbox to a function that strips all but the relevant Ports in the Port dropbox. I'd suggest doing your DOM manipulation using jquery. A: You can end up with a simpler solution than provided above. Instead of customizing template and putting json in a tag, put this json in the beginning of you js file, also put there $().ready call that will assign the listener to the select-box change event, and reference this js file into the ModelAdmin's Media. class MyAdmin(admin.ModelAdmin): class Media: js = ("my_code.js",) Tip: use Firebug or Chrome inspector to investigate the real names of HTML fields on the form. A: I understand that this is a shortcut, and may not be optimal, but have you considered combining the two select widgets into a single one using optgroups? It would save you from writing custom javascript. Since it's a ForeignKey, if they select a port, you know what the switch is. You could have the switches be optgroups, with a value of "", so they can't save after selecting just a switch. Here are the steps I can see: Customize the form fields to omit switch. Change the title of the port form field to Switch/Port. Change the choices of the port form field to a tuple, generated from the switches/ports. Add a custom view for saving that gets the switch from the port and sets the switch of the user to it. If the users/stakeholders would find this acceptable, it's a way to get around JavaScript programming that involves a fair bit of Django programming.
Prepopulate drop-box according to another drop-box choice in Django Admin
I have models like this: class User(models.Model): Switch = models.ForeignKey(Switch, related_name='SwitchUsers') Port = models.ForeignKey(Port) class Switch(models.Model): Name = models.CharField(max_length=50) class Port(models.Model): PortNum = models.PositiveIntegerField() Switch = models.ForeignKey(Switch, related_name = "Ports") When I'm in Admin interface and choose Switch from Switches available, I would like to have Port prepopulated accordingly with Ports from the related Switch. As far as I understand I need to create some JS script to prepopulate it. Unfortunately I don't have this experience, and I would like to keep things simple as it possible and don't rewrite all Django admin interface. Just add this functionality for one Field. Could you please help me with my problem? Thank you.
[ "You are correct that you will need some js to create this. You don't need to re-write the django admin interface. You only need to customize it. This type of a thing requires a few things.\nStart here: http://docs.djangoproject.com/en/1.2/ref/contrib/admin/#modeladmin-objects\nTo include your javascript use the Media class.\nThe django forms give all form inputs consistent ids so it is easy to manipulate them. You will need, however, to \"pass\" your relationship to the client. I mean, on the client you'll need to know which Ports go with which Switch. Depending on how much data you have, there are a couple of approaches for this:\n\nEncode the relationship in json and output it in a tag by customizing the admin template for your model.\nUse ajax. You'll need at least one extra view that takes a Switch and returns a json list (or something similar) for the Ports that go with it.\n\nThe javascript maniuplation should be straight forward: you want to bind the onChange() event of the dropbox to a function that strips all but the relevant Ports in the Port dropbox.\nI'd suggest doing your DOM manipulation using jquery.\n", "You can end up with a simpler solution than provided above.\nInstead of customizing template and putting json in a tag, put this json in the beginning of you js file, also put there $().ready call that will assign the listener to the select-box change event, and reference this js file into the ModelAdmin's Media.\nclass MyAdmin(admin.ModelAdmin):\n class Media:\n js = (\"my_code.js\",)\n\nTip: use Firebug or Chrome inspector to investigate the real names of HTML fields on the form.\n", "I understand that this is a shortcut, and may not be optimal, but have you considered combining the two select widgets into a single one using optgroups? It would save you from writing custom javascript.\nSince it's a ForeignKey, if they select a port, you know what the switch is. You could have the switches be optgroups, with a value of \"\", so they can't save after selecting just a switch. Here are the steps I can see:\n\nCustomize the form fields to omit switch.\nChange the title of the port form field to Switch/Port.\nChange the choices of the port form field to a tuple, generated from the switches/ports.\nAdd a custom view for saving that gets the switch from the port and sets the switch of the user to it.\n\nIf the users/stakeholders would find this acceptable, it's a way to get around JavaScript programming that involves a fair bit of Django programming.\n" ]
[ 1, 0, 0 ]
[]
[]
[ "django", "jquery", "python" ]
stackoverflow_0003000664_django_jquery_python.txt
Q: Python: mysqldb install error So i've been pulling my hair out trying to install the mysqldb package. When i run the build i get a long transcript of errors, heres just part of it, i would posit it all but its huge list of errors [rv@med240-183 MySQL-python-1.2.3c1]$ sudo python setup.py build [sudo] password for rv: running build running build_py copying MySQLdb/release.py -> build/lib.linux-i686-2.6/MySQLdb running build_ext building '_mysql' extension gcc -pthread -fno-strict-aliasing -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m32 -march=i586 -mtune=generic -fasynchronous-unwind-tables -D_GNU_SOURCE -fPIC -fPIC -Dversion_info=(1,2,3,'gamma',1) -D__version__=1.2.3c1 -I/usr/include/mysql -I/usr/include/python2.6 -c _mysql.c -o build/temp.linux-i686-2.6/_mysql.o -g -pipe -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m32 -fasynchronous-unwind-tables -D_GNU_SOURCE -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE -fno-strict-aliasing -fwrapv -fPIC -DUNIV_LINUX _mysql.c:36:23: error: my_config.h: No such file or directory _mysql.c:38:19: error: mysql.h: No such file or directory Any ideas? A: yum install mysql-devel
Python: mysqldb install error
So i've been pulling my hair out trying to install the mysqldb package. When i run the build i get a long transcript of errors, heres just part of it, i would posit it all but its huge list of errors [rv@med240-183 MySQL-python-1.2.3c1]$ sudo python setup.py build [sudo] password for rv: running build running build_py copying MySQLdb/release.py -> build/lib.linux-i686-2.6/MySQLdb running build_ext building '_mysql' extension gcc -pthread -fno-strict-aliasing -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m32 -march=i586 -mtune=generic -fasynchronous-unwind-tables -D_GNU_SOURCE -fPIC -fPIC -Dversion_info=(1,2,3,'gamma',1) -D__version__=1.2.3c1 -I/usr/include/mysql -I/usr/include/python2.6 -c _mysql.c -o build/temp.linux-i686-2.6/_mysql.o -g -pipe -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m32 -fasynchronous-unwind-tables -D_GNU_SOURCE -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE -fno-strict-aliasing -fwrapv -fPIC -DUNIV_LINUX _mysql.c:36:23: error: my_config.h: No such file or directory _mysql.c:38:19: error: mysql.h: No such file or directory Any ideas?
[ "yum install mysql-devel\n\n" ]
[ 3 ]
[]
[]
[ "database", "installation", "mysql", "python" ]
stackoverflow_0003010752_database_installation_mysql_python.txt
Q: Python - wxPython custom button -> unbound method __init__()? what? After looking at questions like this it doesn't make sense that my __init__(self, parrent, id) would be throwing a unbound error? help? main.py import wx from customButton import customButton from wxPython.wx import * class MyFrame(wx.Frame): def __init__(self, parent, ID, title): wxFrame.__init__(self, parent, ID, title, wxDefaultPosition, wxSize(400, 400)) # Non-important code here... # This is the first declaration of the Button1 # This is also where the ERROR is thrown. # Omitting this line causes the window to execute # flawlessly. self.Button1 = customButton.__init__(self, parent, -1) # ... finishes in a basic wx.program style... customButton.py # I've included all of the code in the file # because have no idea where the bug/error happens import wx from wxPython.wx import * class Custom_Button(wx.PyControl): # The BMP's Over_bmp = None #wxEmptyBitmap(1,1,1) # When the mouse is over Norm_bmp = None #wxEmptyBitmap(1,1,1) # The normal BMP Push_bmp = None #wxEmptyBitmap(1,1,1) # The down BMP def __init__(self, parent, id, **kwargs): wx.PyControl.__init__(self,parent, id, **kwargs) # Set the BMP's to the ones given in the constructor #self.Over_bmp = wx.Bitmap(wx.Image(MOUSE_OVER_BMP, wx.BITMAP_TYPE_ANY).ConvertToBitmap()) #self.Norm_bmp = wx.Bitmap(wx.Image(NORM_BMP, wx.BITMAP_TYPE_ANY).ConvertToBitmap()) #self.Push_bmp = wx.Bitmap(wx.Image(PUSH_BMP, wx.BITMAP_TYPE_ANY).ConvertToBitmap()) #self.Pos_bmp = self.pos self.Bind(wx.EVT_LEFT_DOWN, self._onMouseDown) self.Bind(wx.EVT_LEFT_UP, self._onMouseUp) self.Bind(wx.EVT_LEAVE_WINDOW, self._onMouseLeave) self.Bind(wx.EVT_ENTER_WINDOW, self._onMouseEnter) self.Bind(wx.EVT_ERASE_BACKGROUND,self._onEraseBackground) self.Bind(wx.EVT_PAINT,self._onPaint) self._mouseIn = self._mouseDown = False def _onMouseEnter(self, event): self._mouseIn = True def _onMouseLeave(self, event): self._mouseIn = False def _onMouseDown(self, event): self._mouseDown = True def _onMouseUp(self, event): self._mouseDown = False self.sendButtonEvent() def sendButtonEvent(self): event = wx.CommandEvent(wx.wxEVT_COMMAND_BUTTON_CLICKED, self.GetId()) event.SetInt(0) event.SetEventObject(self) self.GetEventHandler().ProcessEvent(event) def _onEraseBackground(self,event): # reduce flicker pass def _onPaint(self, event): dc = wx.BufferedPaintDC(self) dc.SetFont(self.GetFont()) dc.SetBackground(wx.Brush(self.GetBackgroundColour())) dc.Clear() dc.DrawBitmap(self.Norm_bmp) # draw whatever you want to draw # draw glossy bitmaps e.g. dc.DrawBitmap if self._mouseIn: # If the Mouse is over the button dc.DrawBitmap(self, self.Mouse_over_bmp, self.Pos_bmp, useMask=False) if self._mouseDown: # If the Mouse clicks the button dc.DrawBitmap(self, self.Push_bmp, self.Pos_bmp, useMask=False) A: You don't create an object like this: self.Button1 = customButton.__init__(self, parent, -1) you do it like this: self.Button1 = customButton(parent, -1) __init__ is an implicitly invoked method during object creation. A: Don't call __init__() explicitly unless you know you need to. self.Button1 = customButton(parent, -1)
Python - wxPython custom button -> unbound method __init__()? what?
After looking at questions like this it doesn't make sense that my __init__(self, parrent, id) would be throwing a unbound error? help? main.py import wx from customButton import customButton from wxPython.wx import * class MyFrame(wx.Frame): def __init__(self, parent, ID, title): wxFrame.__init__(self, parent, ID, title, wxDefaultPosition, wxSize(400, 400)) # Non-important code here... # This is the first declaration of the Button1 # This is also where the ERROR is thrown. # Omitting this line causes the window to execute # flawlessly. self.Button1 = customButton.__init__(self, parent, -1) # ... finishes in a basic wx.program style... customButton.py # I've included all of the code in the file # because have no idea where the bug/error happens import wx from wxPython.wx import * class Custom_Button(wx.PyControl): # The BMP's Over_bmp = None #wxEmptyBitmap(1,1,1) # When the mouse is over Norm_bmp = None #wxEmptyBitmap(1,1,1) # The normal BMP Push_bmp = None #wxEmptyBitmap(1,1,1) # The down BMP def __init__(self, parent, id, **kwargs): wx.PyControl.__init__(self,parent, id, **kwargs) # Set the BMP's to the ones given in the constructor #self.Over_bmp = wx.Bitmap(wx.Image(MOUSE_OVER_BMP, wx.BITMAP_TYPE_ANY).ConvertToBitmap()) #self.Norm_bmp = wx.Bitmap(wx.Image(NORM_BMP, wx.BITMAP_TYPE_ANY).ConvertToBitmap()) #self.Push_bmp = wx.Bitmap(wx.Image(PUSH_BMP, wx.BITMAP_TYPE_ANY).ConvertToBitmap()) #self.Pos_bmp = self.pos self.Bind(wx.EVT_LEFT_DOWN, self._onMouseDown) self.Bind(wx.EVT_LEFT_UP, self._onMouseUp) self.Bind(wx.EVT_LEAVE_WINDOW, self._onMouseLeave) self.Bind(wx.EVT_ENTER_WINDOW, self._onMouseEnter) self.Bind(wx.EVT_ERASE_BACKGROUND,self._onEraseBackground) self.Bind(wx.EVT_PAINT,self._onPaint) self._mouseIn = self._mouseDown = False def _onMouseEnter(self, event): self._mouseIn = True def _onMouseLeave(self, event): self._mouseIn = False def _onMouseDown(self, event): self._mouseDown = True def _onMouseUp(self, event): self._mouseDown = False self.sendButtonEvent() def sendButtonEvent(self): event = wx.CommandEvent(wx.wxEVT_COMMAND_BUTTON_CLICKED, self.GetId()) event.SetInt(0) event.SetEventObject(self) self.GetEventHandler().ProcessEvent(event) def _onEraseBackground(self,event): # reduce flicker pass def _onPaint(self, event): dc = wx.BufferedPaintDC(self) dc.SetFont(self.GetFont()) dc.SetBackground(wx.Brush(self.GetBackgroundColour())) dc.Clear() dc.DrawBitmap(self.Norm_bmp) # draw whatever you want to draw # draw glossy bitmaps e.g. dc.DrawBitmap if self._mouseIn: # If the Mouse is over the button dc.DrawBitmap(self, self.Mouse_over_bmp, self.Pos_bmp, useMask=False) if self._mouseDown: # If the Mouse clicks the button dc.DrawBitmap(self, self.Push_bmp, self.Pos_bmp, useMask=False)
[ "You don't create an object like this:\nself.Button1 = customButton.__init__(self, parent, -1)\n\nyou do it like this:\nself.Button1 = customButton(parent, -1)\n\n__init__ is an implicitly invoked method during object creation.\n", "Don't call __init__() explicitly unless you know you need to.\nself.Button1 = customButton(parent, -1)\n\n" ]
[ 3, 1 ]
[]
[]
[ "custom_controls", "pydev", "python", "wxpython" ]
stackoverflow_0003010789_custom_controls_pydev_python_wxpython.txt
Q: Connect to an existing process Hole thing is happening on the mac os x. Let's assume that I've opened an program by clicking on an .app icon. It's a python program with GUI which has a separate process that waits for a user input. But as I've opened it by clickin .app icon I dont have access to it's input as I would have if I opened it in Terminal. And the question is: How can I connect new Terminal window to this running program? I tried pipes but I'm not sure how to use them correctly. My guess was to find PID of the app that is running and then pipe to this program by giving a PID. But I have no idea how to do it. I hope you were able to understand what's the problem. Sorry for my weak english :) A: If you need to have a Terminal window connected to your "separate process", I would use the Terminal to launch that process in your python script. I can do that with some applescript code. Here's a simple applescript example. I can open a Terminal window and run the "cd" command like this: tell application "Terminal" activate do script with command "cd /" end tell So now you just need to figure out how to run an applescript from python... which I don't know.
Connect to an existing process
Hole thing is happening on the mac os x. Let's assume that I've opened an program by clicking on an .app icon. It's a python program with GUI which has a separate process that waits for a user input. But as I've opened it by clickin .app icon I dont have access to it's input as I would have if I opened it in Terminal. And the question is: How can I connect new Terminal window to this running program? I tried pipes but I'm not sure how to use them correctly. My guess was to find PID of the app that is running and then pipe to this program by giving a PID. But I have no idea how to do it. I hope you were able to understand what's the problem. Sorry for my weak english :)
[ "If you need to have a Terminal window connected to your \"separate process\", I would use the Terminal to launch that process in your python script. I can do that with some applescript code. Here's a simple applescript example. I can open a Terminal window and run the \"cd\" command like this:\ntell application \"Terminal\"\n activate\n do script with command \"cd /\"\nend tell\n\nSo now you just need to figure out how to run an applescript from python... which I don't know.\n" ]
[ 0 ]
[]
[]
[ "macos", "pipe", "process", "python", "terminal" ]
stackoverflow_0003004791_macos_pipe_process_python_terminal.txt
Q: How do I do import hooks in IronPython/Silverlight? I'm extending TryPython to (along with various other things) allow users to save a file and subsequently import that file. TryPython overloads the built in file operations, so I need to know what parts of import need to hooked into in order for import to use the overloaded file operations. Really, a basic overview of IronPython's import when used in Silverlight would be extremely helpful. I don't need a complete working solution (although I won't stop you from writing one! :). I'm a Python newbie, and I really have no idea where to even begin. Thanks! A: IronPython's import basically works as usual but the file system is abstracted away in Silverlight. This is done by the DLR hosting API's PlatformAdaptionLayer. The end result is that all requests for files to be imported go to the XAP file rather than going to the file system. I would suggest using one of the various ways you can replace importing functionality. You could either redefine import or better yet use the importer hooks
How do I do import hooks in IronPython/Silverlight?
I'm extending TryPython to (along with various other things) allow users to save a file and subsequently import that file. TryPython overloads the built in file operations, so I need to know what parts of import need to hooked into in order for import to use the overloaded file operations. Really, a basic overview of IronPython's import when used in Silverlight would be extremely helpful. I don't need a complete working solution (although I won't stop you from writing one! :). I'm a Python newbie, and I really have no idea where to even begin. Thanks!
[ "IronPython's import basically works as usual but the file system is abstracted away in Silverlight. This is done by the DLR hosting API's PlatformAdaptionLayer. The end result is that all requests for files to be imported go to the XAP file rather than going to the file system.\nI would suggest using one of the various ways you can replace importing functionality. You could either redefine import or better yet use the importer hooks\n" ]
[ 2 ]
[]
[]
[ "ironpython", "python", "silverlight" ]
stackoverflow_0003011031_ironpython_python_silverlight.txt
Q: viewing files in python? I am creating a sort of "Command line" in Python. I already added a few functions, such as changing login/password, executing, etc., But is it possible to browse files in the directory that the main file is in with a command/module, or will I have to make the module myself and use the import command? Same thing with changing directories to view, too. A: Browsing files is as easy as using the standard os module. If you want to do something with those files, that's entirely different. import os all_files = os.listdir('.') # gets all files in current directory To change directories you can issue os.chdir('path/to/change/to'). In fact there are plenty of useful functions found in the os module that facilitate the things you're asking about. Making them pretty and user-friendly, however, is up to you! A: I'd like to see someone write a a semantic file-browser, i.e. one that auto-generates tags for files according to their input and then allows views and searching accordingly. Think about it... take an MP3, lookup the lyrics, run it through Zemanta, bam! a PDF file, a OpenOffice file, etc., that'd be pretty kick-butt! probably fairly intensive too, but it'd be pretty dang cool! Cheers, -C
viewing files in python?
I am creating a sort of "Command line" in Python. I already added a few functions, such as changing login/password, executing, etc., But is it possible to browse files in the directory that the main file is in with a command/module, or will I have to make the module myself and use the import command? Same thing with changing directories to view, too.
[ "Browsing files is as easy as using the standard os module. If you want to do something with those files, that's entirely different.\nimport os\nall_files = os.listdir('.') # gets all files in current directory\n\nTo change directories you can issue os.chdir('path/to/change/to'). In fact there are plenty of useful functions found in the os module that facilitate the things you're asking about. Making them pretty and user-friendly, however, is up to you!\n", "I'd like to see someone write a a semantic file-browser, i.e. one that auto-generates tags for files according to their input and then allows views and searching accordingly.\nThink about it... take an MP3, lookup the lyrics, run it through Zemanta, bam! a PDF file, a OpenOffice file, etc., that'd be pretty kick-butt! probably fairly intensive too, but it'd be pretty dang cool!\nCheers,\n-C\n" ]
[ 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003010864_python.txt
Q: New wxpython controls not displaying until resize I have created a custom control (based on a panel) in wxPython that provides a list of custom controls on panel within it. The user needs to be able to add rows at will and have those rows displayed. I'm having trouble getting the new controls to actually appear after they are added. I know they are present, because they appear after a resize of the frame, or if I add them before Show() is called on the frame. I've convinced myself it's something basic, but I can't find the mistake. The add function looks like this: def addRow(self, id, reference, page, title, note): newRow = NoteListRow(self.listPanel, id, reference, page, title, note) self.listSizer.Add(newRow, flag=wx.EXPAND | wx.LEFT) self.rows.append(newRow) if len(self.rows) == 1: self.highliteRow(newRow) self.Refresh() self.Update() return newRow I assume I'm missing something about how refresh and update are supposed to behave, so even a good extended reference on those would likely be helpful. A: Try self.Layout() Try self.GetParent().Layout() Including a Refresh(). Update() shouldn't be necessary.
New wxpython controls not displaying until resize
I have created a custom control (based on a panel) in wxPython that provides a list of custom controls on panel within it. The user needs to be able to add rows at will and have those rows displayed. I'm having trouble getting the new controls to actually appear after they are added. I know they are present, because they appear after a resize of the frame, or if I add them before Show() is called on the frame. I've convinced myself it's something basic, but I can't find the mistake. The add function looks like this: def addRow(self, id, reference, page, title, note): newRow = NoteListRow(self.listPanel, id, reference, page, title, note) self.listSizer.Add(newRow, flag=wx.EXPAND | wx.LEFT) self.rows.append(newRow) if len(self.rows) == 1: self.highliteRow(newRow) self.Refresh() self.Update() return newRow I assume I'm missing something about how refresh and update are supposed to behave, so even a good extended reference on those would likely be helpful.
[ "Try self.Layout()\nTry self.GetParent().Layout()\nIncluding a Refresh().\nUpdate() shouldn't be necessary.\n" ]
[ 3 ]
[]
[]
[ "python", "user_interface", "wxpython" ]
stackoverflow_0003011231_python_user_interface_wxpython.txt
Q: Why is my simple python gtk+cairo program running so slowly/stutteringly? My program draws circles moving on the window. I think I must be missing some basic gtk/cairo concept because it seems to be running too slowly/stutteringly for what I am doing. Any ideas? Thanks for any help! #!/usr/bin/python import gtk import gtk.gdk as gdk import math import random import gobject # The number of circles and the window size. num = 128 size = 512 # Initialize circle coordinates and velocities. x = [] y = [] xv = [] yv = [] for i in range(num): x.append(random.randint(0, size)) y.append(random.randint(0, size)) xv.append(random.randint(-4, 4)) yv.append(random.randint(-4, 4)) # Draw the circles and update their positions. def expose(*args): cr = darea.window.cairo_create() cr.set_line_width(4) for i in range(num): cr.set_source_rgb(1, 0, 0) cr.arc(x[i], y[i], 8, 0, 2 * math.pi) cr.stroke_preserve() cr.set_source_rgb(1, 1, 1) cr.fill() x[i] += xv[i] y[i] += yv[i] if x[i] > size or x[i] < 0: xv[i] = -xv[i] if y[i] > size or y[i] < 0: yv[i] = -yv[i] # Self-evident? def timeout(): darea.queue_draw() return True # Initialize the window. window = gtk.Window() window.resize(size, size) window.connect("destroy", gtk.main_quit) darea = gtk.DrawingArea() darea.connect("expose-event", expose) window.add(darea) window.show_all() # Self-evident? gobject.idle_add(timeout) gtk.main() A: One of the problems is that you are drawing the same basic object again and again. I'm not sure about GTK+ buffering behavior, but also keep in mind that basic function calls incur a cost in Python. I've added a frame counter to your program, and I with your code, I got around 30fps max. There are several things you can do, for instance compose larger paths before actually calling any fill or stroke method (i.e. will all arcs in a single call). Another solution, which is vastly faster is to compose your ball in an off-screen buffer and then just paint it to the screen repeatedly: def create_basic_image(): img = cairo.ImageSurface(cairo.FORMAT_ARGB32, 24, 24) c = cairo.Context(img) c.set_line_width(4) c.arc(12, 12, 8, 0, 2 * math.pi) c.set_source_rgb(1, 0, 0) c.stroke_preserve() c.set_source_rgb(1, 1, 1) c.fill() return img def expose(sender, event, img): cr = darea.window.cairo_create() for i in range(num): cr.set_source_surface(img, x[i], y[i]) cr.paint() ... # your update code here ... darea.connect("expose-event", expose, create_basic_image()) This gives about 273 fps on my machine. Because of this, you should think about using gobject.timeout_add rather than idle_add. A: I don't see anything fundamentally wrong with your code. To narrow the problem down I tried a different approach that may be minimally faster, but the difference is almost negligible: class Area(gtk.DrawingArea): def do_expose_event(self, event): cr = self.window.cairo_create() # Restrict Cairo to the exposed area; avoid extra work cr.rectangle(event.area.x, event.area.y, event.area.width, event.area.height) cr.clip() cr.set_line_width(4) for i in range(num): cr.set_source_rgb(1, 0, 0) cr.arc(x[i], y[i], 8, 0, 2 * math.pi) cr.stroke_preserve() cr.set_source_rgb(1, 1, 1) cr.fill() x[i] += xv[i] y[i] += yv[i] if x[i] > size or x[i] < 0: xv[i] = -xv[i] if y[i] > size or y[i] < 0: yv[i] = -yv[i] self.queue_draw() gobject.type_register(Area) # Initialize the window. window = gtk.Window() window.resize(size, size) window.connect("destroy", gtk.main_quit) darea = Area() window.add(darea) window.show_all() Also, overriding DrawingArea.draw() with a stub makes no major difference. I'd probably try the Cairo mailing list, or look at Clutter or pygame for drawing a large number of items on the screen. A: I have got the same problem in program was written on C#. Before you leaves Expose event, try to write cr.dispose().
Why is my simple python gtk+cairo program running so slowly/stutteringly?
My program draws circles moving on the window. I think I must be missing some basic gtk/cairo concept because it seems to be running too slowly/stutteringly for what I am doing. Any ideas? Thanks for any help! #!/usr/bin/python import gtk import gtk.gdk as gdk import math import random import gobject # The number of circles and the window size. num = 128 size = 512 # Initialize circle coordinates and velocities. x = [] y = [] xv = [] yv = [] for i in range(num): x.append(random.randint(0, size)) y.append(random.randint(0, size)) xv.append(random.randint(-4, 4)) yv.append(random.randint(-4, 4)) # Draw the circles and update their positions. def expose(*args): cr = darea.window.cairo_create() cr.set_line_width(4) for i in range(num): cr.set_source_rgb(1, 0, 0) cr.arc(x[i], y[i], 8, 0, 2 * math.pi) cr.stroke_preserve() cr.set_source_rgb(1, 1, 1) cr.fill() x[i] += xv[i] y[i] += yv[i] if x[i] > size or x[i] < 0: xv[i] = -xv[i] if y[i] > size or y[i] < 0: yv[i] = -yv[i] # Self-evident? def timeout(): darea.queue_draw() return True # Initialize the window. window = gtk.Window() window.resize(size, size) window.connect("destroy", gtk.main_quit) darea = gtk.DrawingArea() darea.connect("expose-event", expose) window.add(darea) window.show_all() # Self-evident? gobject.idle_add(timeout) gtk.main()
[ "One of the problems is that you are drawing the same basic object again and again. I'm not sure about GTK+ buffering behavior, but also keep in mind that basic function calls incur a cost in Python. I've added a frame counter to your program, and I with your code, I got around 30fps max.\nThere are several things you can do, for instance compose larger paths before actually calling any fill or stroke method (i.e. will all arcs in a single call). Another solution, which is vastly faster is to compose your ball in an off-screen buffer and then just paint it to the screen repeatedly:\ndef create_basic_image():\n img = cairo.ImageSurface(cairo.FORMAT_ARGB32, 24, 24)\n c = cairo.Context(img)\n c.set_line_width(4)\n c.arc(12, 12, 8, 0, 2 * math.pi)\n c.set_source_rgb(1, 0, 0)\n c.stroke_preserve()\n c.set_source_rgb(1, 1, 1)\n c.fill()\n return img\n\ndef expose(sender, event, img):\n cr = darea.window.cairo_create()\n for i in range(num):\n cr.set_source_surface(img, x[i], y[i]) \n cr.paint()\n ... # your update code here\n\n...\ndarea.connect(\"expose-event\", expose, create_basic_image())\n\nThis gives about 273 fps on my machine. Because of this, you should think about using gobject.timeout_add rather than idle_add.\n", "I don't see anything fundamentally wrong with your code. To narrow the problem down I tried a different approach that may be minimally faster, but the difference is almost negligible:\nclass Area(gtk.DrawingArea):\n def do_expose_event(self, event):\n cr = self.window.cairo_create()\n\n # Restrict Cairo to the exposed area; avoid extra work\n cr.rectangle(event.area.x,\n event.area.y,\n event.area.width,\n event.area.height)\n cr.clip()\n\n cr.set_line_width(4)\n for i in range(num):\n cr.set_source_rgb(1, 0, 0)\n cr.arc(x[i], y[i], 8, 0, 2 * math.pi)\n cr.stroke_preserve()\n cr.set_source_rgb(1, 1, 1)\n cr.fill()\n x[i] += xv[i]\n y[i] += yv[i]\n if x[i] > size or x[i] < 0:\n xv[i] = -xv[i]\n if y[i] > size or y[i] < 0:\n yv[i] = -yv[i]\n self.queue_draw()\n\ngobject.type_register(Area)\n\n# Initialize the window.\nwindow = gtk.Window()\nwindow.resize(size, size)\nwindow.connect(\"destroy\", gtk.main_quit)\ndarea = Area()\nwindow.add(darea)\nwindow.show_all()\n\nAlso, overriding DrawingArea.draw() with a stub makes no major difference.\nI'd probably try the Cairo mailing list, or look at Clutter or pygame for drawing a large number of items on the screen.\n", "I have got the same problem in program was written on C#. Before you leaves Expose event, try to write cr.dispose().\n" ]
[ 12, 2, 0 ]
[]
[]
[ "animation", "cairo", "gtk", "pygtk", "python" ]
stackoverflow_0002172525_animation_cairo_gtk_pygtk_python.txt
Q: Global name not defined I wrote a CPU monitoring program in Python. For some reason sometimes the the program will run without any problem. Then other times the program won't even start because of the following error. Traceback (most recent call last): File "", line 244, in run_nodebug File "C:\Python26\CPUR1.7.pyw", line 601, in app = simpleapp_tk(None) File "C:\Python26\CPUR1.7.pyw", line 26, in init self.initialize() File "C:\Python26\CPUR1.7.pyw", line 107, in initialize self.F() File "C:\Python26\CPUR1.7.pyw", line 517, in F S2 = TL.entryVariableS.get() NameError: global name 'TL' is not defined I can't seem to find the problem, maybe someone more experienced may assist me? Here is a snippet of the part giving me trouble: (The second to last line in the snippet is what's giving me trouble) def E(self): if self.selectedM.get() =='Options...': Setup global TL TL = Tkinter.Toplevel(self) menu = Tkinter.Menu(TL) TL.config(menu=menu) filemenu = Tkinter.Menu(menu) menu.add_cascade(label="| Menu |", menu=filemenu) filemenu.add_command(label="Instruction Manual...", command=self.helpmenu) filemenu.add_command(label="About...", command=self.aboutmenu) filemenu.add_separator() filemenu.add_command(label="Exit Options", command=TL.destroy) filemenu.add_command(label="Exit", command=self.destroy) helpmenu = Tkinter.Menu(menu) menu.add_cascade(label="| Help |", menu=helpmenu) helpmenu.add_command(label="Instruction Manual...", command=self.helpmenu) helpmenu.add_separator() helpmenu.add_command(label="Quick Help...", command=self.helpmenu) Title TL.label5 = Tkinter.Label(TL,text="CPU Usage: Options",anchor="center",fg="black",bg="lightgreen",relief="ridge",borderwidth=5,font=('Arial', 18, 'bold')) TL.label5.pack(padx=15,ipadx=5) X Y scale TL.separator = Tkinter.Frame(TL,height=7, bd=1, relief='ridge', bg='grey95') TL.separator.pack(pady=5,padx=5) # TL.sclX = Tkinter.Scale(TL.separator, from_=0, to=1500, orient='horizontal', resolution=1, command=self.A) TL.sclX.grid(column=1,row=0,ipadx=27, sticky='w') TL.label1 = Tkinter.Label(TL.separator,text="X",anchor="s",fg="black",bg="grey95",font=('Arial', 8 ,'bold')) TL.label1.grid(column=0,row=0, pady=1, sticky='S') TL.sclY = Tkinter.Scale(TL.separator, from_=0, to=1500, resolution=1, command=self.A) TL.sclY.grid(column=2,row=1,rowspan=2,sticky='e', padx=4) TL.label3 = Tkinter.Label(TL.separator,text="Y",fg="black",bg="grey95",font=('Arial', 8 ,'bold')) TL.label3.grid(column=2,row=0, padx=10, sticky='e') TL.entryVariable2 = Tkinter.StringVar() TL.entry2 = Tkinter.Entry(TL.separator,textvariable=TL.entryVariable2, fg="grey15",bg="grey90",relief="sunken",insertbackground="black",borderwidth=5,font=('Arial', 10)) TL.entry2.grid(column=1,row=1,ipadx=20, pady=10,sticky='EW') TL.entry2.bind("<Return>", self.B) TL.label2 = Tkinter.Label(TL.separator,text="X:",fg="black",bg="grey95",font=('Arial', 8 ,'bold')) TL.label2.grid(column=0,row=1, ipadx=4, sticky='W') TL.entryVariable1 = Tkinter.StringVar() TL.entry1 = Tkinter.Entry(TL.separator,textvariable=TL.entryVariable1, fg="grey15",bg="grey90",relief="sunken",insertbackground="black",borderwidth=5,font=('Arial', 10)) TL.entry1.grid(column=1,row=2,sticky='EW') TL.entry1.bind("<Return>", self.B) TL.label4 = Tkinter.Label(TL.separator,text="Y:", anchor="center",fg="black",bg="grey95",font=('Arial', 8 ,'bold')) TL.label4.grid(column=0,row=2, ipadx=4, sticky='W') TL.label7 = Tkinter.Label(TL.separator,text="Text Colour:",fg="black",bg="grey95",font=('Arial', 8 ,'bold'),justify='left') TL.label7.grid(column=1,row=3, sticky='W',padx=10,ipady=10,ipadx=30) TL.selectedP = Tkinter.StringVar() TL.opt1 = Tkinter.OptionMenu(TL.separator, TL.selectedP,'Normal', 'White','Black', 'Blue', 'Steel Blue','Green','Light Green','Yellow','Orange' ,'Red',command=self.G) TL.opt1.config(fg="black",bg="grey90",activebackground="grey90",activeforeground="black", anchor="center",relief="raised",direction='right',font=('Arial', 10)) TL.opt1.grid(column=1,row=4,sticky='EW',padx=20,ipadx=20) TL.selectedP.set('Normal') TL.sclS = Tkinter.Scale(TL.separator, from_=10, to=2000, orient='horizontal', resolution=10, command=self.H) TL.sclS.grid(column=1,row=5,ipadx=27, sticky='w') TL.sclS.set(600) TL.entryVariableS = Tkinter.StringVar() TL.entryS = Tkinter.Entry(TL.separator,textvariable=TL.entryVariableS, fg="grey15",bg="grey90",relief="sunken",insertbackground="black",borderwidth=5,font=('Arial', 10)) TL.entryS.grid(column=1,row=6,ipadx=20, pady=10,sticky='EW') TL.entryS.bind("<Return>", self.I) TL.entryVariableS.set(600) # TL.resizable(False,False) TL.title('Options') geomPatt = re.compile(r"(\d+)?x?(\d+)?([+-])(\d+)([+-])(\d+)") s = self.wm_geometry() m = geomPatt.search(s) X = m.group(4) Y = m.group(6) TL.sclY.set(Y) TL.sclX.set(X) if self.selectedM.get() == 'Exit': self.destroy() def F (self): G = round(psutil.cpu_percent(), 1) G1 = str(G) + '%' self.labelVariable.set(G1) if G < 5: self.imageLabel.configure(image=self.image0) if G >= 5: self.imageLabel.configure(image=self.image5) if G >= 10: self.imageLabel.configure(image=self.image10) if G >= 15: self.imageLabel.configure(image=self.image15) if G >= 20: self.imageLabel.configure(image=self.image20) if G >= 25: self.imageLabel.configure(image=self.image25) if G >= 30: self.imageLabel.configure(image=self.image30) if G >= 35: self.imageLabel.configure(image=self.image35) if G >= 40: self.imageLabel.configure(image=self.image40) if G >= 45: self.imageLabel.configure(image=self.image45) if G >= 50: self.imageLabel.configure(image=self.image50) if G >= 55: self.imageLabel.configure(image=self.image55) if G >= 60: self.imageLabel.configure(image=self.image60) if G >= 65: self.imageLabel.configure(image=self.image65) if G >= 70: self.imageLabel.configure(image=self.image70) if G >= 75: self.imageLabel.configure(image=self.image75) if G >= 80: self.imageLabel.configure(image=self.image80) if G >= 85: self.imageLabel.configure(image=self.image85) if G >= 90: self.imageLabel.configure(image=self.image90) if 100> G >= 95: self.imageLabel.configure(image=self.image95) if G == 100: self.imageLabel.configure(image=self.image100) S2 = TL.entryVariableS.get() self.after(int(S2), self.F) A: Edit: If that if self.selectedM.get() =='Options...': statement in E() isn't satisfied, then the global variable TL is never declared which I'm quite sure is what is happening. Then, when F() tries to use TL, it doesn't exist.
Global name not defined
I wrote a CPU monitoring program in Python. For some reason sometimes the the program will run without any problem. Then other times the program won't even start because of the following error. Traceback (most recent call last): File "", line 244, in run_nodebug File "C:\Python26\CPUR1.7.pyw", line 601, in app = simpleapp_tk(None) File "C:\Python26\CPUR1.7.pyw", line 26, in init self.initialize() File "C:\Python26\CPUR1.7.pyw", line 107, in initialize self.F() File "C:\Python26\CPUR1.7.pyw", line 517, in F S2 = TL.entryVariableS.get() NameError: global name 'TL' is not defined I can't seem to find the problem, maybe someone more experienced may assist me? Here is a snippet of the part giving me trouble: (The second to last line in the snippet is what's giving me trouble) def E(self): if self.selectedM.get() =='Options...': Setup global TL TL = Tkinter.Toplevel(self) menu = Tkinter.Menu(TL) TL.config(menu=menu) filemenu = Tkinter.Menu(menu) menu.add_cascade(label="| Menu |", menu=filemenu) filemenu.add_command(label="Instruction Manual...", command=self.helpmenu) filemenu.add_command(label="About...", command=self.aboutmenu) filemenu.add_separator() filemenu.add_command(label="Exit Options", command=TL.destroy) filemenu.add_command(label="Exit", command=self.destroy) helpmenu = Tkinter.Menu(menu) menu.add_cascade(label="| Help |", menu=helpmenu) helpmenu.add_command(label="Instruction Manual...", command=self.helpmenu) helpmenu.add_separator() helpmenu.add_command(label="Quick Help...", command=self.helpmenu) Title TL.label5 = Tkinter.Label(TL,text="CPU Usage: Options",anchor="center",fg="black",bg="lightgreen",relief="ridge",borderwidth=5,font=('Arial', 18, 'bold')) TL.label5.pack(padx=15,ipadx=5) X Y scale TL.separator = Tkinter.Frame(TL,height=7, bd=1, relief='ridge', bg='grey95') TL.separator.pack(pady=5,padx=5) # TL.sclX = Tkinter.Scale(TL.separator, from_=0, to=1500, orient='horizontal', resolution=1, command=self.A) TL.sclX.grid(column=1,row=0,ipadx=27, sticky='w') TL.label1 = Tkinter.Label(TL.separator,text="X",anchor="s",fg="black",bg="grey95",font=('Arial', 8 ,'bold')) TL.label1.grid(column=0,row=0, pady=1, sticky='S') TL.sclY = Tkinter.Scale(TL.separator, from_=0, to=1500, resolution=1, command=self.A) TL.sclY.grid(column=2,row=1,rowspan=2,sticky='e', padx=4) TL.label3 = Tkinter.Label(TL.separator,text="Y",fg="black",bg="grey95",font=('Arial', 8 ,'bold')) TL.label3.grid(column=2,row=0, padx=10, sticky='e') TL.entryVariable2 = Tkinter.StringVar() TL.entry2 = Tkinter.Entry(TL.separator,textvariable=TL.entryVariable2, fg="grey15",bg="grey90",relief="sunken",insertbackground="black",borderwidth=5,font=('Arial', 10)) TL.entry2.grid(column=1,row=1,ipadx=20, pady=10,sticky='EW') TL.entry2.bind("<Return>", self.B) TL.label2 = Tkinter.Label(TL.separator,text="X:",fg="black",bg="grey95",font=('Arial', 8 ,'bold')) TL.label2.grid(column=0,row=1, ipadx=4, sticky='W') TL.entryVariable1 = Tkinter.StringVar() TL.entry1 = Tkinter.Entry(TL.separator,textvariable=TL.entryVariable1, fg="grey15",bg="grey90",relief="sunken",insertbackground="black",borderwidth=5,font=('Arial', 10)) TL.entry1.grid(column=1,row=2,sticky='EW') TL.entry1.bind("<Return>", self.B) TL.label4 = Tkinter.Label(TL.separator,text="Y:", anchor="center",fg="black",bg="grey95",font=('Arial', 8 ,'bold')) TL.label4.grid(column=0,row=2, ipadx=4, sticky='W') TL.label7 = Tkinter.Label(TL.separator,text="Text Colour:",fg="black",bg="grey95",font=('Arial', 8 ,'bold'),justify='left') TL.label7.grid(column=1,row=3, sticky='W',padx=10,ipady=10,ipadx=30) TL.selectedP = Tkinter.StringVar() TL.opt1 = Tkinter.OptionMenu(TL.separator, TL.selectedP,'Normal', 'White','Black', 'Blue', 'Steel Blue','Green','Light Green','Yellow','Orange' ,'Red',command=self.G) TL.opt1.config(fg="black",bg="grey90",activebackground="grey90",activeforeground="black", anchor="center",relief="raised",direction='right',font=('Arial', 10)) TL.opt1.grid(column=1,row=4,sticky='EW',padx=20,ipadx=20) TL.selectedP.set('Normal') TL.sclS = Tkinter.Scale(TL.separator, from_=10, to=2000, orient='horizontal', resolution=10, command=self.H) TL.sclS.grid(column=1,row=5,ipadx=27, sticky='w') TL.sclS.set(600) TL.entryVariableS = Tkinter.StringVar() TL.entryS = Tkinter.Entry(TL.separator,textvariable=TL.entryVariableS, fg="grey15",bg="grey90",relief="sunken",insertbackground="black",borderwidth=5,font=('Arial', 10)) TL.entryS.grid(column=1,row=6,ipadx=20, pady=10,sticky='EW') TL.entryS.bind("<Return>", self.I) TL.entryVariableS.set(600) # TL.resizable(False,False) TL.title('Options') geomPatt = re.compile(r"(\d+)?x?(\d+)?([+-])(\d+)([+-])(\d+)") s = self.wm_geometry() m = geomPatt.search(s) X = m.group(4) Y = m.group(6) TL.sclY.set(Y) TL.sclX.set(X) if self.selectedM.get() == 'Exit': self.destroy() def F (self): G = round(psutil.cpu_percent(), 1) G1 = str(G) + '%' self.labelVariable.set(G1) if G < 5: self.imageLabel.configure(image=self.image0) if G >= 5: self.imageLabel.configure(image=self.image5) if G >= 10: self.imageLabel.configure(image=self.image10) if G >= 15: self.imageLabel.configure(image=self.image15) if G >= 20: self.imageLabel.configure(image=self.image20) if G >= 25: self.imageLabel.configure(image=self.image25) if G >= 30: self.imageLabel.configure(image=self.image30) if G >= 35: self.imageLabel.configure(image=self.image35) if G >= 40: self.imageLabel.configure(image=self.image40) if G >= 45: self.imageLabel.configure(image=self.image45) if G >= 50: self.imageLabel.configure(image=self.image50) if G >= 55: self.imageLabel.configure(image=self.image55) if G >= 60: self.imageLabel.configure(image=self.image60) if G >= 65: self.imageLabel.configure(image=self.image65) if G >= 70: self.imageLabel.configure(image=self.image70) if G >= 75: self.imageLabel.configure(image=self.image75) if G >= 80: self.imageLabel.configure(image=self.image80) if G >= 85: self.imageLabel.configure(image=self.image85) if G >= 90: self.imageLabel.configure(image=self.image90) if 100> G >= 95: self.imageLabel.configure(image=self.image95) if G == 100: self.imageLabel.configure(image=self.image100) S2 = TL.entryVariableS.get() self.after(int(S2), self.F)
[ "Edit:\nIf that if self.selectedM.get() =='Options...': statement in E() isn't satisfied, then the global variable TL is never declared which I'm quite sure is what is happening. Then, when F() tries to use TL, it doesn't exist.\n" ]
[ 2 ]
[]
[]
[ "global_variables", "python", "tkinter" ]
stackoverflow_0003011573_global_variables_python_tkinter.txt
Q: IDLE wont start Python 2.6.5 I was using it as my primary text editor for quite sometime. However, one day it just stopped working. This had happened to me several times before, so I simply tried to end all procceses using windows task manager. However that didn't work. I've recently tried getting it to work again. Whenever I try to reopen it it informs me that it's subprocess couldn't connect. I tried uninstalling it and reinstalling it, yet the problem persists. Anyone have any other solutions? Important facts: Windows 7, Python 2.6.5 A: Honestly I would advise you to stop using IDLE, the fact that it runs program code in the same process as itself caused me a lot of problems when I used it, including things like not refreshing imported modules that were modified. Personally I switched to emacs, but you might like to try something like Notepad++.
IDLE wont start Python 2.6.5
I was using it as my primary text editor for quite sometime. However, one day it just stopped working. This had happened to me several times before, so I simply tried to end all procceses using windows task manager. However that didn't work. I've recently tried getting it to work again. Whenever I try to reopen it it informs me that it's subprocess couldn't connect. I tried uninstalling it and reinstalling it, yet the problem persists. Anyone have any other solutions? Important facts: Windows 7, Python 2.6.5
[ "Honestly I would advise you to stop using IDLE, the fact that it runs program code in the same process as itself caused me a lot of problems when I used it, including things like not refreshing imported modules that were modified. Personally I switched to emacs, but you might like to try something like Notepad++.\n" ]
[ 0 ]
[]
[]
[ "python", "python_idle" ]
stackoverflow_0003010030_python_python_idle.txt
Q: Any faster alternative to reading nth line of a file I have to read a file from a particular line number and I know the line number say "n": I have been thinking of two ways: 1. for i in range(n): fname.readline() k=readline() print k 2. i=0 for line in fname: dictionary[i]=line i=i+1 but I want a faster alternative as I might have to perform this on different files 20000 times. Are there any better alternatives? Also, are there are other performance enhancements for simple looping, as my code has nested loops. A: If the files aren't too huge, the linecache module of the standard library is pretty good -- it lets you very directly ask for the Nth line of such-and-such file. If the files are huge, I recommend something like (warning, untested code): def readlinenum(filepath, n, BUFSIZ=65536): bufs = [None] * 2 previous_lines = lines_so_far = 0 with open(filepath, 'b') as f while True: bufs[0] = f.read(BUFSIZ) if not bufs[0]: raise ValueError('File %s has only %d lines, not %d', filepath, lines_so_far, n) lines_this_block = bufs[0].count('\n') updated_lines_count = lines_so_far + lines_this_block if n < updated_lines_count: break previous_lines = lines_so_far lines_so_far = updated_lines_count bufs[1] = bufs[0] if n == lines_so_far: # line split between blocks buf = bufs[1] + bufs[0] delta = n - previous_lines else: # normal case buf = bufs[0] delta = n = lines_so_far f = cStringIO.StringIO(buf) for i, line in enumerate(f): if i == delta: break return line.rstrip() The general idea is to read in the file as binary, in large blocks (at least as large as the longest possible line) -- the processing (on Windows) from binary to "text" is costly on huge files -- and use the fast .count method of strings on most blocks. At the end we can do the line parsing on a single block (two at most in the anomalous case where the line being sought spans block boundaries). This kind of code requires careful testing and checking (which I haven't performed in this case), being prone to off-by-one and other boundary errors, so I'd recommend it only for truly huge files -- ones that would essentially bust memory if using linecache (which just sucks up the whole file into memory instead of working by blocks). On a typical modern machine with 4GB bytes of RAM, for example, I'd start thinking about such techniques for text files that are over a GB or two. Edit: a commenter does not believe that binary reading a file is much faster than the processing required by text mode (on Windows only). To show how wrong this is, let's use the 'U' ("universal newlines") option that forces the line-end processing to happen on Unix machines too (as I don't have a Windows machine to run this on;-). Using the usual kjv.txt file: $ wc kjv.txt 114150 821108 4834378 kjv.txt (4.8 MB, 114 Klines) -- about 1/1000th of the kind of file sizes I was mentioning earlier: $ python -mtimeit 'f=open("kjv.txt", "rb")' 'f.seek(0); f.read()' 100 loops, best of 3: 13.9 msec per loop $ python -mtimeit 'f=open("kjv.txt", "rU")' 'f.seek(0); f.read()' 10 loops, best of 3: 39.2 msec per loop i.e., just about exactly a factor of 3 cost for the line-end processing (this is on an old-ish laptop, but the ratio should be pretty repeatable elsewhere, too). Reading by a loop on lines, of course, is even slower: $ python -mtimeit 'f=open("kjv.txt", "rU")' 'f.seek(0)' 'for x in f: pass' 10 loops, best of 3: 54.6 msec per loop and using readline as the commented mentioned (with less efficient buffering than directly looping on the file) is worst: $ python -mtimeit 'f=open("kjv.txt", "rU")' 'f.seek(0); x=1' 'while x: x=f.readline()' 10 loops, best of 3: 81.1 msec per loop If, as the question mentions, there are 20,000 files to read (say they're all small-ish, on the order of this kjv.txt), the fastest approach (reading each file in binary mode in a single gulp) should take about 260 seconds, 4-5 minutes, while the slowest one (based on readline) should take about 1600 seconds, almost half an hour -- a pretty significant difference for many, I'd say most, actual applications. A: Unless you know, or can figure out, the offset of line n in your file (for example, if every line were of a fixed width), you will have to read lines until you get to the nth one. Regarding your examples: xrange is faster than range since range has to generate a list, whereas xrange uses a generator if you only need line n, why are you storing all of the lines in a dictionary? A: Caching a list of offsets of every end-of-line character in the file would cost a lot of memory, but caching roughly one per memory page (generally 4KB) gives mostly the same reduction in I/O, and the cost of scanning a couple KB from a known offset is negligible. So, if your average line length is 40 characters, you only have to cache a list of every 100th end-of-line in the file. Exactly where you draw the line depends on how much memory you have and how fast your I/O is. You might even be able to get away with caching a list of the offsets of every 1000th end-of-line character without a noticeable difference in performance from indexing every single one.
Any faster alternative to reading nth line of a file
I have to read a file from a particular line number and I know the line number say "n": I have been thinking of two ways: 1. for i in range(n): fname.readline() k=readline() print k 2. i=0 for line in fname: dictionary[i]=line i=i+1 but I want a faster alternative as I might have to perform this on different files 20000 times. Are there any better alternatives? Also, are there are other performance enhancements for simple looping, as my code has nested loops.
[ "If the files aren't too huge, the linecache module of the standard library is pretty good -- it lets you very directly ask for the Nth line of such-and-such file.\nIf the files are huge, I recommend something like (warning, untested code):\ndef readlinenum(filepath, n, BUFSIZ=65536):\n bufs = [None] * 2\n previous_lines = lines_so_far = 0\n with open(filepath, 'b') as f\n while True:\n bufs[0] = f.read(BUFSIZ)\n if not bufs[0]:\n raise ValueError('File %s has only %d lines, not %d',\n filepath, lines_so_far, n)\n lines_this_block = bufs[0].count('\\n')\n updated_lines_count = lines_so_far + lines_this_block\n if n < updated_lines_count:\n break\n previous_lines = lines_so_far\n lines_so_far = updated_lines_count\n bufs[1] = bufs[0]\n if n == lines_so_far:\n # line split between blocks\n buf = bufs[1] + bufs[0]\n delta = n - previous_lines\n else: # normal case\n buf = bufs[0]\n delta = n = lines_so_far\n f = cStringIO.StringIO(buf)\n for i, line in enumerate(f):\n if i == delta: break\n return line.rstrip()\n\nThe general idea is to read in the file as binary, in large blocks (at least as large as the longest possible line) -- the processing (on Windows) from binary to \"text\" is costly on huge files -- and use the fast .count method of strings on most blocks. At the end we can do the line parsing on a single block (two at most in the anomalous case where the line being sought spans block boundaries).\nThis kind of code requires careful testing and checking (which I haven't performed in this case), being prone to off-by-one and other boundary errors, so I'd recommend it only for truly huge files -- ones that would essentially bust memory if using linecache (which just sucks up the whole file into memory instead of working by blocks). On a typical modern machine with 4GB bytes of RAM, for example, I'd start thinking about such techniques for text files that are over a GB or two. \nEdit: a commenter does not believe that binary reading a file is much faster than the processing required by text mode (on Windows only). To show how wrong this is, let's use the 'U' (\"universal newlines\") option that forces the line-end processing to happen on Unix machines too (as I don't have a Windows machine to run this on;-). Using the usual kjv.txt file:\n$ wc kjv.txt\n 114150 821108 4834378 kjv.txt\n\n(4.8 MB, 114 Klines) -- about 1/1000th of the kind of file sizes I was mentioning earlier:\n$ python -mtimeit 'f=open(\"kjv.txt\", \"rb\")' 'f.seek(0); f.read()'\n100 loops, best of 3: 13.9 msec per loop\n$ python -mtimeit 'f=open(\"kjv.txt\", \"rU\")' 'f.seek(0); f.read()'\n10 loops, best of 3: 39.2 msec per loop\n\ni.e., just about exactly a factor of 3 cost for the line-end processing (this is on an old-ish laptop, but the ratio should be pretty repeatable elsewhere, too).\nReading by a loop on lines, of course, is even slower:\n$ python -mtimeit 'f=open(\"kjv.txt\", \"rU\")' 'f.seek(0)' 'for x in f: pass'\n10 loops, best of 3: 54.6 msec per loop\n\nand using readline as the commented mentioned (with less efficient buffering than directly looping on the file) is worst:\n$ python -mtimeit 'f=open(\"kjv.txt\", \"rU\")' 'f.seek(0); x=1' 'while x: x=f.readline()'\n10 loops, best of 3: 81.1 msec per loop\n\nIf, as the question mentions, there are 20,000 files to read (say they're all small-ish, on the order of this kjv.txt), the fastest approach (reading each file in binary mode in a single gulp) should take about 260 seconds, 4-5 minutes, while the slowest one (based on readline) should take about 1600 seconds, almost half an hour -- a pretty significant difference for many, I'd say most, actual applications.\n", "Unless you know, or can figure out, the offset of line n in your file (for example, if every line were of a fixed width), you will have to read lines until you get to the nth one.\nRegarding your examples:\n\nxrange is faster than range since range has to generate a list, whereas xrange uses a generator\nif you only need line n, why are you storing all of the lines in a dictionary?\n\n", "Caching a list of offsets of every end-of-line character in the file would cost a lot of memory, but caching roughly one per memory page (generally 4KB) gives mostly the same reduction in I/O, and the cost of scanning a couple KB from a known offset is negligible. So, if your average line length is 40 characters, you only have to cache a list of every 100th end-of-line in the file. Exactly where you draw the line depends on how much memory you have and how fast your I/O is. You might even be able to get away with caching a list of the offsets of every 1000th end-of-line character without a noticeable difference in performance from indexing every single one.\n" ]
[ 5, 2, 0 ]
[]
[]
[ "io", "performance", "python" ]
stackoverflow_0003011686_io_performance_python.txt
Q: How to detect non-graceful disconnect of Twisted on Linux? I wrote a server based on Twisted, and I encountered a problem, some of the clients are disconnected not gracefully. For example, the user pulls out the network cable. For a while, the client on Windows is disconnected (the connectionLost is called, and it is also written in Twisted). And on the Linux server side, my connectionLost of twisted is never triggered. Even it try to writes data to client when the connection is lost. Why Twisted can't detect those non-graceful disconnection (even write data to client) on Linux? How to makes Twisted detect non-graceful disconnections? Because the feature Twisted can't detect non-graceful, I have lots of zombie user on my server. ---- Update ---- I thought it might be the feature of socket of unix-like os, so, what is the behavior of socket on unix-like for handling situation like this? Thanks. Victor Lin. A: You're describing the behavior of TCP connections on an unreliable network. Twisted is merely exposing this behavior: after all, when you set up a TCP connection with Twisted, it is nothing more than a TCP connection. You're mistaken when you say that the connectionLost callback isn't invoked even if you try to send data over it. After two minutes, the underlying TCP connection will disappear and Twisted will inform you of this by calling connectionLost. If you need to detect this condition more quickly than that, then you can implement your own timeouts using reactor.callLater. A: Seconding what Jean-Paul said, if you need more fine grained TCP connection management, just use reactor.CallLater. We have exactly that implementation on a Twisted/wxPython trading platform, and it works a treat. You might also want to tweak the behaviour of the ReconnectingClientFactory in order to achieve the results I understand your looking for.
How to detect non-graceful disconnect of Twisted on Linux?
I wrote a server based on Twisted, and I encountered a problem, some of the clients are disconnected not gracefully. For example, the user pulls out the network cable. For a while, the client on Windows is disconnected (the connectionLost is called, and it is also written in Twisted). And on the Linux server side, my connectionLost of twisted is never triggered. Even it try to writes data to client when the connection is lost. Why Twisted can't detect those non-graceful disconnection (even write data to client) on Linux? How to makes Twisted detect non-graceful disconnections? Because the feature Twisted can't detect non-graceful, I have lots of zombie user on my server. ---- Update ---- I thought it might be the feature of socket of unix-like os, so, what is the behavior of socket on unix-like for handling situation like this? Thanks. Victor Lin.
[ "You're describing the behavior of TCP connections on an unreliable network. Twisted is merely exposing this behavior: after all, when you set up a TCP connection with Twisted, it is nothing more than a TCP connection.\nYou're mistaken when you say that the connectionLost callback isn't invoked even if you try to send data over it. After two minutes, the underlying TCP connection will disappear and Twisted will inform you of this by calling connectionLost.\nIf you need to detect this condition more quickly than that, then you can implement your own timeouts using reactor.callLater.\n", "Seconding what Jean-Paul said, if you need more fine grained TCP connection management, just use reactor.CallLater. We have exactly that implementation on a Twisted/wxPython trading platform, and it works a treat. You might also want to tweak the behaviour of the ReconnectingClientFactory in order to achieve the results I understand your looking for.\n" ]
[ 3, 1 ]
[]
[]
[ "networking", "python", "twisted" ]
stackoverflow_0003003450_networking_python_twisted.txt
Q: Reading UTF-8 XML and writing it to a file with Python I'm trying to parse UTF-8 XML file and save some parts of it to another file. Problem is, that this is my first Python script ever and I'm totally confused about the character encoding problems I'm finding. My script fails immediately when it tries to write non-ascii character to a file, but it can print it to command prompt (at least in some level) Here's the XML (from the parts that matter at least, it's a *.resx file which contains UI strings) <?xml version="1.0" encoding="utf-8"?> <root> <resheader name="foo"> <value>bar</value> </resheader> <data name="lorem" xml:space="preserve"> <value>ipsum öä</value> </data> </root> And here's my python script from xml.dom.minidom import parse names = [] values = [] def getStrings(path): dom = parse(path) data = dom.getElementsByTagName("data") for i in range(len(data)): name = data[i].getAttribute("name") names.append(name) value = data[i].getElementsByTagName("value") values.append(value[0].firstChild.nodeValue.encode("utf-8")) def writeToFile(): with open("uiStrings-fi.py", "w") as f: for i in range(len(names)): line = names[i] + '="'+ values[i] + '"' #varName='varValue' f.write(line) f.write("\n") getStrings("ResourceFile.fi-FI.resx") writeToFile() And here's the traceback: Traceback (most recent call last): File "GenerateLanguageFiles.py", line 24, in writeToFile() File "GenerateLanguageFiles.py", line 19, in writeToFile line = names[i] + '="'+ values[i] + '"' #varName='varValue' UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 2: ordinal not in ran ge(128) How should I fix my script so it would read and write UTF-8 characters properly? The files I'm trying to generate would be used in test automation with Robots Framework. A: You'll need to remove the call to encode() - that is, replace nodeValue.encode("utf-8") with nodeValue - and then change the call to open() to with open("uiStrings-fi.py", "w", "utf-8") as f: This uses a "Unicode-aware" version of open() which you will need to import from the codecs module, so also add from codecs import open to the top of the file. The issue is that when you were calling nodeValue.encode("utf-8"), you were converting a Unicode string (Python's internal representation that can store all Unicode characters) into a regular string (which can only store single-byte characters 0-255). Later on, when you construct the line to write to the output file, names[i] is still a Unicode string but values[i] is a regular string. Python tries to convert the regular string to Unicode, which is the more general type, but because you don't specify an explicit conversion, it uses the ASCII codec, which is the default, and ASCII can't handle characters with byte values greater than 127. Unfortunately, several of those do occur in the string values[i] because the UTF-8 encoding uses those upper-range bytes frequently. So Python complains that it sees a character it can't handle. The solution, as I said above, is to defer the conversion from Unicode to bytes until the last possible moment, and you do that by using the Unicode-aware version of open (which will handle the encoding for you). Now that I think about it, instead of what I said above, an alternate solution would be to replace names[i] with names[i].encode("utf-8"). That way, you convert names[i] into a regular string as well, and Python has no reason to try to convert values[i] back to Unicode. Although, one could make the argument that it's good practice to keep your strings as Unicode objects until you write them out to the file... if nothing else, I believe unicode becomes the default in Python 3. A: The XML parser decodes the UTF-8 encoding of the input when it reads the file and all the text nodes and attributes of the resulting DOM are then unicode objects. When you select the interesting data from the DOM, you re-encode the values as UTF-8, but you don't encode the names. The resulting values array contains encoded byte strings while the names array still contains unicode objects. In the line where the encoding error is thrown, Python tries to concatenate such a unicode name and a byte string value. To do so, both values have to be of the same type and Python tries to convert the byte string values[i] to unicode, but it doesn't know that it's UTF-8 encoded and fails when it tries to use the ASCII codec. The easiest way to work around this would be to keep all the strings as Unicode objects and just encode them to UTF-8 when they are written to the file: values.append(value[0].firstChild.nodeValue) # encode not yet ... f.write(line.encode('utf-8')) # but now
Reading UTF-8 XML and writing it to a file with Python
I'm trying to parse UTF-8 XML file and save some parts of it to another file. Problem is, that this is my first Python script ever and I'm totally confused about the character encoding problems I'm finding. My script fails immediately when it tries to write non-ascii character to a file, but it can print it to command prompt (at least in some level) Here's the XML (from the parts that matter at least, it's a *.resx file which contains UI strings) <?xml version="1.0" encoding="utf-8"?> <root> <resheader name="foo"> <value>bar</value> </resheader> <data name="lorem" xml:space="preserve"> <value>ipsum öä</value> </data> </root> And here's my python script from xml.dom.minidom import parse names = [] values = [] def getStrings(path): dom = parse(path) data = dom.getElementsByTagName("data") for i in range(len(data)): name = data[i].getAttribute("name") names.append(name) value = data[i].getElementsByTagName("value") values.append(value[0].firstChild.nodeValue.encode("utf-8")) def writeToFile(): with open("uiStrings-fi.py", "w") as f: for i in range(len(names)): line = names[i] + '="'+ values[i] + '"' #varName='varValue' f.write(line) f.write("\n") getStrings("ResourceFile.fi-FI.resx") writeToFile() And here's the traceback: Traceback (most recent call last): File "GenerateLanguageFiles.py", line 24, in writeToFile() File "GenerateLanguageFiles.py", line 19, in writeToFile line = names[i] + '="'+ values[i] + '"' #varName='varValue' UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 2: ordinal not in ran ge(128) How should I fix my script so it would read and write UTF-8 characters properly? The files I'm trying to generate would be used in test automation with Robots Framework.
[ "You'll need to remove the call to encode() - that is, replace nodeValue.encode(\"utf-8\") with nodeValue - and then change the call to open() to\nwith open(\"uiStrings-fi.py\", \"w\", \"utf-8\") as f:\n\nThis uses a \"Unicode-aware\" version of open() which you will need to import from the codecs module, so also add\nfrom codecs import open\n\nto the top of the file.\nThe issue is that when you were calling nodeValue.encode(\"utf-8\"), you were converting a Unicode string (Python's internal representation that can store all Unicode characters) into a regular string (which can only store single-byte characters 0-255). Later on, when you construct the line to write to the output file, names[i] is still a Unicode string but values[i] is a regular string. Python tries to convert the regular string to Unicode, which is the more general type, but because you don't specify an explicit conversion, it uses the ASCII codec, which is the default, and ASCII can't handle characters with byte values greater than 127. Unfortunately, several of those do occur in the string values[i] because the UTF-8 encoding uses those upper-range bytes frequently. So Python complains that it sees a character it can't handle. The solution, as I said above, is to defer the conversion from Unicode to bytes until the last possible moment, and you do that by using the Unicode-aware version of open (which will handle the encoding for you).\nNow that I think about it, instead of what I said above, an alternate solution would be to replace names[i] with names[i].encode(\"utf-8\"). That way, you convert names[i] into a regular string as well, and Python has no reason to try to convert values[i] back to Unicode. Although, one could make the argument that it's good practice to keep your strings as Unicode objects until you write them out to the file... if nothing else, I believe unicode becomes the default in Python 3.\n", "The XML parser decodes the UTF-8 encoding of the input when it reads the file and all the text nodes and attributes of the resulting DOM are then unicode objects. When you select the interesting data from the DOM, you re-encode the values as UTF-8, but you don't encode the names. The resulting values array contains encoded byte strings while the names array still contains unicode objects.\nIn the line where the encoding error is thrown, Python tries to concatenate such a unicode name and a byte string value. To do so, both values have to be of the same type and Python tries to convert the byte string values[i] to unicode, but it doesn't know that it's UTF-8 encoded and fails when it tries to use the ASCII codec.\nThe easiest way to work around this would be to keep all the strings as Unicode objects and just encode them to UTF-8 when they are written to the file:\nvalues.append(value[0].firstChild.nodeValue) # encode not yet\n...\nf.write(line.encode('utf-8')) # but now\n\n" ]
[ 8, 0 ]
[]
[]
[ "python", "utf_8", "xml" ]
stackoverflow_0003011939_python_utf_8_xml.txt
Q: Track window/control resize in PyQt? I have a window with 2 QTableWidgets, having their scrolling synchronized. The 1st one usually has horizontal scroll, while the 2nd usually (automatically) not. In order for them to show consistent data (row against row) I make the 2nd have the scroll (through property HorizontalScrollBar -> AlwaysOn). But sometimes the 1st table doesn't have the scroll. What's event worse, it may have it or not depending on the window size (when making window wider the scroll disappears). As far as I see there's no signal for resize of window or control (widget). I can, of course, use some constantly running timer to check if 1st table has scroll, but I wounder if there's more pure solution. Thanks! A: The answer was to reimplement the resizeEvent and check table.horizontalScrollBar().isVisible()
Track window/control resize in PyQt?
I have a window with 2 QTableWidgets, having their scrolling synchronized. The 1st one usually has horizontal scroll, while the 2nd usually (automatically) not. In order for them to show consistent data (row against row) I make the 2nd have the scroll (through property HorizontalScrollBar -> AlwaysOn). But sometimes the 1st table doesn't have the scroll. What's event worse, it may have it or not depending on the window size (when making window wider the scroll disappears). As far as I see there's no signal for resize of window or control (widget). I can, of course, use some constantly running timer to check if 1st table has scroll, but I wounder if there's more pure solution. Thanks!
[ "The answer was to reimplement the resizeEvent and check table.horizontalScrollBar().isVisible()\n" ]
[ 0 ]
[]
[]
[ "pyqt4", "python" ]
stackoverflow_0002916052_pyqt4_python.txt
Q: Python style: if statements vs. boolean evaluation One of the ideas of Python's design philosophy is "There should be one ... obvious way to do it." (PEP 20), but that can't always be true. I'm specifically referring to (simple) if statements versus boolean evaluation. Consider the following: if words: self.words = words else: self.words = {} versus self.words = words or {} With such a simple situation, which is preferable, stylistically speaking? With more complicated situations one would choose the if statement for readability, right? A: "There should be only one" can perfectly well always be true; it's the positive assertion "there is only one" that cannot be -- "should" implies a target, a goal, not the possibility of always reaching it (e.g., for numbers a and b, forbidding either b + a or a + b would be so absurd that there just cannot sensibly be "only one way" in this case). In your example, I would agree that the or is preferable in sufficiently simple cases (four lines to do what can be done in one clear and readable line is a waste of vertical space) but not for a predicate of any significant complexity. Deciding what has "significant complexity" is, of course, a judgment call. A: In this case I'd say "Explicit is better than implicit". When someone reads your code, they can make a few assumptions. They can assume that "words" can be either an empty dict or one with data in it (missing the case when it is None) In that case, they might be tempted to optimize your code. They might even be right to do it, if it isn't stated anywhere that you can get a None value. If "words" can in fact be None, I'd try to be clear about that with: self.words = words if words is None: self.words = {} Or possibly an "else" instead of unconditional assignment first. In any case, this way you sort of document the fact that None is an expected value for "words". A: (Edited) well in a case like below, i vote for the conditional expression def somesuch(self, words=None): self.words = words or {} ... of course, if you think that'd improve readability (you can read it aloud that way?), you can try self.words = words if words else {}
Python style: if statements vs. boolean evaluation
One of the ideas of Python's design philosophy is "There should be one ... obvious way to do it." (PEP 20), but that can't always be true. I'm specifically referring to (simple) if statements versus boolean evaluation. Consider the following: if words: self.words = words else: self.words = {} versus self.words = words or {} With such a simple situation, which is preferable, stylistically speaking? With more complicated situations one would choose the if statement for readability, right?
[ "\"There should be only one\" can perfectly well always be true; it's the positive assertion \"there is only one\" that cannot be -- \"should\" implies a target, a goal, not the possibility of always reaching it (e.g., for numbers a and b, forbidding either b + a or a + b would be so absurd that there just cannot sensibly be \"only one way\" in this case).\nIn your example, I would agree that the or is preferable in sufficiently simple cases (four lines to do what can be done in one clear and readable line is a waste of vertical space) but not for a predicate of any significant complexity. Deciding what has \"significant complexity\" is, of course, a judgment call.\n", "In this case I'd say \"Explicit is better than implicit\".\nWhen someone reads your code, they can make a few assumptions.\nThey can assume that \"words\" can be either an empty dict or one with data in it (missing the case when it is None)\nIn that case, they might be tempted to optimize your code. \nThey might even be right to do it, if it isn't stated anywhere that you can get a None value.\nIf \"words\" can in fact be None, I'd try to be clear about that with:\nself.words = words\nif words is None:\n self.words = {}\n\nOr possibly an \"else\" instead of unconditional assignment first. \nIn any case, this way you sort of document the fact that None is an expected value for \"words\".\n", "(Edited)\nwell in a case like below, i vote for the conditional expression\ndef somesuch(self, words=None):\n self.words = words or {}\n ...\n\nof course, if you think that'd improve readability (you can read it aloud that way?), you can try\nself.words = words if words else {}\n\n" ]
[ 9, 2, 0 ]
[]
[]
[ "coding_style", "if_statement", "python" ]
stackoverflow_0003011763_coding_style_if_statement_python.txt
Q: HowTo init Django model, before using it? I'm new to python and django. Apps | Versions: Python 2.6.2 Django (working with PostgreSQL) Question: I wrote a simple model: class OperationType(models.Model): eid = models.IntegerField() name = models.TextField(blank=True) description = models.TextField(blank=True) def __unicode__(self): tpl = 'eid="', str(self.eid), '" name="', self.name, '"' return ''.join(tpl) Now I need to initialize it, for example with this data: 0, "None" 1, "Add" 2, "Edit" 3, "Delete" But I need to initialize this data not with admin web panel, but after class model created in the same code. How to do this? Thanks for help! ADDED: file initial_data.json: [ { "model": "OperationType", "pk": 1, "fields": { "eid": 0, "name": "None", "description": "Do nothing" } }, { "model": "OperationType", "pk": 2, "fields": { "eid": 1, "name": "Add", "description": "Adding transaction" } } ] A: Here. A: You can use fixtures, check the Django Document.
HowTo init Django model, before using it?
I'm new to python and django. Apps | Versions: Python 2.6.2 Django (working with PostgreSQL) Question: I wrote a simple model: class OperationType(models.Model): eid = models.IntegerField() name = models.TextField(blank=True) description = models.TextField(blank=True) def __unicode__(self): tpl = 'eid="', str(self.eid), '" name="', self.name, '"' return ''.join(tpl) Now I need to initialize it, for example with this data: 0, "None" 1, "Add" 2, "Edit" 3, "Delete" But I need to initialize this data not with admin web panel, but after class model created in the same code. How to do this? Thanks for help! ADDED: file initial_data.json: [ { "model": "OperationType", "pk": 1, "fields": { "eid": 0, "name": "None", "description": "Do nothing" } }, { "model": "OperationType", "pk": 2, "fields": { "eid": 1, "name": "Add", "description": "Adding transaction" } } ]
[ "Here.\n", "You can use fixtures, check the Django Document.\n" ]
[ 2, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003012481_django_python.txt
Q: Importing data from a text file using python I have a text file containing data in rows and columns (~17000 rows in total). Each column is a uniform number of characters long, with the 'unused' characters filled in by spaces. For example, the first column is 11 characters long, but the last four characters in that column are always spaces (so that it appears to be a nice column when viewed with a text editor). Sometimes it's more than four if the entry is less than 7 characters. The columns are not otherwise separated by commas, tabs, or spaces. They are also not all the same number of characters (the first two are 11, the next two are 8 and the last one is 5 - but again, some are spaces). What I want to do is import the entires (which are numbers) in the last two columns if the second column contains the string 'OW' somewhere in it. Any help would be greatly appreciated. A: Python's struct.unpack is probably the quickest way to split fixed-length fields. Here's a function that will lazily read your file and return tuples of numbers that match your criteria: import struct def parsefile(filename): with open(filename) as myfile: for line in myfile: line = line.rstrip('\n') fields = struct.unpack('11s11s8s8s5s', line) if 'OW' in fields[1]: yield (int(fields[3]), int(fields[4])) Usage: if __name__ == '__main__': for field in parsefile('file.txt'): print field Test data: 1234567890a1234567890a123456781234567812345 something maybe OW d 111111118888888855555 aaaaa bbbbb 1234 1212121233333 other thinganother OW 121212 6666666644444 Output: (88888888, 55555) (66666666, 44444) A: In Python you can extract a substring at known positions using a slice - this is normally done with the list[start:end] syntax. However you can also create slice objects that you can use later to do the indexing. So you can do something like this: columns = [slice(11,22), slice(30,38), slice(38,44)] myfile = open('some/file/path') for line in myfile: fields = [line[column].strip() for column in columns] if "OW" in fields[0]: value1 = int(fields[1]) value12 = int(fields[2]) .... Separating out the slices into a list makes it easy to change the code if the data format changes, or you need to do stuff with the other fields. A: entries = ((float(line[30:38]), float(line[38:43])) for line in myfile if "OW" in line[11:22]) for num1, num2 in entries: # whatever A: Here's a function which might help you: def rows(f, columnSizes): while True: row = {} for (key, size) in columnSizes: value = f.read(size) if len(value) < size: # EOF return row[key] = value yield row for an example of how it's used: from StringIO import StringIO sample = StringIO("""aaabbbccc d e f g h i """) for row in rows(sample, [('first', 3), ('second', 3), ('third', 4)]): print repr(row) Note that unlike the other answers, this example is not line-delimited (it uses the file purely as a provider of bytes, not an iterator of lines), since you specifically mentioned that the fields were not separated, I assumed that the rows might not be either; the newline is taken into account specifically. You can test if one string is a substring of another with the 'in' operator. For example, >>> 'OW' in 'hello' False >>> 'OW' in 'helOWlo' True So in this case, you might do if 'OW' in row['third']: stuff() but you can obviously test any field for any value as you see fit.
Importing data from a text file using python
I have a text file containing data in rows and columns (~17000 rows in total). Each column is a uniform number of characters long, with the 'unused' characters filled in by spaces. For example, the first column is 11 characters long, but the last four characters in that column are always spaces (so that it appears to be a nice column when viewed with a text editor). Sometimes it's more than four if the entry is less than 7 characters. The columns are not otherwise separated by commas, tabs, or spaces. They are also not all the same number of characters (the first two are 11, the next two are 8 and the last one is 5 - but again, some are spaces). What I want to do is import the entires (which are numbers) in the last two columns if the second column contains the string 'OW' somewhere in it. Any help would be greatly appreciated.
[ "Python's struct.unpack is probably the quickest way to split fixed-length fields. Here's a function that will lazily read your file and return tuples of numbers that match your criteria:\nimport struct\n\ndef parsefile(filename):\n with open(filename) as myfile:\n for line in myfile:\n line = line.rstrip('\\n')\n fields = struct.unpack('11s11s8s8s5s', line)\n if 'OW' in fields[1]:\n yield (int(fields[3]), int(fields[4]))\n\nUsage:\nif __name__ == '__main__':\n for field in parsefile('file.txt'):\n print field\n\nTest data:\n1234567890a1234567890a123456781234567812345\nsomething maybe OW d 111111118888888855555\naaaaa bbbbb 1234 1212121233333\nother thinganother OW 121212 6666666644444\n\nOutput:\n(88888888, 55555)\n(66666666, 44444)\n\n", "In Python you can extract a substring at known positions using a slice - this is normally done with the list[start:end] syntax. However you can also create slice objects that you can use later to do the indexing.\nSo you can do something like this:\ncolumns = [slice(11,22), slice(30,38), slice(38,44)]\n\nmyfile = open('some/file/path')\nfor line in myfile:\n fields = [line[column].strip() for column in columns]\n if \"OW\" in fields[0]:\n value1 = int(fields[1])\n value12 = int(fields[2]) \n ....\n\nSeparating out the slices into a list makes it easy to change the code if the data format changes, or you need to do stuff with the other fields.\n", "entries = ((float(line[30:38]), float(line[38:43])) for line in myfile if \"OW\" in line[11:22])\n\nfor num1, num2 in entries:\n # whatever\n\n", "Here's a function which might help you:\ndef rows(f, columnSizes):\n while True:\n row = {}\n for (key, size) in columnSizes:\n value = f.read(size)\n if len(value) < size: # EOF\n return\n row[key] = value\n yield row\n\nfor an example of how it's used:\nfrom StringIO import StringIO\n\nsample = StringIO(\"\"\"aaabbbccc\nd e f \ng h i \n\"\"\")\n\nfor row in rows(sample, [('first', 3),\n ('second', 3),\n ('third', 4)]):\n print repr(row)\n\nNote that unlike the other answers, this example is not line-delimited (it uses the file purely as a provider of bytes, not an iterator of lines), since you specifically mentioned that the fields were not separated, I assumed that the rows might not be either; the newline is taken into account specifically.\nYou can test if one string is a substring of another with the 'in' operator. For example,\n>>> 'OW' in 'hello'\nFalse\n>>> 'OW' in 'helOWlo'\nTrue\n\nSo in this case, you might do\nif 'OW' in row['third']:\n stuff()\n\nbut you can obviously test any field for any value as you see fit.\n" ]
[ 4, 3, 0, 0 ]
[ "entries = []\nwith open('my_file.txt', 'r') as f:\n for line in f.read().splitlines()\n line = line.split()\n if line[1].find('OW') >= 0\n entries.append( ( int(line[-2]) , int(line[-1]) ) )\n\nentries is an array containing tuples of the last two entries\nedit: oops\n" ]
[ -2 ]
[ "python" ]
stackoverflow_0003012353_python.txt
Q: How to make a increasing numbers after filenames in C? I have a little problem. I need to do some little operations on quite many files in one little program. So far I have decided to operate them in a single loop where I just change the number after the name. The files are all named TFxx.txt where xx is increasing number from 1 to 80. So how can I open them all in a single loop one after one? I have tried this: for(i=1; i<=80; i++) { char name[8] = "TF"+i+".txt"; FILE = open(name, r); /* Do something */ } As you can see the second line would be working in python but not in C. I have tried to do similiar running numbering with C to this program, but I haven't found out yet how to do that. The format doesn't need to be as it is on the second line, but I'd like to have some advice of how can I solve this problem. All I need to do is just be able to open many files and do same operations to them. A: You can use sprintf as follows: for(i=0; i<=80; i++) { char name[32]; memset(name, 0, sizeof(name)); FILE *fp; sprintf(name, "TF%d.txt", i); fp = fopen(name, "r"); /* Do something */ } A: In addition to Daniels answer I would like to add that char name[8] should be little bigger to hold the terminating '\0' i.g. char name[20]; and FILE = open(name,r); should be FILE * fp = fopen(name,"r"); A: Let us suppose yours is just pseudocode; otherwise the problem is not only char name[8] = "TF"+i+".txt"; where you use a sum to concatenate strings and convert an integer into string... (this is reasonable on some languages, absolutely not in C, where the + is just a sum between numbers)... but also FILE = open... is problematic... char name[BUFLEN]; sprintf(name, "TF%d.txt", i); would fill your name (snprintf(name, BUFLEN, "TF%d.txt") could be better, but it is C99, while the other is C89 too). Files can be opened using something like FILE *fh = fopen(name, "r") for reading. A: Maybe I am wrong, but just use fopen instead of open and write "r" instead of r? FILE = fopen(name, "r"); A: And shouldn't char name[32] be outside the for loop?
How to make a increasing numbers after filenames in C?
I have a little problem. I need to do some little operations on quite many files in one little program. So far I have decided to operate them in a single loop where I just change the number after the name. The files are all named TFxx.txt where xx is increasing number from 1 to 80. So how can I open them all in a single loop one after one? I have tried this: for(i=1; i<=80; i++) { char name[8] = "TF"+i+".txt"; FILE = open(name, r); /* Do something */ } As you can see the second line would be working in python but not in C. I have tried to do similiar running numbering with C to this program, but I haven't found out yet how to do that. The format doesn't need to be as it is on the second line, but I'd like to have some advice of how can I solve this problem. All I need to do is just be able to open many files and do same operations to them.
[ "You can use sprintf as follows:\nfor(i=0; i<=80; i++) {\n char name[32];\n memset(name, 0, sizeof(name));\n FILE *fp;\n sprintf(name, \"TF%d.txt\", i);\n fp = fopen(name, \"r\");\n /* Do something */\n }\n\n", "In addition to Daniels answer I would like to add that\nchar name[8] should be little bigger to hold the terminating '\\0' i.g. char name[20];\nand FILE = open(name,r); should be FILE * fp = fopen(name,\"r\");\n", "Let us suppose yours is just pseudocode; otherwise the problem is not only\nchar name[8] = \"TF\"+i+\".txt\";\nwhere you use a sum to concatenate strings and convert an integer into string... (this is reasonable on some languages, absolutely not in C, where the + is just a sum between numbers)... but also FILE = open... is problematic...\nchar name[BUFLEN];\nsprintf(name, \"TF%d.txt\", i);\n\nwould fill your name (snprintf(name, BUFLEN, \"TF%d.txt\") could be better, but it is C99, while the other is C89 too).\nFiles can be opened using something like FILE *fh = fopen(name, \"r\") for reading.\n", "Maybe I am wrong, but just use fopen instead of open and write \"r\" instead of r?\nFILE = fopen(name, \"r\");\n\n", "And shouldn't char name[32] be outside the for loop?\n" ]
[ 5, 1, 1, 0, 0 ]
[]
[]
[ "c", "file_io", "python" ]
stackoverflow_0003012161_c_file_io_python.txt
Q: python threading and performance? I had to do heavy I/o bound operation, i.e Parsing large files and converting from one format to other format. Initially I used to do it serially, i.e parsing one after another..! Performance was very poor ( it used take 90+ seconds). So I decided to use threading to improve the performance. I created one thread for each file. ( 4 threads) for file in file_list: t=threading.Thread(target = self.convertfile,args = file) t.start() ts.append(t) for t in ts: t.join() But for my astonishment, there is no performance improvement whatsoever. Now also it takes around 90+ seconds to complete the task. As this is I/o bound operation , I had expected to improve the performance. A: Under the usual Python interpreter, threading will not allocate more CPU cores to your program because of the global interpreter lock (aka. the GIL). The multiprocessing module could help you out here. (Note that it was introduced in Python 2.6, but backports exist for Python 2.5.) As MSalters says, if your program is I/O bound it's debatable whether this is useful. But it might be worth a shot :) To achieve what you want using this module: import multiprocessing MAX_PARALLEL_TASKS = 8 # I have an Intel Core i7 :) pool = multiprocessing.Pool(MAX_PARALLEL_TASKS) pool.map_async(convertfile, filelist) pool.close() pool.join() Important! The function that you pass to map_async must be pickleable. In general, instance methods are NOT pickleable unless you engineering them to be so! Note that convertfile above is a function. If you actually need to get results back from convertfile, there are ways to do that as well. The examples on the multiprocessing documentation page should clarify. A: Threading allows the OS to allocate more CPU cores to your program. If it's I/O bound, that means that the speed was limited by the I/O susbsystem speed instead of the CPU speed. In those cases, allocating more CPU cores doesn't necessarily help - you're still waiting on the I/O subsystem.
python threading and performance?
I had to do heavy I/o bound operation, i.e Parsing large files and converting from one format to other format. Initially I used to do it serially, i.e parsing one after another..! Performance was very poor ( it used take 90+ seconds). So I decided to use threading to improve the performance. I created one thread for each file. ( 4 threads) for file in file_list: t=threading.Thread(target = self.convertfile,args = file) t.start() ts.append(t) for t in ts: t.join() But for my astonishment, there is no performance improvement whatsoever. Now also it takes around 90+ seconds to complete the task. As this is I/o bound operation , I had expected to improve the performance.
[ "Under the usual Python interpreter, threading will not allocate more CPU cores to your program because of the global interpreter lock (aka. the GIL).\nThe multiprocessing module could help you out here. (Note that it was introduced in Python 2.6, but backports exist for Python 2.5.)\nAs MSalters says, if your program is I/O bound it's debatable whether this is useful. But it might be worth a shot :)\nTo achieve what you want using this module:\nimport multiprocessing\n\nMAX_PARALLEL_TASKS = 8 # I have an Intel Core i7 :)\n\npool = multiprocessing.Pool(MAX_PARALLEL_TASKS)\n\npool.map_async(convertfile, filelist)\n\npool.close()\npool.join()\n\nImportant! The function that you pass to map_async must be pickleable. In general, instance methods are NOT pickleable unless you engineering them to be so! Note that convertfile above is a function.\nIf you actually need to get results back from convertfile, there are ways to do that as well. The examples on the multiprocessing documentation page should clarify.\n", "Threading allows the OS to allocate more CPU cores to your program. If it's I/O bound, that means that the speed was limited by the I/O susbsystem speed instead of the CPU speed. In those cases, allocating more CPU cores doesn't necessarily help - you're still waiting on the I/O subsystem.\n" ]
[ 10, 2 ]
[]
[]
[ "multithreading", "performance", "python" ]
stackoverflow_0003012508_multithreading_performance_python.txt
Q: Character Encoding My text editor allows me to code in several different character formats Ansi, UTF-8, UTF-8(No BOM), UTF-16LE, and UTF-16BE. What is the difference between them? What is commonly regarded as the best format (I'm using Python if that makes a diffrence)? A: "Ansi" is a misnomer and usually refers to some 8-bit encoding that's the default on the current platform (on "western" Windows installations that's usually Windows-1252). It only supports a small set of characters (256 different characters at most). UTF-8 is a variable-length, ASCII-compatible encoding capable of storing any and all Unicode characters. It's a pretty good choice for western text that should support all Unicode characters and a very viable choice in the general case. "UTF-8 (no BOM)" is the name Windows gives to using UTF-8 without writing a Byte Order Marker. Since a BOM is not needed for UTF-8, it shouldn't be used and this would be the correct choice (pretty much everyone else calls this version simply "UTF-8"!). UTF-16LE and UTF-16BE are the Little Endian and Big Endian versions of the UTF-16 encoding. As UTF-8, UTF-16 is capable of representing any Unicode character, however it is not ASCII-compatible. Generally speaking UTF-8 is a great overall choice and has wide compatibility (just make sure not to write the BOM, because that's what most other software expects). UTF-16 could take less space if the majority of your text is composed of non-ASCII characters (i.e. doesn't use the basic latin alphabet). "Ansi" should only be used when you have a specific need to interact with a legacy application that doesn't support Unicode. An important thing about any encoding is that they are meta-data that need to be communicated in addition to the data. This means that you must know the encoding of some byte stream to interpret it as a text correctly. So you should either use formats that document the actual encoding used (XML is a prime example here) or standardize on a single encoding in a given context and use only that. For example, if you start a software project, then you can specify that all your source code is in a given encoding (again: I suggest UTF-8) and stick with that. For Python files specifically, there's a way to specify the encoding of your source files. A: Here. Note that "ANSI" is usually CP1252. A: You'll probably get greatest utility with UTF-8 No BOM. Forget that ANSI and ASCII exist, they are deprecated dinosaurs.
Character Encoding
My text editor allows me to code in several different character formats Ansi, UTF-8, UTF-8(No BOM), UTF-16LE, and UTF-16BE. What is the difference between them? What is commonly regarded as the best format (I'm using Python if that makes a diffrence)?
[ "\n\"Ansi\" is a misnomer and usually refers to some 8-bit encoding that's the default on the current platform (on \"western\" Windows installations that's usually Windows-1252). It only supports a small set of characters (256 different characters at most).\nUTF-8 is a variable-length, ASCII-compatible encoding capable of storing any and all Unicode characters. It's a pretty good choice for western text that should support all Unicode characters and a very viable choice in the general case.\n\"UTF-8 (no BOM)\" is the name Windows gives to using UTF-8 without writing a Byte Order Marker. Since a BOM is not needed for UTF-8, it shouldn't be used and this would be the correct choice (pretty much everyone else calls this version simply \"UTF-8\"!).\nUTF-16LE and UTF-16BE are the Little Endian and Big Endian versions of the UTF-16 encoding. As UTF-8, UTF-16 is capable of representing any Unicode character, however it is not ASCII-compatible.\n\nGenerally speaking UTF-8 is a great overall choice and has wide compatibility (just make sure not to write the BOM, because that's what most other software expects).\nUTF-16 could take less space if the majority of your text is composed of non-ASCII characters (i.e. doesn't use the basic latin alphabet).\n\"Ansi\" should only be used when you have a specific need to interact with a legacy application that doesn't support Unicode.\nAn important thing about any encoding is that they are meta-data that need to be communicated in addition to the data. This means that you must know the encoding of some byte stream to interpret it as a text correctly. So you should either use formats that document the actual encoding used (XML is a prime example here) or standardize on a single encoding in a given context and use only that.\nFor example, if you start a software project, then you can specify that all your source code is in a given encoding (again: I suggest UTF-8) and stick with that.\nFor Python files specifically, there's a way to specify the encoding of your source files.\n", "Here. Note that \"ANSI\" is usually CP1252.\n", "You'll probably get greatest utility with UTF-8 No BOM. Forget that ANSI and ASCII exist, they are deprecated dinosaurs.\n" ]
[ 8, 3, 3 ]
[]
[]
[ "ansi", "python", "utf_16", "utf_8" ]
stackoverflow_0003012821_ansi_python_utf_16_utf_8.txt
Q: How do Django signals work? How does Django's event routing system work? A: Django signals are synchronous. The handlers are executed as soon as the signal is fired, and control returns only when all appropriate handlers have finished. A: You may find the documentation helpful.
How do Django signals work?
How does Django's event routing system work?
[ "Django signals are synchronous. The handlers are executed as soon as the signal is fired, and control returns only when all appropriate handlers have finished.\n", "You may find the documentation helpful.\n" ]
[ 18, 1 ]
[]
[]
[ "django", "python", "signals" ]
stackoverflow_0003012863_django_python_signals.txt
Q: When you write a Titanium app, is the source code visible to users? When you write an HTML/CSS/JavaScript app for Adobe AIR, the source files sit in a directory visible to anyone who looks. Appcelerator Titanium lets you code in JavaScript, Python, and Ruby. Is the bundling similar to AIR, with all the source exposed? A: According to the Titanium FAQ, yes, your source code will be accessible to anyone who looks for it. A: As Nosredna added in the comment they seem to have gotten arround to that change in their newer framework versions. Look at this question to get some insight from an appcelerator found on how the framework works. I understand this as a compilation process that won't leave a trace of your js files in the package.
When you write a Titanium app, is the source code visible to users?
When you write an HTML/CSS/JavaScript app for Adobe AIR, the source files sit in a directory visible to anyone who looks. Appcelerator Titanium lets you code in JavaScript, Python, and Ruby. Is the bundling similar to AIR, with all the source exposed?
[ "According to the Titanium FAQ, yes, your source code will be accessible to anyone who looks for it.\n", "As Nosredna added in the comment they seem to have gotten arround to that change in their newer framework versions. \nLook at this question to get some insight from an appcelerator found on how the framework works. I understand this as a compilation process that won't leave a trace of your js files in the package. \n" ]
[ 5, 2 ]
[]
[]
[ "javascript", "python", "ria", "ruby", "titanium" ]
stackoverflow_0001020838_javascript_python_ria_ruby_titanium.txt
Q: Anyone Know a Great Sparse One Dimensional Array Library in Python? I am working on an algorithm in Python that uses arrays of int64s heavily. The arrays are typically sparse and are read from and written to constantly. I am currently using relatively large native arrays and the performance is good but the memory usage is high (as expected). I would like to be able to have the array implementation not waste space for values that are not used and allow an index offset other than zero. As an example, if my numbers start at 1,000,000 I would like to be able to index my array starting at 1,000,000 and not be required to waste memory with a million unused values. Array reads and writes needs to be fast. Expanding into new territory can be a small delay but reads and writes should be O(1) if possible. Does anybody know of a library that can do it? Thanks! Updated to mention int64 as the data type. A: It sounds like the blist type (documentation, download) might be just what you're looking for (disclaimer: I'm the author). It has exactly the same interface as Python's list, so there's no learning curve, but it has different performance characteristics. In particular, it can efficiently handle sparse lists in many cases. Below is an example that creates a list with 2**29 elements. It's pretty much instantaneous. Sparse lists created in this manner use O(log n) space. >>> from blist import * >>> x = blist([0]) # x is a blist with one element >>> x *= 2**29 # x is a blist with > 500 million elements >>> x.append(5) # append to x >>> y = x[4:-234234] # Take a 500 million element slice from x >>> del x[3:1024] # Delete a few thousand elements from x Operations that iterate over the whole list still take O(n) time (remove, reverse, count, etc.). The documentation spells out the time-complexity for each operation, so you should be able to assess if it will meet your needs. A: You could remap a numpy sparse matrix into a sparse array - or consider using a hash table(a python dict). As far as the offset is concerned, just wrap whatever storage class you are using and make you own insert/lookup/remove methods. A: I don't know any Python so this is probably an un-answer: In some languages you can simulate a sparse array by defining a function from your index space into your data space. For example (pseudo-code): f[1000000] = 32; f[2000000] = 51; In some languages (the best ones) the form of an array reference (eg f[3]) looks just like the form of a function call (eg f[3]). This is, of course, because an array defines a function from an index space into a data space. It's very easy to implement higher-dimensioned sparse arrays this way too. A: Why not just use a dict? sparse = dict() sparse[100000] = 1234 sparse[123456] = 2345 A: Another option - at least if you're willing to implement one yourself - is a Page table. This is commonly used in virtual memory systems to map virtual addresses to physical addresses, and it works best if your address space is sparsely populated, and used addresses are clustered. If used addresses are randomly distributed, this will be less effective. The basic approach of a page table is the same as a Trie - recursive subdivision. A page table has some fixed number of levels, and each node is an array of a fixed size. If the entry for a given subnode is null, all the leaves covered by that node are null. The main advantage of the page table is that lookups are fast, requiring only a few bit-shifts and dereferences. Let's see a straightforward Python implementation of a 2-level pagetable: class Pagetable(object): def __init__(self, num_bits=8): """Creates a new Pagetable with num_bits bits per level. Args: num_bits: The number of bits per pagetable level. A 2 level pagetable will be able to store indexes between 0 and 2^(num_bits*2). """ self.num_bits = num_bits self.mask = (1 << num_bits) - 1 self.root = [None] * (2 ** num_bits) def __getitem__(self, idx): page = self.root[idx >> self.num_bits] return page and page[idx & self.mask] def __setitem__(self, idx, val): page = self.root[idx >> self.num_bits] if not page: page = self.root[idx >> self.num_bits] = [None] * (2 ** self.num_bits) page[idx & self.mask] = val
Anyone Know a Great Sparse One Dimensional Array Library in Python?
I am working on an algorithm in Python that uses arrays of int64s heavily. The arrays are typically sparse and are read from and written to constantly. I am currently using relatively large native arrays and the performance is good but the memory usage is high (as expected). I would like to be able to have the array implementation not waste space for values that are not used and allow an index offset other than zero. As an example, if my numbers start at 1,000,000 I would like to be able to index my array starting at 1,000,000 and not be required to waste memory with a million unused values. Array reads and writes needs to be fast. Expanding into new territory can be a small delay but reads and writes should be O(1) if possible. Does anybody know of a library that can do it? Thanks! Updated to mention int64 as the data type.
[ "It sounds like the blist type (documentation, download) might be just what you're looking for (disclaimer: I'm the author). It has exactly the same interface as Python's list, so there's no learning curve, but it has different performance characteristics. In particular, it can efficiently handle sparse lists in many cases. Below is an example that creates a list with 2**29 elements. It's pretty much instantaneous. Sparse lists created in this manner use O(log n) space.\n>>> from blist import *\n>>> x = blist([0]) # x is a blist with one element\n>>> x *= 2**29 # x is a blist with > 500 million elements\n>>> x.append(5) # append to x\n>>> y = x[4:-234234] # Take a 500 million element slice from x\n>>> del x[3:1024] # Delete a few thousand elements from x\n\nOperations that iterate over the whole list still take O(n) time (remove, reverse, count, etc.). The documentation spells out the time-complexity for each operation, so you should be able to assess if it will meet your needs.\n", "You could remap a numpy sparse matrix into a sparse array - or consider using a hash table(a python dict). As far as the offset is concerned, just wrap whatever storage class you are using and make you own insert/lookup/remove methods.\n", "I don't know any Python so this is probably an un-answer:\nIn some languages you can simulate a sparse array by defining a function from your index space into your data space. For example (pseudo-code):\nf[1000000] = 32;\nf[2000000] = 51;\n\nIn some languages (the best ones) the form of an array reference (eg f[3]) looks just like the form of a function call (eg f[3]). This is, of course, because an array defines a function from an index space into a data space. It's very easy to implement higher-dimensioned sparse arrays this way too.\n", "Why not just use a dict?\nsparse = dict()\nsparse[100000] = 1234\nsparse[123456] = 2345\n\n", "Another option - at least if you're willing to implement one yourself - is a Page table. This is commonly used in virtual memory systems to map virtual addresses to physical addresses, and it works best if your address space is sparsely populated, and used addresses are clustered. If used addresses are randomly distributed, this will be less effective.\nThe basic approach of a page table is the same as a Trie - recursive subdivision. A page table has some fixed number of levels, and each node is an array of a fixed size. If the entry for a given subnode is null, all the leaves covered by that node are null. The main advantage of the page table is that lookups are fast, requiring only a few bit-shifts and dereferences.\nLet's see a straightforward Python implementation of a 2-level pagetable:\nclass Pagetable(object):\n def __init__(self, num_bits=8):\n \"\"\"Creates a new Pagetable with num_bits bits per level.\n\n Args:\n num_bits: The number of bits per pagetable level.\n A 2 level pagetable will be able to store indexes between 0 and 2^(num_bits*2).\n \"\"\"\n self.num_bits = num_bits\n self.mask = (1 << num_bits) - 1\n self.root = [None] * (2 ** num_bits)\n\n def __getitem__(self, idx):\n page = self.root[idx >> self.num_bits]\n return page and page[idx & self.mask]\n\n def __setitem__(self, idx, val):\n page = self.root[idx >> self.num_bits]\n if not page:\n page = self.root[idx >> self.num_bits] = [None] * (2 ** self.num_bits)\n page[idx & self.mask] = val\n\n" ]
[ 4, 1, 1, 1, 1 ]
[]
[]
[ "algorithm", "arrays", "performance", "python", "sparse_array" ]
stackoverflow_0003003008_algorithm_arrays_performance_python_sparse_array.txt
Q: Sequence and merge jpeg images using Python? im doing a project as part of academic programme.Im doing this in linux platform.here i wanted to create a application which retrieve some information from some pdf files .for eg i have pdfs of subject2,subject1,in both the whole pdf is divided in to 4 modules and i want to get the data of module 1 from pdf..for this purpose my tutor told me to use pdftohtml application and convert pdf files to html and jpeg images.now i want to create a Python script which will combine the pages(which have been coverted in to jpeg images) under module 1 and merge it into a single file and then i will convert it back to pdf . how can i do this?.if anyone can provide any such python script which have done any functions similar to this then it will be very helpful. .... thanks in advance A: Not exactly knowing what you mean my sequence - ImageMagick, esp. its 'montage' is probably the tool you need. IM has python interface, too, altough I have never used it. EDIT: As after your edit I do not get the point of this any more, I cannot recommend anything, either. :(
Sequence and merge jpeg images using Python?
im doing a project as part of academic programme.Im doing this in linux platform.here i wanted to create a application which retrieve some information from some pdf files .for eg i have pdfs of subject2,subject1,in both the whole pdf is divided in to 4 modules and i want to get the data of module 1 from pdf..for this purpose my tutor told me to use pdftohtml application and convert pdf files to html and jpeg images.now i want to create a Python script which will combine the pages(which have been coverted in to jpeg images) under module 1 and merge it into a single file and then i will convert it back to pdf . how can i do this?.if anyone can provide any such python script which have done any functions similar to this then it will be very helpful. .... thanks in advance
[ "Not exactly knowing what you mean my sequence - ImageMagick, esp. its 'montage' is probably the tool you need. IM has python interface, too, altough I have never used it. \nEDIT: As after your edit I do not get the point of this any more, I cannot recommend anything, either. :(\n" ]
[ 2 ]
[]
[]
[ "jpeg", "linux", "merge", "pdf", "python" ]
stackoverflow_0003013134_jpeg_linux_merge_pdf_python.txt
Q: add extra data to response object to render in template İ ned to write a code sniplet that enables to disable connection to some parts of a site. Admin and the mainpage will be displayable, but user section (which uses ajax) will be displayed, but can not be used (vith a transparent div set over the page). Also there is a few pages which will be disabled. my logic is that, i write a middleware, def process_request(self, request): if ayar.tonline_kapali: url_parcalari = request.path.split('/') if url_parcalari[0] not in settings.BAGIMSIZ_URLLER: if not request.is_ajax(): return render_to_response('bakim_modu.html') else: return None that code let me to display a "site closed" message for the urls not in BAGIMSIZ_URLLER (which contains urls that will be accessible) But i do not figure out how can i solve the problem about ajax pages... i need to set a header or something to the response and need to check it in the template. A: here documentation for process_view Usage is simple. process_view is called just before Django calls the view, and get few arguments: request - Request object view_func - View function view_args - Arguments view_kwargs - Keyword arguments Which example do you need?
add extra data to response object to render in template
İ ned to write a code sniplet that enables to disable connection to some parts of a site. Admin and the mainpage will be displayable, but user section (which uses ajax) will be displayed, but can not be used (vith a transparent div set over the page). Also there is a few pages which will be disabled. my logic is that, i write a middleware, def process_request(self, request): if ayar.tonline_kapali: url_parcalari = request.path.split('/') if url_parcalari[0] not in settings.BAGIMSIZ_URLLER: if not request.is_ajax(): return render_to_response('bakim_modu.html') else: return None that code let me to display a "site closed" message for the urls not in BAGIMSIZ_URLLER (which contains urls that will be accessible) But i do not figure out how can i solve the problem about ajax pages... i need to set a header or something to the response and need to check it in the template.
[ "here documentation for process_view\nUsage is simple. process_view is called just before Django calls the view, and get few arguments:\n request - Request object\n view_func - View function\n view_args - Arguments\n view_kwargs - Keyword arguments\nWhich example do you need?\n" ]
[ 1 ]
[]
[]
[ "django", "middleware", "python", "request", "response" ]
stackoverflow_0003012341_django_middleware_python_request_response.txt
Q: trunk works tag doesn't? ---ImportError: No module named 2.1.2 Very confused. In my workspace, the trunk works fine when I do a: python ./manage.py runserver 9090 However when I tag it @ 2.1.2 and then check it out clean from the repository to a temporary directory on my desktop.. I get the following error: Traceback (most recent call last): File "./manage.py", line 33, in execute_manager(settings) File "/usr/local/lib/python2.6/dist-packages/django/core/management/__init__.py", line 360, in execute_manager setup_environ(settings_mod) File "/usr/local/lib/python2.6/dist-packages/django/core/management/__init__.py", line 343, in setup_environ project_module = import_module(project_name) File "/usr/local/lib/python2.6/dist-packages/django/utils/importlib.py", line 35, in import_module __import__(name) ImportError: No module named 2.1.2 Is there something obvious I am missing? A: Django does not like it when the project directory contains periods. Rename it before running the project.
trunk works tag doesn't? ---ImportError: No module named 2.1.2
Very confused. In my workspace, the trunk works fine when I do a: python ./manage.py runserver 9090 However when I tag it @ 2.1.2 and then check it out clean from the repository to a temporary directory on my desktop.. I get the following error: Traceback (most recent call last): File "./manage.py", line 33, in execute_manager(settings) File "/usr/local/lib/python2.6/dist-packages/django/core/management/__init__.py", line 360, in execute_manager setup_environ(settings_mod) File "/usr/local/lib/python2.6/dist-packages/django/core/management/__init__.py", line 343, in setup_environ project_module = import_module(project_name) File "/usr/local/lib/python2.6/dist-packages/django/utils/importlib.py", line 35, in import_module __import__(name) ImportError: No module named 2.1.2 Is there something obvious I am missing?
[ "Django does not like it when the project directory contains periods. Rename it before running the project.\n" ]
[ 4 ]
[]
[]
[ "django", "importerror", "python" ]
stackoverflow_0003013819_django_importerror_python.txt
Q: Python : get all exe files in current directory and run them? First of all this is not homework, I'm in a desperate need for a script that will do the following, my problem is, I've never had to deal with python before so I barely know how to use it - and I need it to launch unit tests in TeamCity via a commandline build runner What I need exactly is : a *.bat file that will run the script a python script that will : get all *_test.exe files in the current working directory run all the files which were the result of the search Best regards A: import glob, os def solution(): for fn in glob.glob("*_text.exe"): os.startfile(fn) A: If you copy this into a file, the script should do as you asked. import os # Access the operating system. def solution(): # Create a function for later. for name in os.listdir(os.getcwd()): if name.lower().endswith('_test.exe'): os.startfile(name) solution() # Execute this inside the CWD.
Python : get all exe files in current directory and run them?
First of all this is not homework, I'm in a desperate need for a script that will do the following, my problem is, I've never had to deal with python before so I barely know how to use it - and I need it to launch unit tests in TeamCity via a commandline build runner What I need exactly is : a *.bat file that will run the script a python script that will : get all *_test.exe files in the current working directory run all the files which were the result of the search Best regards
[ "import glob, os\ndef solution():\n for fn in glob.glob(\"*_text.exe\"):\n os.startfile(fn)\n\n", "If you copy this into a file, the script should do as you asked.\nimport os # Access the operating system.\n\ndef solution(): # Create a function for later.\n for name in os.listdir(os.getcwd()):\n if name.lower().endswith('_test.exe'):\n os.startfile(name)\n\nsolution() # Execute this inside the CWD.\n\n" ]
[ 9, 3 ]
[]
[]
[ "python", "teamcity_5.1" ]
stackoverflow_0003014120_python_teamcity_5.1.txt
Q: Talking to an Authentication Server I'm building my startup and I'm thinking ahead for shared use of services. So far I want to allow people who have a user account on one app to be able to use the same user account on another app. This means I will have to build an authentication server. I would like some opinions on how to allow an app to talk to the authentication server. Should I use curl? Should I use Python's http libs? All the code will be in Python. All it's going to do is ask the authentication server if the person is allowed to use that app and the auth server will return a JSON user object. All authorization (roles and resources) will be app independent, so this app will not have to handle that. Sorry if this seems a bit newbish; this is the first time I have separated authentication from the actual application. A: Assuming you plan to write your own auth client code, it isn't event-driven, and you don't need to validate an https certificate, I would suggest using python's built-in urllib2 to call the auth server. This will minimize dependencies, which ought to make deployment and upgrades easier. That being said, there are more than a few existing auth-related protocols and libraries in the world, some of which might save you some time and security worries over writing code from scratch. For example, if you make your auth server speak OpenID, many off-the-self applications and servers (including Apache) will have auth client plugins already made for you. A: Your question isn't really a programming problem so much as it is an architecture problem. What I would recommend for your specific situation is to setup an LDAP server for authentication, authorization, and accounting (AAA). Then have your applications use that (every language has modules and libraries for LDAP). It is a reliable, secure, proven, and well-known way of handling such things. Even if you strictly want to enforce HTTP-based authentication it is easy enough to slap an authentication server in front of your LDAP and call it a day. There's even existing code to do just that so you won't have to re-invent the wheel. A: There is also CAS that you might wont to look at,
Talking to an Authentication Server
I'm building my startup and I'm thinking ahead for shared use of services. So far I want to allow people who have a user account on one app to be able to use the same user account on another app. This means I will have to build an authentication server. I would like some opinions on how to allow an app to talk to the authentication server. Should I use curl? Should I use Python's http libs? All the code will be in Python. All it's going to do is ask the authentication server if the person is allowed to use that app and the auth server will return a JSON user object. All authorization (roles and resources) will be app independent, so this app will not have to handle that. Sorry if this seems a bit newbish; this is the first time I have separated authentication from the actual application.
[ "Assuming you plan to write your own auth client code, it isn't event-driven, and you don't need to validate an https certificate, I would suggest using python's built-in urllib2 to call the auth server. This will minimize dependencies, which ought to make deployment and upgrades easier.\nThat being said, there are more than a few existing auth-related protocols and libraries in the world, some of which might save you some time and security worries over writing code from scratch. For example, if you make your auth server speak OpenID, many off-the-self applications and servers (including Apache) will have auth client plugins already made for you.\n", "Your question isn't really a programming problem so much as it is an architecture problem. What I would recommend for your specific situation is to setup an LDAP server for authentication, authorization, and accounting (AAA). Then have your applications use that (every language has modules and libraries for LDAP). It is a reliable, secure, proven, and well-known way of handling such things.\nEven if you strictly want to enforce HTTP-based authentication it is easy enough to slap an authentication server in front of your LDAP and call it a day. There's even existing code to do just that so you won't have to re-invent the wheel.\n", "There is also CAS that you might wont to look at,\n" ]
[ 1, 0, 0 ]
[]
[]
[ "authentication", "python", "rest" ]
stackoverflow_0002986317_authentication_python_rest.txt
Q: voice communication for python help! I'm currently trying to write a voicechat program in python. All tips/trick is welcome to do this. So far I found pyAudio to be a wrapper of PortAudio. So I played around with that and got an input stream from my microphone to be played back to my speakers. Only RAW of course. But I can't send RAW-data over the netowrk (due the size duh), so I'm looking for a way to encode it. And I searched around the 'net and stumbled over this speex-wrapper for python. It seems to good to be true, and believe me, it was. You see in pyAudio you can set the size of the chunks you want to take from your input audiobuffer, and in that sample code on the link, it's set to 320. Then when it's encoded, its like ~40 bytes of data per chunk, which is fairly acceptable I guess. And now for the problem. I start a sample program which just takes the input stream, encodes the chunks, decodes them and play them (not sending over the network due testing). If I just let my computer idle and run this program it works great, but as soon as I do something, i.e start Firefox or something, the audio input buffer gets all clogged up! It just grows and then it all crashes and gives me an overflow error on the buffer.. OK, so why am I just taking 320 bytes of the stream? I could just take like 1024 bytes or something and that will easy the pressure on the buffer. BUT. If I give speex 1024 bytes of data to encode/decode, it either crashes and says that thats too big for its buffer. OR it encodes/decodes it, but the sound is very noisy and "choppy" as if it only encoded a tiny bit of that 1024 chunk and the rest is static noise. So the sound sounds like a helicopter, lol. I did some research and it seems that speex only can convert 320 bytes of data at time, and well, 640 for wide-band. But that's the standard? How can I fix this problem? How should I construct my program to work with speex? I could use a middle-buffer tho that takes all available data to read from the buffer, then chunk this up in 320 bits and encode/decode them. But this takes a bit longer time and seems like a very bad solution of the problem.. Because as far as I know, there's no other encoder for python that encodes the audio so it can be sent over the network in acceptable small packages, or? I've been googling for three days now. Also there is this pyMedia library, I don't know if its good to convert to mp3/ogg for this kind of software. Thank in in advance for reading this, hope anyone can help me! (: A: You could try Huffman encoding, it's a pretty neat concept. I don't know how fast you could make it, but I'm sure if you created your own C/C++ module you could make it a lot faster. Of course, there may be already some modules out there that do exactly what you need - I've just never used them, so I'm completely unaware of their existence.
voice communication for python help!
I'm currently trying to write a voicechat program in python. All tips/trick is welcome to do this. So far I found pyAudio to be a wrapper of PortAudio. So I played around with that and got an input stream from my microphone to be played back to my speakers. Only RAW of course. But I can't send RAW-data over the netowrk (due the size duh), so I'm looking for a way to encode it. And I searched around the 'net and stumbled over this speex-wrapper for python. It seems to good to be true, and believe me, it was. You see in pyAudio you can set the size of the chunks you want to take from your input audiobuffer, and in that sample code on the link, it's set to 320. Then when it's encoded, its like ~40 bytes of data per chunk, which is fairly acceptable I guess. And now for the problem. I start a sample program which just takes the input stream, encodes the chunks, decodes them and play them (not sending over the network due testing). If I just let my computer idle and run this program it works great, but as soon as I do something, i.e start Firefox or something, the audio input buffer gets all clogged up! It just grows and then it all crashes and gives me an overflow error on the buffer.. OK, so why am I just taking 320 bytes of the stream? I could just take like 1024 bytes or something and that will easy the pressure on the buffer. BUT. If I give speex 1024 bytes of data to encode/decode, it either crashes and says that thats too big for its buffer. OR it encodes/decodes it, but the sound is very noisy and "choppy" as if it only encoded a tiny bit of that 1024 chunk and the rest is static noise. So the sound sounds like a helicopter, lol. I did some research and it seems that speex only can convert 320 bytes of data at time, and well, 640 for wide-band. But that's the standard? How can I fix this problem? How should I construct my program to work with speex? I could use a middle-buffer tho that takes all available data to read from the buffer, then chunk this up in 320 bits and encode/decode them. But this takes a bit longer time and seems like a very bad solution of the problem.. Because as far as I know, there's no other encoder for python that encodes the audio so it can be sent over the network in acceptable small packages, or? I've been googling for three days now. Also there is this pyMedia library, I don't know if its good to convert to mp3/ogg for this kind of software. Thank in in advance for reading this, hope anyone can help me! (:
[ "You could try Huffman encoding, it's a pretty neat concept. I don't know how fast you could make it, but I'm sure if you created your own C/C++ module you could make it a lot faster.\nOf course, there may be already some modules out there that do exactly what you need - I've just never used them, so I'm completely unaware of their existence.\n" ]
[ 0 ]
[]
[]
[ "networking", "python", "speex", "tcp", "voip" ]
stackoverflow_0003013592_networking_python_speex_tcp_voip.txt
Q: How to delete every reference of an object in Python? Supose you have something like: x = "something" b = x l = [b] How can you delete the object only having one reference, say x? del x won't do the trick; the object is still reachable from b, for example. A: No no no. Python has a garbage collector that has very strong territory issues - it won't mess with you creating objects, you don't mess with it deleting objects. Simply put, it can't be done, and for a good reason. If, for instance, your need comes from cases of, say, caching algorithms that keep references, but should not prevent data from being garbage collected once no one is using it, you might want to take a look at weakref. A: The only solution I see right now is that you should make sure that you are holding the only reference to x, everyone else must not get x itself but a weak reference pointing to x. Weak references are implemented in the weakref module and you can use it this way: >>> import weakref >>> class TestClass(object): ... def bark(self): ... print "woof!" ... def __del__(self): ... print "destructor called" ... >>> x = TestClass() >>> b = weakref.proxy(x) >>> b <weakproxy at 0x7fa44dbddd08; to TestClass at 0x7fa44f9093d0> >>> b.bark() woof! >>> del x destructor called >>> b.bark() Traceback (most recent call last): File "<stdin>", line 1, in <module> ReferenceError: weakly-referenced object no longer exists However, note that not all classes can be weak-referenced. In particular, most built-in types cannot. Some built-in types can be weak-referenced if you subclass them (like dict), but others cannot (like int). A: You don't. That's the entire point. Imagine if l is in a library outside of your control. It has every right to expect that the collection elements don't dissappear. Also, imagine if it was otherwise. You'd have questions here on SO "How do I prevent others from deleting my objects?". As a language designer, you can't satisfy both demands.
How to delete every reference of an object in Python?
Supose you have something like: x = "something" b = x l = [b] How can you delete the object only having one reference, say x? del x won't do the trick; the object is still reachable from b, for example.
[ "No no no. Python has a garbage collector that has very strong territory issues - it won't mess with you creating objects, you don't mess with it deleting objects.\nSimply put, it can't be done, and for a good reason.\nIf, for instance, your need comes from cases of, say, caching algorithms that keep references, but should not prevent data from being garbage collected once no one is using it, you might want to take a look at weakref.\n", "The only solution I see right now is that you should make sure that you are holding the only reference to x, everyone else must not get x itself but a weak reference pointing to x. Weak references are implemented in the weakref module and you can use it this way:\n>>> import weakref\n>>> class TestClass(object):\n... def bark(self):\n... print \"woof!\"\n... def __del__(self):\n... print \"destructor called\"\n...\n>>> x = TestClass()\n>>> b = weakref.proxy(x)\n>>> b\n<weakproxy at 0x7fa44dbddd08; to TestClass at 0x7fa44f9093d0>\n>>> b.bark()\nwoof!\n>>> del x\ndestructor called\n>>> b.bark()\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nReferenceError: weakly-referenced object no longer exists\n\nHowever, note that not all classes can be weak-referenced. In particular, most built-in types cannot. Some built-in types can be weak-referenced if you subclass them (like dict), but others cannot (like int).\n", "You don't. That's the entire point. Imagine if l is in a library outside of your control. It has every right to expect that the collection elements don't dissappear.\nAlso, imagine if it was otherwise. You'd have questions here on SO \"How do I prevent others from deleting my objects?\". As a language designer, you can't satisfy both demands. \n" ]
[ 18, 12, 4 ]
[]
[]
[ "del", "garbage_collection", "python", "reference", "weak_references" ]
stackoverflow_0003013304_del_garbage_collection_python_reference_weak_references.txt
Q: PyQt4: My database displays empty cells I am using the pyqt4 framework to do some displays for database forms. Unfortunately, I hit a snag while trying to filter and display my database by last name. Assume that the database connection works. Also assume that I have the correct amount of items in my tupleHeader since I use the same initializeModel method for other methods (like the search() function described below, and it works fine. I call the display() function and it works perfectly fine, but when creating a proxyModel from the sourceModel, and trying to display the proxyModel with my search function, I have empty cells displayed. When I restrict my search so that it filters half my database, it shows that many cells (so most of this is working). But it will not display anything from the database itself. Below is some of my code: from PyQt4 import QtGui, QtCore, QtSql self.caseSensitivity = QtCore.Qt.CaseInsensitive self.syntax = QtCore.QRegExp.FixedString def initializeModel(self, model): model.setTable(self.table) #model.setEditStrategy(QtSql.QSqlTableModel.OnManualSubmit) b = 0 for a in self.tupleHeader: model.setHeaderData(b, QtCore.Qt.Horizontal, QtGui.qApp.tr(a)) b += 1 model.select() def display(self): '''reads all row data and displays it on a tableview''' self.connectdb(self.db, self.localhost, self.dbname, self.username, self.password) model = QtSql.QSqlTableModel() self.initializeModel(model) self.view.setModel(model) self.disconnectdb(self.db) def search(self, searchQuery): '''queries database data, filters it, and displays it on a tableview''' sourceModel = QtSql.QSqlTableModel() proxyModel = QtGui.QSortFilterProxyModel() self.initializeModel(sourceModel) proxyModel.setSourceModel(sourceModel) # allows to edit proxyModel without changing underying model #searchQuery contains the last name that I am filtering with regExp = QtCore.QRegExp(searchQuery, self.caseSensitivity, self.syntax) proxyModel.setFilterRegExp(regExp) proxyModel.setFilterKeyColumn(2) # this column holds the last names # self.view contains the table itemview my application uses to display the database self.view.setModel(proxyModel) EDIT: I am not interested in keeping this piece of code, I just want to know why it allows the table to show the table's content instead of a bunch of empty cells print self.proxyModel.filterAcceptsRow(2, self.sourceModel) Also, if you put in this after the last statement ( self.view.setModel(proxyModel) ), it will show the table, even if it does send an error: print self.proxyModel.filterAcceptsRow(2, self.sourceModel) TypeError: QSortFilterProxyModel.filterAcceptsRow(int, QModelIndex): argument 2 has unexpected type 'QSqlTableModel' It doesn't matter what the arguments are or whether I use filterAcceptsRow ro filterAcceptsColumn, it displays the table. Does this narrow down the problem some? Thank you for your time searching for this coding error/bug, and happy hunting! A: While I could not find the solution to my problem, it solved itself. I am not certain, but I think it was this code snippet that made it work. self.dbmanip = CoreDB(self.userTableView, self.table) This was put inside of the SetupUi() method created by the Qt4 Designer. I think either the dbmanip that contained the TableView lost the information from the proxyModel, or (more likely), I may have referenced the wrong table between the proxyModel and the original Model (that created the proxyModel), and then couldn't display because it was calling the cell structure from one table and the actual information from another. These are all guesses though. Still, problem solved.
PyQt4: My database displays empty cells
I am using the pyqt4 framework to do some displays for database forms. Unfortunately, I hit a snag while trying to filter and display my database by last name. Assume that the database connection works. Also assume that I have the correct amount of items in my tupleHeader since I use the same initializeModel method for other methods (like the search() function described below, and it works fine. I call the display() function and it works perfectly fine, but when creating a proxyModel from the sourceModel, and trying to display the proxyModel with my search function, I have empty cells displayed. When I restrict my search so that it filters half my database, it shows that many cells (so most of this is working). But it will not display anything from the database itself. Below is some of my code: from PyQt4 import QtGui, QtCore, QtSql self.caseSensitivity = QtCore.Qt.CaseInsensitive self.syntax = QtCore.QRegExp.FixedString def initializeModel(self, model): model.setTable(self.table) #model.setEditStrategy(QtSql.QSqlTableModel.OnManualSubmit) b = 0 for a in self.tupleHeader: model.setHeaderData(b, QtCore.Qt.Horizontal, QtGui.qApp.tr(a)) b += 1 model.select() def display(self): '''reads all row data and displays it on a tableview''' self.connectdb(self.db, self.localhost, self.dbname, self.username, self.password) model = QtSql.QSqlTableModel() self.initializeModel(model) self.view.setModel(model) self.disconnectdb(self.db) def search(self, searchQuery): '''queries database data, filters it, and displays it on a tableview''' sourceModel = QtSql.QSqlTableModel() proxyModel = QtGui.QSortFilterProxyModel() self.initializeModel(sourceModel) proxyModel.setSourceModel(sourceModel) # allows to edit proxyModel without changing underying model #searchQuery contains the last name that I am filtering with regExp = QtCore.QRegExp(searchQuery, self.caseSensitivity, self.syntax) proxyModel.setFilterRegExp(regExp) proxyModel.setFilterKeyColumn(2) # this column holds the last names # self.view contains the table itemview my application uses to display the database self.view.setModel(proxyModel) EDIT: I am not interested in keeping this piece of code, I just want to know why it allows the table to show the table's content instead of a bunch of empty cells print self.proxyModel.filterAcceptsRow(2, self.sourceModel) Also, if you put in this after the last statement ( self.view.setModel(proxyModel) ), it will show the table, even if it does send an error: print self.proxyModel.filterAcceptsRow(2, self.sourceModel) TypeError: QSortFilterProxyModel.filterAcceptsRow(int, QModelIndex): argument 2 has unexpected type 'QSqlTableModel' It doesn't matter what the arguments are or whether I use filterAcceptsRow ro filterAcceptsColumn, it displays the table. Does this narrow down the problem some? Thank you for your time searching for this coding error/bug, and happy hunting!
[ "While I could not find the solution to my problem, it solved itself. I am not certain, but I think it was this code snippet that made it work.\nself.dbmanip = CoreDB(self.userTableView, self.table)\n\nThis was put inside of the SetupUi() method created by the Qt4 Designer. I think either the dbmanip that contained the TableView lost the information from the proxyModel, or (more likely), I may have referenced the wrong table between the proxyModel and the original Model (that created the proxyModel), and then couldn't display because it was calling the cell structure from one table and the actual information from another.\nThese are all guesses though. Still, problem solved.\n" ]
[ 0 ]
[]
[]
[ "pyqt4", "python", "qt", "qt4", "qt4.6" ]
stackoverflow_0002997418_pyqt4_python_qt_qt4_qt4.6.txt
Q: Python ftplib - any way to shut it up? I am writing a test harness in python and as part of the testing I need to initialise an FTP server and upload various files. I am using ftplib and everything is working ok. The only problem I have is that I am seeing loads of FTP text appearing in the console window intermixed with my test results, which makes scanning the results quite tricky. I haven't found a way to shut ftp lib up and stop this happening, does anyone know how to stop this? A: You need to manually pass empty (or otherwise customized) callbacks to at least retrlines and dir. By default they print to stdout (questionable design). By default calls (probably for debugging) like myFTP.retrlines(command) myFTP.dir(someDir) will print to your terminal. Remove them or use custom callbacks: myFTP.retrlines(command, retrlinesCallback) myFTP.dir(someDir, dirCallback) retrlinesCallback and dirCallback functions could have logic to e.g. print to the terminal only if debugging is enabled. There is also a set_debuglevel option. The default is 0 (no debugging), but it might be set higher somewhere in the code.
Python ftplib - any way to shut it up?
I am writing a test harness in python and as part of the testing I need to initialise an FTP server and upload various files. I am using ftplib and everything is working ok. The only problem I have is that I am seeing loads of FTP text appearing in the console window intermixed with my test results, which makes scanning the results quite tricky. I haven't found a way to shut ftp lib up and stop this happening, does anyone know how to stop this?
[ "You need to manually pass empty (or otherwise customized) callbacks to at least retrlines and dir. By default they print to stdout (questionable design). By default calls (probably for debugging) like \nmyFTP.retrlines(command)\nmyFTP.dir(someDir)\n\nwill print to your terminal. Remove them or use custom callbacks:\nmyFTP.retrlines(command, retrlinesCallback)\nmyFTP.dir(someDir, dirCallback)\n\nretrlinesCallback and dirCallback functions could have logic to e.g. print to the terminal only if debugging is enabled. \nThere is also a set_debuglevel option. The default is 0 (no debugging), but it might be set higher somewhere in the code.\n" ]
[ 4 ]
[]
[]
[ "ftplib", "python" ]
stackoverflow_0003014624_ftplib_python.txt
Q: What are the implications of running python with the optimize flag? What does Python do differently when running with the -O (optimize) flag? A: assert statements are completely eliminated, as are statement blocks of the form if __debug__: ... (so you can put your debug code in such statements blocks and just run with -O to avoid that debug code). With -OO, in addition, docstrings are also eliminated. A: From the docs: You can use the -O or -OO switches on the Python command to reduce the size of a compiled module. The -O switch removes assert statements, the -OO switch removes both assert statements and __doc__ strings. Since some programs may rely on having these available, you should only use this option if you know what you’re doing. “Optimized” modules have an opt- tag and are usually smaller. Future releases may change the effects of optimization. A program doesn’t run any faster when it is read from a .pyc file than when it is read from a .py file; the only thing that’s faster about .pyc files is the speed with which they are loaded. So in other words, almost nothing. A: From What does the -O flag do? It somewhat depends on the Python version. To find out precisely what it does, search the source code for Py_OptimizeFlag. In 2.5, it causes the interpreter to load .pyo files, not .pyc files (in .zip files, just makes .pyo preferred over .pyc) causes __debug__ to have a value of 0 ignores assert statements in source code treats __debug__ statically as being 0 causes the byte code generator to save .pyo files, not .pyc A: As answered in python optimization mode: python -O does the following currently: completely ignores asserts sets the special builtin name __debug__ to False (which by default is True) and when called as python -OO removes docstrings from the code I don't know why everyone forgets to mention the __debug__ issue; perhaps it is because I'm the only one using it :) An if __debug__ construct creates no bytecode at all when running under -O, and I find that very useful.
What are the implications of running python with the optimize flag?
What does Python do differently when running with the -O (optimize) flag?
[ "assert statements are completely eliminated, as are statement blocks of the form if __debug__: ... (so you can put your debug code in such statements blocks and just run with -O to avoid that debug code).\nWith -OO, in addition, docstrings are also eliminated.\n", "From the docs:\n\n\nYou can use the -O or -OO switches on the Python command to reduce the size of a compiled module. The -O switch removes assert statements, the -OO switch removes both assert statements and __doc__ strings. Since some programs may rely on having these available, you should only use this option if you know what you’re doing. “Optimized” modules have an opt- tag and are usually smaller. Future releases may change the effects of optimization.\nA program doesn’t run any faster when it is read from a .pyc file than when it is read from a .py file; the only thing that’s faster about .pyc files is the speed with which they are loaded.\n\n\nSo in other words, almost nothing.\n", "From What does the -O flag do?\n\nIt somewhat depends on the Python\n version. To find out precisely what it\n does, search the source code for\n Py_OptimizeFlag. In 2.5, it\n\ncauses the interpreter to load .pyo files, not .pyc files (in .zip files,\n just makes .pyo preferred over .pyc)\ncauses __debug__ to have a value of 0\nignores assert statements in source code\ntreats __debug__ statically as being 0\ncauses the byte code generator to save .pyo files, not .pyc\n\n\n", "As answered in python optimization mode:\npython -O does the following currently:\n\ncompletely ignores asserts\nsets the special builtin name __debug__ to False (which by default is True)\n\nand when called as python -OO\n\nremoves docstrings from the code\n\nI don't know why everyone forgets to mention the __debug__ issue; perhaps it is because I'm the only one using it :) An if __debug__ construct creates no bytecode at all when running under -O, and I find that very useful.\n" ]
[ 39, 34, 10, 9 ]
[]
[]
[ "optimization", "python" ]
stackoverflow_0002830358_optimization_python.txt
Q: How to accept localized date format (e.g dd/mm/yy) in a DateField on an admin form? Is it possible to customize a django application to have accept localized date format (e.g dd/mm/yy) in a DateField on an admin form ? I have a model class : class MyModel(models.Model): date = models.DateField("Date") And associated admin class class MyModelAdmin(admin.ModelAdmin): pass On django administration interface, I would like to be able to input a date in following format : dd/mm/yyyy. However, the date field in the admin form expects yyyy-mm-dd. How can I customize things ? Nota bene : I have already specified my custom language code (fr-FR) in settings.py, but it seems to have no effect on this date input matter. Thanks in advance for your answer A: The admin system uses a default ModelForm for editing the objects. You'll need to provide a custom form so that you can begin overriding field behaviour. Inside your modelform, override the field using a DateField, and use the input_formats option. MY_DATE_FORMATS = ['%d/%m/%Y',] class MyModelForm(forms.ModelForm): date = forms.DateField(input_formats=MY_DATE_FORMATS) class Meta: model = MyModel class MyModelAdmin(admin.ModelAdmin): form = MyModelForm A: The fix proposed by Ben is working but the calendar on the right is not shown anymore. Here is an improvement. The calendar will still be shown and the date will be displayed with the %d%%M/%Y format. from django.forms.models import ModelForm from django.contrib.admin.widgets import AdminDateWidget from django.forms.fields import DateField class MyModelForm(ModelForm): date = DateField(input_formats=['%d/%m/%Y',],widget=AdminDateWidget(format='%d/%m/%Y')) class Meta: model = MyModel class MyModelAdmin(admin.ModelAdmin): form = MyModelForm When clicking on a day in the calendar, the value of the field has the %Y-%m-%d format but is is accepted as a valid date format. PS: Thanks to Daniel Roseman for his answer to this question
How to accept localized date format (e.g dd/mm/yy) in a DateField on an admin form?
Is it possible to customize a django application to have accept localized date format (e.g dd/mm/yy) in a DateField on an admin form ? I have a model class : class MyModel(models.Model): date = models.DateField("Date") And associated admin class class MyModelAdmin(admin.ModelAdmin): pass On django administration interface, I would like to be able to input a date in following format : dd/mm/yyyy. However, the date field in the admin form expects yyyy-mm-dd. How can I customize things ? Nota bene : I have already specified my custom language code (fr-FR) in settings.py, but it seems to have no effect on this date input matter. Thanks in advance for your answer
[ "The admin system uses a default ModelForm for editing the objects. You'll need to provide a custom form so that you can begin overriding field behaviour.\nInside your modelform, override the field using a DateField, and use the input_formats option.\nMY_DATE_FORMATS = ['%d/%m/%Y',]\n\nclass MyModelForm(forms.ModelForm):\n date = forms.DateField(input_formats=MY_DATE_FORMATS)\n class Meta:\n model = MyModel\n\nclass MyModelAdmin(admin.ModelAdmin):\n form = MyModelForm\n\n", "The fix proposed by Ben is working but the calendar on the right is not shown anymore.\nHere is an improvement. The calendar will still be shown and the date will be displayed with the %d%%M/%Y format.\nfrom django.forms.models import ModelForm\nfrom django.contrib.admin.widgets import AdminDateWidget\nfrom django.forms.fields import DateField \n\nclass MyModelForm(ModelForm):\n date = DateField(input_formats=['%d/%m/%Y',],widget=AdminDateWidget(format='%d/%m/%Y'))\n class Meta:\n model = MyModel\n\nclass MyModelAdmin(admin.ModelAdmin):\n form = MyModelForm\n\nWhen clicking on a day in the calendar, the value of the field has the %Y-%m-%d format but is is accepted as a valid date format. \nPS: Thanks to Daniel Roseman for his answer to this question \n" ]
[ 5, 2 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0002439801_django_django_admin_python.txt
Q: Problem with eastern european characters when scraping data from the European Parliament Website EDIT: thanks a lot for all the answers an points raised. As a novice I am a bit overwhelmed, but it is a great motivation for continuing learning python!! I am trying to scrape a lot of data from the European Parliament website for a research project. The first step is to create a list of all parliamentarians, however due to the many Eastern European names and the accents they use i get a lot of missing entries. Here is an example of what is giving me troubles (notice the accents at the end of the family name): <td class="listcontentlight_left"> <a href="/members/expert/alphaOrder/view.do?language=EN&amp;id=28276" title="ANDRIKIENĖ, Laima Liucija">ANDRIKIENĖ, Laima Liucija</a> <br/> Group of the European People's Party (Christian Democrats) <br/> </td> So far I have been using PyParser and the following code: #parser_names name = Word(alphanums + alphas8bit) begin, end = map(Suppress, "><") names = begin + ZeroOrMore(name) + "," + ZeroOrMore(name) + end for name in names.searchString(page): print(name) However this does not catch the name from the html above. Any advice in how to proceed? Best, Thomas P.S: Here is all the code i have so far: # -*- coding: utf-8 -*- import urllib.request from pyparsing_py3 import * page = urllib.request.urlopen("http://www.europarl.europa.eu/members/expert/alphaOrder.do?letter=B&language=EN") page = page.read().decode("utf8") #parser_names name = Word(alphanums + alphas8bit) begin, end = map(Suppress, "><") names = begin + ZeroOrMore(name) + "," + ZeroOrMore(name) + end for name in names.searchString(page): print(name) A: I was able to show 31 names starting with A with code: extended_chars = srange(r"[\0x80-\0x7FF]") special_chars = ' -''' name = Word(alphanums + alphas8bit + extended_chars + special_chars) As John noticed you need more unicode characters (extended_chars) and some names have hypehen etc. (special chars). Count how many names you received and check if page has the same count as I do for 'A'. Range 0x80-0x87F encode 2 bytes sequences in utf8 of probably all european languages. In pyparsing examples there is greetingInGreek.py for Greek and other example for Korean texts parsing. If 2 bytes are not enough then try: extended_chars = u''.join(unichr(c) for c in xrange(127, 65536, 1)) A: Are you sure that writing your own parser to pick bits out of HTML is the best option? You might find it easier to use a dedicated HTML parser. Beautiful Soup which lets you specify the location you're interested in using the DOM, so pulling the text from the first link inside a table cell with class "listcontentlight_left" is quite easy: soup = BeautifulSoup(htmlDocument) cells = soup.findAll("td", "listcontentlight_left") for cell in cells: print cell.a.string A: Looks like you've got some kind of encoding problem if you are getting western European names OK (they have lots of accents etc also!). Show us all of your code plus the URL of a typical page that you are trying to scrape and has the East-only problem. Displaying the piece of html that you have is not much use; we have no idea what transformations it has been through; at the very least, use the result of the repr() function. Update The offending character in that MEP's name is U+0116 (LATIN LETTER CAPITAL E WITH DOT ABOVE). So it is not included in pyparsing's "alphanums + alphas8bit". The Westies (latin-1) will all fit in what you've got already. I know little about pyparsing; you'll need to find a pyparsing expression that includes ALL unicode alphabetics ... not just Latin-n in case they start using Cyrillic for the Bulgarian MEPs instead of the current transcription into ASCII :-) Other observations: (1) alphaNUMs ... digits in a name? (2) names may include apostrophe and hyphen e.g. O'Reilly, Foughbarre-Smith A: at first i thought i’d recommend to try and build a custom letter class from python’s unicodedata.category method, which, when given a character, will tell you what class that codepoint is assigned to acc to the unicode character category; this would tell you whether a codepoint is e.g. an uppercase or lowercase letter, a digit or whatever. on second thought and remiscent of an answer i gave the other day, let me suggest another approach. there are many implicit assumptions we have to get rid of when going from national to global; one of them is certainly that ‘a character equals a byte’, and one other is that ‘a person’s name is made up of letters, and i know what the possible letters are’. unicode is vast, and the eu currently has 23 official languages written in three alphabets; exactly what characters are used for each language will involve quite a bit of work to figure out. greek uses those fancy apostrophies and is distributed across at least 367 codepoints; bulgarian uses the cyrillic alphabet with a slew of extra characters unique to the language. so why not simply turn the tables and take advantage of the larger context those names appear in? i brosed through some sample data and it looks like the general pattern for MEP names is LASTNAME, Firstname with (1) the last name in (almost) upper case; (2) a comma and a space; (3) the given names in ordinary case. this even holds in more ‘deviant’ examples like GERINGER de OEDENBERG, Lidia Joanna, GALLAGHER, Pat the Cope (wow), McGUINNESS, Mairead. It would take some work to recover the ordinary case from the last names (maybe leave all the lower case letters in place, and lower-case any capital letters that are preceded by another capital letters), but to extract the names is, in fact simple: fullname := lastname ", " firstname lastname := character+ firstname := character+ that’s right—since the EUP was so nice to present names enclosed in an HTML tag, you already know the maximum extent of it, so you can just cut out that maximum extent and split it up in two parts. as i see it, all you have to look for is the first occurrence of a sequence of comma, space—everything before that is the last, anything behind that the given names of the person. i call that the ‘silhouette approach’ since it’s like looking at the negative, the outline, rather than the positive, what the form is made up from. as has been noted earlier, some names use hyphens; now there are several codepoints in unicode that look like hyphens. let’s hope the typists over there in brussels were consistent in their usage. ah, and there are many surnames using apostrophes, like d'Hondt, d'Alambert. happy hunting: possible incarnations include U+0060, U+00B4, U+0027, U+02BC and a fair number of look-alikes. most of these codepoints would be ‘wrong’ to use in surnames, but when was the last time you saw thos dits used correctly? i somewhat distrust that alphanums + alphas8bit + extended_chars + special_chars pattern; at least that alphanums part is a tad bogey as it seems to include digits (which ones? unicode defines a few hundred digit characters), and that alphas8bit thingy does reek of a solvent made for another time. unicode conceptually works in a 32bit space. what’s 8bit intended to mean? letters found in codepage 852? c’mon this is 2010. ah, and looking back i see you seem to be parsing the HTML with pyparsing. don’t do that. use e.g. beautiful soup for sorting out the markup; it’s quite good at dealing even with faulty HTML (most HTML in the wild does not validate) and once you get your head about it’s admittedly wonderlandish API (all you ever need is probably the find() method) it will be simple to fish out exactly those snippets of text you’re looking for. A: Even though BeautifulSoup is the de facto standard for HTML parsing, pyparsing has some alternative approaches that lend themselves to HTML too (certainly a leg up over brute force reg exps). One function in particular is makeHTMLTags, which takes a single string argument (the base tag), and returns a 2-tuple of pyparsing expressions, one for the opening tag and one for the closing tag. Note that the opening tag expression does far more than just return the equivalent of "<"+tag+">". It also: handles upper/lower casing of the tag itself handles embedded attributes (returning them as named results) handles attribute names that have namespaces handles attribute values in single, double, or no quotes handles empty tags, as indicated by a trailing '/' before the closing '>' can be filtered for specific attributes using the withAttribute parse action So instead of trying to match the specific name content, I suggest you try matching the surrounding <a> tag, and then accessing the title attribute. Something like this: aTag,aEnd = makeHTMLTags("a") for t,_,_ in aTag.scanString(page): if ";id=" in t.href: print t.title Now you get whatever is in the title attribute, regardless of character set.
Problem with eastern european characters when scraping data from the European Parliament Website
EDIT: thanks a lot for all the answers an points raised. As a novice I am a bit overwhelmed, but it is a great motivation for continuing learning python!! I am trying to scrape a lot of data from the European Parliament website for a research project. The first step is to create a list of all parliamentarians, however due to the many Eastern European names and the accents they use i get a lot of missing entries. Here is an example of what is giving me troubles (notice the accents at the end of the family name): <td class="listcontentlight_left"> <a href="/members/expert/alphaOrder/view.do?language=EN&amp;id=28276" title="ANDRIKIENĖ, Laima Liucija">ANDRIKIENĖ, Laima Liucija</a> <br/> Group of the European People's Party (Christian Democrats) <br/> </td> So far I have been using PyParser and the following code: #parser_names name = Word(alphanums + alphas8bit) begin, end = map(Suppress, "><") names = begin + ZeroOrMore(name) + "," + ZeroOrMore(name) + end for name in names.searchString(page): print(name) However this does not catch the name from the html above. Any advice in how to proceed? Best, Thomas P.S: Here is all the code i have so far: # -*- coding: utf-8 -*- import urllib.request from pyparsing_py3 import * page = urllib.request.urlopen("http://www.europarl.europa.eu/members/expert/alphaOrder.do?letter=B&language=EN") page = page.read().decode("utf8") #parser_names name = Word(alphanums + alphas8bit) begin, end = map(Suppress, "><") names = begin + ZeroOrMore(name) + "," + ZeroOrMore(name) + end for name in names.searchString(page): print(name)
[ "I was able to show 31 names starting with A with code:\nextended_chars = srange(r\"[\\0x80-\\0x7FF]\")\nspecial_chars = ' -'''\nname = Word(alphanums + alphas8bit + extended_chars + special_chars)\n\nAs John noticed you need more unicode characters (extended_chars) and some names have hypehen etc. (special chars). Count how many names you received and check if page has the same count as I do for 'A'.\nRange 0x80-0x87F encode 2 bytes sequences in utf8 of probably all european languages. In pyparsing examples there is greetingInGreek.py for Greek and other example for Korean texts parsing.\nIf 2 bytes are not enough then try:\nextended_chars = u''.join(unichr(c) for c in xrange(127, 65536, 1))\n\n", "Are you sure that writing your own parser to pick bits out of HTML is the best option? You might find it easier to use a dedicated HTML parser. Beautiful Soup which lets you specify the location you're interested in using the DOM, so pulling the text from the first link inside a table cell with class \"listcontentlight_left\" is quite easy:\nsoup = BeautifulSoup(htmlDocument)\ncells = soup.findAll(\"td\", \"listcontentlight_left\")\nfor cell in cells:\n print cell.a.string\n\n", "Looks like you've got some kind of encoding problem if you are getting western European names OK (they have lots of accents etc also!). Show us all of your code plus the URL of a typical page that you are trying to scrape and has the East-only problem. Displaying the piece of html that you have is not much use; we have no idea what transformations it has been through; at the very least, use the result of the repr() function.\nUpdate The offending character in that MEP's name is U+0116 (LATIN LETTER CAPITAL E WITH DOT ABOVE). So it is not included in pyparsing's \"alphanums + alphas8bit\". The Westies (latin-1) will all fit in what you've got already. I know little about pyparsing; you'll need to find a pyparsing expression that includes ALL unicode alphabetics ... not just Latin-n in case they start using Cyrillic for the Bulgarian MEPs instead of the current transcription into ASCII :-)\nOther observations:\n(1) alphaNUMs ... digits in a name?\n(2) names may include apostrophe and hyphen e.g. O'Reilly, Foughbarre-Smith \n", "at first i thought i’d recommend to try and build a custom letter class from python’s unicodedata.category method, which, when given a character, will tell you what class that codepoint is assigned to acc to the unicode character category; this would tell you whether a codepoint is e.g. an uppercase or lowercase letter, a digit or whatever. \non second thought and remiscent of an answer i gave the other day, let me suggest another approach. there are many implicit assumptions we have to get rid of when going from national to global; one of them is certainly that ‘a character equals a byte’, and one other is that ‘a person’s name is made up of letters, and i know what the possible letters are’. unicode is vast, and the eu currently has 23 official languages written in three alphabets; exactly what characters are used for each language will involve quite a bit of work to figure out. greek uses those fancy apostrophies and is distributed across at least 367 codepoints; bulgarian uses the cyrillic alphabet with a slew of extra characters unique to the language.\nso why not simply turn the tables and take advantage of the larger context those names appear in? i brosed through some sample data and it looks like the general pattern for MEP names is LASTNAME, Firstname with (1) the last name in (almost) upper case; (2) a comma and a space; (3) the given names in ordinary case. this even holds in more ‘deviant’ examples like GERINGER de OEDENBERG, Lidia Joanna, GALLAGHER, Pat the Cope (wow), McGUINNESS, Mairead. It would take some work to recover the ordinary case from the last names (maybe leave all the lower case letters in place, and lower-case any capital letters that are preceded by another capital letters), but to extract the names is, in fact simple:\nfullname := lastname \", \" firstname\nlastname := character+\nfirstname := character+\n\nthat’s right—since the EUP was so nice to present names enclosed in an HTML tag, you already know the maximum extent of it, so you can just cut out that maximum extent and split it up in two parts. as i see it, all you have to look for is the first occurrence of a sequence of comma, space—everything before that is the last, anything behind that the given names of the person. i call that the ‘silhouette approach’ since it’s like looking at the negative, the outline, rather than the positive, what the form is made up from.\nas has been noted earlier, some names use hyphens; now there are several codepoints in unicode that look like hyphens. let’s hope the typists over there in brussels were consistent in their usage. ah, and there are many surnames using apostrophes, like d'Hondt, d'Alambert. happy hunting: possible incarnations include U+0060, U+00B4, U+0027, U+02BC and a fair number of look-alikes. most of these codepoints would be ‘wrong’ to use in surnames, but when was the last time you saw thos dits used correctly?\ni somewhat distrust that alphanums + alphas8bit + extended_chars + special_chars pattern; at least that alphanums part is a tad bogey as it seems to include digits (which ones? unicode defines a few hundred digit characters), and that alphas8bit thingy does reek of a solvent made for another time. unicode conceptually works in a 32bit space. what’s 8bit intended to mean? letters found in codepage 852? c’mon this is 2010.\nah, and looking back i see you seem to be parsing the HTML with pyparsing. don’t do that. use e.g. beautiful soup for sorting out the markup; it’s quite good at dealing even with faulty HTML (most HTML in the wild does not validate) and once you get your head about it’s admittedly wonderlandish API (all you ever need is probably the find() method) it will be simple to fish out exactly those snippets of text you’re looking for. \n", "Even though BeautifulSoup is the de facto standard for HTML parsing, pyparsing has some alternative approaches that lend themselves to HTML too (certainly a leg up over brute force reg exps). One function in particular is makeHTMLTags, which takes a single string argument (the base tag), and returns a 2-tuple of pyparsing expressions, one for the opening tag and one for the closing tag. Note that the opening tag expression does far more than just return the equivalent of \"<\"+tag+\">\". It also:\n\nhandles upper/lower casing of the tag\nitself\nhandles embedded attributes\n(returning them as named results)\nhandles attribute names that have\nnamespaces \nhandles attribute values in single, double, or no quotes\nhandles empty tags, as indicated by a\ntrailing '/' before the closing '>'\ncan be filtered for specific\nattributes using the withAttribute\nparse action\n\nSo instead of trying to match the specific name content, I suggest you try matching the surrounding <a> tag, and then accessing the title attribute. Something like this:\naTag,aEnd = makeHTMLTags(\"a\")\nfor t,_,_ in aTag.scanString(page):\n if \";id=\" in t.href:\n print t.title\n\nNow you get whatever is in the title attribute, regardless of character set.\n" ]
[ 2, 2, 1, 1, 0 ]
[]
[]
[ "html_parsing", "python", "screen_scraping" ]
stackoverflow_0003013355_html_parsing_python_screen_scraping.txt
Q: Preserve file attributes in ZipFile I'm looking for a way to preserve the file attributes (eg. read-only) of a file that gets written to a zipfile.ZipFile instance. The files I add to the zip archive gets their file attributes reset, eg. the read-only flag is gone when inspecting the archive with zip applications and after unzip. My current environment is Windows and I'm having problems with the ZipInfo.external_attr method. Surely there must be an standard way of preserving file attributes when writing to ZipFile? A: The problem I had was the heavily undocumented zipfile.ZipInfo.external_attr. All examples I found of this object refeered to the *nix file permission style. My implementation will run on windows. So I went about some "reverse engineering". Heh. The magic number for windows read-only ZipInfo.external_attr is 33. As in: z = zipfile.ZipFile(targetFile, 'w') (path, filename) = os.path.split(sourceFile) bytes = file(sourceFile, 'rb') info = zipfile.ZipInfo(filename) info.external_attr = 33 z.writestr(info, bytes.read()) bytes.close() z.close() If you need to find the correct value for another type of attribute create the zipfile as you want it with some windows zip app and run this on it: z = zipfile.ZipFile(sourceFile, 'r') info = z.getinfo('fileToTest.ext') print ("create_system", info.create_system) print ("external_attr", info.external_attr) print ("internal_attr", info.internal_attr) Cheers!
Preserve file attributes in ZipFile
I'm looking for a way to preserve the file attributes (eg. read-only) of a file that gets written to a zipfile.ZipFile instance. The files I add to the zip archive gets their file attributes reset, eg. the read-only flag is gone when inspecting the archive with zip applications and after unzip. My current environment is Windows and I'm having problems with the ZipInfo.external_attr method. Surely there must be an standard way of preserving file attributes when writing to ZipFile?
[ "The problem I had was the heavily undocumented zipfile.ZipInfo.external_attr. All examples I found of this object refeered to the *nix file permission style.\nMy implementation will run on windows.\nSo I went about some \"reverse engineering\". Heh.\nThe magic number for windows read-only ZipInfo.external_attr is 33.\nAs in:\nz = zipfile.ZipFile(targetFile, 'w')\n(path, filename) = os.path.split(sourceFile)\nbytes = file(sourceFile, 'rb')\ninfo = zipfile.ZipInfo(filename)\ninfo.external_attr = 33\nz.writestr(info, bytes.read())\nbytes.close()\nz.close()\n\nIf you need to find the correct value for another type of attribute create the zipfile as you want it with some windows zip app and run this on it:\nz = zipfile.ZipFile(sourceFile, 'r')\ninfo = z.getinfo('fileToTest.ext')\nprint (\"create_system\", info.create_system)\nprint (\"external_attr\", info.external_attr)\nprint (\"internal_attr\", info.internal_attr)\n\nCheers!\n" ]
[ 4 ]
[]
[]
[ "file", "python", "python_zipfile", "zip" ]
stackoverflow_0003007233_file_python_python_zipfile_zip.txt
Q: How to expose a web appication via API? we have create a web application on top of google app engine and python. which is almost about to complete it web front phase. I would also like to make it available almost all part of it to external applications. { via , xml , json , http , as many as possible. } . what's the best way to do it ? any library either for python or django available out ther ? Thanks. A: Maybe django-piston could be of interest for you. But I do not know if there are restrictions for appengine. A: First of all there is no much difference between service for humans and for robots (web-services). But restish -- mini-framework for building RESTful web services can be your choice.
How to expose a web appication via API?
we have create a web application on top of google app engine and python. which is almost about to complete it web front phase. I would also like to make it available almost all part of it to external applications. { via , xml , json , http , as many as possible. } . what's the best way to do it ? any library either for python or django available out ther ? Thanks.
[ "Maybe django-piston could be of interest for you. But I do not know if there are restrictions for appengine.\n", "First of all there is no much difference between service for humans and for robots (web-services).\nBut restish -- mini-framework for building RESTful web services can be your choice.\n" ]
[ 4, 2 ]
[]
[]
[ "api", "google_app_engine", "python" ]
stackoverflow_0003014631_api_google_app_engine_python.txt
Q: Using RE to retrieve an ID I am trying to use RE to match a changing ID and extract it. I am having some bother getting it working. The String is: m = 'Some Text That exists version 1.0.41.476 Fri Jun 4 16:50:56 EDT 2010' The code I have tried so far is: r = re.compile(r'(s*\s*)(\S+)') m = m.match(r) Can anyone help extract this string. Thanks A: >>> m = 'Some Text That exists version 1.0.41.476 Fri Jun 4 16:50:56 EDT 2010' >>> import re >>> re.search(r'version (\S+)', m).group(1) ('1.0.41.476',) A: Here are RE-based and string-based versions: import re def bystr(text): words = text.split() index = words.index('version') + 1 return words[index] def byre(text, there=re.compile(r'version\s+(\S+)')): return there.search(text).group(1) m = 'Some Text That exists version 1.0.41.476 Fri Jun 4 16:50:56 EDT 2010' if __name__ == '__main__': print bystr(m) print byre(m) (run as main script to confirm they return the same result -- a string, not a tuple as an existing answer peculiarly shows), and here's the timing of each (on my slow laptop): $ python -mtimeit -s'import are' 'are.bystr(are.m)' 100000 loops, best of 3: 4.29 usec per loop $ python -mtimeit -s'import are' 'are.byre(are.m)' 100000 loops, best of 3: 3.25 usec per loop While RE often have a bad reputation in the Python community, even this simple example shows that, when appropriate, they can often be faster than simple string manipulation -- in this case, the RE version takes only about 3/4 of the time that the string version takes. A: You don't necessarily have to use a regular expression to extract a substring. def get_version_number(text): """Assumes that the word 'version' appears before the version number in the text.""" words = text.split() index = words.index('version') + 1 return words[index] if __name__ == '__main__': m = 'Some Text That exists version 1.0.41.476 Fri Jun 4 16:50:56 EDT 2010' print get_version_number(m) print repr(get_version_number(m))
Using RE to retrieve an ID
I am trying to use RE to match a changing ID and extract it. I am having some bother getting it working. The String is: m = 'Some Text That exists version 1.0.41.476 Fri Jun 4 16:50:56 EDT 2010' The code I have tried so far is: r = re.compile(r'(s*\s*)(\S+)') m = m.match(r) Can anyone help extract this string. Thanks
[ ">>> m = 'Some Text That exists version 1.0.41.476 Fri Jun 4 16:50:56 EDT 2010'\n>>> import re\n>>> re.search(r'version (\\S+)', m).group(1)\n('1.0.41.476',)\n\n", "Here are RE-based and string-based versions:\nimport re\n\ndef bystr(text):\n words = text.split()\n index = words.index('version') + 1\n return words[index]\n\ndef byre(text, there=re.compile(r'version\\s+(\\S+)')):\n return there.search(text).group(1)\n\nm = 'Some Text That exists version 1.0.41.476 Fri Jun 4 16:50:56 EDT 2010'\n\nif __name__ == '__main__':\n print bystr(m)\n print byre(m)\n\n(run as main script to confirm they return the same result -- a string, not a tuple as an existing answer peculiarly shows), and here's the timing of each (on my slow laptop):\n$ python -mtimeit -s'import are' 'are.bystr(are.m)'\n100000 loops, best of 3: 4.29 usec per loop\n$ python -mtimeit -s'import are' 'are.byre(are.m)'\n100000 loops, best of 3: 3.25 usec per loop\n\nWhile RE often have a bad reputation in the Python community, even this simple example shows that, when appropriate, they can often be faster than simple string manipulation -- in this case, the RE version takes only about 3/4 of the time that the string version takes.\n", "You don't necessarily have to use a regular expression to extract a substring.\ndef get_version_number(text):\n \"\"\"Assumes that the word 'version' appears before the version number in the \n text.\"\"\"\n words = text.split()\n index = words.index('version') + 1\n return words[index]\n\nif __name__ == '__main__':\n m = 'Some Text That exists version 1.0.41.476 Fri Jun 4 16:50:56 EDT 2010'\n\n print get_version_number(m)\n print repr(get_version_number(m))\n\n" ]
[ 4, 2, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003015028_python_regex.txt
Q: Python and libpcap. find source mac address of packet I'm writing python program to build mac-address cache using pcap. But pcap module for python has no good documentation. I have found this page http://pylibpcap.sourceforge.net/ with code example and it works fine. Can anybody modify this example to make it able to show the source mac-address for each packet? Or point me to the documentation where I can read about it ... updated Here is a code part where information about mac addresses were cut. def print_packet(pktlen, data, timestamp): if not data: return if data[12:14]=='\x08\x00': decoded=decode_ip_packet(data[14:]) print '\n%s.%f %s > %s' % (time.strftime('%H:%M', time.localtime(timestamp)), timestamp % 60, decoded['source_address'], decoded['destination_address']) for key in ['version', 'header_len', 'tos', 'total_len', 'id', 'flags', 'fragment_offset', 'ttl']: print ' %s: %d' % (key, decoded[key]) print ' protocol: %s' % protocols[decoded['protocol']] print ' header checksum: %d' % decoded['checksum'] print ' data:' dumphex(decoded['data']) First 14 octets in data are destination, source mac-addr and ether type. decoded=decode_ip_packet(data[14:]) I need to parse them to get this info. Task is done. A: Google "Ethernet frame formats". The first 6 octets of a packet is the destination MAC address, which is immediately followed by the 6 octets of source MAC address. This Wikipedia page may help. A: Oh my god man, why are you doing this ? Use Scapy instead.
Python and libpcap. find source mac address of packet
I'm writing python program to build mac-address cache using pcap. But pcap module for python has no good documentation. I have found this page http://pylibpcap.sourceforge.net/ with code example and it works fine. Can anybody modify this example to make it able to show the source mac-address for each packet? Or point me to the documentation where I can read about it ... updated Here is a code part where information about mac addresses were cut. def print_packet(pktlen, data, timestamp): if not data: return if data[12:14]=='\x08\x00': decoded=decode_ip_packet(data[14:]) print '\n%s.%f %s > %s' % (time.strftime('%H:%M', time.localtime(timestamp)), timestamp % 60, decoded['source_address'], decoded['destination_address']) for key in ['version', 'header_len', 'tos', 'total_len', 'id', 'flags', 'fragment_offset', 'ttl']: print ' %s: %d' % (key, decoded[key]) print ' protocol: %s' % protocols[decoded['protocol']] print ' header checksum: %d' % decoded['checksum'] print ' data:' dumphex(decoded['data']) First 14 octets in data are destination, source mac-addr and ether type. decoded=decode_ip_packet(data[14:]) I need to parse them to get this info. Task is done.
[ "Google \"Ethernet frame formats\". The first 6 octets of a packet is the destination MAC address, which is immediately followed by the 6 octets of source MAC address.\nThis Wikipedia page may help.\n", "Oh my god man, why are you doing this ? Use Scapy instead.\n" ]
[ 3, 2 ]
[]
[]
[ "libpcap", "mac_address", "pcap", "python" ]
stackoverflow_0003014218_libpcap_mac_address_pcap_python.txt
Q: When will Unladen Swallow be "done" or "ready" for real use? It looks like Google hasn't updated the results section since the Q4 2009 posting. I've been wondering when it will be put in the Python trunk, and if it's, in any way, production ready. Also, "We aspire to do no original work" is in the Q4 plan. Did Google bite off more than what they could handle, or does anyone know what the real story is? A: According to this, Unladen Swallow will be a part of python 3, it is an officially accepted PEP: http://www.python.org/dev/peps/pep-3146/
When will Unladen Swallow be "done" or "ready" for real use?
It looks like Google hasn't updated the results section since the Q4 2009 posting. I've been wondering when it will be put in the Python trunk, and if it's, in any way, production ready. Also, "We aspire to do no original work" is in the Q4 plan. Did Google bite off more than what they could handle, or does anyone know what the real story is?
[ "According to this, Unladen Swallow will be a part of python 3, it is an officially accepted PEP: http://www.python.org/dev/peps/pep-3146/\n" ]
[ 2 ]
[]
[]
[ "python", "unladen_swallow" ]
stackoverflow_0003016134_python_unladen_swallow.txt
Q: Editing django code within django - Django just wondering if it would be possible in some experimental way, to edit django app code within django safely to then refresh the compiled files. Would be great if someone has tried something similar already or has some ideas. I would like to be able to edit small bits of code from a web interface, so I can easily maintain a couple of experimental projects. Help would be great! Thanks. A: Providing an editing interface is one half of the battle but it's pretty straightforward. There are already apps out there to provide editing of templates and media files so it's pretty much just an extension of that. The hardest part is restarting the server which would have to happen in order for the new code to be compiled. I don't think there's a way to do this from within the server so here's how I would do it: When you make an edit, create a new file in the project root. eg an empty file called restart. Write an bash script to look for that file, if it exists, restart the site and delete the file. Cron the script to run once every 10 seconds. It shouldn't use any meaningful resources. One serious issue is if you introduce bugs. You could test-compile (ie running the dev-server before you restart the site and check the input) but that's not very robust and you could easily end up in a situation where you lose access to the site. As that's the case, it might be wise to set up the editor as a completely separate site so you're never locked out... A: SO question about wsgi servers that support automatic code reload. It should provide enough info to get you started.
Editing django code within django - Django
just wondering if it would be possible in some experimental way, to edit django app code within django safely to then refresh the compiled files. Would be great if someone has tried something similar already or has some ideas. I would like to be able to edit small bits of code from a web interface, so I can easily maintain a couple of experimental projects. Help would be great! Thanks.
[ "Providing an editing interface is one half of the battle but it's pretty straightforward. There are already apps out there to provide editing of templates and media files so it's pretty much just an extension of that.\nThe hardest part is restarting the server which would have to happen in order for the new code to be compiled. I don't think there's a way to do this from within the server so here's how I would do it:\n\nWhen you make an edit, create a new file in the project root. eg an empty file called restart.\nWrite an bash script to look for that file, if it exists, restart the site and delete the file.\nCron the script to run once every 10 seconds. It shouldn't use any meaningful resources.\n\nOne serious issue is if you introduce bugs. You could test-compile (ie running the dev-server before you restart the site and check the input) but that's not very robust and you could easily end up in a situation where you lose access to the site.\nAs that's the case, it might be wise to set up the editor as a completely separate site so you're never locked out...\n", "SO question about wsgi servers that support automatic code reload. It should provide enough info to get you started.\n" ]
[ 3, 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003015825_django_python.txt
Q: Give a reference to a python instance attribute at class definition I have a class with attributes which have a reference to another attribute of this class. See class Device, value1 and value2 holding a reference to interface: class Interface(object): def __init__(self): self.port=None class Value(object): def __init__(self, interface, name): self.interface=interface self.name=name def get(self): return "Getting Value \"%s\" with interface \"%s\""%(self.name, self.interface.port) class Device(object): interface=Interface() value1=Value(interface, name="value1") value2=Value(interface, name="value2") def __init__(self, port): self.interface.port=port if __name__=="__main__": d1=Device("Foo") print d1.value1.get() # >>> Getting Value "value1" with interface "Foo" d2=Device("Bar") print d2.value1.get() # >>> Getting Value "value1" with interface "Bar" print d1.value1.get() # >>> Getting Value "value1" with interface "Bar" The last print is wrong, cause d1 should have the interface "Foo". I know whats going wrong: The line interface=Interface() line is executed, when the class definition is parsed (once). So every Device class has the same instance of interface. I could change the Device class to: class Device(object): interface=Interface() value1=Value(interface, name="value1") value2=Value(interface, name="value2") def __init__(self, port): self.interface=Interface() self.interface.port=port So this is also not working: The values still have the reference to the original interface instance and the self.interface is just another instance... The output now is: >>> Getting Value "value1" with interface "None" >>> Getting Value "value1" with interface "None" >>> Getting Value "value1" with interface "None" So how could I solve this the pythonic way? I could setup a function in the Device class to look for attributes with type Value and reassign them the new interface. Isn't this a common problem with a typical solution for it? Thanks! A: interface is a class attribute. So when you do d2=Device("Bar") you are changing the port of the interface for all objects of class Device. If you want to have these attributes per object instance, you have to put them into the __init__ method: class Device(object): def __init__(self, port): self.interface=Interface() self.value1=Value(self.interface, name="value1") self.value2=Value(self.interface, name="value2") self.interface.port=port You should only use class attributes if you really want to share a value with all the objects. Other than that, I don't know what you try to accomplish here. Why defining it as class attribute in the first place? A: You can't defer the interface lookup unless your values are methods of Device. Perhaps something like this does what you want? def value(name): def get(self): print 'Getting %s from port %s' % (name, self.interface.port) def set(self, v): print 'Setting %s to %s on port %s' % (name, v, self.interface.port) return property(get, set) class Device(object): value1 = value('value1') value2 = value('value2') def __init__(self, interface): self.interface = interface class Interface(object): def __init__(self, port): self.port = port d = Device(Interface(1234)) d.value1 d.value2 = 42 If you want your values to do more than get and set, then it's more difficult.
Give a reference to a python instance attribute at class definition
I have a class with attributes which have a reference to another attribute of this class. See class Device, value1 and value2 holding a reference to interface: class Interface(object): def __init__(self): self.port=None class Value(object): def __init__(self, interface, name): self.interface=interface self.name=name def get(self): return "Getting Value \"%s\" with interface \"%s\""%(self.name, self.interface.port) class Device(object): interface=Interface() value1=Value(interface, name="value1") value2=Value(interface, name="value2") def __init__(self, port): self.interface.port=port if __name__=="__main__": d1=Device("Foo") print d1.value1.get() # >>> Getting Value "value1" with interface "Foo" d2=Device("Bar") print d2.value1.get() # >>> Getting Value "value1" with interface "Bar" print d1.value1.get() # >>> Getting Value "value1" with interface "Bar" The last print is wrong, cause d1 should have the interface "Foo". I know whats going wrong: The line interface=Interface() line is executed, when the class definition is parsed (once). So every Device class has the same instance of interface. I could change the Device class to: class Device(object): interface=Interface() value1=Value(interface, name="value1") value2=Value(interface, name="value2") def __init__(self, port): self.interface=Interface() self.interface.port=port So this is also not working: The values still have the reference to the original interface instance and the self.interface is just another instance... The output now is: >>> Getting Value "value1" with interface "None" >>> Getting Value "value1" with interface "None" >>> Getting Value "value1" with interface "None" So how could I solve this the pythonic way? I could setup a function in the Device class to look for attributes with type Value and reassign them the new interface. Isn't this a common problem with a typical solution for it? Thanks!
[ "interface is a class attribute. So when you do\nd2=Device(\"Bar\")\n\nyou are changing the port of the interface for all objects of class Device. \n\nIf you want to have these attributes per object instance, you have to put them into the __init__ method:\nclass Device(object):\n def __init__(self, port):\n self.interface=Interface()\n self.value1=Value(self.interface, name=\"value1\")\n self.value2=Value(self.interface, name=\"value2\")\n self.interface.port=port\n\n\nYou should only use class attributes if you really want to share a value with all the objects.\nOther than that, I don't know what you try to accomplish here. Why defining it as class attribute in the first place?\n", "You can't defer the interface lookup unless your values are methods of Device. Perhaps something like this does what you want?\ndef value(name):\n def get(self):\n print 'Getting %s from port %s' % (name, self.interface.port)\n def set(self, v):\n print 'Setting %s to %s on port %s' % (name, v, self.interface.port)\n return property(get, set)\n\nclass Device(object):\n value1 = value('value1')\n value2 = value('value2')\n def __init__(self, interface):\n self.interface = interface\n\nclass Interface(object):\n def __init__(self, port):\n self.port = port\n\nd = Device(Interface(1234))\nd.value1\nd.value2 = 42\n\nIf you want your values to do more than get and set, then it's more difficult.\n" ]
[ 4, 2 ]
[]
[]
[ "attributes", "class", "python", "reference" ]
stackoverflow_0003016770_attributes_class_python_reference.txt
Q: How to change the amount of increments in pyplot axis Hi probably quite a simple question but.. When plotting a graph using matplotlib.pyplot my Y axis goes from -0.04 to 0.03 which is fine but there are 8 labels for increments (eg 0.03,0.02,0.01 etc.). I need more maybe 16 or so. Thanks for your help A: Matplotlib has several different algorithms for choosing tick locations automatically, and e.g. LinearLocator or MaxNLocator may suit your purpose. See the major_minor demo for how to use Locators in general, and the ticker api documentation for the various Locators available. The documentation for the individual classes is somewhat sparse, but guessing based on the argument names tends to work fine. A: Use set_yticks() to change the tick locations. For example: import scipy, pylab fig = pylab.figure() ax = fig.add_subplot(1,1,1) ax.plot(scipy.randn(8)) ax.set_yticks(scipy.arange(-1.5,1.5,0.25)) fig.show() pylab.yticks() is another option. (source: stevetjoa.com)
How to change the amount of increments in pyplot axis
Hi probably quite a simple question but.. When plotting a graph using matplotlib.pyplot my Y axis goes from -0.04 to 0.03 which is fine but there are 8 labels for increments (eg 0.03,0.02,0.01 etc.). I need more maybe 16 or so. Thanks for your help
[ "Matplotlib has several different algorithms for choosing tick locations automatically, and e.g. LinearLocator or MaxNLocator may suit your purpose. See the major_minor demo for how to use Locators in general, and the ticker api documentation for the various Locators available. The documentation for the individual classes is somewhat sparse, but guessing based on the argument names tends to work fine.\n", "Use set_yticks() to change the tick locations. For example:\nimport scipy, pylab\nfig = pylab.figure()\nax = fig.add_subplot(1,1,1)\nax.plot(scipy.randn(8))\nax.set_yticks(scipy.arange(-1.5,1.5,0.25))\nfig.show()\n\npylab.yticks() is another option.\n\n(source: stevetjoa.com) \n" ]
[ 5, 3 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0003013350_matplotlib_python.txt
Q: Import problem with PyCrypto in Jython I am currently trying to get python bittorrent tracker running inside of jython and i encountered this problem: the tracker uses PyCrypto library which i compiled for my platform and added into the python path. When i try to run code, however, i get following error: Exception in thread "MainThread" Traceback (most recent call last): File "./python_dep/BitTorrent-5.2.2/bittorrent-tracker.py", line 21, in <module> from BitTorrent.track import track File "./python_dep/BitTorrent-5.2.2/BitTorrent/track.py", line 50, in <module> from BitTorrent.UI import Size File "./python_dep/BitTorrent-5.2.2/BitTorrent/UI.py", line 37, in <module> from BitTorrent.MultiTorrent import UnknownInfohash, TorrentAlreadyInQueue, TorrentAlreadyRunning, TorrentNotRunning File "./python_dep/BitTorrent-5.2.2/BitTorrent/MultiTorrent.py", line 25, in <module> from BitTorrent.Torrent import Feedback, Torrent File "./python_dep/BitTorrent-5.2.2/BitTorrent/Torrent.py", line 32, in <module> from BitTorrent.ConnectionManager import ConnectionManager File "./python_dep/BitTorrent-5.2.2/BitTorrent/ConnectionManager.py", line 22, in <module> from BitTorrent.Connector import Connector File "./python_dep/BitTorrent-5.2.2/BitTorrent/Connector.py", line 27, in <module> from Crypto.Cipher import ARC4 ImportError: cannot import name ARC4 Java Result: 1 I am pretty sure that the library is in the python path, because command import Crypto.Cipher works, while from Crypto.Cipher import ARC4 does not. The java code i run looks like this: package jythTest; import org.python.util.PythonInterpreter; public class Main { public static void main(String[] args) { PythonInterpreter pythonInterpreter = new PythonInterpreter(); pythonInterpreter.exec("import sys"); pythonInterpreter.exec("sys.path.append(\"./python_dep/BitTorrent-5.2.2/\")"); pythonInterpreter.exec("sys.path.append(\"./python_dep/Twisted-10.0.0/\")"); pythonInterpreter.exec("sys.path.append(\"./python_dep/Zope-3.4.0/build/lib.linux-i686-2.6\")"); pythonInterpreter.exec("sys.path.append(\"./python_dep\")"); pythonInterpreter.exec("sys.path.append(\"./python_dep/pycrypto-2.0.1/build/lib.linux-i686-2.6\")"); pythonInterpreter.exec("sys.path.append(\"import Crypto.Cipher\")"); //pythonInterpreter.exec("print sys.path"); pythonInterpreter.execfile("./python_dep/BitTorrent-5.2.2/bittorrent-tracker.py"); } } Thanks in advance to anyone who could provide any kind of help. A: This is happening probably because pycrypto is a C-extension, and Jython will not be able to call it without a Java wrapper for this extension. A: I am not sure this applies to your situation, but some googling led to this: (from http://wiki.python.org/jython/JythonFaq/InstallingJython) Jython cannot find your Java class, even though it exists in the class path. This shows up as "ImportError: cannot import name xxx" or "AttributeError: java package xxx' has no attribute 'yyy'" This happens when Jython is installed as a Java extension (i.e. when jython.jar is installed in java\jre\lib\ext) and your classes are installed in the classpath. The reason is Java extensions can only see other extensions, not other classes defined in the CLASSPATH or passed in to java using the --classpath option. There are two ways to fix this: 1) Move your classes to the java\jre\lib\ext directory. 2) Remove jython.jar from the java\jre\lib\ext directory and put jython.jar in the CLASSPATH or use the java --classpath option. (from the Jython-users mailing list) And another, similar issue, but different nonetheless: (from http://bugs.jython.org/issue1878866) I have a similar problem in Linux with jython 2.5. Inside jython2.5.0/Lib/site-packages a have a foo directory where there is a Java class (Bar.class) and a jython class (BarPy.py). i have also put an empty __init__.py file. In the jython interpreter environment I can always import Bar like this: "from foo import Bar" however I cannot import BarPy. If I delete the java class from the directory then I can import the jython script
Import problem with PyCrypto in Jython
I am currently trying to get python bittorrent tracker running inside of jython and i encountered this problem: the tracker uses PyCrypto library which i compiled for my platform and added into the python path. When i try to run code, however, i get following error: Exception in thread "MainThread" Traceback (most recent call last): File "./python_dep/BitTorrent-5.2.2/bittorrent-tracker.py", line 21, in <module> from BitTorrent.track import track File "./python_dep/BitTorrent-5.2.2/BitTorrent/track.py", line 50, in <module> from BitTorrent.UI import Size File "./python_dep/BitTorrent-5.2.2/BitTorrent/UI.py", line 37, in <module> from BitTorrent.MultiTorrent import UnknownInfohash, TorrentAlreadyInQueue, TorrentAlreadyRunning, TorrentNotRunning File "./python_dep/BitTorrent-5.2.2/BitTorrent/MultiTorrent.py", line 25, in <module> from BitTorrent.Torrent import Feedback, Torrent File "./python_dep/BitTorrent-5.2.2/BitTorrent/Torrent.py", line 32, in <module> from BitTorrent.ConnectionManager import ConnectionManager File "./python_dep/BitTorrent-5.2.2/BitTorrent/ConnectionManager.py", line 22, in <module> from BitTorrent.Connector import Connector File "./python_dep/BitTorrent-5.2.2/BitTorrent/Connector.py", line 27, in <module> from Crypto.Cipher import ARC4 ImportError: cannot import name ARC4 Java Result: 1 I am pretty sure that the library is in the python path, because command import Crypto.Cipher works, while from Crypto.Cipher import ARC4 does not. The java code i run looks like this: package jythTest; import org.python.util.PythonInterpreter; public class Main { public static void main(String[] args) { PythonInterpreter pythonInterpreter = new PythonInterpreter(); pythonInterpreter.exec("import sys"); pythonInterpreter.exec("sys.path.append(\"./python_dep/BitTorrent-5.2.2/\")"); pythonInterpreter.exec("sys.path.append(\"./python_dep/Twisted-10.0.0/\")"); pythonInterpreter.exec("sys.path.append(\"./python_dep/Zope-3.4.0/build/lib.linux-i686-2.6\")"); pythonInterpreter.exec("sys.path.append(\"./python_dep\")"); pythonInterpreter.exec("sys.path.append(\"./python_dep/pycrypto-2.0.1/build/lib.linux-i686-2.6\")"); pythonInterpreter.exec("sys.path.append(\"import Crypto.Cipher\")"); //pythonInterpreter.exec("print sys.path"); pythonInterpreter.execfile("./python_dep/BitTorrent-5.2.2/bittorrent-tracker.py"); } } Thanks in advance to anyone who could provide any kind of help.
[ "This is happening probably because pycrypto is a C-extension, and Jython will not be able to call it without a Java wrapper for this extension.\n", "I am not sure this applies to your situation, but some googling led to this:\n(from http://wiki.python.org/jython/JythonFaq/InstallingJython)\n\nJython cannot find your Java class,\n even though it exists in the class\n path. This shows up as \"ImportError:\n cannot import name xxx\" or\n \"AttributeError: java package xxx' has\n no attribute 'yyy'\"\nThis happens when Jython is installed\n as a Java extension (i.e. when\n jython.jar is installed in\n java\\jre\\lib\\ext) and your classes\n are installed in the classpath.\nThe reason is Java extensions can only\n see other extensions, not other\n classes defined in the CLASSPATH or\n passed in to java using the\n --classpath option.\nThere are two ways to fix this:\n1) Move your classes to the\n java\\jre\\lib\\ext directory.\n2) Remove jython.jar from the\n java\\jre\\lib\\ext directory and put\n jython.jar in the CLASSPATH or use the\n java --classpath option.\n(from the Jython-users mailing list)\n\nAnd another, similar issue, but different nonetheless:\n(from http://bugs.jython.org/issue1878866)\n\nI have a similar problem in Linux with jython 2.5. Inside\n jython2.5.0/Lib/site-packages a have a foo directory where there is a\n Java class (Bar.class) and a jython class (BarPy.py). i have also put an\n empty __init__.py file. In the jython interpreter environment I can\n always import Bar like this: \"from foo import Bar\" however I cannot\n import BarPy. If I delete the java class from the directory then I can\n import the jython script\n\n" ]
[ 4, 0 ]
[]
[]
[ "jython", "pycrypto", "python" ]
stackoverflow_0003017341_jython_pycrypto_python.txt
Q: CherryPy behind Nginx reverse-proxy POST requests corrupted/truncated I have put my application using Cherrypy 3.1.2 behind Nginx configured as a reverse-proxy. All is working right for GET requests, but all POST requests return HTTP 400 - Malformed header. I traced into CherryPy WSGI-Server source code to see the request-handling code and found out that if for GET requests the first request line correctly reads like for example: GET /home HTTP/1.0 for POST requests it's like: <HTTP headers truncated at front> POST /home HTTP/1.0 So instead of the correctly formed request containing GET/POST request line followed by HTTP headers, for POST requests my application receives from Nginx: First HTTP header lines truncated from start by some number of bytes Then a blank line indicating end od HTTP headers THEN a "POST /home HTTP/1.0", that was clearly expected as a first line of the request. EDIT: That's the end of request, so there's also NO body data that should follow HTTP POST headers. Additionally, the number of bytes of the truncation from p.1 seems to depend on how much POST data there is on a form, for example the more characters I type in /home FORM fields, the more characters into the HTTP headers are removed. Apparently Nginx is somehow corrupting the header when it passes it to upstream server (my application). BUT: when I just for test made Nginx redirect to some external web sites (using POST requests too) - everything goes fine. So I'm now pretty stuck. My configuration is: Windows XP Prof, Python/2.5.1, CherryPy/3.1.2, Nginx/0.8.32 Browsers: FireFox 2.0, IE 7.0 My application (running standalone) is generally working and tested under a number of configurations. I use pretty basic Nginx config like: upstream backend { server localhost:8088 weight=1; } server { listen 80; server_name localhost; location / { #proxy_read_timeout 300; proxy_pass http://backend; #proxy_redirect default; } } Although tried many other examples and configurations of proxy_pass found on the net. Any ideas where to look for the problem? Nginx configuration, my CherryPy app or elsewhere? NEW: I found, that it works correctly but only for POST requests having zero body content length (made an empty without any fields to test that). And verified that the count of bytes truncated from the begginning is equal to Content-length + some small const number (probably 2). A: you could try the parameters: ignore_invalid_headers on; sendfile on; in the http block... also might try disabling keepalives and ensure you're logging access/errors to debug.
CherryPy behind Nginx reverse-proxy POST requests corrupted/truncated
I have put my application using Cherrypy 3.1.2 behind Nginx configured as a reverse-proxy. All is working right for GET requests, but all POST requests return HTTP 400 - Malformed header. I traced into CherryPy WSGI-Server source code to see the request-handling code and found out that if for GET requests the first request line correctly reads like for example: GET /home HTTP/1.0 for POST requests it's like: <HTTP headers truncated at front> POST /home HTTP/1.0 So instead of the correctly formed request containing GET/POST request line followed by HTTP headers, for POST requests my application receives from Nginx: First HTTP header lines truncated from start by some number of bytes Then a blank line indicating end od HTTP headers THEN a "POST /home HTTP/1.0", that was clearly expected as a first line of the request. EDIT: That's the end of request, so there's also NO body data that should follow HTTP POST headers. Additionally, the number of bytes of the truncation from p.1 seems to depend on how much POST data there is on a form, for example the more characters I type in /home FORM fields, the more characters into the HTTP headers are removed. Apparently Nginx is somehow corrupting the header when it passes it to upstream server (my application). BUT: when I just for test made Nginx redirect to some external web sites (using POST requests too) - everything goes fine. So I'm now pretty stuck. My configuration is: Windows XP Prof, Python/2.5.1, CherryPy/3.1.2, Nginx/0.8.32 Browsers: FireFox 2.0, IE 7.0 My application (running standalone) is generally working and tested under a number of configurations. I use pretty basic Nginx config like: upstream backend { server localhost:8088 weight=1; } server { listen 80; server_name localhost; location / { #proxy_read_timeout 300; proxy_pass http://backend; #proxy_redirect default; } } Although tried many other examples and configurations of proxy_pass found on the net. Any ideas where to look for the problem? Nginx configuration, my CherryPy app or elsewhere? NEW: I found, that it works correctly but only for POST requests having zero body content length (made an empty without any fields to test that). And verified that the count of bytes truncated from the begginning is equal to Content-length + some small const number (probably 2).
[ "you could try the parameters:\nignore_invalid_headers on;\nsendfile on;\n\nin the http block... also might try disabling keepalives and ensure you're logging access/errors to debug.\n" ]
[ 1 ]
[]
[]
[ "cherrypy", "nginx", "python", "reverse_proxy" ]
stackoverflow_0002272931_cherrypy_nginx_python_reverse_proxy.txt
Q: Idea on parsing character syntax diagram Folks I'm implementing a weird thing, I have to write a utility to parse a syntax diagram in plain text format and convert it to xml format, the thing basically is identical as this from IBM(like in the "Creating a No-Conversion Job" part): http://publib.boulder.ibm.com/infocenter/idshelp/v10/index.jsp?topic=/com.ibm.sqls.doc/sqls17.htm Typical parser/lexer like ANTLR / yacc/ bison seems cannot deal with this kind of stuff, one idea I have is to convert the syntax diagram to a character bitmap and define some function like more_up,move_down, left, right or so in order to traverse the whole diagram to simulate the understanding process as human naked eye. Tho it sounds not proficient enough, I didn't figure out other better approach. Did anybody once play with a similar scenario? Maybe you could kindly shed some light on this. Thank you in advance! A: I've never done anything like that before, but this is how I would approach it. First, I'd start off with something like this: class CharGrid(object): def __init__(self, text): self.lines = text.split('\n') def __getitem__(self, pos): try: col, row = pos except (TypeError, ValueError): raise KeyError('%r not a 2-tuple' % (pos,)) if row >= len(self.lines): return ' ' line = self.lines[row] if col >= len(line): return ' ' return line[col] so that I can access the characters in the text via 2D coordinates: grid = CharGrid("""Creating a No-Conversion Job >>-onpladm create job--job--+--------------+-- -n---------------> '- -p--project-' >-- -d--device-- -D--database-- -t--table-----------------------> .---------------------------------------------------------------------. V | >----+-----------------------------------------------------------------+-+->< | (1) | '-+-------------+--+-------------+--| Setting the Run Mode |------' '- -S--server-' '- -T--target-' """) print ''.join((grid[0,0], grid[1,0], grid[2,0])) print ''.join((grid[0,2], grid[1,2])) (yielding) Cre >> After that, the task would be converting the 2D grid of characters into a 1D sequence of symbols: read the label off the first line scan down the first column until you find >> scan right from the current position until you find [whatever] ... etc. Follow the chart in eyeball-order. Once you have a 1D sequence of symbols, you can use a conventional parsing technique on that. A: The "character grid" idea for accessing single characters seems like a foundation step; another answer shows how to do that just fine. Now you can access the grid randomly and follow horizontal or vertical lines easily. The real problem is that you want to construct a graph representing what the character grid says. Such a graph will consist of (duh), nodes, arcs, and annotations. Probably the easiest thing to find are the nodes, which are likely indicated (see other answer) by characters representing branching points in the diagram (e.g. +). Each arc will be a string of characaters leading to a bend in the arc, or to another node. Following such strings of characters should be pretty straighforward (:-) ) and can produce a string representing the arc even if it has bends in it. You'll likely want to enumerate all nodes (just scan the array). Node annotations must reasonably be nearby and you can simply scan a small radious around the node locations. You'll want to enumerate each arc leaving a node, and collect the string representing the arc. I'd feed the arc-string to a lexer to tear it apart; it may have interesting content (e.g., an annotation as in inline sequence of characters). At this point you have nodes and arcs with associated annotations. Constructing the corresponding graph from these should be pretty easy.
Idea on parsing character syntax diagram
Folks I'm implementing a weird thing, I have to write a utility to parse a syntax diagram in plain text format and convert it to xml format, the thing basically is identical as this from IBM(like in the "Creating a No-Conversion Job" part): http://publib.boulder.ibm.com/infocenter/idshelp/v10/index.jsp?topic=/com.ibm.sqls.doc/sqls17.htm Typical parser/lexer like ANTLR / yacc/ bison seems cannot deal with this kind of stuff, one idea I have is to convert the syntax diagram to a character bitmap and define some function like more_up,move_down, left, right or so in order to traverse the whole diagram to simulate the understanding process as human naked eye. Tho it sounds not proficient enough, I didn't figure out other better approach. Did anybody once play with a similar scenario? Maybe you could kindly shed some light on this. Thank you in advance!
[ "I've never done anything like that before, but this is how I would approach it.\nFirst, I'd start off with something like this:\nclass CharGrid(object):\n def __init__(self, text):\n self.lines = text.split('\\n')\n\n def __getitem__(self, pos):\n try:\n col, row = pos\n except (TypeError, ValueError):\n raise KeyError('%r not a 2-tuple' % (pos,))\n if row >= len(self.lines):\n return ' '\n line = self.lines[row]\n if col >= len(line):\n return ' '\n return line[col]\n\nso that I can access the characters in the text via 2D coordinates:\ngrid = CharGrid(\"\"\"Creating a No-Conversion Job\n\n>>-onpladm create job--job--+--------------+-- -n--------------->\n '- -p--project-'\n\n>-- -d--device-- -D--database-- -t--table----------------------->\n\n .---------------------------------------------------------------------.\n V |\n>----+-----------------------------------------------------------------+-+-><\n | (1) |\n '-+-------------+--+-------------+--| Setting the Run Mode |------'\n '- -S--server-' '- -T--target-'\n\"\"\")\n\nprint ''.join((grid[0,0], grid[1,0], grid[2,0]))\nprint ''.join((grid[0,2], grid[1,2]))\n\n(yielding)\nCre\n>>\n\nAfter that, the task would be converting the 2D grid of characters into a 1D sequence of symbols:\n\nread the label off the first line\nscan down the first column until you find >>\nscan right from the current position until you find [whatever]\n\n... etc. Follow the chart in eyeball-order.\nOnce you have a 1D sequence of symbols, you can use a conventional parsing technique on that.\n", "The \"character grid\" idea for accessing single characters seems like a foundation step;\nanother answer shows how to do that just fine. Now you can access the grid randomly and follow horizontal or vertical lines easily.\nThe real problem is that you want to construct a graph representing what the character grid says. Such a graph will consist of (duh), nodes, arcs, and annotations.\nProbably the easiest thing to find are the nodes, which are likely indicated (see other answer) by characters representing branching points in the diagram (e.g. +). Each arc will be a string of characaters leading to a bend in the arc, or to another node. Following such strings of characters should be pretty straighforward (:-) ) and can produce a string representing the arc even if it has bends in it.\nYou'll likely want to enumerate all nodes (just scan the array). Node annotations\nmust reasonably be nearby and you can simply scan a small radious around the node locations.\nYou'll want to enumerate each arc leaving a node, and collect the string representing the arc.\nI'd feed the arc-string to a lexer to tear it apart; it may have interesting content (e.g., an annotation as in inline sequence of characters).\nAt this point you have nodes and arcs with associated annotations. Constructing the corresponding graph from these should be pretty easy.\n" ]
[ 2, 1 ]
[]
[]
[ "parsing", "python", "xml" ]
stackoverflow_0003015569_parsing_python_xml.txt
Q: python distutils does not include data_files I am new to distutils.. I am trying to include few data files along with the package.. here is my code.. from distutils.core import setup setup(name='Scrapper', version='1.0', description='Scrapper', packages=['app', 'db', 'model', 'util'], data_files=[('app', ['app/scrapper.db'])] ) The zip file created after executing python setup.py sdist does not include the scrapper.db file. I have scrapper.db file in the app directory.. thanks for the help. A: You probably need to add a MANIFEST.in file containing "include app/scrapper.db". It's a bug in distutils that makes this necessary: anything in data_files or package_data should be included in the generated MANIFEST automatically. But in Python 2.6 and earlier, it is not, so you have to include it in MANIFEST.in. The bug is fixed in Python 2.7. A: Try removing MANIFEST, that way distutils will be forced to regenerate it. Note: I've been using python 3.x, so I don't know if this works with 2.x or not.
python distutils does not include data_files
I am new to distutils.. I am trying to include few data files along with the package.. here is my code.. from distutils.core import setup setup(name='Scrapper', version='1.0', description='Scrapper', packages=['app', 'db', 'model', 'util'], data_files=[('app', ['app/scrapper.db'])] ) The zip file created after executing python setup.py sdist does not include the scrapper.db file. I have scrapper.db file in the app directory.. thanks for the help.
[ "You probably need to add a MANIFEST.in file containing \"include app/scrapper.db\". \nIt's a bug in distutils that makes this necessary: anything in data_files or package_data should be included in the generated MANIFEST automatically. But in Python 2.6 and earlier, it is not, so you have to include it in MANIFEST.in. \nThe bug is fixed in Python 2.7.\n", "Try removing MANIFEST, that way distutils will be forced to regenerate it.\nNote: I've been using python 3.x, so I don't know if this works with 2.x or not.\n" ]
[ 21, 1 ]
[]
[]
[ "distutils", "installation", "python" ]
stackoverflow_0002994396_distutils_installation_python.txt
Q: How to create a translucid/alpha-transparent rectangle using wxpython? I have a wx.panel and I want to put a translucid rectangle on a part of it. How can I do that using wxpython? A: You can do this using a wx.GraphicsContext, and there's a good example in the wxPython demo (located in the Miscellaneous category).
How to create a translucid/alpha-transparent rectangle using wxpython?
I have a wx.panel and I want to put a translucid rectangle on a part of it. How can I do that using wxpython?
[ "You can do this using a wx.GraphicsContext, and there's a good example in the wxPython demo (located in the Miscellaneous category).\n" ]
[ 1 ]
[]
[]
[ "python", "translucency", "transparency", "transparent", "wxpython" ]
stackoverflow_0003016497_python_translucency_transparency_transparent_wxpython.txt
Q: Pylons 1.0 AttributeError: 'module' object has no attribute 'metadata' Python noob trying to learn Pylons. I'm using the QuickWiki tutorial (http://pylonshq.com/docs/en/1.0/tutorials/quickwiki_tutorial/) from the 1.0 documentation, but this alleged "1.0" doc seems to just be "0.9.7"; I suspect that this has something to do with the error I'm getting. When I execute "paster setup-app development.ini", I get this: (mydevenv)lucid@lucid-laptop:~/QuickWiki$ paster setup-app development.ini Traceback (most recent call last): ... edited for brevity... File "/home/lucid/mydevenv/lib/python2.6/site-packages/setuptools-0.6c11-py2.6.egg/pkg_resources.py", line 1954, in load File "/home/lucid/QuickWiki/quickwiki/config/middleware.py", line 11, in <module> from quickwiki.config.environment import load_environment File "/home/lucid/QuickWiki/quickwiki/config/environment.py", line 12, in <module> from quickwiki.model import init_model File "/home/lucid/QuickWiki/quickwiki/model/__init__.py", line 27, in <module> pages_table = sa.Table('pages', meta.metadata, AttributeError: 'module' object has no attribute 'metadata' (mydevenv)lucid@lucid-laptop:~/QuickWiki$ A: This is mistake in documentation http://pylonshq.com/docs/en/1.0/tutorials/quickwiki_tutorial/ Declare pages_table like this from quickwiki.model.meta import Base pages_table = sa.Table('pages', Base.metadata, sa.Column('title', sa.types.Unicode(40), primary_key=True), sa.Column('content', sa.types.UnicodeText(), default='') ) No loger meta.metadata, use meta.Base.metadata and define you models using SqlAlchemy declarative base extension http://www.sqlalchemy.org/docs/05/ormtutorial.html#creating-table-class-and-mapper-all-at-once-declaratively A: Your comment on estin answer asks whether this changes between SqlAlchemy 0.5 and 0.6. It does not. It's the same. It is Pylons which have different defaults now. As estin says Pylons defaults to creating a declarative_base() so that you can use SqlAlchemy declaratively. class MyRecord(Base): __tablename__ = "myrecord" id = Column(Integer, primary_key=True) data = Column(Unicode, nullable=False) This is instead of specifying first the tables using Table() constructs, then creating your classes and then using mapper() to map them together. SqlAlchemy Declarative does this automatically. Quickwiki tells you to use the explicit non-declarative version of SqlAlchemy which is there are no reason for (declarative is more concise). Pylons used to expose the default metadata as model.meta.metadata but now it is created by declarative_base() and exposed in model.meta.Base.metadata. A: Just in case anyone runs into the same issue, I'm including my model.init and websetup: """=========================__init__.py=========================""" """The application's model objects""" from quickwiki.model.meta import Session, Base def init_model(engine): """Call me before using any of the tables or classes in the model""" Session.configure(bind=engine) import logging import re import sets from docutils.core import publish_parts from pylons import url from quickwiki.lib.helpers import link_to log = logging.getLogger(__name__) # disable docutils security hazards: # http://docutils.sourceforge.net/docs/howto/security.html SAFE_DOCUTILS = dict(file_insertion_enabled=False, raw_enabled=False) wikiwords = re.compile(r"\b([A-Z]\w+[A-Z]+\w+)", re.UNICODE) from sqlalchemy import orm import sqlalchemy as sa pages_table = sa.Table('pages', Base.metadata, sa.Column('title', sa.types.Unicode(40), primary_key=True), sa.Column('content', sa.types.UnicodeText(), default='') ) class Page(object): def __init__(self, title, content=None): self.title = title self.content = content def get_wiki_content(self): """Convert reStructuredText content to HTML for display, and create links for WikiWords """ content = publish_parts(self.content, writer_name='html', settings_overrides=SAFE_DOCUTILS)['html_body'] titles = sets.Set(wikiwords.findall(content)) for title in titles: title_url = url(controller='pages', action='show', title=title) content = content.replace(title, link_to(title, title_url)) return content def __unicode__(self): return self.title __str__ = __unicode__ orm.mapper(Page, pages_table) """=========================websetup.py=========================""" """Setup the QuickWiki application""" import logging import pylons.test from quickwiki.config.environment import load_environment from quickwiki.model.meta import Session, Base from quickwiki import model log = logging.getLogger(__name__) def setup_app(command, conf, vars): """Place any commands to setup quickwiki here""" load_environment(conf.global_conf, conf.local_conf) # Create the tables if they don't already exist log.info("Creating tables...") Base.metadata.create_all(bind=Session.bind) log.info("Successfully set up.") log.info("Adding front page data...") page = model.Page(title=u'FrontPage', content=u'**Welcome** to the QuickWiki front page!') Session.add(page) Session.commit() log.info("Successfully set up.")
Pylons 1.0 AttributeError: 'module' object has no attribute 'metadata'
Python noob trying to learn Pylons. I'm using the QuickWiki tutorial (http://pylonshq.com/docs/en/1.0/tutorials/quickwiki_tutorial/) from the 1.0 documentation, but this alleged "1.0" doc seems to just be "0.9.7"; I suspect that this has something to do with the error I'm getting. When I execute "paster setup-app development.ini", I get this: (mydevenv)lucid@lucid-laptop:~/QuickWiki$ paster setup-app development.ini Traceback (most recent call last): ... edited for brevity... File "/home/lucid/mydevenv/lib/python2.6/site-packages/setuptools-0.6c11-py2.6.egg/pkg_resources.py", line 1954, in load File "/home/lucid/QuickWiki/quickwiki/config/middleware.py", line 11, in <module> from quickwiki.config.environment import load_environment File "/home/lucid/QuickWiki/quickwiki/config/environment.py", line 12, in <module> from quickwiki.model import init_model File "/home/lucid/QuickWiki/quickwiki/model/__init__.py", line 27, in <module> pages_table = sa.Table('pages', meta.metadata, AttributeError: 'module' object has no attribute 'metadata' (mydevenv)lucid@lucid-laptop:~/QuickWiki$
[ "This is mistake in documentation http://pylonshq.com/docs/en/1.0/tutorials/quickwiki_tutorial/ \nDeclare pages_table like this\nfrom quickwiki.model.meta import Base\npages_table = sa.Table('pages', Base.metadata,\n sa.Column('title', sa.types.Unicode(40), primary_key=True),\n sa.Column('content', sa.types.UnicodeText(), default='')\n )\n\nNo loger meta.metadata, use meta.Base.metadata and define you models using SqlAlchemy declarative base extension http://www.sqlalchemy.org/docs/05/ormtutorial.html#creating-table-class-and-mapper-all-at-once-declaratively\n", "Your comment on estin answer asks whether this changes between SqlAlchemy 0.5 and 0.6.\nIt does not. It's the same. It is Pylons which have different defaults now.\nAs estin says Pylons defaults to creating a declarative_base() so that you can use SqlAlchemy declaratively.\nclass MyRecord(Base):\n __tablename__ = \"myrecord\"\n\n id = Column(Integer, primary_key=True)\n data = Column(Unicode, nullable=False)\n\nThis is instead of specifying first the tables using Table() constructs, then creating your classes and then using mapper() to map them together.\nSqlAlchemy Declarative does this automatically. Quickwiki tells you to use the explicit non-declarative version of SqlAlchemy which is there are no reason for (declarative is more concise). Pylons used to expose the default metadata as model.meta.metadata but now it is created by declarative_base() and exposed in model.meta.Base.metadata.\n", "Just in case anyone runs into the same issue, I'm including my model.init and websetup:\n\"\"\"=========================__init__.py=========================\"\"\"\n \"\"\"The application's model objects\"\"\"\nfrom quickwiki.model.meta import Session, Base\n\n\ndef init_model(engine):\n \"\"\"Call me before using any of the tables or classes in the model\"\"\"\n Session.configure(bind=engine)\n\nimport logging\nimport re\nimport sets\nfrom docutils.core import publish_parts\n\nfrom pylons import url\nfrom quickwiki.lib.helpers import link_to\n\nlog = logging.getLogger(__name__)\n\n# disable docutils security hazards:\n# http://docutils.sourceforge.net/docs/howto/security.html\nSAFE_DOCUTILS = dict(file_insertion_enabled=False, raw_enabled=False)\nwikiwords = re.compile(r\"\\b([A-Z]\\w+[A-Z]+\\w+)\", re.UNICODE)\n\nfrom sqlalchemy import orm\nimport sqlalchemy as sa\n\npages_table = sa.Table('pages', Base.metadata,\n sa.Column('title', sa.types.Unicode(40), primary_key=True),\n sa.Column('content', sa.types.UnicodeText(), default='')\n )\n\nclass Page(object):\n\n def __init__(self, title, content=None):\n self.title = title\n self.content = content\n\n def get_wiki_content(self):\n \"\"\"Convert reStructuredText content to HTML for display, and\n create links for WikiWords\n \"\"\"\n content = publish_parts(self.content, writer_name='html',\n settings_overrides=SAFE_DOCUTILS)['html_body']\n titles = sets.Set(wikiwords.findall(content))\n for title in titles:\n title_url = url(controller='pages', action='show', title=title)\n content = content.replace(title, link_to(title, title_url))\n return content\n\n def __unicode__(self):\n return self.title\n\n __str__ = __unicode__\n\norm.mapper(Page, pages_table)\n\n\"\"\"=========================websetup.py=========================\"\"\"\n\n\"\"\"Setup the QuickWiki application\"\"\"\nimport logging\n\nimport pylons.test\n\nfrom quickwiki.config.environment import load_environment\nfrom quickwiki.model.meta import Session, Base\nfrom quickwiki import model\n\nlog = logging.getLogger(__name__)\n\ndef setup_app(command, conf, vars):\n \"\"\"Place any commands to setup quickwiki here\"\"\"\n load_environment(conf.global_conf, conf.local_conf)\n\n # Create the tables if they don't already exist\n log.info(\"Creating tables...\")\n Base.metadata.create_all(bind=Session.bind)\n log.info(\"Successfully set up.\")\n\n log.info(\"Adding front page data...\")\n page = model.Page(title=u'FrontPage',\n content=u'**Welcome** to the QuickWiki front page!')\n\n Session.add(page)\n Session.commit()\n log.info(\"Successfully set up.\")\n\n" ]
[ 4, 2, 2 ]
[]
[]
[ "attributeerror", "metadata", "pylons", "python", "sqlalchemy" ]
stackoverflow_0003011108_attributeerror_metadata_pylons_python_sqlalchemy.txt
Q: Create a color generator from given colormap in matplotlib I have a series of lines that each need to be plotted with a separate colour. Each line is actually made up of several data sets (positive, negative regions etc.) and so I'd like to be able to create a generator that will feed one colour at a time across a spectrum, for example the gist_rainbow map shown here. I have found the following works but it seems very complicated and more importantly difficult to remember, from pylab import * NUM_COLORS = 22 mp = cm.datad['gist_rainbow'] get_color = matplotlib.colors.LinearSegmentedColormap.from_list(mp, colors=['r', 'b'], N=NUM_COLORS) ... # Then in a for loop this_color = get_color(float(i)/NUM_COLORS) Moreover, it does not cover the range of colours in the gist_rainbow map, I have to redefine a map. Maybe a generator is not the best way to do this, if so what is the accepted way? A: To index colors from a specific colormap you can use: import pylab NUM_COLORS = 22 cm = pylab.get_cmap('gist_rainbow') for i in range(NUM_COLORS): color = cm(1.*i/NUM_COLORS) # color will now be an RGBA tuple # or if you really want a generator: cgen = (cm(1.*i/NUM_COLORS) for i in range(NUM_COLORS))
Create a color generator from given colormap in matplotlib
I have a series of lines that each need to be plotted with a separate colour. Each line is actually made up of several data sets (positive, negative regions etc.) and so I'd like to be able to create a generator that will feed one colour at a time across a spectrum, for example the gist_rainbow map shown here. I have found the following works but it seems very complicated and more importantly difficult to remember, from pylab import * NUM_COLORS = 22 mp = cm.datad['gist_rainbow'] get_color = matplotlib.colors.LinearSegmentedColormap.from_list(mp, colors=['r', 'b'], N=NUM_COLORS) ... # Then in a for loop this_color = get_color(float(i)/NUM_COLORS) Moreover, it does not cover the range of colours in the gist_rainbow map, I have to redefine a map. Maybe a generator is not the best way to do this, if so what is the accepted way?
[ "To index colors from a specific colormap you can use:\nimport pylab\nNUM_COLORS = 22\n\ncm = pylab.get_cmap('gist_rainbow')\nfor i in range(NUM_COLORS):\n color = cm(1.*i/NUM_COLORS) # color will now be an RGBA tuple\n\n# or if you really want a generator:\ncgen = (cm(1.*i/NUM_COLORS) for i in range(NUM_COLORS))\n\n" ]
[ 35 ]
[]
[]
[ "color_mapping", "matplotlib", "python" ]
stackoverflow_0003016283_color_mapping_matplotlib_python.txt
Q: How can I display multiple django modelformset forms in grouped fieldsets? I have a problem with needing to provide multiple model backed forms on the same page. I understand how to do this with single forms, i.e. just create both the forms call them something different then use the appropriate names in the template. Now how exactly do you expand that solution to work with modelformsets? The wrinkle, of course, is that each 'form' must be rendered together in the appropriate fieldset. For example I want my template to produce something like this: Home Base Description: Want ice cream? Home Base Description: Want ice cream? I am using a loop like this to process the results (after form validation) base_models = base_formset.save(commit=False) like_models = like_formset.save(commit=False) for base_model, likes_model in map(None, base_models, likes_models): which works as I'd expect (I'm using map because the # of forms can be different). The problem is that I can't figure out a way to do the same thing with the templating engine. The system does work if I layout all the base models together then all the likes models after wards, but it doesn't meet the layout requirements. EDIT: Updated the problem statement to be more clear about what exactly I'm processing (I'm processing models not forms in the for loop) A: In the view: forms = itertools.izip(base_forms, likes_forms) In the template: {% for (base_form,like_form) in forms %} A: After doing a fair amount of poking around and hack experimenting I've come up with the following solution thanks in huge part to Ignacio Vazquez-Abrams :) In the view: forms = itertools.izip_longest((None,),base_formset.forms, likes_formset.forms) In the template: {% for (garbage1, base_form, like_form, garbage2) in forms %} The astute reader might notice that the number of arguments in the unpacking list is one larger than what was given to the izip_longest() method. You might also note that there is an effectively blank list as the first argument. I could never get the template to display the first argument in the list hence the dummy first argument. Also I found that N-1 list elements were being rendered in the template. I also stumbled upon the fact that the template doesn't much care about a size mismatch so by padding the front and the back I was able to get the forms I actually wanted to display! NOTE: When processing the POST I simply construct the formsets that I'm working with since all the phantom data isn't being sent back through the POST. Certainly not the cleanest solution and it is probably extremely vulnerable to upgrade breakage, but it's practical enough to work for me for now.
How can I display multiple django modelformset forms in grouped fieldsets?
I have a problem with needing to provide multiple model backed forms on the same page. I understand how to do this with single forms, i.e. just create both the forms call them something different then use the appropriate names in the template. Now how exactly do you expand that solution to work with modelformsets? The wrinkle, of course, is that each 'form' must be rendered together in the appropriate fieldset. For example I want my template to produce something like this: Home Base Description: Want ice cream? Home Base Description: Want ice cream? I am using a loop like this to process the results (after form validation) base_models = base_formset.save(commit=False) like_models = like_formset.save(commit=False) for base_model, likes_model in map(None, base_models, likes_models): which works as I'd expect (I'm using map because the # of forms can be different). The problem is that I can't figure out a way to do the same thing with the templating engine. The system does work if I layout all the base models together then all the likes models after wards, but it doesn't meet the layout requirements. EDIT: Updated the problem statement to be more clear about what exactly I'm processing (I'm processing models not forms in the for loop)
[ "In the view:\nforms = itertools.izip(base_forms, likes_forms)\n\nIn the template:\n{% for (base_form,like_form) in forms %}\n\n", "After doing a fair amount of poking around and hack experimenting I've come up with the following solution thanks in huge part to Ignacio Vazquez-Abrams :)\nIn the view:\nforms = itertools.izip_longest((None,),base_formset.forms, likes_formset.forms)\n\nIn the template:\n{% for (garbage1, base_form, like_form, garbage2) in forms %}\n\nThe astute reader might notice that the number of arguments in the unpacking list is one larger than what was given to the izip_longest() method. You might also note that there is an effectively blank list as the first argument.\nI could never get the template to display the first argument in the list hence the dummy first argument. Also I found that N-1 list elements were being rendered in the template. I also stumbled upon the fact that the template doesn't much care about a size mismatch so by padding the front and the back I was able to get the forms I actually wanted to display!\nNOTE: When processing the POST I simply construct the formsets that I'm working with since all the phantom data isn't being sent back through the POST.\nCertainly not the cleanest solution and it is probably extremely vulnerable to upgrade breakage, but it's practical enough to work for me for now.\n" ]
[ 2, 0 ]
[]
[]
[ "django_forms", "django_models", "django_templates", "python" ]
stackoverflow_0003010783_django_forms_django_models_django_templates_python.txt
Q: Problems replacing a Python extension module while Python script is executing I'm trying to solve the following problem: Say I have a Python script (let's call it Test.py) which uses a C++ extension module (made via SWIG, let's call the module "Example"). I have Test.py, Example.py, and _Example.so in the same directory. Now, in the middle of running Test.py, I want to make a change to my Example module, recompile (which will overwrite the existing .so), and use a command to gracefully stop Test.py which is still using the old version of the module (Test.py has some cleaning up to do, which uses some stuff which is defined in the Example module), then start it up again, using the new version of the module. Gracefully stopping Test.py and THEN recompiling the module is not an option in my case. The problem is, as soon as _Example.so is overwritten and Test.py tries to access anything defined in the Example module (while gracefully stopping), I get a segmentation fault. One solution to this is to explicitly name the Example module by appending a version number at the end, but I was wondering if there was a better solution (I don't want to be importing Example_1_0)? A: You could, on starting Test.py, copy the Example.* files to a temp folder unique for that instance (take a look at tempfile.mkdtemp, it can create safe, unique folders), add that to sys.path and then import Example; and on Test.py shutdown remove that folder (shutils.rmtree) at the cleanup stage. This would mean that each instance of Test.py would run on its own copy of the Example module, not interfering with the others, and would update to the new one only upon relaunch. You would need the Example.* files not to be on the same folder as Test.py for this, otherwise the import would get those first. Just storing them on a subfolder should be fine. A: What you could is compile to the temporary name (Example_1_0) but as soon as the Test.py is stopped, rename to _Example.so and then restart Test.py. Edit: Since you're running multiple instances, you might consider using some type of stack/generator/symlink threading to link it all together to do your own "garbage collection" on _Example.so: You could have the main tester script running, launching the Test.py scripts with subprocess. Each Test.py could take _ExampleXXX.so as a command line argument. Then you keep a reference count to each .so file - when the refcount drops to zero, that version of the module is eliminated and the process is respawned with the newest version of _Example.so. It might be a bit tricky, but you may just be able to use while True: #Do stuff for p in myprocesses: retcode = p.poll() # Set to [None][1] if the process hasn't finished # Do something with the return code or some similar logic.
Problems replacing a Python extension module while Python script is executing
I'm trying to solve the following problem: Say I have a Python script (let's call it Test.py) which uses a C++ extension module (made via SWIG, let's call the module "Example"). I have Test.py, Example.py, and _Example.so in the same directory. Now, in the middle of running Test.py, I want to make a change to my Example module, recompile (which will overwrite the existing .so), and use a command to gracefully stop Test.py which is still using the old version of the module (Test.py has some cleaning up to do, which uses some stuff which is defined in the Example module), then start it up again, using the new version of the module. Gracefully stopping Test.py and THEN recompiling the module is not an option in my case. The problem is, as soon as _Example.so is overwritten and Test.py tries to access anything defined in the Example module (while gracefully stopping), I get a segmentation fault. One solution to this is to explicitly name the Example module by appending a version number at the end, but I was wondering if there was a better solution (I don't want to be importing Example_1_0)?
[ "You could, on starting Test.py, copy the Example.* files to a temp folder unique for that instance (take a look at tempfile.mkdtemp, it can create safe, unique folders), add that to sys.path and then import Example; and on Test.py shutdown remove that folder (shutils.rmtree) at the cleanup stage.\nThis would mean that each instance of Test.py would run on its own copy of the Example module, not interfering with the others, and would update to the new one only upon relaunch.\nYou would need the Example.* files not to be on the same folder as Test.py for this, otherwise the import would get those first. Just storing them on a subfolder should be fine.\n", "What you could is compile to the temporary name (Example_1_0) but as soon as the Test.py is stopped, rename to _Example.so and then restart Test.py.\n\nEdit:\nSince you're running multiple instances, you might consider using some type of stack/generator/symlink threading to link it all together to do your own \"garbage collection\" on _Example.so:\nYou could have the main tester script running, launching the Test.py scripts with subprocess. Each Test.py could take _ExampleXXX.so as a command line argument. Then you keep a reference count to each .so file - when the refcount drops to zero, that version of the module is eliminated and the process is respawned with the newest version of _Example.so.\nIt might be a bit tricky, but you may just be able to use \nwhile True:\n #Do stuff\n for p in myprocesses:\n retcode = p.poll() # Set to [None][1] if the process hasn't finished\n # Do something with the return code\n\nor some similar logic.\n" ]
[ 2, 0 ]
[]
[]
[ "python", "segmentation_fault", "swig" ]
stackoverflow_0003018122_python_segmentation_fault_swig.txt
Q: Finding new IP in a file I have a file of IP addresses called "IPs". When I parse a new IP from my logs, I'd like to see if the new IP is already in file IPs, before I add it. I know how to add the new IP to the file, but I'm having trouble seeing if the new IP is already in the file. !/usr/bin/python from IPy import IP IP = IP('192.168.1.2') #f=open(IP('IPs', 'r')) #This line doesn't work f=open('IPs', 'r') # this one doesn't work for line in f: if IP == line: print "Found " +IP +" before" f.close() In the file "IPs", each IP address is on it's own line. As such: 222.111.222.111 222.111.222.112 Also tried to put the file IPs in to an array, but not having good luck with that either. Any ideas? Thank you, Gary A: iplist = [] # With takes care of all the fun file handling stuff (closing, etc.) with open('ips.txt', 'r') as f: for line in f: iplist.append(line.strip()) # Gets rid of the newlines at the end # Change the above to this for Python versions < 2.6 f = open('ips.txt', 'r') for line in f: iplist.append(line.strip()) f.close() newip = '192.168.1.2' if newip not in iplist: f = open('ips.txt', 'a') # append mode, please f.write(newip+'\n') Now you have your IPs in a list (iplist) and you can easily add your newip to it iplist.append(newip) or do anything else you please. Edit: Some excellent books for learning Python: If you're worried about programming being difficult, there's a book that's geared towards kids, but I honestly found it both easy-to-digest and informative. Snake Wrangling for Kids Another great resource for learning Python is How to Think Like a Computer Scientist. There's also the tutorial on the official Python website. It's a little dry compared to the previous ones. Alan Gauld, one of the foremost contributors to the tutor@python.org mailing list has this tutorial that's really good and also is adapted to Python 3. He also includes some other languages for comparison. If you want a good dead-tree book, I've heard that Core Python Programming by Wesley Chun is a really good resource. He also contributes to the python tutor list every so often. The tutor list is another good place to learn about python - reading, replying, and asking your own questions. I actually learned most of my python by trying to answer as many of the questions I could. I'd seriously recommend subscribing to the tutor list if you want to learn Python. A: It's a trivial code but i think it is short and pretty in Python, so here is how i'd write it: ip = '192.168.1.2' lookFor = ip + '\n' f = open('ips.txt', 'a+') for line in f: if line == lookFor: print 'found', ip, 'before.' break else: print ip, 'not found, adding to file.' print >>f, ip f.close() It opens the file in append mode, reads and if not found (that's what else to a for does - executes if the loop exited normally and not via break) - appends the new IP. ta-da! Now will be ineffective when you have a lot of IPs. Here is another hack i thought of, it uses 1 file per 1 IP as a flag: import os ip = '192.168.1.2' fname = ip + '.ip' if os.access(fname, os.F_OK): print 'found', ip, 'before.' else: print ip, 'not found, registering.' open(fname, 'w').close() Why is this fast? Because most file systems these days (except FAT on Windows but NTFS is ok) organize the list of files in a directory into a B-tree structure, so checking for a file existence is a fast operation O(log N) instead of enumerating whole list. (I am not saying this is practical - depends on amount of IPs you expect to see and your sysadmin benevolence.) A: Why do you need this IP thing? Use simple strings. !#/usr/bin/env python ip = "192.168.1.2" + "\n" ### Fixed -- see comments f = open('IPs', 'r') for line in f: if line.count(ip): print "Found " + ip f.close() Besides, this looks more like a task for grep and friends.
Finding new IP in a file
I have a file of IP addresses called "IPs". When I parse a new IP from my logs, I'd like to see if the new IP is already in file IPs, before I add it. I know how to add the new IP to the file, but I'm having trouble seeing if the new IP is already in the file. !/usr/bin/python from IPy import IP IP = IP('192.168.1.2') #f=open(IP('IPs', 'r')) #This line doesn't work f=open('IPs', 'r') # this one doesn't work for line in f: if IP == line: print "Found " +IP +" before" f.close() In the file "IPs", each IP address is on it's own line. As such: 222.111.222.111 222.111.222.112 Also tried to put the file IPs in to an array, but not having good luck with that either. Any ideas? Thank you, Gary
[ "iplist = []\n\n# With takes care of all the fun file handling stuff (closing, etc.)\nwith open('ips.txt', 'r') as f:\n for line in f:\n iplist.append(line.strip()) # Gets rid of the newlines at the end\n\n# Change the above to this for Python versions < 2.6\nf = open('ips.txt', 'r')\nfor line in f:\n iplist.append(line.strip())\nf.close()\n\nnewip = '192.168.1.2'\n\nif newip not in iplist:\n f = open('ips.txt', 'a') # append mode, please\n f.write(newip+'\\n')\n\nNow you have your IPs in a list (iplist) and you can easily add your newip to it iplist.append(newip) or do anything else you please.\n\nEdit: \nSome excellent books for learning Python:\nIf you're worried about programming being difficult, there's a book that's geared towards kids, but I honestly found it both easy-to-digest and informative.\nSnake Wrangling for Kids\nAnother great resource for learning Python is How to Think Like a Computer Scientist.\nThere's also the tutorial on the official Python website. It's a little dry compared to the previous ones.\nAlan Gauld, one of the foremost contributors to the tutor@python.org mailing list has this tutorial that's really good and also is adapted to Python 3. He also includes some other languages for comparison.\nIf you want a good dead-tree book, I've heard that Core Python Programming by Wesley Chun is a really good resource. He also contributes to the python tutor list every so often.\nThe tutor list is another good place to learn about python - reading, replying, and asking your own questions. I actually learned most of my python by trying to answer as many of the questions I could. I'd seriously recommend subscribing to the tutor list if you want to learn Python.\n", "It's a trivial code but i think it is short and pretty in Python, so here is how i'd write it:\nip = '192.168.1.2'\n\nlookFor = ip + '\\n'\nf = open('ips.txt', 'a+')\nfor line in f:\n if line == lookFor:\n print 'found', ip, 'before.'\n break\nelse:\n print ip, 'not found, adding to file.'\n print >>f, ip\nf.close()\n\nIt opens the file in append mode, reads and if not found (that's what else to a for does - executes if the loop exited normally and not via break) - appends the new IP. ta-da!\nNow will be ineffective when you have a lot of IPs. Here is another hack i thought of, it uses 1 file per 1 IP as a flag:\nimport os\n\nip = '192.168.1.2'\n\nfname = ip + '.ip'\nif os.access(fname, os.F_OK):\n print 'found', ip, 'before.'\nelse:\n print ip, 'not found, registering.'\n open(fname, 'w').close()\n\nWhy is this fast? Because most file systems these days (except FAT on Windows but NTFS is ok) organize the list of files in a directory into a B-tree structure, so checking for a file existence is a fast operation O(log N) instead of enumerating whole list. \n(I am not saying this is practical - depends on amount of IPs you expect to see and your sysadmin benevolence.)\n", "Why do you need this IP thing? Use simple strings.\n!#/usr/bin/env python\n\nip = \"192.168.1.2\" + \"\\n\" ### Fixed -- see comments\nf = open('IPs', 'r')\nfor line in f:\n if line.count(ip):\n print \"Found \" + ip\nf.close()\n\nBesides, this looks more like a task for grep and friends.\n" ]
[ 3, 2, 1 ]
[]
[]
[ "compare", "ip_address", "ironpython", "python" ]
stackoverflow_0003017176_compare_ip_address_ironpython_python.txt
Q: Missing 'read' prompt in bash when using ssh? Please tell me I'm missing something really obvious here: $ cat ~/bashplay/f #!/bin/bash read -p 'RDY> ' x echo $x $ ~/bashplay/f RDY> direct execution direct execution $ ssh somehost ~/bashplay/f indirect via ssh indirect via ssh Note the missing "RDY>" prompt when using ssh. I see the same thing in python when using the "readline" package. Anyone know why? A: From man bash: -p prompt Display prompt on standard error, without a trailing new‐ line, before attempting to read any input. The prompt is displayed only if input is coming from a terminal. Use the ssh option -t which forces pseudo tty allocation: ssh -t somehost ~/bashplay/f
Missing 'read' prompt in bash when using ssh?
Please tell me I'm missing something really obvious here: $ cat ~/bashplay/f #!/bin/bash read -p 'RDY> ' x echo $x $ ~/bashplay/f RDY> direct execution direct execution $ ssh somehost ~/bashplay/f indirect via ssh indirect via ssh Note the missing "RDY>" prompt when using ssh. I see the same thing in python when using the "readline" package. Anyone know why?
[ "From man bash:\n\n-p prompt\n Display prompt on standard error, without a trailing new‐\n line, before attempting to read any input. The prompt is\n displayed only if input is coming from a terminal.\n\nUse the ssh option -t which forces pseudo tty allocation:\nssh -t somehost ~/bashplay/f\n\n" ]
[ 5 ]
[]
[]
[ "bash", "python", "readline", "ssh" ]
stackoverflow_0003018036_bash_python_readline_ssh.txt
Q: How exactly does a python (django) request happen? does it have to reparse all the codebase? With a scripting language like python (or php), things are not compiled down to bytecode like in .net or java. So does this mean that on every request, it has to go through the entire application and parse/compile it? Or at least all the code required for the given call stack? A: With a scripting language like python (or php), things are not compiled down to bytecode like in .net or java. Wrong: everything you import in Python gets compiled to bytecode (and saved as .pyc files if you can write to the directory containing the source you're importing -- standard libraries &c are generally pre-compiled, depending on the installation choices of course). Just keep the main script short and simple (importing some module and calling a function in it) and you'll be using compiled bytecode throughout. (Python's compiler is designed to be extremely fast -- with implications including that it doesn't do a lot of otherwise reasonable optimizations -- but avoiding it altogether is still faster;-). A: When running as CGI, yes, the entire project needs to be loaded for each request. FastCGI and mod_wsgi keep the project in memory and talk to it over a socket.
How exactly does a python (django) request happen? does it have to reparse all the codebase?
With a scripting language like python (or php), things are not compiled down to bytecode like in .net or java. So does this mean that on every request, it has to go through the entire application and parse/compile it? Or at least all the code required for the given call stack?
[ "\nWith a scripting language like python\n (or php), things are not compiled down\n to bytecode like in .net or java.\n\nWrong: everything you import in Python gets compiled to bytecode (and saved as .pyc files if you can write to the directory containing the source you're importing -- standard libraries &c are generally pre-compiled, depending on the installation choices of course). Just keep the main script short and simple (importing some module and calling a function in it) and you'll be using compiled bytecode throughout. (Python's compiler is designed to be extremely fast -- with implications including that it doesn't do a lot of otherwise reasonable optimizations -- but avoiding it altogether is still faster;-).\n", "When running as CGI, yes, the entire project needs to be loaded for each request. FastCGI and mod_wsgi keep the project in memory and talk to it over a socket.\n" ]
[ 5, 3 ]
[]
[]
[ "django", "pipeline", "python", "request_pipeline" ]
stackoverflow_0003018690_django_pipeline_python_request_pipeline.txt
Q: Form values in a list item Here is the site mock-up I'm working on for my job: http://dev.arm.gov/~noensie/dqhands/cgi-bin/explorer. I'm still a novice in web developing and I need help with placing form values in a list item to pass on to another page. I'd rather not go in great detail the purpose of this website, but in terms of its basic use, select the parameters in the middle column for a request and add it to the list on the right column by pressing on "add request" button when it appears. After the list have been populated, a user would submit the selected requests, which will direct them to another page based on the requests selected (or added to the list, same thing). That last sentence is where I'm having a problem. Right now, each of request in the list in the right column are <li> elements and I assign them attribute values that needed to be passed on to the next page. I tried inserting a hidden input with same values, but I'm still not sure how to utilize that; I'm not even sure using the hidden input is the correct way. Also the "submit request" button is located outside the <form> block. I was going to utilize javascript and jQuery to enable the button to serialize the values in the <form> block, but I don't know quite how to do that. Go ahead and take a look at my javascript code (index.js) and slay me, or, I mean, my code. It's still pretty elementary and short (~260 lines, that's short right?). I will take any help for this problem (as the matter of fact, if you see any other problems or a better way of implementation of something, go ahead and mention that too); tips, advice, code samples, or whatever else you can contribute, it will be greatly appreciated. Tri EDIT: I am using python as the server-side language A: You should use hidden input fields. It depends on what server side language you fancy using, but I'd go for the following naming scheme for your hidden fields: request[][site] request[][datastream] request[][facility] request[][date] The "[]" notation places the data in an array (for PHP at least). The posted data could therefore be iterated as follows: foreach($_POST as $request) { $theSiteForThisRequest = $request["site"]; $theDatastreamForThisRequest = $request["datastream"]; $theFacilityForThisRequest = $request["site"]; $theDateForThisRequest = $request["date"]; } Try and get the submit button inside the <form> if you can, but if not you can do the following: $('#yourSubmitButton').bind('click', function () { $('#yourForm').submit(); });
Form values in a list item
Here is the site mock-up I'm working on for my job: http://dev.arm.gov/~noensie/dqhands/cgi-bin/explorer. I'm still a novice in web developing and I need help with placing form values in a list item to pass on to another page. I'd rather not go in great detail the purpose of this website, but in terms of its basic use, select the parameters in the middle column for a request and add it to the list on the right column by pressing on "add request" button when it appears. After the list have been populated, a user would submit the selected requests, which will direct them to another page based on the requests selected (or added to the list, same thing). That last sentence is where I'm having a problem. Right now, each of request in the list in the right column are <li> elements and I assign them attribute values that needed to be passed on to the next page. I tried inserting a hidden input with same values, but I'm still not sure how to utilize that; I'm not even sure using the hidden input is the correct way. Also the "submit request" button is located outside the <form> block. I was going to utilize javascript and jQuery to enable the button to serialize the values in the <form> block, but I don't know quite how to do that. Go ahead and take a look at my javascript code (index.js) and slay me, or, I mean, my code. It's still pretty elementary and short (~260 lines, that's short right?). I will take any help for this problem (as the matter of fact, if you see any other problems or a better way of implementation of something, go ahead and mention that too); tips, advice, code samples, or whatever else you can contribute, it will be greatly appreciated. Tri EDIT: I am using python as the server-side language
[ "You should use hidden input fields.\nIt depends on what server side language you fancy using, but I'd go for the following naming scheme for your hidden fields:\nrequest[][site]\nrequest[][datastream]\nrequest[][facility]\nrequest[][date]\n\nThe \"[]\" notation places the data in an array (for PHP at least). The posted data could therefore be iterated as follows:\nforeach($_POST as $request) {\n $theSiteForThisRequest = $request[\"site\"];\n $theDatastreamForThisRequest = $request[\"datastream\"];\n $theFacilityForThisRequest = $request[\"site\"];\n $theDateForThisRequest = $request[\"date\"];\n}\n\nTry and get the submit button inside the <form> if you can, but if not you can do the following:\n$('#yourSubmitButton').bind('click', function () {\n $('#yourForm').submit();\n});\n\n" ]
[ 2 ]
[]
[]
[ "html", "javascript", "jquery", "python" ]
stackoverflow_0003018760_html_javascript_jquery_python.txt
Q: How do i print a table in python? I am trying to print the output of the following code in two columns using the python launcher: def main(): print "This program illustrates a chaotic function" n = input("How many numbers should I print? ") x = input("Enter a numbers between 0 and 1: ") y = input("Enter another number between 0 and 1: ") for i in range(n): x = 2.0 * x * (1 - x) print #?? for i in range(n): y = 2.0 * y * (1 - y) print #?? main() A: for x, y in listOfTwotuples: print x, y Given that you've provided no details I've gone ahead and assumed that you've got a list of two-tuples. Update your question with more info and I'll update my answer to match! edit: with actual details now If in each loop you store the numbers in a list, you can then use zip to get the format needed to use my code snippet above. So after reading the input in (be careful with input by the way, using raw_input is better, google why): xs = [] ys = [] for i in range(n): xs.append(2.0 * x * (1 - x)) for i in range(n): ys.append(2.0 * y * (1 - y)) Then you can use zip to apply my code snippet above: for x, y in zip(xs, ys): print x, y zip takes one list [0, 1, 2, ...] and another [10, 20, 30, ...] to produce a list of tuples with these lists [(0, 10), (1, 20), (2, 30), ...]. A: >>>print "a table in python? using two columns" a table in python? using two columns ;-) A: Check out the format string syntax which will help you to pad strings with spaces to get columns. A: If all you want is an x and a y value on each line, then once the preliminaries are done, you can say: for i in range(n): x = 2 * x * (1 - x) y = 2 * y * (1 - y) print x,y
How do i print a table in python?
I am trying to print the output of the following code in two columns using the python launcher: def main(): print "This program illustrates a chaotic function" n = input("How many numbers should I print? ") x = input("Enter a numbers between 0 and 1: ") y = input("Enter another number between 0 and 1: ") for i in range(n): x = 2.0 * x * (1 - x) print #?? for i in range(n): y = 2.0 * y * (1 - y) print #?? main()
[ "for x, y in listOfTwotuples:\n print x, y\n\nGiven that you've provided no details I've gone ahead and assumed that you've got a list of two-tuples. Update your question with more info and I'll update my answer to match!\nedit: with actual details now\nIf in each loop you store the numbers in a list, you can then use zip to get the format needed to use my code snippet above.\nSo after reading the input in (be careful with input by the way, using raw_input is better, google why):\nxs = []\nys = []\nfor i in range(n):\n xs.append(2.0 * x * (1 - x))\nfor i in range(n):\n ys.append(2.0 * y * (1 - y))\n\nThen you can use zip to apply my code snippet above:\nfor x, y in zip(xs, ys):\n print x, y\n\nzip takes one list [0, 1, 2, ...] and another [10, 20, 30, ...] to produce a list of tuples with these lists [(0, 10), (1, 20), (2, 30), ...].\n", ">>>print \"a table in python? using two columns\"\na table in python? using two columns\n\n;-)\n", "Check out the format string syntax which will help you to pad strings with spaces to get columns.\n", "If all you want is an x and a y value on each line, then once the preliminaries are done, you can say:\nfor i in range(n):\n x = 2 * x * (1 - x)\n y = 2 * y * (1 - y)\n print x,y\n\n" ]
[ 3, 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003018295_python.txt
Q: The LoadLibraryA method returns error code 1114 (ERROR_DLL_INIT_FAILED) after more than 1000 cycles of loading/unloading I'm programing on C++, I'm using Visual Studio 2008, Windows XP, and I have the following problem: My application, that is a DLL that can be used from Python, loads an external dll, uses the required methods, and then unloads this external Dll. It's working properly, but after more than 1000 cycles the method "LoadLibraryA" returns a NULL reference. The main steps are: HINSTANCE h = NULL; h = LoadLibraryA(dllfile.c_str()); DWORD dw = GetLastError(); The error got is: ERROR_DLL_INIT_FAILED 1114 (0x45A) A dynamic link library (DLL) initialization routine failed. The Dll is unloaded by using the following: FreeLibrary(mDLL); mDLL = NULL; Where mDLL is defined like this: HINSTANCE mDLL; First alternative tried: Just load the Dll only once, and unloaded it when the application ends. This fix the problem but introduces a new one. When the application ends, instead of first executing the DllMain method of my applicaion, wich unloads the external DLL, is executing first the DllMain method of the other Dll. This cause the following error because my application is trying to unload a Dll that was unload by itself previously. "Unhandled exception at 0x04a00d07 (DllName.DLL) in Python.exe: 0xC0000005: Access violation reading location 0x0000006b". Any suggestion will be welcomed. Thanks in advance. Regards. A: Make sure that initialization code of the loaded/unloaded library doesn't leak memory. Many libraries expect to be loaded only once and not always clean up their resources properly. E.g. in C++ file at the top level one can declare and initialize a variable like this: AClass *a = new AClass(1,2,3); The code would be executed when library is loaded automatically. Yet, now, it is impossible to free the hanging instance as library doesn't know precisely when/how it is going to be unloaded. In the case one can either replace "AClass *a" with "AClass a" or write your own DllMain for the library and free resources on DLL_PROCESS_DETACH. If you have no control over the library's code, then it might make sense to create a cache of loaded libraries and simply never unload them. It is very hard to imagine that there would be unlimited number of libraries to overload such cache.
The LoadLibraryA method returns error code 1114 (ERROR_DLL_INIT_FAILED) after more than 1000 cycles of loading/unloading
I'm programing on C++, I'm using Visual Studio 2008, Windows XP, and I have the following problem: My application, that is a DLL that can be used from Python, loads an external dll, uses the required methods, and then unloads this external Dll. It's working properly, but after more than 1000 cycles the method "LoadLibraryA" returns a NULL reference. The main steps are: HINSTANCE h = NULL; h = LoadLibraryA(dllfile.c_str()); DWORD dw = GetLastError(); The error got is: ERROR_DLL_INIT_FAILED 1114 (0x45A) A dynamic link library (DLL) initialization routine failed. The Dll is unloaded by using the following: FreeLibrary(mDLL); mDLL = NULL; Where mDLL is defined like this: HINSTANCE mDLL; First alternative tried: Just load the Dll only once, and unloaded it when the application ends. This fix the problem but introduces a new one. When the application ends, instead of first executing the DllMain method of my applicaion, wich unloads the external DLL, is executing first the DllMain method of the other Dll. This cause the following error because my application is trying to unload a Dll that was unload by itself previously. "Unhandled exception at 0x04a00d07 (DllName.DLL) in Python.exe: 0xC0000005: Access violation reading location 0x0000006b". Any suggestion will be welcomed. Thanks in advance. Regards.
[ "Make sure that initialization code of the loaded/unloaded library doesn't leak memory. Many libraries expect to be loaded only once and not always clean up their resources properly.\nE.g. in C++ file at the top level one can declare and initialize a variable like this:\nAClass *a = new AClass(1,2,3);\n\nThe code would be executed when library is loaded automatically. Yet, now, it is impossible to free the hanging instance as library doesn't know precisely when/how it is going to be unloaded. In the case one can either replace \"AClass *a\" with \"AClass a\" or write your own DllMain for the library and free resources on DLL_PROCESS_DETACH.\nIf you have no control over the library's code, then it might make sense to create a cache of loaded libraries and simply never unload them. It is very hard to imagine that there would be unlimited number of libraries to overload such cache.\n" ]
[ 1 ]
[]
[]
[ "c++", "loadlibrary", "python" ]
stackoverflow_0003018348_c++_loadlibrary_python.txt
Q: 64-bit integers in Cython I'm trying to interface a C++ library (pHash) with Python using Cython, but I have trouble with some of the types. The library functions use "unsigned long long" and I can't find a way to declare variables and parameters with this type. I searched for a list of the types that I can use with cdef but I found nothing. Can anyone point me to such a list (if it exists) or otherwise suggest a way to use 64 bit types in Cython? Thanks. A: I've been able to use both unsigned long long and long long just fine with cdef. See for instance my answer to this question here. I just tried running the same code there with unsigned long long instead of long long and it worked just fine. Can you be more specific about what problems you are having with these types? Maybe you could post some source code that isn't working for you? A: Here is one of my answers using unsigned long long with cython Simple Python Challenge: Fastest Bitwise XOR on Data Buffers
64-bit integers in Cython
I'm trying to interface a C++ library (pHash) with Python using Cython, but I have trouble with some of the types. The library functions use "unsigned long long" and I can't find a way to declare variables and parameters with this type. I searched for a list of the types that I can use with cdef but I found nothing. Can anyone point me to such a list (if it exists) or otherwise suggest a way to use 64 bit types in Cython? Thanks.
[ "I've been able to use both unsigned long long and long long just fine with cdef. See for instance my answer to this question here. I just tried running the same code there with unsigned long long instead of long long and it worked just fine. Can you be more specific about what problems you are having with these types? Maybe you could post some source code that isn't working for you?\n", "Here is one of my answers using unsigned long long with cython\nSimple Python Challenge: Fastest Bitwise XOR on Data Buffers\n" ]
[ 5, 3 ]
[]
[]
[ "cython", "python", "types" ]
stackoverflow_0003018425_cython_python_types.txt
Q: How do I get the key of an item when doing a FOR loop through a dictionary or list in Python? I am new to Python. Say I have a list: list = ['A','B','C','D'] The key for each item respectively here is 0,1,2,3 - right? Now I am going to loop through it with a for loop... for item in list: print item That's great, I can print out my list. How do I get the key here? For example being able to do: print key print item on each loop? If this isn't possible with a list, where keys are not declared myself, is it possible with a Dictionary? Thanks A: The answer is different for lists and dicts. A list has no key. Each item will have an index. You can enumerate a list like this: >>> l = ['A','B','C','D'] >>> for index, item in enumerate(l): ... print index ... print item ... 0 A 1 B 2 C 3 D I used your example here, but called the list 'l', to avoid a clash with a reserved word. If you iterate over a dict, you are handed the key: >>> d = {0: 'apple', 1: 'banana', 2: 'cherry', 3: 'damson', } >>> for k in d: ... print k ... print d[k] ... 0 apple 1 banana 2 cherry 3 damson A: You want the index, not the key. For this you can use enumerate: for index, item in enumerate(l): print index print item This is mentioned in the section Looping Techniques in the Python tutorial which also covers looping over dictionaries while getting both the key and the value. >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'} >>> for k, v in knights.iteritems(): ... print k, v ... gallahad the pure robin the brave A: You should use a dictionary, anyway you could do something like: for index, item in enumerate(yourlist): print "index:%d item:%s" % (index, item)
How do I get the key of an item when doing a FOR loop through a dictionary or list in Python?
I am new to Python. Say I have a list: list = ['A','B','C','D'] The key for each item respectively here is 0,1,2,3 - right? Now I am going to loop through it with a for loop... for item in list: print item That's great, I can print out my list. How do I get the key here? For example being able to do: print key print item on each loop? If this isn't possible with a list, where keys are not declared myself, is it possible with a Dictionary? Thanks
[ "The answer is different for lists and dicts. \nA list has no key. Each item will have an index. You can enumerate a list like this:\n>>> l = ['A','B','C','D']\n>>> for index, item in enumerate(l):\n... print index\n... print item\n... \n0\nA\n1\nB\n2\nC\n3\nD\n\nI used your example here, but called the list 'l', to avoid a clash with a reserved word.\nIf you iterate over a dict, you are handed the key:\n>>> d = {0: 'apple', 1: 'banana', 2: 'cherry', 3: 'damson', }\n>>> for k in d:\n... print k\n... print d[k]\n... \n0\napple\n1\nbanana\n2\ncherry\n3\ndamson\n\n", "You want the index, not the key. For this you can use enumerate:\nfor index, item in enumerate(l):\n print index\n print item\n\nThis is mentioned in the section Looping Techniques in the Python tutorial which also covers looping over dictionaries while getting both the key and the value.\n>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}\n>>> for k, v in knights.iteritems():\n... print k, v\n...\ngallahad the pure\nrobin the brave\n\n", "You should use a dictionary, anyway you could do something like:\nfor index, item in enumerate(yourlist):\n print \"index:%d item:%s\" % (index, item)\n\n" ]
[ 24, 11, 3 ]
[]
[]
[ "python" ]
stackoverflow_0003019049_python.txt
Q: Binning into timeslots - Is there a better way than using list comp? I have a dataset of events (tweets to be specific) that I am trying to bin / discretize. The following code seems to work fine so far (assuming 100 bins): HOUR = timedelta(hours=1) start = datetime.datetime(2009,01,01) z = [dt + x*HOUR for x in xrange(1, 100)] But then, I came across this fateful line at python docs 'This makes possible an idiom for clustering a data series into n-length groups using zip(*[iter(s)]*n)'. The zip idiom does indeed work - but I can't understand how (what is the * operator for instance?). How could I use to make my code prettier? I'm guessing this means I should make a generator / iterable for time that yields the time in graduations of an HOUR? A: The expression from the docs looks like this: zip(*[iter(s)]*n) This is equivalent to: it = iter(s) zip(*[it, it, ..., it]) # n times The [...]*n repeats the list n times, and this results in a list that contains nreferences to the same iterator. This is again equal to: it = iter(s) zip(it, it, ..., it) # turning a list into positional parameters The * before the list turns the list elements into positional parameters of the function call. Now, when zip is called, it starts from left to right to call the iterators to obtain elements that should be grouped together. Since all parameters refer to the same iterator, this yields the first n elements of the initial sequence. Then that process continues for the second group in the resulting list, and so on. The result is the same as if you had constructed the list like this (evaluated from left to right): it = iter(s) [(it.next(), it.next(), ..., it.next()), (it.next(), it.next(), ..., it.next()), ...] A: I will try to explain zip(*[iter(s)]*n) in terms of a simpler example: imagine you have the list s = [1, 2, 3, 4, 5, 6] iter(s) gives you a listiterator object that will yield the next number from s each time you ask for an element. [iter(s)] * n gives you the list with iter(s) in it n times e.g. [iter(s)] * 2 = [<listiterator object>, <listiterator object>] - the key here is that these are 2 references to the same iterator object, not 2 distinct iterator objects. zip takes a number of sequences and returns a list of tuples where each tuple contains the ith element from each of the sequences. e.g. zip([1,2], [3,4], [5,6]) = [(1, 3, 5), (2, 4, 6)] where (1, 3, 5) are the first elements from the parameters passed to zip and (2, 4, 6) are the second elements from the parameters passed to zip. The * in front of *[iter(s)]*n converts the [iter(s)]*n from being a list into being multiple parameters being passed to zip. so if n is 2 we get zip(<listiterator object>, <listiterator object>) zip will request the next element from each of its parameters but because these are both references to the same iterator this will result in (1, 2), it does the same again resulting in (3, 4) and again resulting in (5, 6) and then there are no more elements so it stops. Hence the result [(1, 2), (3, 4), (5, 6)]. This is the clustering a data series into n-length groups as mentioned.
Binning into timeslots - Is there a better way than using list comp?
I have a dataset of events (tweets to be specific) that I am trying to bin / discretize. The following code seems to work fine so far (assuming 100 bins): HOUR = timedelta(hours=1) start = datetime.datetime(2009,01,01) z = [dt + x*HOUR for x in xrange(1, 100)] But then, I came across this fateful line at python docs 'This makes possible an idiom for clustering a data series into n-length groups using zip(*[iter(s)]*n)'. The zip idiom does indeed work - but I can't understand how (what is the * operator for instance?). How could I use to make my code prettier? I'm guessing this means I should make a generator / iterable for time that yields the time in graduations of an HOUR?
[ "The expression from the docs looks like this:\nzip(*[iter(s)]*n)\n\nThis is equivalent to:\nit = iter(s)\nzip(*[it, it, ..., it]) # n times\n\nThe [...]*n repeats the list n times, and this results in a list that contains nreferences to the same iterator.\nThis is again equal to:\nit = iter(s)\nzip(it, it, ..., it) # turning a list into positional parameters\n\nThe * before the list turns the list elements into positional parameters of the function call.\nNow, when zip is called, it starts from left to right to call the iterators to obtain elements that should be grouped together. Since all parameters refer to the same iterator, this yields the first n elements of the initial sequence. Then that process continues for the second group in the resulting list, and so on.\nThe result is the same as if you had constructed the list like this (evaluated from left to right):\nit = iter(s)\n[(it.next(), it.next(), ..., it.next()), (it.next(), it.next(), ..., it.next()), ...]\n\n", "I will try to explain zip(*[iter(s)]*n) in terms of a simpler example:\nimagine you have the list s = [1, 2, 3, 4, 5, 6]\niter(s) gives you a listiterator object that will yield the next number from s each time you ask for an element.\n[iter(s)] * n gives you the list with iter(s) in it n times e.g. [iter(s)] * 2 = [<listiterator object>, <listiterator object>] - the key here is that these are 2 references to the same iterator object, not 2 distinct iterator objects.\nzip takes a number of sequences and returns a list of tuples where each tuple contains the ith element from each of the sequences. e.g. zip([1,2], [3,4], [5,6]) = [(1, 3, 5), (2, 4, 6)] where (1, 3, 5) are the first elements from the parameters passed to zip and (2, 4, 6) are the second elements from the parameters passed to zip.\nThe * in front of *[iter(s)]*n converts the [iter(s)]*n from being a list into being multiple parameters being passed to zip. so if n is 2 we get zip(<listiterator object>, <listiterator object>)\nzip will request the next element from each of its parameters but because these are both references to the same iterator this will result in (1, 2), it does the same again resulting in (3, 4) and again resulting in (5, 6) and then there are no more elements so it stops. Hence the result [(1, 2), (3, 4), (5, 6)]. This is the clustering a data series into n-length groups as mentioned.\n" ]
[ 5, 5 ]
[]
[]
[ "python" ]
stackoverflow_0003019084_python.txt
Q: Python's string.translate() doesn't fully work? Given this example, I get the error that follows: print u'\2033'.translate({2033:u'd'}) C:\Python26\lib\encodings\cp437.pyc in encode(self, input, errors) 10 11 def encode(self,input,errors='strict'): ---> 12 return codecs.charmap_encode(input,errors,encoding_map) 13 14 def decode(self,input,errors='strict'): UnicodeEncodeError: 'charmap' codec can't encode character u'\x83' in position 0 A: Try this instead: >>> print u'\u2033'.translate({0x2033:u'd'}) d Since you used u'\2033' instead of u'\u2033', The result was two characters: u'\203'+u'3'. Trying to print this gave an exception because your terminal's encoding doesn't support the character u'\203' (which is the same as u'\x83'). Also note the difference between 2033 and 0x2033 in the dictionary: The \uxxxx escape sequence takes its value in hexadecimal, so you'd need 0x2033 to match it. Regarding your question's title, string.translate (the translate function in the string module) doesn't support a dictionary as a parameter, but calling .translate on the unicode string itself (as you did in the question body) works.
Python's string.translate() doesn't fully work?
Given this example, I get the error that follows: print u'\2033'.translate({2033:u'd'}) C:\Python26\lib\encodings\cp437.pyc in encode(self, input, errors) 10 11 def encode(self,input,errors='strict'): ---> 12 return codecs.charmap_encode(input,errors,encoding_map) 13 14 def decode(self,input,errors='strict'): UnicodeEncodeError: 'charmap' codec can't encode character u'\x83' in position 0
[ "Try this instead:\n>>> print u'\\u2033'.translate({0x2033:u'd'})\nd\n\nSince you used u'\\2033' instead of u'\\u2033', The result was two characters: u'\\203'+u'3'. Trying to print this gave an exception because your terminal's encoding doesn't support the character u'\\203' (which is the same as u'\\x83').\nAlso note the difference between 2033 and 0x2033 in the dictionary: The \\uxxxx escape sequence takes its value in hexadecimal, so you'd need 0x2033 to match it.\nRegarding your question's title, string.translate (the translate function in the string module) doesn't support a dictionary as a parameter, but calling .translate on the unicode string itself (as you did in the question body) works.\n" ]
[ 6 ]
[]
[]
[ "python", "unicode" ]
stackoverflow_0003019381_python_unicode.txt
Q: How can I build a wrapper to wait for listening on a port? I am looking for a way of programmatically testing a script written with the asyncore Python module. My test consists of launching the script in question -- if a TCP listen socket is opened, the test passes. Otherwise, if the script dies before getting to that point, the test fails. The purpose of this is knowing if a nightly build works (at least up to a point) or not. I was thinking the best way to test would be to launch the script in some kind of sandbox wrapper which waits for a socket request. I don't care about actually listening for anything on that port, just intercepting the request and using that as an indication that my test passed. I think it would be preferable to intercept the open socket request, rather than polling at set intervals (I hate polling!). But I'm a bit out of my depths as far as how exactly to do this. Can I do this with a shell script? Or perhaps I need to override the asyncore module at the Python level? Thanks in advance, - B A: This felt like code-golf: #!/bin/sh # iamwaiting: run a command for a specified time then kill it # returns the status of cmd on normal termination opath=$PATH PATH=/bin:/usr:/bin SIGNAL= case $1 in -*) SIGNAL=$1; shift;; esac case $# in 0|1) echo 'usage iamwaiting [-signal] wait cmd [args]' 1>&2; exit 2;; esac wait=$1 ; shift PATH=$opath "$@" & child=$! # unfortunately, this script takes at least wait seconds to run sleep $wait if kill ${SIGNAL:--2} $child 2> /dev/null ; then echo "iamwaiting timeout after $wait seconds: $@" 1>&2 exit 1 else wait $child exit $? fi runs thusly: $ iamwaiting 5 dd if=/dev/zero of=/dev/null count=5 5+0 records in 5+0 records out 2560 bytes (2.6 kB) copied, 2.0973e-05 s, 122 MB/s $ echo $? 0 $ iamwaiting -9 5 dd if=/dev/zero of=/dev/null iamwaiting timeout after 5 seconds: dd if=/dev/zero of=/dev/null $ echo $? 1 $ iamwaiting 1 cat /dev/does-not-exist cat: /dev/does-not-exist: No such file or directory $ echo $? 1 I'd be wary of testing asyncore programs with asynchore routines, but I'm superstitious that way. A: Another option is to mock the socket module before importing the asyncore module. Of course, then you have to make sure that the mock works properly first.
How can I build a wrapper to wait for listening on a port?
I am looking for a way of programmatically testing a script written with the asyncore Python module. My test consists of launching the script in question -- if a TCP listen socket is opened, the test passes. Otherwise, if the script dies before getting to that point, the test fails. The purpose of this is knowing if a nightly build works (at least up to a point) or not. I was thinking the best way to test would be to launch the script in some kind of sandbox wrapper which waits for a socket request. I don't care about actually listening for anything on that port, just intercepting the request and using that as an indication that my test passed. I think it would be preferable to intercept the open socket request, rather than polling at set intervals (I hate polling!). But I'm a bit out of my depths as far as how exactly to do this. Can I do this with a shell script? Or perhaps I need to override the asyncore module at the Python level? Thanks in advance, - B
[ "This felt like code-golf:\n#!/bin/sh\n# iamwaiting: run a command for a specified time then kill it\n# returns the status of cmd on normal termination\n\n\nopath=$PATH\nPATH=/bin:/usr:/bin\n\nSIGNAL=\ncase $1 in\n -*) SIGNAL=$1; shift;;\nesac\n\ncase $# in\n 0|1) echo 'usage iamwaiting [-signal] wait cmd [args]' 1>&2; exit 2;;\nesac\n\nwait=$1 ; shift\n\nPATH=$opath \"$@\" &\nchild=$!\n\n# unfortunately, this script takes at least wait seconds to run\nsleep $wait\n\nif kill ${SIGNAL:--2} $child 2> /dev/null ; then\n echo \"iamwaiting timeout after $wait seconds: $@\" 1>&2\n exit 1\nelse\n wait $child\n exit $?\nfi\n\nruns thusly:\n$ iamwaiting 5 dd if=/dev/zero of=/dev/null count=5\n5+0 records in\n5+0 records out\n2560 bytes (2.6 kB) copied, 2.0973e-05 s, 122 MB/s\n$ echo $?\n0\n$ iamwaiting -9 5 dd if=/dev/zero of=/dev/null \niamwaiting timeout after 5 seconds: dd if=/dev/zero of=/dev/null\n$ echo $?\n1\n$ iamwaiting 1 cat /dev/does-not-exist\ncat: /dev/does-not-exist: No such file or directory\n$ echo $?\n1\n\nI'd be wary of testing asyncore programs with asynchore routines, but I'm superstitious that way.\n", "Another option is to mock the socket module before importing the asyncore module. Of course, then you have to make sure that the mock works properly first.\n" ]
[ 0, 0 ]
[]
[]
[ "python", "sockets", "testing", "wrapper" ]
stackoverflow_0003014686_python_sockets_testing_wrapper.txt