title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
How does Qt work (exactly)?
3,045,745
11
2010-06-15T13:49:18Z
3,045,754
15
2010-06-15T13:50:34Z
[ "python", "qt" ]
When you write an application using Qt, can it just be run right away in different operating systems? And (correct me if I'm wrong) you don't need to have Qt already installed in all of the different platforms where you want to execute your application? How exactly does this work? Does Qt compile to the desired platfo...
Qt (ideally) provides source compatibility, not binary compatibility. You still have to compile the application separately for each platform, and use the appropriate dynamic Qt libraries (which also need to be compiled separately, and have some platform-specific code). For your final question, the user would need Pyth...
How does Qt work (exactly)?
3,045,745
11
2010-06-15T13:49:18Z
3,046,602
12
2010-06-15T15:26:40Z
[ "python", "qt" ]
When you write an application using Qt, can it just be run right away in different operating systems? And (correct me if I'm wrong) you don't need to have Qt already installed in all of the different platforms where you want to execute your application? How exactly does this work? Does Qt compile to the desired platfo...
PyQT [and its open source cousin PySide] are a great cross-platform QT binding for python, but it is not a magic solution for shipping your application for all platforms without doing any packaging/installer maintenance. I think maybe you might be expecting some magic. QT is a cross-platform library written in C++. Th...
Simple wrapping of C code with cython
3,046,305
36
2010-06-15T14:49:53Z
3,071,942
56
2010-06-18T17:45:13Z
[ "python", "numpy", "cython" ]
I have a number of C functions, and I would like to call them from python. cython seems to be the way to go, but I can't really find an example of how exactly this is done. My C function looks like this: ``` void calculate_daily ( char *db_name, int grid_id, int year, double *dtmp, double *dtmn,...
Here's a tiny but complete example of passing numpy arrays to an external C function, logically ``` fc( int N, double* a, double* b, double* z ) # z = a + b ``` using Cython. (This is surely well-known to those who know it well. Comments are welcome. Last change: 23 Feb 2011, for Cython 0.14.) First read or skim [C...
Simple wrapping of C code with cython
3,046,305
36
2010-06-15T14:49:53Z
9,116,735
10
2012-02-02T17:14:48Z
[ "python", "numpy", "cython" ]
I have a number of C functions, and I would like to call them from python. cython seems to be the way to go, but I can't really find an example of how exactly this is done. My C function looks like this: ``` void calculate_daily ( char *db_name, int grid_id, int year, double *dtmp, double *dtmn,...
The following Cython code from <http://article.gmane.org/gmane.comp.python.cython.user/5625> doesn't require explicit casts and also handles non-continous arrays: ``` def fpy(A): cdef np.ndarray[np.double_t, ndim=2, mode="c"] A_c A_c = np.ascontiguousarray(A, dtype=np.double) fc(&A_c[0,0]) ```
How to exclude results with get_object_or_404?
3,046,419
12
2010-06-15T15:03:58Z
3,046,550
15
2010-06-15T15:19:34Z
[ "python", "django", "orm" ]
In Django you can use the exclude to create SQL similar to `not equal`. An example could be. ``` Model.objects.exclude(status='deleted') ``` Now this works great and exclude is very flexible. Since I'm a bit lazy, I would like to get that functionality when using `get_object_or_404`, but I haven't found a way to do t...
Use [`django.db.models.Q`](http://docs.djangoproject.com/en/1.2/topics/db/queries/#complex-lookups-with-q-objects): ``` from django.db.models import Q model = get_object_or_404(MyModel, ~Q(status='deleted'), pk=id) ``` The Q objects lets you do NOT (with `~` operator) and OR (with `|` operator) in addition to AND. ...
how to perform square root without using math module?
3,047,012
6
2010-06-15T16:19:01Z
3,047,046
22
2010-06-15T16:23:09Z
[ "python" ]
i want to find the square root of a number without using the math module,as i need to call the function some 20k times and dont want to slow down the execution by linking to the math module each time the function is called is there any faster and easier way for finding square root??
Importing the math module only happens once, and you probably won't get much faster than the math module. There is also an older Stackoverflow question regarding [Which is faster in Python: x\*\*.5 or math.sqrt(x)?](http://stackoverflow.com/questions/327002/which-is-faster-in-python-x-5-or-math-sqrtx). It is not clear ...
how to perform square root without using math module?
3,047,012
6
2010-06-15T16:19:01Z
3,047,425
9
2010-06-15T17:16:08Z
[ "python" ]
i want to find the square root of a number without using the math module,as i need to call the function some 20k times and dont want to slow down the execution by linking to the math module each time the function is called is there any faster and easier way for finding square root??
As Fabian said, it's hard to be faster than `math.sqrt`. The reason is that it calls the correspond function from the C library, with CPython. However, you can speed things up by removing the overhead of attribute lookup: ``` from math import sqrt ``` Each subsequent call to sqrt will *not* have to look it up in the...
in-memory database in Python
3,047,412
12
2010-06-15T17:13:56Z
3,047,435
20
2010-06-15T17:18:25Z
[ "python", "sql", "database", "in-memory-database" ]
I'm doing some queries in Python on a large database to get some stats out of the database. I want these stats to be in-memory so other programs can use them without going to a database. I was thinking of how to structure them, and after trying to set up some complicated nested dictionaries, I realized that a good rep...
SQLite3 might work. The Python interface [does support](http://docs.python.org/library/sqlite3.html) the in-memory implementation that the SQLite3 C API offers. From the spec: > You can also supply the special name > :memory: to create a database in RAM. It's also relatively cheap with transactions, depending on wha...
Building lxml for Python 2.7 on Windows
3,047,542
29
2010-06-15T17:35:02Z
5,122,521
55
2011-02-25T20:54:42Z
[ "python", "windows", "lxml", "building", "python-c-extension" ]
I am trying to build lxml for Python 2.7 on Windows 64 bit machine. I couldn't find lxml egg for Python 2.7 version. So I am compiling it from sources. I am following instructions on this site <http://lxml.de/build.html> under static linking section. I am getting error ``` C:\Documents and Settings\Administrator\Des...
I bet you're not using VS 2008 for this :) There's [def find\_vcvarsall(version):](http://hg.python.org/releasing/2.7.6/file/ba31940588b6/Lib/distutils/msvc9compiler.py#l219) function (guess what, it looks for vcvarsall.bat) in distutils with the following comment > At first it tries to find the > productdir of VS 20...
Is this a valid quine?
3,047,583
3
2010-06-15T17:41:08Z
3,047,597
9
2010-06-15T17:43:03Z
[ "python", "quine" ]
``` def start(fileName): fileReader = open(fileName) for row in fileReader: print row, if __name__ == "__main__": import sys if len(sys.argv) <= 1: print "usage quine /path/to/file" sys.exit(-1) fileName = sys.argv[0] start(fileName) ``` > > python quine.py foo
No, a quine shouldn't take in any input: > A quine takes no input. Allowing input would permit the source code to be fed to the program via the keyboard, opening the source file of the program, and similar mechanisms. From [Quine (computing)](http://en.wikipedia.org/wiki/Quine_%28computing%29). **UPDATE** You need ...
How can I update only certain fields in a Django model form?
3,047,700
9
2010-06-15T17:57:00Z
3,047,967
9
2010-06-15T18:28:32Z
[ "python", "django" ]
I have a model form that I use to update a model. ``` class Turtle(models.Model): name = models.CharField(max_length=50, blank=False) description = models.TextField(blank=True) class TurtleForm(forms.ModelForm): class Meta: model = Turtle ``` Sometimes I don't need to update the entire model, but...
Only use specified fields: ``` class FirstModelForm(forms.ModelForm): class Meta: model = TheModel fields = ('title',) def clean_title(self.... ``` See <http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#controlling-which-fields-are-used-with-fields-and-exclude> It is common to use...
Why can't easy_install find MySQLdb?
3,047,848
65
2010-06-15T18:15:11Z
3,047,938
138
2010-06-15T18:25:12Z
[ "python", "mysql", "easy-install" ]
This is what I tried: ``` $ easy_install-2.6 -d /home/user/lib/python2.6 MySQLdb Searching for MySQLdb Reading http://pypi.python.org/simple/MySQLdb/ Couldn't find index page for 'MySQLdb' (maybe misspelled?) Scanning index of all packages (this may take a while) Reading http://pypi.python.org/simple/ No l...
You have the wrong package name. [MySQL-python](http://pypi.python.org/pypi/MySQL-python/) is the right one: ``` easy_install MySQL-python ``` or ``` pip install MySQL-python ```
Why can't easy_install find MySQLdb?
3,047,848
65
2010-06-15T18:15:11Z
4,572,346
7
2010-12-31T21:19:14Z
[ "python", "mysql", "easy-install" ]
This is what I tried: ``` $ easy_install-2.6 -d /home/user/lib/python2.6 MySQLdb Searching for MySQLdb Reading http://pypi.python.org/simple/MySQLdb/ Couldn't find index page for 'MySQLdb' (maybe misspelled?) Scanning index of all packages (this may take a while) Reading http://pypi.python.org/simple/ No l...
Adam is right but before you run `easy_install MySQL-python` you need to make sure `python-dev` is installed as it is not installed by default. Install is with `apt-get install python-dev`.
Eventlet or gevent or Stackless + Twisted, Pylons, Django and SQL Alchemy
3,048,012
35
2010-06-15T18:32:50Z
3,050,700
27
2010-06-16T04:21:28Z
[ "python", "gevent", "pypy", "eventlet", "python-stackless" ]
We're using Twisted extensively for apps requiring a great deal of asynchronous io. There are some cases where stuff is cpu bound instead and for that we spawn a pool of processes to do the work and have a system for managing these across multiple servers as well - all done in Twisted. Works great. The problem is that ...
You might want to check out: * [Comparing gevent to eventlet](http://blog.gevent.org/2010/02/27/why-gevent/) * [Reports from users who moved from twisted or eventlet to gevent](http://groups.google.com/group/gevent/browse_thread/thread/4de9703e5dca8271) Eventlet and gevent are not really comparable to Stackless, beca...
Help with pyHook error
3,049,068
4
2010-06-15T21:12:08Z
3,050,403
8
2010-06-16T02:40:34Z
[ "python", "windows" ]
I'm trying to make a global hotkey with pyhook in python that is supposed to work only with the alt key pressed. here is the source: ``` import pyHook import pythoncom hm = pyHook.HookManager() def OnKeyboardEvent(event): if event.Alt == 32 and event.KeyID == 49: print 'HERE WILL BE THE CODE' hm.KeyDow...
Note from the [tutorial](http://sourceforge.net/apps/mediawiki/pyhook/index.php?title=PyHook_Tutorial) that you need a return value at the end of your handler: ``` def OnKeyboardEvent(event): if event.Alt == 32 and event.KeyID == 49: print 'HERE WILL BE THE CODE' # return True to pass the event to oth...
floating point equality in Python and in general
3,049,101
15
2010-06-15T21:15:40Z
3,049,686
7
2010-06-15T22:59:32Z
[ "python", "floating-point", "equality" ]
I have a piece of code that behaves differently depending on whether I go through a dictionary to get conversion factors or whether I use them directly. The following piece of code will print `1.0 == 1.0 -> False` But if you replace `factors[units_from]` with `10.0` and `factors[units_to ]` with `1.0 / 2.54` it will ...
As has been shown comparing two floats (or doubles etc) can be problematic. Generally, instead of comparing for exact equality they should be checked against an error bound. If they are within the error bound, they are considered equal. That is much easier said than done. The nature of floating point make a fixed erro...
Where do I put utility functions in my Python project?
3,049,569
8
2010-06-15T22:35:05Z
3,058,446
8
2010-06-17T02:02:12Z
[ "python", "function", "import", "utilities" ]
I need to create a function to rotate a given matrix (list of lists) clockwise, and I need to use it in my `Table` class. Where should I put this utility function (called `rotateMatrixClockwise`) so I can call it easily from within a function in my `Table` class?
**Make it a static function...** * add the @staticmethod decorator * don't include 'self' as the first argument Your definition would be: ``` @staticmethod def rotateMatrixClockwise(): # enter code here... ``` Which will make it callable everywhere you imported 'table' by calling: ``` table.rotateMatrixClockwi...
How to convert MP3 to WAV in Python
3,049,572
9
2010-06-15T22:36:04Z
12,391,451
15
2012-09-12T15:19:14Z
[ "python", "mp3" ]
If I have an MP3 file how can I convert it to a WAV file? (preferably, using a pure python approach)
I maintain an open source library, [pydub](http://pydub.com), which can help you out with that. ``` from pydub import AudioSegment sound = AudioSegment.from_mp3("/path/to/file.mp3") sound.export("/output/path", format="wav") ``` One caveat: it uses ffmpeg to handle audio format conversions (except for wav files, whic...
Change browser proxy settings from Python?
3,050,262
7
2010-06-16T02:01:06Z
6,445,513
12
2011-06-22T19:38:32Z
[ "python", "browser", "proxy", "settings" ]
I have written a program that relies on a proxy to function. I now need a script that will check to see if the browser is set to use the right proxy, and if not, change it to use it. I need this implemented for as many browsers as possible, but is only required for ***Internet Explorer, Google Chrome, Mozilla Firefox, ...
The Windows stores its system wide proxy in the registry, look in the the `HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings`. You can use the Python \_winreg module to change it (or just winreg if you use Python 3). Here is a sample code ``` import _winreg as winreg INTERNET_SETTINGS = wi...
On Ubuntu, how do you install a newer version of python and keep the older python version?
3,050,512
8
2010-06-16T03:18:12Z
3,050,521
9
2010-06-16T03:20:50Z
[ "python", "ubuntu", "installation", "gnu", "configure" ]
Background: * I am using Ubuntu * The newer python version is not in the apt-get repository (or synaptic) * I plan on keeping the old version as the default python when you call "python" from the command line * I plan on calling the new python using pythonX.X (X.X is the new version). **Given the background, how do y...
When you install from source, by default, the installation goes in `/usr/local` -- the executable in particular becomes `/usr/local/bin/pythonX.Y` with a symlink to it that's named `/usr/local/python`. Ubuntu's own installation is in `/usr/` (e.g., `/usr/bin/python`), so the new installation won't overwrite it. Take ca...
Is it possible to use multiple programming languages on one webiste
3,050,682
11
2010-06-16T04:14:58Z
3,050,687
21
2010-06-16T04:16:51Z
[ "java", "php", "python", "webserver" ]
Suppose i have one webiste with simple pages in php like ``` page1.php page2.php ``` Now there is one page where i want some detailed functioning and i want to use python for that and it will look like ``` page3.py ``` and in other page i want to use java like ``` page4.jsp ``` Provided i have installed python , ...
Yes. It's possible. Where you will find yourself in trouble is when you want to share server-side information among them (I.E. sessions). Other than that, you can use (but I would advise against it) all languages you want on a website.
Is it possible to use multiple programming languages on one webiste
3,050,682
11
2010-06-16T04:14:58Z
3,050,693
10
2010-06-16T04:18:48Z
[ "java", "php", "python", "webserver" ]
Suppose i have one webiste with simple pages in php like ``` page1.php page2.php ``` Now there is one page where i want some detailed functioning and i want to use python for that and it will look like ``` page3.py ``` and in other page i want to use java like ``` page4.jsp ``` Provided i have installed python , ...
Yes, it is possible, but you definitely should NOT do it. Communication between pages running different technologies will not be elegant, if for no other reason than the fact that you won't get a shared session pool. Session bridges are possible, but they are a pain to do. I would say you are making a mistake if you ...
How to document class attributes in Python?
3,051,241
56
2010-06-16T06:58:53Z
3,051,356
36
2010-06-16T07:25:10Z
[ "python", "class", "documentation", "docstring", "class-attributes" ]
I'm writing a lightweight class whose attributes are intended to be publicly accessible, and only sometimes overridden in specific instantiations. There's no provision in the Python language for creating docstrings for class attributes, or any sort of attributes, for that matter. What is the accepted way, should there ...
To avoid confusion: the term *property* has a [specific meaning](http://docs.python.org/library/functions.html#property) in python. What you're talking about is what we call [*class attributes*](http://docs.python.org/tutorial/classes.html#class-objects). Since they are always acted upon through their class, I find tha...
How to document class attributes in Python?
3,051,241
56
2010-06-16T06:58:53Z
9,558,703
15
2012-03-04T20:52:28Z
[ "python", "class", "documentation", "docstring", "class-attributes" ]
I'm writing a lightweight class whose attributes are intended to be publicly accessible, and only sometimes overridden in specific instantiations. There's no provision in the Python language for creating docstrings for class attributes, or any sort of attributes, for that matter. What is the accepted way, should there ...
You cite the PEP257: Docstring Conventions, in the section [What is a docstring](http://www.python.org/dev/peps/pep-0257/#what-is-a-docstring) it is stated: > String literals occurring elsewhere in Python code may also act as documentation. They are not recognized by the Python bytecode compiler and are not accessible...
jquery-like HTML parsing in Python?
3,051,295
43
2010-06-16T07:12:12Z
3,051,310
11
2010-06-16T07:14:40Z
[ "jquery", "python" ]
Is there any Python library that allows me to parse an HTML document similar to what jQuery does? i.e. I'd like to be able to use CSS selector syntax to grab an arbitrary set of nodes from the document, read their content/attributes, etc. The only Python HTML parsing lib I've used before was BeautifulSoup, and even t...
The [lxml](http://lxml.de/) library supports [CSS selectors](http://lxml.de/cssselect.html).
jquery-like HTML parsing in Python?
3,051,295
43
2010-06-16T07:12:12Z
3,051,389
42
2010-06-16T07:32:01Z
[ "jquery", "python" ]
Is there any Python library that allows me to parse an HTML document similar to what jQuery does? i.e. I'd like to be able to use CSS selector syntax to grab an arbitrary set of nodes from the document, read their content/attributes, etc. The only Python HTML parsing lib I've used before was BeautifulSoup, and even t...
If you are fluent with [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup), you could just add [soupselect](http://code.google.com/p/soupselect/) to your libs. Soupselect is a CSS selector extension for BeautifulSoup. Usage: ``` >>> from BeautifulSoup import BeautifulSoup as Soup >>> from soupselect impor...
jquery-like HTML parsing in Python?
3,051,295
43
2010-06-16T07:12:12Z
5,957,573
26
2011-05-10T23:19:20Z
[ "jquery", "python" ]
Is there any Python library that allows me to parse an HTML document similar to what jQuery does? i.e. I'd like to be able to use CSS selector syntax to grab an arbitrary set of nodes from the document, read their content/attributes, etc. The only Python HTML parsing lib I've used before was BeautifulSoup, and even t...
Consider PyQuery: <http://packages.python.org/pyquery/> ``` >>> from pyquery import PyQuery as pq >>> from lxml import etree >>> import urllib >>> d = pq("<html></html>") >>> d = pq(etree.fromstring("<html></html>")) >>> d = pq(url='http://google.com/') >>> d = pq(url='http://google.com/', opener=lambda url: urllib.u...
Multi-part template issue with Jinja2
3,052,702
4
2010-06-16T11:09:57Z
3,052,840
10
2010-06-16T11:33:56Z
[ "python", "templates", "jinja2" ]
When creating templates I typically have 3 separate parts (header, body, footer) which I combine to pass a single string to the web-server (CherryPy in this case). My first approach is as follows... ``` from jinja2 import Environment, FileSystemLoader env = Environment(loader=FileSystemLoader('')) tmpl = env.get_te...
If you don't want to do template inheritance, have you considered `include`? ``` {% include 'header.html' %} Body {% include 'footer.html' %} ```
Python - output from functions?
3,052,793
5
2010-06-16T11:27:05Z
3,052,827
16
2010-06-16T11:32:16Z
[ "python", "function" ]
I have a very rudimentary question. Assume I call a function, e.g., ``` def foo(): x = 'hello world' ``` How do I get the function to return x in such a way that I can use it as the input for another function or use the variable within the body of a program? When I use return and call the variable within anothe...
``` def foo(): x = 'hello world' return x # return 'hello world' would do, too foo() print x # NameError - x is not defined outside the function y = foo() print y # this works x = foo() print x # this also works, and it's a completely different x than that inside # foo() z = bar(x) # of...
Django models avoid duplicates
3,052,975
3
2010-06-16T11:58:56Z
3,053,032
8
2010-06-16T12:05:54Z
[ "python", "django", "django-models", "django-templates", "django-views" ]
In models: ``` class Getdata(models.Model): title = models.CharField(max_length=255) state = models.CharField(max_length=2, choices=STATE, default="0") name = models.ForeignKey(School) created_by = models.ForeignKey(profile) def __unicode__(self): return self.id() ``` In templates: ``` <...
If an individual field needs to be unique, then you just add `unique=True`: ``` class Getdata(models.Model): title = models.CharField(max_length=255, unique=True) state = models.CharField(max_length=2, choices=STATE, default="0") name = models.ForeignKey(School) created_by = models.ForeignKey(profile) ...
Converting Numpy Lstsq residual value to R^2
3,054,191
7
2010-06-16T14:27:37Z
3,057,858
13
2010-06-16T23:17:59Z
[ "python", "numpy", "linear-regression" ]
I am performing a least squares regression as below (univariate). I would like to express the significance of the result in terms of R^2. Numpy returns a value of unscaled residual, what would be a sensible way of normalizing this. ``` field_clean,back_clean = rid_zeros(backscatter,field_data) num_vals = len(field_cle...
See <http://en.wikipedia.org/wiki/Coefficient_of_determination> Your R2 value = ``` 1 - residual / sum((y - y.mean())**2) ``` which is equivalent to ``` 1 - residual / (n * y.var()) ``` As an example: ``` import numpy as np # Make some data... n = 10 x = np.arange(n) y = 3 * x + 5 + np.random.random(n) # Note t...
Auto-register class methods using decorator
3,054,372
8
2010-06-16T14:47:49Z
3,054,505
12
2010-06-16T15:00:52Z
[ "python", "oop", "design-patterns", "decorator", "metaclass" ]
I want to be able to create a python decorator that automatically "registers" class methods in a global repository (with some properties). Example code: ``` class my_class(object): @register(prop1,prop2) def my_method( arg1,arg2 ): # method code here... @register(prop3,prop4) def my_other_met...
Not with just a decorator, no. But a metaclass can automatically work with a class after its been created. If your `register` decorator just makes notes about what the metaclass should do, you can do the following: ``` registry = {} class RegisteringType(type): def __init__(cls, name, bases, attrs): for k...
Auto-register class methods using decorator
3,054,372
8
2010-06-16T14:47:49Z
3,054,949
8
2010-06-16T15:52:10Z
[ "python", "oop", "design-patterns", "decorator", "metaclass" ]
I want to be able to create a python decorator that automatically "registers" class methods in a global repository (with some properties). Example code: ``` class my_class(object): @register(prop1,prop2) def my_method( arg1,arg2 ): # method code here... @register(prop3,prop4) def my_other_met...
Here's a little love for class decorators. I think the syntax is slightly simpler than that required for metaclasses. ``` def class_register(cls): cls._propdict={} for methodname in dir(cls): method=getattr(cls,methodname) if hasattr(method,'_prop'): cls._propdict.update({cls.__name...
Iterate over the lines of a string
3,054,604
68
2010-06-16T15:13:55Z
3,054,831
84
2010-06-16T15:38:43Z
[ "python", "string", "iterator" ]
I have a multi-line string defined like this: ``` foo = """ this is a multi-line string. """ ``` This string us used as test-input for a parser I am writing. The parser-function receives a `file`-object as input and iterates over it. It does also call the `next()` method directly to skip lines, so I really need an i...
Here are three possibilities: ``` foo = """ this is a multi-line string. """ def f1(foo=foo): return iter(foo.splitlines()) def f2(foo=foo): retval = '' for char in foo: retval += char if not char == '\n' else '' if char == '\n': yield retval retval = '' if retval...
Iterate over the lines of a string
3,054,604
68
2010-06-16T15:13:55Z
3,054,898
22
2010-06-16T15:46:22Z
[ "python", "string", "iterator" ]
I have a multi-line string defined like this: ``` foo = """ this is a multi-line string. """ ``` This string us used as test-input for a parser I am writing. The parser-function receives a `file`-object as input and iterates over it. It does also call the `next()` method directly to skip lines, so I really need an i...
I'm not sure what you mean by "then again by the parser". After the splitting has been done, there's no further traversal of the *string*, only a traversal of the *list* of split strings. This will probably actually be the fastest way to accomplish this, so long as the size of your string isn't absolutely huge. The fac...
How slow is Python's string concatenation vs. str.join?
3,055,477
24
2010-06-16T16:58:00Z
3,055,541
39
2010-06-16T17:07:24Z
[ "python", "string", "list", "string-concatenation" ]
As a result of the comments in my answer on [this thread](http://stackoverflow.com/questions/3054604/iterate-over-the-lines-of-a-string/3054679#3054679), I wanted to know what the speed difference is between the `+=` operator and `''.join()` So what is the speed comparison between the two?
From: [Efficient String Concatenation](https://waymoot.org/home/python_string/) **Method 1:** ``` def method1(): out_str = '' for num in xrange(loop_count): out_str += `num` return out_str ``` **Method 4:** ``` def method4(): str_list = [] for num in xrange(loop_count): str_list.append(`num`) re...
How slow is Python's string concatenation vs. str.join?
3,055,477
24
2010-06-16T16:58:00Z
3,055,558
7
2010-06-16T17:10:19Z
[ "python", "string", "list", "string-concatenation" ]
As a result of the comments in my answer on [this thread](http://stackoverflow.com/questions/3054604/iterate-over-the-lines-of-a-string/3054679#3054679), I wanted to know what the speed difference is between the `+=` operator and `''.join()` So what is the speed comparison between the two?
My original code was wrong, it appears that `+` concatenation is usually faster (especially with newer versions of Python on newer hardware) The times are as follows: ``` Iterations: 1,000,000 ``` Python 3.3 on Windows 7, Core i7 ``` String of len: 1 took: 0.5710 0.2880 seconds String of len: 4 took: ...
filename and line number of python script
3,056,048
33
2010-06-16T18:19:22Z
3,056,270
58
2010-06-16T18:52:51Z
[ "python", "debugging", "file" ]
How can I get the file name and line number in python script. Exactly the file information we get from an exception traceback. In this case without raising an exception.
Thanks to mcandre, the answer is: ``` from inspect import currentframe, getframeinfo frameinfo = getframeinfo(currentframe()) print frameinfo.filename, frameinfo.lineno ```
Binomial test in Python for very large numbers
3,056,179
8
2010-06-16T18:38:08Z
3,056,276
9
2010-06-16T18:53:54Z
[ "python", "binomial-coefficients" ]
I need to do a binomial test in Python that allows calculation for 'n' numbers of the order of 10000. I have implemented a quick binomial\_test function using scipy.misc.comb, however, it is pretty much limited around n = 1000, I guess because it reaches the biggest representable number while computing factorials or t...
Edited to add this comment: please note that, as Daniel Stutzbach mentions, the "binomial test" is probably not what the original poster was asking for (though he did use this expression). He seems to be asking for the probability density function of a binomial distribution, which is not what I'm suggesting below. Hav...
Using Django view variables inside templates
3,056,263
6
2010-06-16T18:51:31Z
3,056,293
14
2010-06-16T18:56:12Z
[ "python", "django", "templates", "views" ]
this is a rather basic question (I'm new to Django) but I'm having trouble using a variable set in my view inside my template. If I initialize a string or list inside my view (i.e. h = "hello") and then attempt to call it inside a template: `{{ h }}` there is neither output nor errors. Similarly, if I try to use a...
In order to have access to a variable in a template, it needs to be in the the context used to render that template. My guess is you aren't passing a context dictionary to the template when you render it. <http://docs.djangoproject.com/en/dev/topics/http/shortcuts/#render-to-response> The "dictionary" referenced ther...
Scipy interpolation on a numpy array
3,057,015
9
2010-06-16T20:42:00Z
3,058,047
9
2010-06-17T00:03:05Z
[ "python", "numpy", "scipy", "interpolation" ]
I have a lookup table that is defined the following way: ``` | <1 2 3 4 5+ -------|---------------------------- <10000 | 3.6 6.5 9.1 11.5 13.8 20000 | 3.9 7.3 10.0 13.1 15.9 20000+ | 4.5 9.2 12.2 14.8 18.2 TR_ua1 = np.array([ [3.6, 6.5, 9.1, 11.5, 13.8], [3.9, 7.3, 1...
Edit: Updated things to reflect your clarifications above. Your question is much clearer now, thanks! Basically, you're just wanting to interpolate a 2D array at an arbitrary point. [scipy.ndimage.map\_coordinates](http://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.interpolation.map_coordinates.html) i...
Passing variable urlname to url tag in django template
3,057,318
16
2010-06-16T21:26:56Z
3,060,595
8
2010-06-17T09:54:20Z
[ "python", "django", "django-urls", "django-templates" ]
What I'd like to do (for a recent changes 'widget' - not a django widget in this case) is pass a urlname into my template as a variable, then use it like so: `{% url sitechangeobject.urlname %}` Where urlname is a string containing a valid name for a url. Is this possible? The template keeps breaking saying it can't f...
**Note: this answer is only really relevant to versions of django before 1.3. If you are using django 1.3 or later, the required functionality is built-in - please see [meshy's answer](http://stackoverflow.com/a/8490469/1002).** The built-in `url` tag cannot do this. However [django-reversetag](http://github.com/ulope...
Passing variable urlname to url tag in django template
3,057,318
16
2010-06-16T21:26:56Z
8,490,469
27
2011-12-13T14:02:51Z
[ "python", "django", "django-urls", "django-templates" ]
What I'd like to do (for a recent changes 'widget' - not a django widget in this case) is pass a urlname into my template as a variable, then use it like so: `{% url sitechangeobject.urlname %}` Where urlname is a string containing a valid name for a url. Is this possible? The template keeps breaking saying it can't f...
As of Django 1.3 the `{% url %}` tag properly supports: ``` {% url view_name_variable %} {% url 'view_name_string' %} ``` ...this becomes the default behaviour in Django 1.5. Previously, you had only the option to do this: ``` {% url view_name_string %} ``` To get the tag to work in this way in Django 1.3 and 1.4 ...
How to make credit card payments in Django?
3,057,643
18
2010-06-16T22:30:52Z
3,057,810
11
2010-06-16T23:05:18Z
[ "python", "django", "credit-card", "payment" ]
I need to accept credit card payments on my site that provides a service outside the U.S., but I will not be through paypal, where should I start? anyone knows how I can do this?
As mentioned in the previous answer, you need a [merchant account](http://en.wikipedia.org/wiki/Merchant_account) and a [payment gateway](http://en.wikipedia.org/wiki/Payment_gateway). I'd recommend [BrainTree](http://www.braintreepaymentsolutions.com/) if you're processing enough payments that they'll accept you. The...
Can django lazy-load fields in a model?
3,057,916
11
2010-06-16T23:31:20Z
3,057,974
10
2010-06-16T23:45:34Z
[ "python", "django", "django-models" ]
One of my django models has a large `TextField` which I often don't need to use. Is there a way to tell django to "lazy-load" this field? i.e. not to bother pulling it from the database unless I explicitly ask for it. I'm wasting a lot of memory and bandwidth pulling this `TextField` into python every time I refer to t...
The functionality happens when you make the query, using the `defer()` statement, instead of in the model definition. Check it out here in the docs: <http://docs.djangoproject.com/en/dev/ref/models/querysets/#defer> Now, actually, your alternative solution of refactoring and pulling the data into another table is a re...
represent binary search trees in python
3,058,665
5
2010-06-17T03:19:09Z
3,058,685
11
2010-06-17T03:26:50Z
[ "python", "data-structures", "binary-tree", "binary-search-tree" ]
how do i represent binary search trees in python?
``` class Node(object): def __init__(self, payload): self.payload = payload self.left = self.right = 0 # this concludes the "how to represent" asked in the question. Once you # represent a BST tree like this, you can of course add a variety of # methods to modify it, "walk" over it, and so fort...
Programmatically getting an access token for using the Facebook Graph API
3,058,723
31
2010-06-17T03:41:24Z
3,259,465
8
2010-07-15T19:56:37Z
[ "python", "bash", "facebook" ]
I am trying to put together a bash or python script to play with the facebook graph API. Using the API looks simple, but I'm having trouble setting up curl in my bash script to call authorize and access\_token. Does anyone have a working example?
You first need to [set up an application](http://www.facebook.com/developers/createapp.php). The following will then spit out an access token given your application ID and secret: ``` > curl -F type=client_cred -F client_id=[...] -F client_secret=[...] https://graph.facebook.com/oauth/access_token ```
Programmatically getting an access token for using the Facebook Graph API
3,058,723
31
2010-06-17T03:41:24Z
5,426,804
28
2011-03-24T23:23:53Z
[ "python", "bash", "facebook" ]
I am trying to put together a bash or python script to play with the facebook graph API. Using the API looks simple, but I'm having trouble setting up curl in my bash script to call authorize and access\_token. Does anyone have a working example?
Better late than never, maybe others searching for that will find it. I got it working with Python 2.6 on a MacBook. This requires you to have * the Python facebook module installed: <https://github.com/pythonforfacebook/facebook-sdk>, * an actual Facebook app set up * and the profile you want to post to must have gr...
Programmatically getting an access token for using the Facebook Graph API
3,058,723
31
2010-06-17T03:41:24Z
9,371,126
13
2012-02-21T02:02:23Z
[ "python", "bash", "facebook" ]
I am trying to put together a bash or python script to play with the facebook graph API. Using the API looks simple, but I'm having trouble setting up curl in my bash script to call authorize and access\_token. Does anyone have a working example?
Easy! Just use [facebook-sdk](https://github.com/pythonforfacebook/facebook-sdk/). get\_app\_access\_token(app\_id, app\_secret) -- exactly what you're after ;-)
Programmatically getting an access token for using the Facebook Graph API
3,058,723
31
2010-06-17T03:41:24Z
26,844,734
9
2014-11-10T13:15:18Z
[ "python", "bash", "facebook" ]
I am trying to put together a bash or python script to play with the facebook graph API. Using the API looks simple, but I'm having trouble setting up curl in my bash script to call authorize and access\_token. Does anyone have a working example?
Here you go, as simple as it can get. Doesn’t require any 3rd-party SDK etc. > Make sure Python 'requests' module is installed ``` import requests def get_fb_token(app_id, app_secret): payload = {'grant_type': 'client_credentials', 'client_id': app_id, 'client_secret': app_secret} file = request...
How can I access namespaced XML elements using BeautifulSoup?
3,058,912
6
2010-06-17T04:40:40Z
3,059,012
8
2010-06-17T05:06:23Z
[ "python", "xml", "xml-parsing", "beautifulsoup", "xml-namespaces" ]
I have an XML document which reads like this: ``` <xml> <web:Web> <web:Total>4000</web:Total> <web:Offset>0</web:Offset> </web:Web> </xml> ``` my question is how do I access them using a library like BeautifulSoup in python? xmlDom.web["Web"].Total ? does not work?
[BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) isn't a DOM library per se (it doesn't implement the DOM APIs). To make matters more complicated, you're using namespaces in that xml fragment. To parse that specific piece of XML, you'd use BeautifulSoup as follows: ``` from BeautifulSoup import Beautiful...
how to get wav samples from a wav file?
3,059,089
5
2010-06-17T05:26:19Z
3,059,140
12
2010-06-17T05:38:42Z
[ "python", "wav" ]
I want to know how to get samples out of a .wav file in order to perform windowed join of two .wav files. Can any one please tell how to do this?
The [wave](http://docs.python.org/library/wave.html?highlight=wav#module-wave) module of the standard library is the key: after of course `import wave` at the top of your code, `wave.open('the.wav', 'r')` returns a "wave read" object from which you can read frames with the `.readframes` method, which returns a string o...
How to substitute into a regular expression group in Python
3,059,151
6
2010-06-17T05:41:25Z
3,059,319
7
2010-06-17T06:17:49Z
[ "python", "regex" ]
``` >>> s = 'foo: "apples", bar: "oranges"' >>> pattern = 'foo: "(.*)"' ``` I want to be able to substitute into the group like this: ``` >>> re.sub(pattern, 'pears', s, group=1) 'foo: "pears", bar: "oranges"' ``` Is there a nice way to do this?
For me works something like: ``` rx = re.compile(r'(foo: ")(.*?)(".*)') s_new = rx.sub(r'\g<1>pears\g<3>', s) print(s_new) ``` Notice `?`in re, so it ends with first `"`, also notice `"` in groups 1 and 3 because they must be in output. Instead of `\g<1>` (or `\g<number>`) you can use just `\1`, but remember to use ...
Manipulating binary data in Python
3,059,301
13
2010-06-17T06:12:41Z
3,059,345
21
2010-06-17T06:23:49Z
[ "python", "binary", "hex" ]
I am opening up a binary file like so: ``` file = open("test/test.x", 'rb') ``` and reading in lines to a list. Each line looks a little like: ``` '\xbe\x00\xc8d\xf8d\x08\xe4.\x07~\x03\x9e\x07\xbe\x03\xde\x07\xfe\n' ``` I am having a hard time manipulating this data. If I try and print each line, python freezes, an...
To print it, you can do something like this: ``` print repr(data) ``` For the whole thing as hex: ``` print data.encode('hex') ``` For the decimal value of each byte: ``` print ' '.join([str(ord(a)) for a in data]) ``` To unpack binary integers, etc. from the data as if they originally came from a C-style struct,...
numpy array assignment problem
3,059,395
19
2010-06-17T06:33:53Z
3,059,553
44
2010-06-17T07:07:07Z
[ "python", "arrays", "numpy" ]
I have a strange problem in Python 2.6.5 with Numpy. I assign a numpy array, then equate a new variable to it. When I perform any operation to the new array, the original's values also change. Why is that? Please see the example below. Kindly enlighten me, as I'm fairly new to Python, and programming in general. -Suja...
That's actually not a problem at all; it's the way arrays (and other objects) work in Python. Think about it like this: the array you created in your code example is an object that sits at some location in memory. But you can't use it in your program by telling Python where in memory to go look for it; you have to giv...
Python MySQL wrong architecture error
3,061,277
26
2010-06-17T11:38:44Z
5,081,388
29
2011-02-22T17:08:46Z
[ "python", "mysql", "install" ]
I've been at this for some time and read many sites on the subject. suspect I have junk lying about causing this problem. But where? This is the error when I import MySQLdb in python: ``` >>> import MySQLdb /Library/Python/2.6/site-packages/MySQL_python-1.2.3c1-py2.6-macosx-10.6-universal.egg/_mysql.py:3: UserWar...
I have a fresh MacBook Air, and I managed to get MySQLdb working by doing the following: (Snow Leopard 10.6.6, preinstalled Python) ``` uname -a Darwin Braindamage.local 10.6.0 Darwin Kernel Version 10.6.0: Wed Nov 10 18:13:17 PST 2010; root:xnu-1504.9.26~3/RELEASE_I386 i386 ``` Download the MySQL 32-bit dmg file fro...
Python MySQL wrong architecture error
3,061,277
26
2010-06-17T11:38:44Z
7,552,035
12
2011-09-26T07:49:36Z
[ "python", "mysql", "install" ]
I've been at this for some time and read many sites on the subject. suspect I have junk lying about causing this problem. But where? This is the error when I import MySQLdb in python: ``` >>> import MySQLdb /Library/Python/2.6/site-packages/MySQL_python-1.2.3c1-py2.6-macosx-10.6-universal.egg/_mysql.py:3: UserWar...
I just struggled with the same, despite the many answers, so I'll risk adding another: * Run `python -c 'import platform; print platform.platform()'`. Does it end in "64 bit"? * Do `ls -l /usr/local/mysql`. It's a symlink: does it end in "x86\_64"? If python says "64 bit", then you want mysql for "x86\_64" (search fo...
How can I iterate over only the first variable of a tuple
3,061,336
5
2010-06-17T11:47:52Z
3,061,354
8
2010-06-17T11:50:08Z
[ "python", "tuples", "loops" ]
In python, when you have a list of tuples, you can iterate over them. For example when you have 3d points then: ``` for x,y,z in points: pass # do something with x y or z ``` What if you only want to use the first variable, or the first and the third. Is there any skipping symbol in python?
Is something preventing you from not touching variables that you're not interested in? There is a conventional use of underscore in Python to indicate variable that you're not interested. E.g.: ``` for x, _,_ in points: print(x) ``` You need to understand that this is just a convention and has no bearing on perfo...
How can I iterate over only the first variable of a tuple
3,061,336
5
2010-06-17T11:47:52Z
3,061,358
7
2010-06-17T11:50:38Z
[ "python", "tuples", "loops" ]
In python, when you have a list of tuples, you can iterate over them. For example when you have 3d points then: ``` for x,y,z in points: pass # do something with x y or z ``` What if you only want to use the first variable, or the first and the third. Is there any skipping symbol in python?
Yes, the underscore: ``` >>> a=(1,2,3,4) >>> b,_,_,c = a >>> b,c (1, 4) ``` This is not exactly 'skipping', just a convention. Underscore variable still gets the value assigned: ``` >>> _ 3 ```
Numpy array dimensions
3,061,761
154
2010-06-17T12:55:51Z
3,061,789
219
2010-06-17T12:59:46Z
[ "python", "arrays", "numpy", "dimensions" ]
I'm currently trying to learn Numpy and Python. Given the following array: ``` import numpy as N a = N.array([[1,2],[1,2]]) ``` Is there a function that returns the dimensions of `a` (e.g.a is a 2 by 2 array)? `size()` returns 4 and that doesn't help very much.
It is [`.shape`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.shape.html#numpy.ndarray.shape): > ndarray.**shape** > Tuple of array dimensions. Thus: ``` >>> a.shape (2, 2) ```
Numpy array dimensions
3,061,761
154
2010-06-17T12:55:51Z
33,088,216
14
2015-10-12T18:51:41Z
[ "python", "arrays", "numpy", "dimensions" ]
I'm currently trying to learn Numpy and Python. Given the following array: ``` import numpy as N a = N.array([[1,2],[1,2]]) ``` Is there a function that returns the dimensions of `a` (e.g.a is a 2 by 2 array)? `size()` returns 4 and that doesn't help very much.
``` >>> N.shape(a) (2,2) ``` Also works if the input is not a numpy array but a list of lists ``` >>> a = [[1,2],[1,2]] >>> N.shape(a) (2,2) ```
How to get the level of the logging record in a custom logging.Handler in Python?
3,061,924
4
2010-06-17T13:16:02Z
3,062,695
8
2010-06-17T14:43:46Z
[ "python", "logging" ]
I would like to make custom logger methods either by a custom logging handlers or a custom logger class and dispatch the logging records to different targets. For example: ``` log = logging.getLogger('application') log.progress('time remaining %d sec' % i) custom method for logging to: - database sta...
`record` is an instance of [LogRecord](http://docs.python.org/library/logging.html?highlight=logging.handler#logging.LogRecord): ``` >>> import logging >>> rec = logging.LogRecord('bob', 1, 'foo', 23, 'ciao', (), False) ``` and your method can just access the attributes of interest (I'm splitting `dir`'s result for e...
Why don't we require interfaces in dynamic languages?
3,062,701
16
2010-06-17T14:44:15Z
3,062,839
20
2010-06-17T14:59:58Z
[ "c#", "java", "python", "dynamic-languages" ]
Is it just because of dynamic typing we don't require a concept of interfaces(like in Java and C#) in python?
The `interface` as a keyword and artifact was introduced by Java1 ( and C# took it from there ) to describe what the contract an object must adhere was. But, interface has always been a key part of Object Oriented Paradigm and basically it represents the methods an object has to respond. Java just enforces this mechan...
Maximal Length of List to Shuffle with Python random.shuffle?
3,062,741
28
2010-06-17T14:48:22Z
3,062,966
52
2010-06-17T15:15:31Z
[ "python", "random", "shuffle" ]
I have a list which I shuffle with the Python built in shuffle function (`random.shuffle`) However, the Python reference states: > Note that for even rather small `len(x)`, the total number of permutations of x is larger than the period of most random number generators; this implies that most permutations of a long s...
TL;DR: It "breaks" on lists with over 2080 elements, but don't worry too much :) Complete answer: First of all, notice that "shuffling" a list can be understood (conceptually) as generating all possible permutations of the elements of the lists, and picking one of these permutations at random. Then, you must remembe...
Maximal Length of List to Shuffle with Python random.shuffle?
3,062,741
28
2010-06-17T14:48:22Z
18,628,010
15
2013-09-05T04:53:08Z
[ "python", "random", "shuffle" ]
I have a list which I shuffle with the Python built in shuffle function (`random.shuffle`) However, the Python reference states: > Note that for even rather small `len(x)`, the total number of permutations of x is larger than the period of most random number generators; this implies that most permutations of a long s...
I wrote that comment in the Python source originally, so maybe I can clarify ;-) When the comment was introduced, Python's Wichmann-Hill generator had a much shorter period, and we couldn't even generate all the permutations of a deck of cards. The period is astronomically larger now, and 2080 is correct for the curr...
How to implement python to find value between xml tags?
3,063,319
3
2010-06-17T15:52:15Z
3,063,397
8
2010-06-17T16:01:34Z
[ "python" ]
I am using google site to retrieve weather information , I want to find values between XML tags. Following code give me weather condition of a city , but I am unable to obtain other parameters such as temperature and if possible explain working of split function implied in the code: ``` import urllib def getWeather(c...
[USE](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454) [A](http://stackoverflow.com/questions/335250/parsing-xml-with-regex-in-java/335446#335446) [PARSER](http://stackoverflow.com/questions/2426812/how-can-i-match-xml-tags-and-attributes-with-a-regula...
How to return an image in an HTTP response with CherryPy
3,064,374
7
2010-06-17T18:15:32Z
3,080,830
15
2010-06-20T20:26:45Z
[ "python", "http", "cherrypy", "cairo" ]
I have code which generates a Cairo `ImageSurface`, and I expose it like so: ``` def preview(...): surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) ... cherrypy.response.headers['Content-Type'] = "image/png" return surface.get_data() preview.exposed = True ``` This doesn't work (browse...
Add these imports: ``` from cherrypy.lib import file_generator import StringIO ``` and then go like this: ``` def index(self): surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) cherrypy.response.headers['Content-Type'] = "image/png" buffer = StringIO.StringIO() surface.write_to_png(bu...
Communicate multiple times with a process without breaking the pipe?
3,065,060
19
2010-06-17T19:43:03Z
3,066,718
16
2010-06-18T01:42:31Z
[ "python", "pipe", "subprocess" ]
It's not the first time I'm having this problem, and it's really bugging me. Whenever I open a pipe using the Python `subprocess` module, I can only `communicate` with it once, as the documentation specifies: `Read data from stdout and stderr, until end-of-file is reached` ``` proc = sub.Popen("psql -h darwin -d main_...
I think you misunderstand communicate... <http://docs.python.org/library/subprocess.html#subprocess.Popen.communicate> communicate sends a string to the other process and then waits on it to finish... (Like you said waits for the EOF listening to the stdout & stderror) What you should do instead is: ``` proc.stdin....
Extending Django Flatpages to accept template tags
3,066,270
6
2010-06-17T23:12:00Z
3,067,759
8
2010-06-18T07:04:58Z
[ "python", "django", "django-flatpages" ]
I use django flatpages for a lot of content on our site, I'd like to extend it to accept django template tags in the content as well. I found this [snippet](http://djangosnippets.org/snippets/861/) but after much larking about I couldn't get it to work. Am I correct in assuming that you would need too "subclass" the d...
**1.** A simple page view wich will render template tags by loading a template for each page: in `url.py` ``` url(r'^page/(?P<slug>.*)/$','my_app.views.page_detail', name='page_url'), ``` in `my_app/views.py` ``` def page_detail (request, slug): return render_to_response('page/' + slug + '.html', {}, ...
What Language is This?
3,066,970
5
2010-06-18T03:05:48Z
3,066,980
9
2010-06-18T03:09:47Z
[ "python", "language-identification" ]
Going through some example code sent to me and honestly, I have no idea what language this is ``` def uniqify(arr): b = {} for i in arr: b[i] = 1 return b.keys() ``` Is it Python? I am also curious what keys() does. It's obvious it returns an array but what does it do the array that calls the...
Yes, it's Python. `b.keys` returns a list of all the keys in the dictionary `b`. Each item in the sequence `arr` becomes a key in `b` whose value is `1`. Note that lists and tuples are typically used where arrays would be used in other languages. Also note that `arr` can be any iterable object (list, tuple, set, dict,...
What Language is This?
3,066,970
5
2010-06-18T03:05:48Z
3,066,986
8
2010-06-18T03:11:54Z
[ "python", "language-identification" ]
Going through some example code sent to me and honestly, I have no idea what language this is ``` def uniqify(arr): b = {} for i in arr: b[i] = 1 return b.keys() ``` Is it Python? I am also curious what keys() does. It's obvious it returns an array but what does it do the array that calls the...
Yes, it's Python. b is a dict (dictionary) which is a mapping of keys to values. b.keys() returns a list of keys. However this code is rather old fashioned. `set(arr)` will return a set of the unique values in arr.
What Language is This?
3,066,970
5
2010-06-18T03:05:48Z
3,066,989
17
2010-06-18T03:12:41Z
[ "python", "language-identification" ]
Going through some example code sent to me and honestly, I have no idea what language this is ``` def uniqify(arr): b = {} for i in arr: b[i] = 1 return b.keys() ``` Is it Python? I am also curious what keys() does. It's obvious it returns an array but what does it do the array that calls the...
As Longpoke explained, it's python, using a dict get the unique items. However, it's bad python. ``` list(set(arr)) ``` Does the same thing. No need to re-invent the wheel.
Not getting exact result in python with the values leading zero. Please tell me what is going on there
3,067,409
6
2010-06-18T05:35:26Z
3,067,412
14
2010-06-18T05:37:31Z
[ "python" ]
> > > zipcode = 02132 > > > > > > print zipcode result = 1114
A leading zero means octal. 2132 in octal equals 1114 in decimal. They [removed](http://docs.python.org/release/3.0.1/whatsnew/3.0.html) this behavior in Python 3.0.
Not getting exact result in python with the values leading zero. Please tell me what is going on there
3,067,409
6
2010-06-18T05:35:26Z
3,067,424
9
2010-06-18T05:40:23Z
[ "python" ]
> > > zipcode = 02132 > > > > > > print zipcode result = 1114
In Python 2.x, number with a leading zero is interpreted as octal (base-eight). Python 3.x requires a leading "0o" to indicate an octal number. You probably want to treat a zipcode as a string to keep the leading zeroes intact.
A set union find algorithm
3,067,529
15
2010-06-18T06:05:33Z
3,067,582
13
2010-06-18T06:21:52Z
[ "python", "algorithm", "set" ]
I have thousands of lines of 1 to 100 numbers, every line define a group of numbers and a relationship among them. I need to get the sets of related numbers. Little Example: If I have this 7 lines of data ``` T1 T2 T3 T4 T5 T6 T1 T5 T4 T3 T4 T7 ``` I need a not so slow algorithm to know that the sets here are: ```...
Treat your numbers T1, T2, etc. as graph vertices. Any two numbers appearing together on a line are joined by an edge. Then your problem amounts to finding all the [connected components](http://en.wikipedia.org/wiki/Connected_component_%28graph_theory%29) in this graph. You can do this by starting with T1, then doing a...
A set union find algorithm
3,067,529
15
2010-06-18T06:05:33Z
3,067,672
9
2010-06-18T06:44:16Z
[ "python", "algorithm", "set" ]
I have thousands of lines of 1 to 100 numbers, every line define a group of numbers and a relationship among them. I need to get the sets of related numbers. Little Example: If I have this 7 lines of data ``` T1 T2 T3 T4 T5 T6 T1 T5 T4 T3 T4 T7 ``` I need a not so slow algorithm to know that the sets here are: ```...
Once you have built the data structure, exactly what queries do you want to run against it? Show us your existing code. What is a T(x)? You talk about "groups of numbers" but your sample data shows T1, T2, etc; please explain. Have you read this: <http://en.wikipedia.org/wiki/Disjoint-set_data_structure> Try looking ...
How can I sandbox Python in pure Python?
3,068,139
35
2010-06-18T08:28:48Z
3,068,475
33
2010-06-18T09:21:39Z
[ "python", "scripting" ]
I'm developing a web game in pure Python, and want some simple scripting available to allow for more dynamic game content. Game content can be added live by privileged users. It would be nice if the scripting language could be Python. However, it can't run with access to the environment the game runs on since a malici...
This is really non-trivial. There are two ways to sandbox Python. One is to create a restricted environment (i.e., very few globals etc.) and `exec` your code inside this environment. This is what Messa is suggesting. It's nice but there are lots of ways to break out of the sandbox and create trouble. There was a thre...
Permission to view, but not to change! - Django
3,068,843
15
2010-06-18T10:30:39Z
5,364,408
12
2011-03-19T19:35:39Z
[ "python", "django", "django-admin" ]
is it possible to give users the permission to view, but not to change or delete. currently in the only permissions I see are "add", "change" and "delete"... but there is no "read/view" in there. I really need this as some users will only be able to consult the admin panel, in order to see what has been added in.
In admin.py ``` # Main reusable Admin class for only viewing class ViewAdmin(admin.ModelAdmin): """ Custom made change_form template just for viewing purposes You need to copy this from /django/contrib/admin/templates/admin/change_form.html And then put that in your template folder that is specified i...
How to store an integer leaded by zeros in django
3,069,989
7
2010-06-18T13:28:49Z
3,070,118
12
2010-06-18T13:44:39Z
[ "python", "django", "django-models", "django-admin" ]
I'm trying to store a number in django that looks like this: ``` 000001 ``` My problem is that if I type this inside an IntegerField it gets converted to "1" without the leading zeros. I've tried also with a DecimalField with the same result. How can I store the leading zeros whithout using a CharField? (I need to ma...
Don't store it with the leading zeros. Format it on output instead: ``` (in view: value = 1) {{ value|stringformat:"04d" }} # displays as 0001 ```
reduce python list of objects to dict object.id -> object
3,070,242
13
2010-06-18T14:03:08Z
3,070,270
27
2010-06-18T14:06:58Z
[ "python", "lambda", "dictionary" ]
You have list of objects each of them have id property. Here's my way to covert it to dict where keys are ids and values are objects: ``` reduce( lambda x,y: dict(x.items() + { y.id : y}.items()), list, {} ) ``` Suggest better way to do it.
In Python 3.x: ``` object_dict = {x.id: x for x in object_list} ``` In both Python 3.x and Python 2.4+: ``` object_dict = dict((x.id, x) for x in object_list) ``` `(x.id, x) for x in object_list` is a generator comprehension (and, nicely, does not need to be wrapped in parentheses like a list comprehension needs to...
reduce python list of objects to dict object.id -> object
3,070,242
13
2010-06-18T14:03:08Z
3,070,276
7
2010-06-18T14:07:29Z
[ "python", "lambda", "dictionary" ]
You have list of objects each of them have id property. Here's my way to covert it to dict where keys are ids and values are objects: ``` reduce( lambda x,y: dict(x.items() + { y.id : y}.items()), list, {} ) ``` Suggest better way to do it.
``` dict([(x.id, x) for x in list]) ```
Problem accessing config files within a Python egg
3,071,327
7
2010-06-18T16:14:35Z
3,071,402
9
2010-06-18T16:25:15Z
[ "python", "file", "egg" ]
I have a Python project that has the following structure: ``` package1 class.py class2.py ... package2 otherClass.py otherClass2.py ... config dev_settings.ini prod_settings.ini ``` I wrote a setup.py file that converts this into an egg with the same file structure. (When I examine it using a zip prog...
The problem is, the config files are not files anymore - they're packaged within the egg. It's not easy to find the answer in the docs, but it is there. From the [setuptools developer's guide](http://peak.telecommunity.com/DevCenter/setuptools#accessing-data-files-at-runtime): > Typically, existing programs manipulate...
Efficient method to calculate the rank vector of a list in Python
3,071,415
20
2010-06-18T16:27:08Z
3,071,441
34
2010-06-18T16:30:45Z
[ "python", "list", "sorting", "ranking" ]
I'm looking for an efficient way to calculate the rank vector of a list in Python, similar to R's `rank` function. In a simple list with no ties between the elements, element *i* of the rank vector of a list `l` should be *x* if and only if `l[i]` is the *x*-th element in the sorted list. This is simple so far, the fol...
Using scipy, the function you are looking for is scipy.stats.rankdata : ``` In [13]: import scipy.stats as ss In [19]: ss.rankdata([3, 1, 4, 15, 92]) Out[19]: array([ 2., 1., 3., 4., 5.]) In [20]: ss.rankdata([1, 2, 3, 3, 3, 4, 5]) Out[20]: array([ 1., 2., 4., 4., 4., 6., 7.]) ``` The ranks start at 1, rat...
AssertRaises non-callable
3,073,009
6
2010-06-18T20:53:13Z
3,073,049
8
2010-06-18T20:59:59Z
[ "python", "unit-testing" ]
Say I have the class ``` class myClass(object): pname = "" def __getName(self): return pname def __setName(self, newname): if not isalpha(newname): raise ValueError("Error") elif self.pname = newname name = property(fget=__getName,fset=__setName) ``` Seeing as these ...
Make your own callable. ``` class TestMyClass(unittest.TestCase): def test_should_raise(self): x = myClass() def assign_bad_name(): x.name = "7" self.assertRaises(ValueError, assign_bad_name) ```
Python 2.5.4 - ImportError: No module named etree.ElementTree
3,073,033
9
2010-06-18T20:57:29Z
3,073,183
7
2010-06-18T21:26:05Z
[ "python", "import", "elementtree" ]
I'm running Python 2.5.4 on Windows and I keep getting an error when trying to import the ElementTree or cElementTree modules. The code is very simple (I'm following a tutorial): ``` import xml.etree.ElementTree as xml root = xml.Element('root') child = xml.Element('child') root.append(child) child.attrib['name'] = "...
You missed the very important line in the tutorial ``` import xml.etree.ElementTree as xml ``` This makes xml.etree.ElementTree now known as xml throughout the module. I happen to have python 2.5.4 and I have verified that the same code you have above works: ``` user@Comp test$ cat test.py import xml.etree.Element...
Python 2.5.4 - ImportError: No module named etree.ElementTree
3,073,033
9
2010-06-18T20:57:29Z
10,324,708
36
2012-04-25T22:25:39Z
[ "python", "import", "elementtree" ]
I'm running Python 2.5.4 on Windows and I keep getting an error when trying to import the ElementTree or cElementTree modules. The code is very simple (I'm following a tutorial): ``` import xml.etree.ElementTree as xml root = xml.Element('root') child = xml.Element('child') root.append(child) child.attrib['name'] = "...
Because your original file name is **C:\xml.py** Change the file name to any other name
Python 2.5.4 - ImportError: No module named etree.ElementTree
3,073,033
9
2010-06-18T20:57:29Z
12,224,480
8
2012-09-01T02:45:49Z
[ "python", "import", "elementtree" ]
I'm running Python 2.5.4 on Windows and I keep getting an error when trying to import the ElementTree or cElementTree modules. The code is very simple (I'm following a tutorial): ``` import xml.etree.ElementTree as xml root = xml.Element('root') child = xml.Element('child') root.append(child) child.attrib['name'] = "...
I got the same error `report("ImportError: No module named etree.ElementTree")` when naming the test file as `xml.py`. And it got **fixed** when I renamed it to something else like `xmltest.py`.
Python Nose Import Error
3,073,259
84
2010-06-18T21:46:18Z
3,073,368
154
2010-06-18T22:09:39Z
[ "python", "nose", "python-import" ]
I can't seem to get the [nose testing framework](https://nose.readthedocs.org/en/latest/) to recognize modules beneath my test script in the file structure. I've set up the simplest example that demonstrates the problem. I'll explain it below. Here's the the package file structure: ``` ./__init__.py ./foo.py ./tests ...
You've got an `__init__.py` in your top level directory. That makes it a package. If you remove it, your `nosetests` should work. If you don't remove it, you'll have to change your `import` to `import dir.foo`, where `dir` is the name of your directory.
Python Nose Import Error
3,073,259
84
2010-06-18T21:46:18Z
22,595,259
18
2014-03-23T18:37:50Z
[ "python", "nose", "python-import" ]
I can't seem to get the [nose testing framework](https://nose.readthedocs.org/en/latest/) to recognize modules beneath my test script in the file structure. I've set up the simplest example that demonstrates the problem. I'll explain it below. Here's the the package file structure: ``` ./__init__.py ./foo.py ./tests ...
Are you in a virtualenv? In my case, `nosetests` was the one in `/usr/bin/nosetests`, which was using `/usr/bin/python`. The packages in the virtualenv definitely won't be in the system path. The following fixed this: ``` source myvirtualenv/activate pip install nose which nosetests /home/me/myvirtualenv/bin/nosetests...
Clean Up HTML in Python
3,073,881
10
2010-06-19T00:44:28Z
3,073,988
12
2010-06-19T01:31:57Z
[ "python", "html", "django" ]
I'm aggregating content from a few external sources and am finding that some of it contains errors in its HTML/DOM. A good example would be HTML missing closing tags or malformed tag attributes. Is there a way to clean up the errors in Python natively or any third party modules I could install?
I would suggest [Beautifulsoup](http://www.crummy.com/software/BeautifulSoup/). It has a wonderful parser that can deal with malformed tags quite gracefully. Once you've read in the entire tree you can just output the result. ``` from BeautifulSoup import BeautifulSoup tree = BeautifulSoup(bad_html) good_html = tree.p...
How to override equals() in google app engine data model type?
3,074,275
11
2010-06-19T03:58:40Z
3,074,404
14
2010-06-19T04:57:16Z
[ "python", "google-app-engine", "web-applications" ]
I'm using the Python libraries for Google App Engine. How can I override the `equals()` method on a class so that it judges equality on the `user_id` field of the following class: ``` class UserAccount(db.Model): # compare all equality tests on user_id user = db.UserProperty(required=True) user_id = db.Str...
Override operators `__eq__` (==) and `__ne__` (!=) e.g. ``` class UserAccount(db.Model): def __eq__(self, other): if isinstance(other, UserAccount): return self.user_id == other.user_id return NotImplemented def __ne__(self, other): result = self.__eq__(other) if ...
python - Which is the better way to enable/disable logging?
3,075,202
2
2010-06-19T10:41:16Z
3,075,271
10
2010-06-19T11:13:25Z
[ "python", "logging" ]
Which is better way to enable/disable logging? 1) Changing log levels, ``` logging.disable(logging.CRITICAL) ``` 2) ``` log = None ``` And logging messages this way, ``` if log: log.info("log message") ``` So that we can avoid unnecessary string constructions in case of logging disabled...
1 is best, ideally via a configuration file or command line argument (--quiet) 2 will just clutter up your code If you want to avoid expensive string construction (this is probably worthwhile about 0.001% of the time in my experience), use: ``` if logger.isEnabledFor(logging.DEBUG): logger.debug("Message with %s...
(python) recursively remove capitalisation from directory structure?
3,075,443
2
2010-06-19T12:20:22Z
3,075,668
10
2010-06-19T13:33:29Z
[ "python", "uppercase" ]
uppercase letters - what's the point of them? all they give you is rsi. i'd like to remove as much capitalisation as possible from my directory structure. how would i write a script to do this in python? it should recursively parse a specified directory, identify the file/folder names with capital letters and rename ...
`os.walk` is great for doing recursive stuff with the filesystem. ``` import os def lowercase_rename( dir ): # renames all subforders of dir, not including dir itself def rename_all( root, items): for name in items: try: os.rename( os.path.join(root, name), ...
How can I get href links from HTML using Python?
3,075,550
19
2010-06-19T12:58:08Z
3,075,561
18
2010-06-19T13:02:24Z
[ "python", "html", "hyperlink", "href" ]
``` import urllib2 website = "WEBSITE" openwebsite = urllib2.urlopen(website) html = getwebsite.read() print html ``` So far so good. But I want only href links from the plain text HTML. How can I solve this problem?
You can use the [HTMLParser](http://docs.python.org/library/htmlparser.html#example-html-parser-application) module. The code would probably look something like this: ``` from HTMLParser import HTMLParser class MyHTMLParser(HTMLParser): def handle_starttag(self, tag, attrs): # Only parse the 'anchor' ta...
How can I get href links from HTML using Python?
3,075,550
19
2010-06-19T12:58:08Z
3,075,568
42
2010-06-19T13:04:10Z
[ "python", "html", "hyperlink", "href" ]
``` import urllib2 website = "WEBSITE" openwebsite = urllib2.urlopen(website) html = getwebsite.read() print html ``` So far so good. But I want only href links from the plain text HTML. How can I solve this problem?
Try with [Beautifulsoup](http://www.crummy.com/software/BeautifulSoup/): ``` from BeautifulSoup import BeautifulSoup import urllib2 import re html_page = urllib2.urlopen("http://www.yourwebsite.com") soup = BeautifulSoup(html_page) for link in soup.findAll('a'): print link.get('href') ``` In case you just want l...
How can I get href links from HTML using Python?
3,075,550
19
2010-06-19T12:58:08Z
3,075,580
7
2010-06-19T13:07:17Z
[ "python", "html", "hyperlink", "href" ]
``` import urllib2 website = "WEBSITE" openwebsite = urllib2.urlopen(website) html = getwebsite.read() print html ``` So far so good. But I want only href links from the plain text HTML. How can I solve this problem?
Look at using the beautiful soup html parsing library. <http://www.crummy.com/software/BeautifulSoup/> You will do something like this: ``` import BeautifulSoup soup = BeautifulSoup.BeautifulSoup(html) for link in soup.findAll("a"): print link.get("href") ```
How to make django messages StackOverflow style?
3,076,365
11
2010-06-19T16:52:15Z
3,083,459
7
2010-06-21T09:32:20Z
[ "python", "ajax", "django", "django-users" ]
I'd like to use Django's Messages module, however, I would like my messages to persist until the user clicks an X next to the message as opposed to having messages disappear as soon as the user reloads the page. I am stumped with two issues: How do I make the messages' context processor **not** delete the messages onc...
Since 1.2, Django has a new messages framework--[`django.contrib.messages`](http://docs.djangoproject.com/en/dev/ref/contrib/messages/#ref-contrib-messages)--that is now completely detached from the `auth` module and offers much more functionality. For instance, it provides a basic way of handling the [expiration of me...
How to make django messages StackOverflow style?
3,076,365
11
2010-06-19T16:52:15Z
3,084,273
8
2010-06-21T11:37:00Z
[ "python", "ajax", "django", "django-users" ]
I'd like to use Django's Messages module, however, I would like my messages to persist until the user clicks an X next to the message as opposed to having messages disappear as soon as the user reloads the page. I am stumped with two issues: How do I make the messages' context processor **not** delete the messages onc...
In your case `django.contrib.messages` won't bring you anywhere good. It's a message system inspired by RoR flash system, where messages aren't supposed to stay around You should create your own messaging system (django-persistent-messages maybe?) that would save messages for registered users in database. * It's a fa...
Python virtual classes: doing it right?
3,076,537
10
2010-06-19T17:32:32Z
3,076,563
10
2010-06-19T17:39:46Z
[ "python", "class", "inheritance", "virtual", "abstract" ]
I have been reading documentation describing class inheritance, abstract base classes and even python interfaces. But nothing seams to be exactly what I want. Namely, a simple way of building virtual classes. When the virtual class gets called, I would like it to instantiate some more specific class based on what the p...
I would prefer doing it with a factory: ``` def factory(description): if description == "It's flat": return Line(description) elif description == "It's spiky": return Triangle(description) elif description == "It's big": return Rectangle(description) ``` or: ``` def factory(description): classDi...
Python virtual classes: doing it right?
3,076,537
10
2010-06-19T17:32:32Z
3,076,636
15
2010-06-19T18:03:21Z
[ "python", "class", "inheritance", "virtual", "abstract" ]
I have been reading documentation describing class inheritance, abstract base classes and even python interfaces. But nothing seams to be exactly what I want. Namely, a simple way of building virtual classes. When the virtual class gets called, I would like it to instantiate some more specific class based on what the p...
I agree with [TooAngel](http://stackoverflow.com/questions/3076537/python-virtual-classes-doing-it-right/3076563#3076563), but I'd use the [*\_\_new\_\_ method*](http://docs.python.org/reference/datamodel.html#object.__new__). ``` class Shape(object): def __new__(cls, *args, **kwargs): if cls is Shape: ...