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
Is there a Python equivalent of Ruby's 'any?' function?
2,323,147
7
2010-02-24T01:58:11Z
2,323,165
20
2010-02-24T02:02:18Z
[ "python", "ruby", "list" ]
In Ruby, you can call [Enumerable#any?](http://ruby-doc.org/core/classes/Enumerable.html#M003132) on a enumerable object to see if any of its elements satisfies the predicate you pass in the block. Like so: ``` lst.any?{|e| pred(e) } ``` In Python, there's an `any` function that does something similar, but on a list ...
``` any(pred(x) for x in lst) ``` alternatively ``` from itertools import imap any(imap(pred, lst)) ```
zip() alternative for iterating through two iterables
2,323,394
11
2010-02-24T03:04:45Z
2,323,422
19
2010-02-24T03:11:49Z
[ "python" ]
I have two large (~100 GB) text files that must be iterated through simultaneously. Zip works well for smaller files but I found out that it's actually making a list of lines from my two files. This means that every line gets stored in memory. I don't need to do anything with the lines more than once. ``` handle1 = o...
[`itertools`](http://docs.python.org/library/itertools.html) has a function [`izip`](http://docs.python.org/library/itertools.html#itertools.izip) that does that ``` from itertools import izip for i, j in izip(handle1, handle2): ... ``` If the files are of different sizes you may use [`izip_longest`](http://docs....
zip() alternative for iterating through two iterables
2,323,394
11
2010-02-24T03:04:45Z
2,323,522
14
2010-02-24T03:38:16Z
[ "python" ]
I have two large (~100 GB) text files that must be iterated through simultaneously. Zip works well for smaller files but I found out that it's actually making a list of lines from my two files. This means that every line gets stored in memory. I don't need to do anything with the lines more than once. ``` handle1 = o...
You can use **izip\_longest** like this to pad the shorter file with empty lines in **python 2.6** ``` from itertools import izip_longest with handle1 as open('filea', 'r'): with handle2 as open('fileb', 'r'): for i, j in izip_longest(handle1, handle2, fillvalue=""): ... ``` or in **python3....
Is there any difference between cpython and python
2,324,208
20
2010-02-24T06:51:54Z
2,324,217
25
2010-02-24T06:53:59Z
[ "python" ]
I want to know the difference between CPython and Python because I have heard Python is developed in C - then what is the use of CPython?
Python is a language. [CPython](http://en.wikipedia.org/wiki/CPython) is the default byte-code interpreter of Python, which is written in C. There is also other implementation of Python such as IronPython (for .NET), Jython (for Java), etc.
Is there any difference between cpython and python
2,324,208
20
2010-02-24T06:51:54Z
2,324,220
11
2010-02-24T06:54:36Z
[ "python" ]
I want to know the difference between CPython and Python because I have heard Python is developed in C - then what is the use of CPython?
> [CPython](http://wiki.python.org/moin/CPython) is **Guido van Rossum**'s > reference version of the Python > computing language. It's most often > called simply "Python"; speakers say > "CPython" generally to distinguish it > explicitly from other implementations.
How to calculate the statistics "t-test" with numpy
2,324,438
18
2010-02-24T07:57:10Z
2,324,487
22
2010-02-24T08:10:17Z
[ "python", "statistics", "numpy", "scipy" ]
I'm looking to generate some statistics about a model I created in python. I'd like to generate the t-test on it, but was wondering if there was an easy way to do this with numpy/scipy. Are there any good explanations around? For example, I have three related datasets that look like this: ``` [55.0, 55.0, 47.0, 47.0,...
In a [scipy.stats](http://docs.scipy.org/doc/scipy/reference/stats.html#module-scipy.stats) package there are few `ttest_...` functions. See example from [here](http://docs.scipy.org/doc/scipy/reference/tutorial/stats.html#t-test-and-ks-test): ``` >>> print 't-statistic = %6.3f pvalue = %6.4f' % stats.ttest_1samp(x, ...
What is the official name of this construct?
2,324,453
5
2010-02-24T08:01:46Z
2,324,472
10
2010-02-24T08:06:01Z
[ "python" ]
In python: ``` >>> a = b or {} ```
I don't think it has an official name, it's just a clever/lazy way to be concise. It's roughly equivalent to: ``` a = b if b else {} ``` or: ``` if b: a = b else: a = {} ``` I wrote this as a comment but I think it's worth mentioning here: You have to be very careful when using this trick. If your intentio...
Is line wrap comment possible in Python?
2,324,483
7
2010-02-24T08:08:52Z
2,324,494
7
2010-02-24T08:11:48Z
[ "python", "comments" ]
I have a long string that I build with a bunch of calculated values. I then write this string to a file. I have it formatted like: ``` string = str(a/b)+\ '\t'+str(c)\ '\t'+str(d)\ ... '\n' ``` I would like to add comment to what each value represents but commenting with `#` or `''...
A simple solution is to use parenthesis instead: ``` string = (str(a/b)+ #this value is something '\t'+str(c)+ #this value is another thing '\t'+str(d)+ #and this one too ... '\n') ```
Debugging python programs in emacs
2,324,758
40
2010-02-24T09:04:45Z
2,325,751
38
2010-02-24T12:02:10Z
[ "python", "debugging", "emacs", "pdb" ]
How to debug python programs in emacs? I use python-mode.el I get reference like import pdb; pdb.set\_trace(); but not sure how to use it.
Type `M-x cd` to change directory to the location of the program you wish to debug. Type `M-x pdb`. You'll be prompted with `Run pdb (like this): pdb`. Enter the name of the program (e.g. `test.py`). At the `(Pdb)` prompt, type `help` to learn about how to use pdb. Alternatively, you can put ``` import pdb pdb.set_...
Debugging python programs in emacs
2,324,758
40
2010-02-24T09:04:45Z
19,168,037
13
2013-10-03T19:51:12Z
[ "python", "debugging", "emacs", "pdb" ]
How to debug python programs in emacs? I use python-mode.el I get reference like import pdb; pdb.set\_trace(); but not sure how to use it.
For me, I needed to replace the default "pdb" with ``` python -m pdb myscript.py ```
Why join is faster than normal concatenation
2,324,963
10
2010-02-24T09:44:23Z
2,325,011
13
2010-02-24T09:51:52Z
[ "javascript", "python", "performance", "join", "string-concatenation" ]
I've seen several examples from different languages that unambiguously prove that joining elements of a list(array) is times faster that just concatenating string. Unfortunately I didn't find an explanation why? Can someone explain the inner algorithm that works under both operations and why is the one faster than anot...
The reason is that strings in Python (and many other languages) are [immutable objects](http://en.wikipedia.org/wiki/Immutable_object) - that is, once created, they can't be changed. Instead, concatenating a string actually makes a *new* string which consists of the contents of the two smaller strings being concatenate...
Why join is faster than normal concatenation
2,324,963
10
2010-02-24T09:44:23Z
2,325,018
12
2010-02-24T09:52:31Z
[ "javascript", "python", "performance", "join", "string-concatenation" ]
I've seen several examples from different languages that unambiguously prove that joining elements of a list(array) is times faster that just concatenating string. Unfortunately I didn't find an explanation why? Can someone explain the inner algorithm that works under both operations and why is the one faster than anot...
The code in a join function knows upfront all the strings its being asked to concatenate and how large those strings are hence it can calculate the final string length before beginning the operation. Hence it need only allocate memory for the final string once and then it can place each source string (and delimiter) in...
Python path: Reusing Python module
2,325,418
3
2010-02-24T11:03:54Z
2,325,460
8
2010-02-24T11:13:21Z
[ "python", "ubuntu", "path" ]
I have written a small DB access module that is extensively reused in many programs. My code is stored in a single directory tree `/projects` for backup and versioning reasons, and so the module should be placed within this directory tree, say at `/projects/my_py_lib/dbconn.py`. I want to easily configure Python to a...
You can add a `PYTHONPATH` environment variable to your `.bashrc` file. eg. ``` export PYTHONPATH=/projects/my_py_lib ```
How to fix "ImportError: No module named ..." error in Python?
2,325,923
47
2010-02-24T12:31:09Z
2,326,045
52
2010-02-24T12:47:46Z
[ "python" ]
What is the correct way to fix this ImportError error? I have the following directory structure: ``` /home/bodacydo /home/bodacydo/work /home/bodacydo/work/project /home/bodacydo/work/project/programs /home/bodacydo/work/project/foo ``` And I am in the directory ``` /home/bodacydo/work/project ``` Now if I type `...
Python does not add the current directory to `sys.path`, but rather the directory that the script is in. Add `/home/bodacydo/work/project` to either `sys.path` or `$PYTHONPATH`.
How to fix "ImportError: No module named ..." error in Python?
2,325,923
47
2010-02-24T12:31:09Z
2,326,120
18
2010-02-24T13:00:37Z
[ "python" ]
What is the correct way to fix this ImportError error? I have the following directory structure: ``` /home/bodacydo /home/bodacydo/work /home/bodacydo/work/project /home/bodacydo/work/project/programs /home/bodacydo/work/project/foo ``` And I am in the directory ``` /home/bodacydo/work/project ``` Now if I type `...
Do you have a file called `__init__.py` in the foo directory? If not then python won't recognise foo as a python package. See the [section on packages](http://docs.python.org/tutorial/modules.html#packages) in the python tutorial for more information.
Anyone using Django in the "Enterprise"
2,326,671
26
2010-02-24T14:29:14Z
2,326,975
14
2010-02-24T15:07:07Z
[ "java", "python", "ruby-on-rails", "django", "enterprise" ]
I know that the word “enterprise” gives some people the creeps, but I am curious to know if anyone has experience creating enterprise applications, similar to something like say… Java EE applications, which are highly concurrent, distributed applications with Django? I know Java has its own issues but its kind of...
Is this what you're looking for? <http://code.djangoproject.com/wiki/DjangoSuccessStories> Or are you looking for this list? <http://www.djangosites.org/> Here are Django powered sites in rating order: <http://www.djangosites.org/highest-rated/> How about Django sites focused on "business": <http://www.djangosites....
Anyone using Django in the "Enterprise"
2,326,671
26
2010-02-24T14:29:14Z
2,327,568
7
2010-02-24T16:21:31Z
[ "java", "python", "ruby-on-rails", "django", "enterprise" ]
I know that the word “enterprise” gives some people the creeps, but I am curious to know if anyone has experience creating enterprise applications, similar to something like say… Java EE applications, which are highly concurrent, distributed applications with Django? I know Java has its own issues but its kind of...
For the systems you want to replace, you may find that it is desirable to use something more powerful than Django's ORM like SQLAlchemy. It's not a question of scaling, but the fact is that Django's ORM makes it hard to build complex queries and often pushes you to do in Python what should be done by your RDBMS — whe...
Anyone using Django in the "Enterprise"
2,326,671
26
2010-02-24T14:29:14Z
6,459,735
13
2011-06-23T19:44:44Z
[ "java", "python", "ruby-on-rails", "django", "enterprise" ]
I know that the word “enterprise” gives some people the creeps, but I am curious to know if anyone has experience creating enterprise applications, similar to something like say… Java EE applications, which are highly concurrent, distributed applications with Django? I know Java has its own issues but its kind of...
One of the biggest drawbacks in django is that although in theory the concept of applications being self-contained sounds nice, in practice it really doesn't work that well; even if you find some app that provides functionality that you need - it is not always easy to plug it in and go - you will always need to edit/ha...
Anyone using Django in the "Enterprise"
2,326,671
26
2010-02-24T14:29:14Z
9,905,892
7
2012-03-28T10:46:27Z
[ "java", "python", "ruby-on-rails", "django", "enterprise" ]
I know that the word “enterprise” gives some people the creeps, but I am curious to know if anyone has experience creating enterprise applications, similar to something like say… Java EE applications, which are highly concurrent, distributed applications with Django? I know Java has its own issues but its kind of...
My Company uses Django for at least six large scale enterprises such as mercedes, adidas. we often use the Jython wrapper. The advantages are * reduced development cost compared to Java/C# * runs stable via wrappers in IIS or Tomcat/Java environments * protects our software from copycats Therefore we are well satisfi...
MATLAB to Python Code conversion (NumPy, SciPy, MatplotLib?)
2,326,786
3
2010-02-24T14:44:14Z
2,326,918
11
2010-02-24T14:58:01Z
[ "python", "matlab", "numpy", "matplotlib", "scipy" ]
I'm trying to convert the following code to Python from MATLAB for an EEG Project (partly because Python's slightly cheaper!) Hopefully someone can point me in the right direction: I've started to alter it but got bogged down: Particularly trying to find equivalent functions. Tried scipy.org (NumPy\_for\_Matlab\_User...
Um... lots of things. Python has no `end` keyword, so you clearly need to read more about Python's syntax. Python arrays and slices are indexed with `[]` not `()`. Ranges are expressed as range(0,10) for example, but slices in the Matlab sense only exist in extension packages like numpy and each one has its own inter...
How to set target hosts in Fabric file
2,326,797
101
2010-02-24T14:45:11Z
2,366,774
21
2010-03-02T21:07:15Z
[ "python", "host", "fabric" ]
I want to use Fabric to deploy my web app code to development, staging and production servers. My fabfile: ``` def deploy_2_dev(): deploy('dev') def deploy_2_staging(): deploy('staging') def deploy_2_prod(): deploy('prod') def deploy(server): print 'env.hosts:', env.hosts env.hosts = [server] print 'env...
Was stuck on this myself, but finally figured it out. You simply *can't* set the env.hosts configuration from *within* a task. Each task is executed N times, once for each Host specified, so the setting is fundamentally outside of task scope. Looking at your code above, you could simply do this: ``` @hosts('dev') def...
How to set target hosts in Fabric file
2,326,797
101
2010-02-24T14:45:11Z
2,415,868
9
2010-03-10T09:52:17Z
[ "python", "host", "fabric" ]
I want to use Fabric to deploy my web app code to development, staging and production servers. My fabfile: ``` def deploy_2_dev(): deploy('dev') def deploy_2_staging(): deploy('staging') def deploy_2_prod(): deploy('prod') def deploy(server): print 'env.hosts:', env.hosts env.hosts = [server] print 'env...
You need to set `host_string` an example would be: ``` from fabric.context_managers import settings as _settings def _get_hardware_node(virtualized): return "localhost" def mystuff(virtualized): real_host = _get_hardware_node(virtualized) with _settings( host_string=real_host): run("echo ...
How to set target hosts in Fabric file
2,326,797
101
2010-02-24T14:45:11Z
4,687,027
119
2011-01-14T00:53:14Z
[ "python", "host", "fabric" ]
I want to use Fabric to deploy my web app code to development, staging and production servers. My fabfile: ``` def deploy_2_dev(): deploy('dev') def deploy_2_staging(): deploy('staging') def deploy_2_prod(): deploy('prod') def deploy(server): print 'env.hosts:', env.hosts env.hosts = [server] print 'env...
I do this by declaring an actual function for each environment. For example: ``` def test(): env.user = 'testuser' env.hosts = ['test.server.com'] def prod(): env.user = 'produser' env.hosts = ['prod.server.com'] def deploy(): ... ``` Using the above functions, I would type the following to depl...
How to set target hosts in Fabric file
2,326,797
101
2010-02-24T14:45:11Z
5,465,497
8
2011-03-28T21:50:36Z
[ "python", "host", "fabric" ]
I want to use Fabric to deploy my web app code to development, staging and production servers. My fabfile: ``` def deploy_2_dev(): deploy('dev') def deploy_2_staging(): deploy('staging') def deploy_2_prod(): deploy('prod') def deploy(server): print 'env.hosts:', env.hosts env.hosts = [server] print 'env...
To explain why it's even an issue. The command *fab* is leveraging fabric the library to run the tasks on the host lists. If you try and change the host list inside a task, you're esentially attempting to change a list while iterating over it. Or in the case where you have no hosts defined, loop over an empty list wher...
How to set target hosts in Fabric file
2,326,797
101
2010-02-24T14:45:11Z
6,313,237
66
2011-06-11T00:22:43Z
[ "python", "host", "fabric" ]
I want to use Fabric to deploy my web app code to development, staging and production servers. My fabfile: ``` def deploy_2_dev(): deploy('dev') def deploy_2_staging(): deploy('staging') def deploy_2_prod(): deploy('prod') def deploy(server): print 'env.hosts:', env.hosts env.hosts = [server] print 'env...
Use [roledefs](http://docs.fabfile.org/en/latest/usage/execution.html#roles) ``` from fabric.api import env, run env.roledefs = { 'test': ['localhost'], 'dev': ['user@dev.example.com'], 'staging': ['user@staging.example.com'], 'production': ['user@production.example.com'] } def deploy(): run('ec...
How to set target hosts in Fabric file
2,326,797
101
2010-02-24T14:45:11Z
6,383,234
42
2011-06-17T08:31:04Z
[ "python", "host", "fabric" ]
I want to use Fabric to deploy my web app code to development, staging and production servers. My fabfile: ``` def deploy_2_dev(): deploy('dev') def deploy_2_staging(): deploy('staging') def deploy_2_prod(): deploy('prod') def deploy(server): print 'env.hosts:', env.hosts env.hosts = [server] print 'env...
Here's a simpler version of [serverhorrors answer](http://stackoverflow.com/a/2415868/116973): ``` from fabric.api import settings def mystuff(): with settings(host_string='12.34.56.78'): run("hostname -f") ```
How to set target hosts in Fabric file
2,326,797
101
2010-02-24T14:45:11Z
16,889,529
9
2013-06-03T03:06:31Z
[ "python", "host", "fabric" ]
I want to use Fabric to deploy my web app code to development, staging and production servers. My fabfile: ``` def deploy_2_dev(): deploy('dev') def deploy_2_staging(): deploy('staging') def deploy_2_prod(): deploy('prod') def deploy(server): print 'env.hosts:', env.hosts env.hosts = [server] print 'env...
Contrary to some other answers, it *is* possible to modify the `env` environment variables within a task. However, this `env` will only be used for subsequent tasks executed using the `fabric.tasks.execute` function. ``` from fabric.api import task, roles, run, env from fabric.tasks import execute # Not a task, plain...
How to set target hosts in Fabric file
2,326,797
101
2010-02-24T14:45:11Z
18,367,572
13
2013-08-21T20:58:10Z
[ "python", "host", "fabric" ]
I want to use Fabric to deploy my web app code to development, staging and production servers. My fabfile: ``` def deploy_2_dev(): deploy('dev') def deploy_2_staging(): deploy('staging') def deploy_2_prod(): deploy('prod') def deploy(server): print 'env.hosts:', env.hosts env.hosts = [server] print 'env...
Since fab 1.5 this is a documented way to dynamically set hosts. <http://docs.fabfile.org/en/1.7/usage/execution.html#dynamic-hosts> Quote from the doc below. > Using execute with dynamically-set host lists > > A common intermediate-to-advanced use case for Fabric is to > parameterize lookup of one’s target host l...
Where should sys.path.append('...') statement go?
2,327,322
2
2010-02-24T15:51:42Z
2,327,376
8
2010-02-24T15:56:31Z
[ "python", "coding-style" ]
Just after standard pythonmodule imports? If I postpone it to the main function and do my specific module imports before it, it gives error (which is quite obvious). Python Style guide no where mentions the correct location for it.
It should go before the `import` or `from` statements that need it (which as you say is obvious). So for example a module could start with: ``` import sys import os import math try: import foo except ImportError: if 'foopath' in sys.path: raise sys.path.append('foopath') import foo ``` Note that I've made the...
ctypes loading a c shared library that has dependencies
2,327,344
15
2010-02-24T15:53:21Z
2,328,002
12
2010-02-24T17:22:52Z
[ "python", "linux", "ctypes" ]
On Linux, I have a c shared library that depends on other libs. LD\_LIBRARY\_PATH is properly set to allow the linker to load all the libraries. When I do: ``` libgidcwf = ctypes.cdll.LoadLibrary(libidcwf_path) ``` I get the following error: ``` Traceback (most recent call last): File "libwfm_test.py", line 12,...
It would seem that libwav.so does not declare it's dependency on the library defining ODBCGeneralQuery. Try running `ldd path-to-my-lib/libwav.so` and see if there's something missing. If this is a shared library that you are building you should add `-llibname` to the linking command (the one that is something like `gc...
It is said best way to deploy django is using wsgi, I am wondering why?
2,327,355
7
2010-02-24T15:54:41Z
2,327,403
15
2010-02-24T15:58:49Z
[ "python", "django", "mod-wsgi", "wsgi", "django-wsgi" ]
We are deploying django application, I found in the documentation that it is recommended to use WSGI appoach for doing that. Before deploying I wanted to know, why it is recommended over other two approaches i.e. using mod\_python and fastcgi... Thanks a lot.
`wsgi` is usually preferred because it decouples your choice of framework from your choice of web server: if tomorrow you want to move, say, from Apache to nginx, or whatever, the move is trivially easy with wsgi, not so easy otherwise. Furthermore, using wsgi affords you the option to add some middleware that's frame...
timing block of code in Python without putting it in a function
2,327,719
12
2010-02-24T16:42:27Z
2,327,873
24
2010-02-24T17:04:14Z
[ "python", "datetime", "benchmarking" ]
I'd like to time a block of code without putting it in a separate function. for example: ``` def myfunc: # some code here t1 = time.time() # block of code to time here t2 = time.time() print "Code took %s seconds." %(str(t2-t1)) ``` however, I'd like to do this with the timeit module in a cleaner way, but I...
You can do this with the `with` statement. For example: ``` import time from contextlib import contextmanager @contextmanager def measureTime(title): t1 = time.clock() yield t2 = time.clock() print '%s: %0.2f seconds elapsed' % (title, t2-t1) ``` To be used like this: ``` def myFunc(): #.....
How to best use GPS data?
2,327,813
6
2010-02-24T16:57:37Z
2,327,837
9
2010-02-24T17:00:18Z
[ "python", "android", "gps", "filtering" ]
I am currently developing an application that receives GPS data gathered using and android phone. I need to analyze that data in terms of speed, acceleration, etc... My question is: Can I trust the speed values returned by the phone? Or should I use the difference in position and time between two points to get the val...
Except using rather complicated data signal processing techniques, or by using an accelerometer and dead reckoning (which is highly inaccurate), a GPS device cannot measure its own velocity. Due to this, the velocity data provided by a GPS unit is interpolated using the exact same method you want to use. The two probab...
Django i18n: Common causes for translations not appearing
2,328,185
11
2010-02-24T17:45:12Z
2,381,694
12
2010-03-04T18:23:50Z
[ "python", "django", "translation", "gettext", "django-multilingual" ]
I am making a multilingual Django website. I created a messages file, populated and compiled it. I checked the site (the admin in this case,) in my wanted language (Hebrew) and most phrases appear in Hebrew like they should, but some don't. I checked the source and these still appear as `_('Whatever')` like they should...
Maybe the translated strings are marked as `fuzzy`?
Django i18n: Common causes for translations not appearing
2,328,185
11
2010-02-24T17:45:12Z
19,865,528
7
2013-11-08T17:56:18Z
[ "python", "django", "translation", "gettext", "django-multilingual" ]
I am making a multilingual Django website. I created a messages file, populated and compiled it. I checked the site (the admin in this case,) in my wanted language (Hebrew) and most phrases appear in Hebrew like they should, but some don't. I checked the source and these still appear as `_('Whatever')` like they should...
Just got hit by one. I had the `locale/` directory in the root of my project, but by default [Django looks for translations](https://docs.djangoproject.com/en/1.6/topics/i18n/translation/#how-django-discovers-translations) in the `INSTALLED_APPS` directories, and in the default translations. So it didn't find the trans...
How much leeway do I have to leave myself to learn a new language?
2,328,230
13
2010-02-24T17:53:26Z
2,328,346
8
2010-02-24T18:10:08Z
[ "java", "python" ]
I'm a relatively new hire, and I'm starting on a small, fairly simple project. The language that this project will be implemented in is still to be determined. The question basically boils down to - Java or Python? Here's the dilemma: My manager would prefer it to be done in Python. I don't object to that, but I have ...
I think it depends on the area of the project. While GUI is not hard in Python, any kind of GUI-framework will have a somewhat steep learning curve. If it is a webapp, I'd say go for Python. The added time for learning is quickly gained back by easy of use of the many Python webframeworks. The big risk is that you wil...
How much leeway do I have to leave myself to learn a new language?
2,328,230
13
2010-02-24T17:53:26Z
2,328,364
7
2010-02-24T18:13:01Z
[ "java", "python" ]
I'm a relatively new hire, and I'm starting on a small, fairly simple project. The language that this project will be implemented in is still to be determined. The question basically boils down to - Java or Python? Here's the dilemma: My manager would prefer it to be done in Python. I don't object to that, but I have ...
You have roughly 5 weeks to complete the project. If you're confident the Java version would take 2 weeks, that leaves 3 weeks to flail around with the Python version until you have to give up. I say go for it. Python is relatively easy to pick up. I think three weeks of work is enough to time to know whether you can f...
Python:Extend the 'dict' class
2,328,235
17
2010-02-24T17:55:17Z
2,328,259
9
2010-02-24T17:58:48Z
[ "python", "extend", "dictionary" ]
I have to solve this exercise: > Python's dictionaries do not preserve the order of inserted data nor store the data sorted by the key. Write an extension for the dict class whose instances will keep the data sorted by their key value. Note that the order must be preserved also when new elements are added. How do I e...
The implementation of dict will not help you with the task. What you want is a class that has the same interface as `dict`, but a different implementation. [That will require to implement methods like `__getitem__`, `__setitem__`, etc.](http://docs.python.org/reference/datamodel.html#emulating-container-types) If you G...
Python:Extend the 'dict' class
2,328,235
17
2010-02-24T17:55:17Z
2,329,727
17
2010-02-24T21:34:46Z
[ "python", "extend", "dictionary" ]
I have to solve this exercise: > Python's dictionaries do not preserve the order of inserted data nor store the data sorted by the key. Write an extension for the dict class whose instances will keep the data sorted by their key value. Note that the order must be preserved also when new elements are added. How do I e...
You can either subclass `dict` or `UserDict`, since van already talked about UserDict, lets look at `dict`. Type `help(dict)` into an interpreter and you see a big list of methods. You will need to override all the methods that modify the dict as well as the methods that iterate over the dict. Methods that modify the...
Python code optimization (20x slower than C)
2,328,495
4
2010-02-24T18:33:02Z
2,328,590
16
2010-02-24T18:45:23Z
[ "python", "optimization", "math", "performance" ]
I've written this very badly optimized C code that does a simple math calculation: ``` #include <stdio.h> #include <math.h> #include <stdlib.h> #define MIN(a, b) (((a) < (b)) ? (a) : (b)) #define MAX(a, b) (((a) > (b)) ? (a) : (b)) unsigned long long int p(int); float fullCheck(int); int main(int argc, char **argv)...
Since `quickCheck` is being called close to 25,000,000 times, you might want to use memoization to cache the answers. You can do memoization in C as well as Python. Things will be much faster in C, also. You're computing `1/6` in each iteration of quickCheck. I'm not sure if this will be optimized out by Python, but ...
Python code optimization (20x slower than C)
2,328,495
4
2010-02-24T18:33:02Z
2,328,859
9
2010-02-24T19:29:50Z
[ "python", "optimization", "math", "performance" ]
I've written this very badly optimized C code that does a simple math calculation: ``` #include <stdio.h> #include <math.h> #include <stdlib.h> #define MIN(a, b) (((a) < (b)) ? (a) : (b)) #define MAX(a, b) (((a) > (b)) ? (a) : (b)) unsigned long long int p(int); float fullCheck(int); int main(int argc, char **argv)...
I made it go from ~7 seconds to ~3 seconds on my machine: * Precomputed `i * (3 * i - 1 ) / 2` for each value, in yours it was computed twice quite a lot * Cached calls to quickCheck * Removed `if i == g` by adding +1 to the range * Removed `if p_i > p_g` since p\_i is *always* smaller than p\_g Also put the quickChe...
Transforming nested Python loops into list comprehensions
2,329,165
3
2010-02-24T20:17:30Z
2,329,193
7
2010-02-24T20:21:17Z
[ "python", "list-comprehension" ]
I've started working on some Project Euler problems, and have solved [number 4](http://projecteuler.net/index.php?section=problems&id=4) with a simple brute force solution: ``` def mprods(a,b): c = range(a,b) f = [] for d in c: for e in c: f.append(d*e) return f max([z for z in mprods(100,1000) if str(z)==('...
``` c = range(a, b) print [d * e for d in c for e in c] ```
Fastest Way to Delete a Line from Large File in Python
2,329,417
20
2010-02-24T20:51:01Z
2,329,972
10
2010-02-24T22:05:34Z
[ "python", "optimization" ]
I am working with a very large (~11GB) text file on a Linux system. I am running it through a program which is checking the file for errors. Once an error is found, I need to either fix the line or remove the line entirely. And then repeat... Eventually once I'm comfortable with the process, I'll automate it entirely....
You can have two file objects for the same file at the same time (one for reading, one for writing): ``` def removeLine(filename, lineno): fro = open(filename, "rb") current_line = 0 while current_line < lineno: fro.readline() current_line += 1 seekpoint = fro.tell() frw = open(fi...
Fastest Way to Delete a Line from Large File in Python
2,329,417
20
2010-02-24T20:51:01Z
2,330,081
7
2010-02-24T22:22:11Z
[ "python", "optimization" ]
I am working with a very large (~11GB) text file on a Linux system. I am running it through a program which is checking the file for errors. Once an error is found, I need to either fix the line or remove the line entirely. And then repeat... Eventually once I'm comfortable with the process, I'll automate it entirely....
Modify the file **in place**, offending line is replaced with spaces so the remainder of the file does not need to be shuffled around on disk. You can also "*fix*" the line in place if the fix is not longer than the line you are replacing ``` import os from mmap import mmap def removeLine(filename, lineno): f=os.o...
In Python with sqlite is it necessary to close a cursor?
2,330,344
21
2010-02-24T23:02:16Z
2,330,419
12
2010-02-24T23:15:31Z
[ "python", "sqlite" ]
Here is the scenario. In your function you're executing statements using a cursor, but one of them fails and an exception is thrown. Your program exits out of the function before closing the cursor it was working with. Will the cursor float around taking up space? Do I have to close the cursor? Additionally, the Pytho...
It's probably a good idea (although it might not matter much with sqlite, don't know there, but it'll make your code more portable). Further, with recent Python (2.5+), it's easy: ``` from __future__ import with_statement from contextlib import closing with closing(db.cursor()) as cursor: # do some stuff ```
How to set the program title in python
2,330,393
9
2010-02-24T23:11:43Z
2,330,596
9
2010-02-24T23:55:10Z
[ "python", "osx", "title", "menubar" ]
I have been building a large python program for a while, and would like to know how I would go about setting the title of the program? On a mac the title of program, which has focus, is shown in the top left corner of the screen, next the the apple menu. Currently this only shows the word "Python", but I would of cours...
It depends on what type of application you have. If it's a graphical application, most graphical toolkits allow you to change the title of a window (tk, which comes with python, allows you to do this by calling the `title()` method of your window object, as does gtk, for which you can use the `set_title()` method on a ...
How to convert ctypes' c_long to Python's int?
2,330,587
11
2010-02-24T23:53:17Z
2,330,610
20
2010-02-24T23:57:12Z
[ "python", "ctypes" ]
`int(c_long(1))` doesn't work.
``` >>> ctypes.c_long(1).value 1 ```
Colorize PyLint Output?
2,330,608
3
2010-02-24T23:56:51Z
2,333,150
8
2010-02-25T10:07:01Z
[ "python", "pylint", "colorize" ]
Anyone have any tricks/techniques for colorizing PyLint output?
`$ pylint --output-format=colorized` Try `$ pylint --help | less` for more useful tricks.
Why am I getting no attribute '__getitem__' error for dictionary?
2,331,015
14
2010-02-25T01:43:58Z
2,331,026
23
2010-02-25T01:47:01Z
[ "python", "dictionary", "optparse" ]
Why am I getting no attribute `__getitem__` error for dictionary: ``` Traceback (most recent call last): File "./thumbnail.py", line 39, in <module> main() File "./thumbnail.py", line 19, in main options['input_pattern'] AttributeError: Values instance has no attribute '__getitem__' ``` Here's the code: ...
`options` is not a dict: ``` print options.input_pattern ```
Why am I getting no attribute '__getitem__' error for dictionary?
2,331,015
14
2010-02-25T01:43:58Z
3,120,306
7
2010-06-25T18:05:00Z
[ "python", "dictionary", "optparse" ]
Why am I getting no attribute `__getitem__` error for dictionary: ``` Traceback (most recent call last): File "./thumbnail.py", line 39, in <module> main() File "./thumbnail.py", line 19, in main options['input_pattern'] AttributeError: Values instance has no attribute '__getitem__' ``` Here's the code: ...
If you must have a dict, use ``` options.__dict__ ```
piping output of subprocess.Popen to files
2,331,339
30
2010-02-25T03:08:15Z
2,331,376
38
2010-02-25T03:16:44Z
[ "python", "subprocess", "stdout" ]
I need to launch a number of long-running processes with `subprocess.Popen`, and would like to have the `stdout` and `stderr` from each automatically piped to separate log files. Each process will run simultaneously for several minutes, and I want two log files (`stdout` and `stderr`) **per process** to be written to a...
You can pass `stdout` and `stderr` as parameters to `Popen()` ``` subprocess.Popen(self, args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, ...
piping output of subprocess.Popen to files
2,331,339
30
2010-02-25T03:08:15Z
2,331,379
26
2010-02-25T03:18:00Z
[ "python", "subprocess", "stdout" ]
I need to launch a number of long-running processes with `subprocess.Popen`, and would like to have the `stdout` and `stderr` from each automatically piped to separate log files. Each process will run simultaneously for several minutes, and I want two log files (`stdout` and `stderr`) **per process** to be written to a...
Per [the docs](http://docs.python.org/library/subprocess.html?highlight=popen#subprocess.Popen), > stdin, stdout and stderr specify the > executed programs’ standard input, > standard output and standard error > file handles, respectively. Valid > values are PIPE, an existing file > descriptor (a positive integer), ...
datetime.datetime.utcnow() why no tzinfo?
2,331,592
115
2010-02-25T04:14:00Z
2,331,635
36
2010-02-25T04:27:46Z
[ "python", "datetime" ]
``` datetime.datetime.utcnow() datetime.datetime(2010, 2, 25, 4, 14, 37, 366086) ``` Why does this datetime not have any tz info say its a utc date.
The standard Python libraries don't include any tzinfo classes (but [see pep 431](https://www.python.org/dev/peps/pep-0431/)). I can only guess at the reasons. Personally I think it was a mistake not to include a tzinfo class for UTC, because that one is uncontroversial enough to have a standard implementation. **Edit...
datetime.datetime.utcnow() why no tzinfo?
2,331,592
115
2010-02-25T04:14:00Z
2,331,640
101
2010-02-25T04:28:53Z
[ "python", "datetime" ]
``` datetime.datetime.utcnow() datetime.datetime(2010, 2, 25, 4, 14, 37, 366086) ``` Why does this datetime not have any tz info say its a utc date.
That means it is timezone naive, so you can't use it with `datetime.astimezone` you can give it a timezone like this ``` import pytz # 3rd party: $ pip install pytz u = datetime.utcnow() u = u.replace(tzinfo=pytz.utc) #NOTE: it works only with a fixed utc offset ``` now you can change timezones ``` print(u.astime...
datetime.datetime.utcnow() why no tzinfo?
2,331,592
115
2010-02-25T04:14:00Z
19,839,238
15
2013-11-07T15:03:14Z
[ "python", "datetime" ]
``` datetime.datetime.utcnow() datetime.datetime(2010, 2, 25, 4, 14, 37, 366086) ``` Why does this datetime not have any tz info say its a utc date.
The `pytz` module is one option, and there is another `python-dateutil`, which although is also third party package, may already be available depending on your other dependencies and operating system. I just wanted to include this methodology for reference- if you've already installed `python-dateutil` for other purpo...
datetime.datetime.utcnow() why no tzinfo?
2,331,592
115
2010-02-25T04:14:00Z
24,666,683
25
2014-07-10T02:43:55Z
[ "python", "datetime" ]
``` datetime.datetime.utcnow() datetime.datetime(2010, 2, 25, 4, 14, 37, 366086) ``` Why does this datetime not have any tz info say its a utc date.
Note that for Python 3.2 onwards, the `datetime` module contains `datetime.timezone`. The documentation for [`datetime.utcnow()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.utcnow) says: > An aware current UTC datetime can be obtained by calling `datetime.now(timezone.utc)`. So you can do: ```...
How to decode JSON with Python
2,331,943
19
2010-02-25T05:51:01Z
2,331,958
22
2010-02-25T05:54:25Z
[ "python", "json" ]
I'm getting my JSON from reddit.com, essentially [something like this.](http://www.reddit.com/.json) I have done quite a bit of reading, but I don't really understand how I can grab the information I want from this JSON (I want a list of the story links). I understand that I can "decode" the JSON into a dictionary, but...
If you're using Python 2.6 or later, use the built-in [`json`](http://docs.python.org/library/json.html) library. Otherwise, use [`simplejson`](http://code.google.com/p/simplejson/) which has exactly the same interface. You can do this adaptively without having to check the Python version yourself, using code such as ...
How to decode JSON with Python
2,331,943
19
2010-02-25T05:51:01Z
2,331,967
13
2010-02-25T05:55:53Z
[ "python", "json" ]
I'm getting my JSON from reddit.com, essentially [something like this.](http://www.reddit.com/.json) I have done quite a bit of reading, but I don't really understand how I can grab the information I want from this JSON (I want a list of the story links). I understand that I can "decode" the JSON into a dictionary, but...
``` import urllib2 import json u = urllib2.urlopen('http://www.reddit.com/.json') print json.load(u) u.close() ```
Emacs: Set/Reset python debug breakpoint
2,332,164
4
2010-02-25T06:43:06Z
2,350,051
7
2010-02-28T04:09:14Z
[ "python", "debugging", "emacs", "elisp", "customization" ]
I use python debugger pdb. I use emacs for python programming. I use python-mode.el. My idea is to make emacs intuitive. So I need the following help for python programs (.py) 1. Whenever I press 'F9' key, the emacs should put "import pdb; pdb.set\_trace();" statements in the current line and move the current line to ...
to do 1) ``` (defun add-py-debug () "add debug code and move line down" (interactive) (move-beginning-of-line 1) (insert "import pdb; pdb.set_trace();\n")) (local-set-key (kbd "<f9>") 'add-py-debug) ``` to do 2) you probably have to change the syntax highlighting of the python mode, or wr...
How do I get my python object back from a QVariant in PyQt4?
2,333,420
5
2010-02-25T10:59:20Z
2,334,019
12
2010-02-25T12:46:34Z
[ "python", "pyqt4", "qvariant", "qabstractitemmodel" ]
I am creating a subclass of `QAbstractItemModel` to be displayed in an `QTreeView`. My `index()` and `parent()` function creates the `QModelIndex` using the `QAbstractItemModel` inherited function `createIndex` and providing it the `row`, `column`, and `data` needed. Here, for testing purposes, data is a Python string...
Have you tried this? ``` my_python_object = my_qvariant.toPyObject() ``` <http://pyqt.sourceforge.net/Docs/PyQt4/qvariant.html#toPyObject> (just for completeness, but there isn't much to see there...)
Return common element indices between two numpy arrays
2,333,593
8
2010-02-25T11:29:34Z
2,333,682
7
2010-02-25T11:47:30Z
[ "python", "arrays", "numpy" ]
I have two arrays, a1 and a2. Assume `len(a2) >> len(a1)`, and that a1 is a subset of a2. I would like a quick way to return the a2 indices of all elements in a1. The time-intensive way to do this is obviously: ``` from operator import indexOf indices = [] for i in a1: indices.append(indexOf(a2,i)) ``` This of c...
How about ``` numpy.nonzero(numpy.in1d(a2, a1))[0] ``` This should be fast. From my basic testing, it's about 7 times faster than your second code snippet for `len(a2) == 100`, `len(a1) == 10000`, and only one common element at index 45. This assumes that both `a1` and `a2` have no repeating elements.
Python equivalents of the common Perl modules?
2,333,851
6
2010-02-25T12:17:01Z
2,333,883
14
2010-02-25T12:23:44Z
[ "python", "perl", "migration" ]
I need to rewrite some Perl code in python. So I'm looking for the closest modules to what I'm using now in Perl (i.e. with similar functionality and stability): * [DBI](http://search.cpan.org/perldoc/DBI) + [DBD::mysql](http://search.cpan.org/perldoc/DBD%3a%3amysql) * [LWP::UserAgent](http://search.cpan.org/perldoc/L...
* All Python database modules use the same API, so either [`MySQLdb`](http://sourceforge.net/projects/mysql-python/) or [`oursql`](http://packages.python.org/oursql/) will work. * [`urllib2`](http://docs.python.org/library/urllib2.html) * [`mechanize`](http://wwwsearch.sourceforge.net/mechanize/) * [`etree`](http://doc...
Python equivalents of the common Perl modules?
2,333,851
6
2010-02-25T12:17:01Z
2,334,047
15
2010-02-25T12:52:00Z
[ "python", "perl", "migration" ]
I need to rewrite some Perl code in python. So I'm looking for the closest modules to what I'm using now in Perl (i.e. with similar functionality and stability): * [DBI](http://search.cpan.org/perldoc/DBI) + [DBD::mysql](http://search.cpan.org/perldoc/DBD%3a%3amysql) * [LWP::UserAgent](http://search.cpan.org/perldoc/L...
### DBI + DBD::mysql * [MySQLdb](http://sourceforge.net/projects/mysql-python/) ### LWP::UserAgent * [urllib](http://docs.python.org/library/urllib.html) (Python STL) * [urllib2](http://docs.python.org/library/urllib2.html) (Python STL) ### WWW::Mechanize * [Mechanize](http://wwwsearch.sourceforge.net/mechanize/) ...
atomic writing to file with Python
2,333,872
32
2010-02-25T12:21:41Z
2,333,979
65
2010-02-25T12:39:49Z
[ "python", "file-io", "atomic" ]
I am using Python to write chunks of text to files in a single operation: ``` open(file, 'w').write(text) ``` If the script is interrupted so a file write does not complete I want to have no file rather than a partially complete file. Can this be done?
Write data to a temporary file and when data has been successfully written, rename the file to the correct destination file e.g ``` f = open(tmpFile, 'w') f.write(text) # make sure that all data is on disk # see http://stackoverflow.com/questions/7433057/is-rename-without-fsync-safe f.flush() os.fsync(f.fileno()) f.c...
Django queries: how to make contains OR not_contains queries
2,334,698
6
2010-02-25T14:35:41Z
2,334,784
12
2010-02-25T14:43:52Z
[ "python", "django" ]
I have to make a query that will get records containing "wd2" substring or not containing "wd" string at all. Is there any way to do it nicely? Seems something like: `Record.objects.filter( Q(parameter__icontains="wd2") | Q( ## what should be here? ## ) )`
From the django [q object documentation](http://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects): > You can compose statements of arbitrary complexity by combining Q objects with the & and | operators and use parenthetical grouping. Also, Q objects can be negated using the ~ operator, a...
What is the scope of a defaulted parameter in Python?
2,335,160
11
2010-02-25T15:26:36Z
2,335,174
12
2010-02-25T15:28:08Z
[ "python", "scope", "parameters", "default-value", "function-calls" ]
When you define a function in Python with an array parameter, what is the scope of that parameter? This example is taken from the Python tutorial: ``` def f(a, L=[]): L.append(a) return L print f(1) print f(2) print f(3) ``` Prints: ``` [1] [1, 2] [1, 2, 3] ``` I'm not quite sure if I understand what's ha...
The scope is as you would expect. The perhaps surprising thing is that the default value is only calculated once and reused, so each time you call the function you get the same list, not a new list initialized to []. The list is stored in `f.func_defaults`. ``` def f(a, L=[]): L.append(a) return L print f(1...
How can I get the window focused on Windows and re-size it?
2,335,721
6
2010-02-25T16:38:06Z
2,335,734
7
2010-02-25T16:39:47Z
[ "python", "windows" ]
I want to get the focused window so I can resize it... how can I do it?
Use the [GetForegroundWindow](http://msdn.microsoft.com/en-us/library/ms633505%28VS.85%29.aspx) Win32 API to get the window handle. Then use the [MoveWindow](http://msdn.microsoft.com/en-us/library/ms633534%28VS.85%29.aspx) (or [SetWindowPos](http://msdn.microsoft.com/en-us/library/ms633545%28VS.85%29.aspx) if you pre...
Is fortran-like print in python possible?
2,335,856
5
2010-02-25T16:53:17Z
2,335,878
9
2010-02-25T16:55:53Z
[ "python", "fortran" ]
is it possible some way to "print" in python in a fortran like way like this? ``` 1 4.5656 2 24.0900 3 698.2300 4 -3.5000 ``` So the decimal points is always in the same column, and we get always 3 or n decimal numbers? Thanks
``` >>> '%11.4f' % -3.5 ' -3.5000' ``` or the new style formatting: ``` >>> '{:11.4f}'.format(-3.5) ' -3.5000' ``` more about [format specifiers in the docs](http://docs.python.org/library/string.html#formatspec).
Transaction within transaction
2,336,950
6
2010-02-25T19:28:44Z
2,337,881
14
2010-02-25T21:44:35Z
[ "python", "database", "postgresql", "sqlalchemy" ]
I want to know if open a transaction inside another is safe and encouraged? I have a method: ``` def foo(): session.begin try: stuffs except Exception, e: session.rollback() raise e session.commit() ``` and a method that calls the first one, inside a transaction: ``` def ...
there are two ways two nest transactions in SQLAlchemy. One is virtual transactions, where SQLAlchemy keeps track of how many begin's you have issued and issues the commit only when the outermost transaction commits. The rollback however is issued immediately. Because the transaction is virtual - i.e. the database know...
Jython image manipulation
2,337,110
5
2010-02-25T19:47:51Z
17,864,427
9
2013-07-25T17:08:03Z
[ "python", "jython", "image-manipulation", "jes" ]
This program is supposed to take the outline of an image, then split it into different quadrants, then color it, such as the Andy Warhol Marilyn Monroe picture. Every function up to the "Warholize" function works but it gets stuck on `c=getPixel(picEdge,x,y)` under the `warholize` function at which I'm not sure what t...
I put the difference and intensity functions into the makeOutline function. I have called the warholize function from the makeOutline function. Also, you needed to get the colors for the separate quadrants, here, I've just used getRed pixel to see if it is black or white (full color or not). In this case I have used...
Set a DTD using minidom in python
2,337,285
4
2010-02-25T20:16:35Z
2,340,579
7
2010-02-26T09:32:44Z
[ "python", "xml", "dtd", "minidom" ]
I am trying to include a reference to a DTD in my XML doc using minidom. I am creating the document like: ``` doc = Document() foo = doc.createElement('foo') doc.appendChild(foo) doc.toxml() ``` This gives me: ``` <?xml version="1.0" ?> <foo/> ``` I need to get something like: ``` <?xml version="1.0" ?> <!DOCTYPE...
The documentation is out of date. Use the source, Luke. I do it something like this. ``` from xml.dom.minidom import DOMImplementation imp = DOMImplementation() doctype = imp.createDocumentType( qualifiedName='foo', publicId='', systemId='http://www.path.to.my.dtd.com/my.dtd', ) doc = imp.createDocument(...
Python/Django polling of database has memory leak
2,338,041
12
2010-02-25T22:08:13Z
2,338,335
31
2010-02-25T23:05:38Z
[ "python", "django", "memory-leaks", "daemon" ]
I've got a Python script running Django for database and memcache, but it's notably runnning as a standalone daemon (i.e. not responding to webserver requests). The daemon checks a Django model Requisition for objects with a `status=STATUS_NEW`, then marks them STATUS\_WORKING and puts them into a queue. A number of p...
You need to regularly reset a list of queries that Django keeps for debugging purposes. Normally it is cleared after every request, but since your application is not request based, you need to do this manually: ``` from django import db db.reset_queries() ``` --- See also: * ["Debugging Django memory leak with Tra...
How to use Corba with Python
2,338,331
8
2010-02-25T23:04:48Z
2,378,881
9
2010-03-04T11:34:39Z
[ "python", "corba" ]
I'm wondering if anyone have a good resource for working with Corba in Python? I've googled around and saw that fnorb was recommended by some, but that it doesn't support some new features in Corba. Omniorb seemed like a good alternative, but I have no idea how to use it with Python (not fnorb either). Any advice is a...
What's wrong with the omniORBpy [User's Guide](http://omniorb.sourceforge.net/omnipy3/omniORBpy/) ?
Python sorting - A list of objects
2,338,531
26
2010-02-25T23:55:48Z
2,338,540
49
2010-02-25T23:59:13Z
[ "python", "list", "sorting" ]
I'd like to use the somelist.sort() method to do this if possible. I have a list containing objects, all objects have a member variable resultType that is an integer. I'd like to sort the list using this number. How do I do this? Thanks!
``` somelist.sort(key = lambda x: x.resultType) ``` Here's another way to do the same thing that you will often see used: ``` import operator s.sort(key = operator.attrgetter('resultType')) ``` You might also want to look at [`sorted`](http://docs.python.org/library/functions.html#sorted) if you haven't seen it alre...
Python sorting - A list of objects
2,338,531
26
2010-02-25T23:55:48Z
2,338,567
8
2010-02-26T00:03:11Z
[ "python", "list", "sorting" ]
I'd like to use the somelist.sort() method to do this if possible. I have a list containing objects, all objects have a member variable resultType that is an integer. I'd like to sort the list using this number. How do I do this? Thanks!
Of course, it doesn't have to be a lambda. Any function passed in, such as the below one, will work ``` def numeric_compare(x, y): if x > y: return 1 elif x == y: return 0 else: #x < y return -1 a = [5, 2, 3, 1, 4] a.sort(numeric_compare) ``` Source : [Python Sorting](http://wiki.python.o...
Python - pyparsing unicode characters
2,339,386
10
2010-02-26T03:52:11Z
2,340,659
17
2010-02-26T09:43:50Z
[ "python", "unicode", "nlp", "pyparsing" ]
:) I tried using w = Word(printables), but it isn't working. How should I give the spec for this. 'w' is meant to process Hindi characters (UTF-8) The code specifies the grammar and parses accordingly. ``` 671.assess :: अहसास ::2 x=number + "." + src + "::" + w + "::" + number + "." + number ``` If there...
Pyparsing's `printables` only deals with strings in the ASCII range of characters. You want printables in the full Unicode range, like this: ``` unicodePrintables = u''.join(unichr(c) for c in xrange(sys.maxunicode) if not unichr(c).isspace()) ``` Now you can define `trans` us...
How can I make URLs in Django similar to stackoverflow?
2,339,436
5
2010-02-26T04:08:36Z
2,339,466
8
2010-02-26T04:15:34Z
[ "python", "django", "url", "friendly-url", "slug" ]
I'm creating a video site. I want my direct urls to a video to look like example.com/watch/this-is-a-slug-1 where 1 is the video id. I don't want the slug to matter though. example.com/watch/this-is-another-slug-1 should point to the same page. On SO, /questions/id is the only part of the url that matters. How can I do...
Stack Overflow uses the form ``` example.com/watch/1/this-is-a-slug ``` which is easier to handle. You're opening a can of worms if you want the ID to be at the end of the slug token, since then it'll (for example) restrict what kinds of slugs you can use, or just make it harder on yourself. You can use a url handle...
reading a os.popen(command) into a string
2,339,469
11
2010-02-26T04:17:42Z
2,339,494
17
2010-02-26T04:26:01Z
[ "python", "string", "popen" ]
I'm not to sure if my title is right. What I'm doing is writing a python script to automate some of my code writing. So I'm parsing through a .h file. but I want to expand all macros before I start. so I want to do a call to the shell to: ``` gcc -E myHeader.h ``` Which should out put the post preprocessed version of...
The `os.popen` function just returns a file-like object. You can use it like so: ``` import os process = os.popen('gcc -E myHeader.h') preprocessed = process.read() process.close() ``` As others have said, you should be using `subprocess.Popen`. It's designed to be a [safer version](http://docs.python.org/library/su...
reading a os.popen(command) into a string
2,339,469
11
2010-02-26T04:17:42Z
2,339,788
11
2010-02-26T06:03:23Z
[ "python", "string", "popen" ]
I'm not to sure if my title is right. What I'm doing is writing a python script to automate some of my code writing. So I'm parsing through a .h file. but I want to expand all macros before I start. so I want to do a call to the shell to: ``` gcc -E myHeader.h ``` Which should out put the post preprocessed version of...
``` import subprocess p = subprocess.popen('gcc -E myHeader.h'.split(), stdout=subprocess.PIPE) preprocessed, _ = p.communicate() ``` String `preprocessed` now has the preprocessed source you require -- and you've used the "right" (modern) way to shell to a subprocess, rather than old not-so-like...
Creating a Cron Job - Linux / Python
2,339,725
3
2010-02-26T05:46:07Z
2,339,753
7
2010-02-26T05:55:00Z
[ "python", "linux", "django", "ubuntu" ]
Hi I have a Django script that I need to run, I think the commands could be called through bash. Thing is the script causes memory leaks after a long a period of time, so I would like to create an external cron job which calls the Python script. So the script would terminate and restart while retaking the lost memory...
If you have an executable, say `/home/bin/foobar`, that restarts the script, and want to run it (say) every 10 minutes, the crontab entry needs to be: ``` */10 * * * * /home/bin/foobar ``` which says to run it at every minute divisible by 10, every hour, every day. If you save this (and any other periodic jobs you ...
fabric password
2,339,735
28
2010-02-26T05:48:50Z
2,339,767
42
2010-02-26T05:58:37Z
[ "python", "fabric" ]
Every time fabric runs, it asks for root password, can it be sent along same for automated proposes. ``` fab staging test ```
`fab -h` will show you all the options, you can also read them [here](http://docs.fabfile.org/en/1.10/usage/fab.html#command-line-options). In particular, and I quote, > -p PASSWORD, --password=PASSWORD > > Sets env.password to the given string; > it will then be used as the default > password when making SSH connect...
fabric password
2,339,735
28
2010-02-26T05:48:50Z
2,340,889
49
2010-02-26T10:29:15Z
[ "python", "fabric" ]
Every time fabric runs, it asks for root password, can it be sent along same for automated proposes. ``` fab staging test ```
I know you've asked about password but wouldn't it better to configure the system so that you can doing fabric (i.e. SSH) without password? For this, on local machine do: 1. `ssh-keygen` and agree with all defaults (if you have no reasons do otherwise) 2. `cat ~/.ssh/id_rsa.pub` and copy that key On remote machine: ...
fabric password
2,339,735
28
2010-02-26T05:48:50Z
5,568,219
36
2011-04-06T14:40:18Z
[ "python", "fabric" ]
Every time fabric runs, it asks for root password, can it be sent along same for automated proposes. ``` fab staging test ```
You can also set passwords on a per host basis. It wasn't obvious to me, so here it goes for anyone looking for this: ``` from fabric import env env.hosts = ['user1@host1:port1', 'user2@host2.port2'] env.passwords = {'user1@host1:port1': 'password1', 'user2@host2.port2': 'password2'} ``` Fabric caches used passwords ...
Why copy post data in Django instead of working with it directly?
2,339,857
5
2010-02-26T06:26:44Z
2,339,963
10
2010-02-26T06:57:26Z
[ "python", "django" ]
Django code samples involving post data often shows code similar to this: ``` if request.method == "POST": post = request.POST.copy() #do stuff with post data ``` Is there a reason for copying the post data instead of working with it directly?
I think it is because `request.POST` itself is defined immutable. If you want a version you can actually change (mutability), you need a copy of the data to work with. See [this link](http://docs.djangoproject.com/en/1.6/ref/request-response/#querydict-objects) (request.POST is a QueryDict instance). --- > ### [clas...
Decrypt VIM encrypted file in Python
2,340,096
3
2010-02-26T07:32:56Z
2,340,228
7
2010-02-26T08:06:27Z
[ "python", "vim", "encryption" ]
In my Python web app, I would need to decrypt a file that was encrypted using VIM. Assuming the web app knows the password used to encrypt the file in VIM, how do I write code to decrypt ?
Turns out that vim uses the same encryption as PKZIP: ``` from zipfile import _ZipDecrypter fp = open(somefile, 'rb') zd = _ZipDecrypter(somekey) fp.read(12) print ''.join(zd(c) for c in fp.read()) fp.close() ```
Python 3.1.1 string to hex
2,340,319
33
2010-02-26T08:27:09Z
2,340,339
15
2010-02-26T08:31:05Z
[ "python", "string", "python-3.x", "hex" ]
I am trying to use `str.encode()` but I get ``` >>> "hello".encode(hex) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: must be string, not builtin_function_or_method ``` I have tried a bunch of variations and they seem to all work in Python 2.5.2, so what do I need to do to get th...
You've already got some good answers, but I thought you might be interested in a bit of the background too. Firstly you're missing the quotes. It should be: ``` "hello".encode("hex") ``` Secondly this codec hasn't been ported to Python 3.1. See [here](http://bugs.python.org/issue7475). It seems that they haven't yet...
Python 3.1.1 string to hex
2,340,319
33
2010-02-26T08:27:09Z
2,340,358
44
2010-02-26T08:36:12Z
[ "python", "string", "python-3.x", "hex" ]
I am trying to use `str.encode()` but I get ``` >>> "hello".encode(hex) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: must be string, not builtin_function_or_method ``` I have tried a bunch of variations and they seem to all work in Python 2.5.2, so what do I need to do to get th...
The `hex` codec has been chucked in 3.x. Use [`binascii`](http://docs.python.org/3.1/library/binascii.html#binascii.b2a_hex) instead: ``` >>> binascii.hexlify(b'hello') b'68656c6c6f' ```
Python 3.1.1 string to hex
2,340,319
33
2010-02-26T08:27:09Z
13,546,090
8
2012-11-24T22:05:49Z
[ "python", "string", "python-3.x", "hex" ]
I am trying to use `str.encode()` but I get ``` >>> "hello".encode(hex) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: must be string, not builtin_function_or_method ``` I have tried a bunch of variations and they seem to all work in Python 2.5.2, so what do I need to do to get th...
binascii methodes are easier by the way ``` >>> import binascii >>> x=b'test' >>> x=binascii.hexlify(x) >>> x b'74657374' >>> y=str(x,'ascii') >>> y '74657374' >>> x=binascii.unhexlify(x) >>> x b'test' >>> y=str(x,'ascii') >>> y 'test' ``` Hope it helps. :)
calculate mean and variance with one iteration
2,341,340
15
2010-02-26T11:51:59Z
2,341,505
11
2010-02-26T12:28:05Z
[ "python", "iterator" ]
I have an iterator of numbers, for example a file object: ``` f = open("datafile.dat") ``` now I want to compute: ``` mean = get_mean(f) sigma = get_sigma(f, mean) ``` What is the best implementation? Suppose that the file is big and I would like to avoid to read it twice.
If you want to iterate once, you can write your sum function: ``` def mysum(l): s2 = 0 s = 0 for e in l: s += e s2 += e * e return (s, s2) ``` and use the result in your `sigma` function. **Edit**: now you can calculate the variance like this: (s2 - (s\*s) / N) / N By taking account ...
how to make python to return floating point?
2,341,771
3
2010-02-26T13:11:58Z
2,341,791
8
2010-02-26T13:13:53Z
[ "python" ]
hi I want python to return 0.5 if I write 1/2 (and not 1.0/2.0). how do I make python to return the floating point? (I tried using getcontext().prec form decimal module) thanks Ariel
Use this, or switch to Python 3.0+ ``` from __future__ import division ```
Remove default apps from Django-admin
2,342,031
33
2010-02-26T13:50:26Z
2,342,136
63
2010-02-26T14:10:13Z
[ "python", "django", "django-admin" ]
By default, in Django-admin there is Users, Groups, and Sites apps. How can I remove Groups and Sites? I tried to remove `admin.autodiscover()` from root urls. Then, when I added something like `admin.site.register(User, UserAdmin)` somewhere in my app models I got an `AlreadyRegistered` exception (this is fairly righ...
In an admin.py you know will definitely be loaded, try: ``` admin.site.unregister(User) admin.site.unregister(Group) admin.site.unregister(Site) ```
Can I write parts of the Google App Engine code in Java, other parts in Python?
2,342,059
7
2010-02-26T13:55:59Z
2,342,111
9
2010-02-26T14:06:07Z
[ "java", "python", "google-app-engine" ]
Google App Engine supports both Python and Java application development. Can I have both in the same application?
> **Can I run Java and Python code in the same app?** > > Each version of the app must specify a runtime language and it is possible to have version x of your app running Java, while version y is running Python. It would also be possible to use Jython. Source: [Google App Engine for Java FAQ](http://code.google.com/ap...
Open a file in the proper encoding automatically
2,342,284
6
2010-02-26T14:34:27Z
2,342,313
7
2010-02-26T14:39:06Z
[ "python" ]
I'm dealing with some problems in a few files about the encoding. We receive files from other company and have to read them (the files are in csv format) Strangely, the files appear to be encoded in UTF-16. I am managing to do that, but I have to open them using the `codecs` module and specifying the encoding, this wa...
[chardet](http://pypi.python.org/pypi/chardet) can help you. > Character encoding auto-detection in > Python 2 and 3. As smart as your > browser. Open source.
How to build an image object in PIL/Python
2,343,115
4
2010-02-26T16:33:11Z
2,344,074
7
2010-02-26T18:55:22Z
[ "python", "image", "python-imaging-library" ]
I have a list of 3-item tuples that is the result of list(PIL.Image.getdata()). How do I do the opposite: build a PIL.Image object from this list?
The output of `getdata()` does not include the image format or the size, so you'll need to preserve those (or get the information some other way). Then do this, using the [`putdata()`](http://effbot.org/imagingbook/image.htm#tag-Image.Image.putdata) method: ``` # get data from old image (as you already did) data = lis...
Is there any Python wrapper around cron?
2,343,403
5
2010-02-26T17:11:23Z
2,348,796
9
2010-02-27T20:12:51Z
[ "python", "cron", "wrapper" ]
I'm looking for a wrapper around cron. I've stumbled upon PyCron but it's a Python implementation, not a wrapper. Do you know any good cron Python wrapper ? If not, did you test PyCron, and what can you tell about it ? //EDIT (As an answer to comment asking for more details): I am looking for something to set a cr...
[`python-crontab`](http://pypi.python.org/pypi/python-crontab/) allows you to read and write user crontabs via python programs. ``` from crontab import CronTab tab = CronTab() cron = tab.new(command='/foo/bar') cron.every_reboot() tab.write() ```
Easiest way to serialize a simple class object with simplejson?
2,343,535
21
2010-02-26T17:31:25Z
2,343,640
22
2010-02-26T17:49:22Z
[ "python", "json", "simplejson" ]
I'm trying to serialize a list of python objects with JSON (using simplejson) and am getting the error that the object "is not JSON serializable". The class is a simple class having fields that are only integers, strings, and floats, and inherits similar fields from one parent superclass, e.g.: ``` class ParentClass:...
I've used this strategy in the past and been pretty happy with it: Encode your custom objects as JSON object literals (like Python `dict`s) with the following structure: ``` { '__ClassName__': { ... } } ``` That's essentially a one-item `dict` whose single key is a special string that specifies what kind of object is...
NLP project, python or C++
2,344,081
2
2010-02-26T18:56:41Z
2,344,106
7
2010-02-26T19:02:29Z
[ "c++", "python", "boost", "nlp" ]
We are working on Arabic Natural Language Processing project, we have limited our choices to either write the code in Python or C++ (and Boost library). We are thinking of these points: * Python + Slower than C++ (There is ongoing work to make Python faster) + Better UTF8 support + Faster in writing tests and t...
Write it in Python, profile it, and if you need to speed parts of it up, write them in C++. Python and C++ are similar enough that the "familiar" advantage with C++ will be irrelevant pretty quick. I say this as someone who has developed primarily in C++ and has recently gotten serious with Python. I like them both, b...
NLP project, python or C++
2,344,081
2
2010-02-26T18:56:41Z
2,344,124
9
2010-02-26T19:05:50Z
[ "c++", "python", "boost", "nlp" ]
We are working on Arabic Natural Language Processing project, we have limited our choices to either write the code in Python or C++ (and Boost library). We are thinking of these points: * Python + Slower than C++ (There is ongoing work to make Python faster) + Better UTF8 support + Faster in writing tests and t...
Although this is subjective and argumentative, there is evidence that you can write a successful NLP project in python like [NLTK](http://code.google.com/p/nltk/). They also have a [comparison of NLP functionality in different languages](http://nltk.googlecode.com/svn/trunk/doc/howto/nlp-python.html): --- (Quoting fr...
Python script is running. I have a method name as a string. How do I call this method?
2,344,212
5
2010-02-26T19:20:54Z
2,344,226
7
2010-02-26T19:23:18Z
[ "python" ]
everyone. Please see example below. I'd like to supply a string to 'schedule\_action' method which specifies, what Bot-class method should be called. In the example below I've represented it as 'bot.action()' but I have no idea how to do it correctly. Please help ``` class Bot: def work(self): pass def fight(s...
In short, ``` getattr(bot, action)() ``` getattr will look up an attribute on the object by name -- attributes can be data or member methods The extra `()` at the end calls the method. You could get the method in a separate step, like this, as well: ``` method_to_call = getattr(bot, action) method_to_call() ``` An...
Python script is running. I have a method name as a string. How do I call this method?
2,344,212
5
2010-02-26T19:20:54Z
2,344,228
13
2010-02-26T19:23:27Z
[ "python" ]
everyone. Please see example below. I'd like to supply a string to 'schedule\_action' method which specifies, what Bot-class method should be called. In the example below I've represented it as 'bot.action()' but I have no idea how to do it correctly. Please help ``` class Bot: def work(self): pass def fight(s...
Use [getattr](http://docs.python.org/library/functions.html#getattr): ``` class Bot: def fight(self): print "fighting is fun!" class Scheduler: def schedule_action(self,action): bot = Bot() getattr(bot,action)() scheduler = Scheduler() scheduler.schedule_action('fight') ``` Note ...