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
Sorting JSON data by keys value
13,438,574
3
2012-11-18T08:23:34Z
13,438,666
9
2012-11-18T08:39:20Z
[ "python", "json", "discogs-api" ]
I am currently getting JSON data from the discogs API (mp3 tag data) and wish to sort the results by the key's value. In this case I am trying to get data for a Guns n Roses song and the output has 1988 as the first one while the data actually has a record from 1987. How can I sort this data so that I can get to the so...
Something like this: ``` #filter json_object['results'] first, as some of the items are missing the key 'year' In [33]: results=[x for x in json_object['results'] if 'year' in x] In [34]: sorted(results,key=lambda x:x['year']) ``` **or :** ``` In [80]: sorted(results,key=itemgetter('year')) ```
How to filter rows of Pandas dataframe by checking whether sub-level index value within a list?
13,439,098
4
2012-11-18T09:56:00Z
13,447,678
10
2012-11-19T04:26:44Z
[ "python", "pandas" ]
I have a sample Pandas dataframe `df` which has multi\_level index: ``` >>> df STK_Name ROIC mg_r STK_ID RPT_Date 002410 20111231 ??? 0.401 0.956 300204 20111231 ??? 0.375 0.881 300295 20111231 ???? 2.370 0.867 300288 20111231 ???? 1.195 0.861 600106...
How about using the `level` parameter in [`DataFrame.reindex`](http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.reindex.html)? ``` In [14]: df Out[14]: 0 1 a 0 0.007288 -0.840392 1 0.652740 0.597250 b 0 -1.197735 0.822150 1 -0.242030 -0.655058 In [15]: stk_list = ['a'] ...
How to filter rows of Pandas dataframe by checking whether sub-level index value within a list?
13,439,098
4
2012-11-18T09:56:00Z
13,453,153
9
2012-11-19T11:48:31Z
[ "python", "pandas" ]
I have a sample Pandas dataframe `df` which has multi\_level index: ``` >>> df STK_Name ROIC mg_r STK_ID RPT_Date 002410 20111231 ??? 0.401 0.956 300204 20111231 ??? 0.375 0.881 300295 20111231 ???? 2.370 0.867 300288 20111231 ???? 1.195 0.861 600106...
You can try: ``` df[df.index.map(lambda x: x[0] in stk_list)] ``` Example: ``` In : stk_list Out: ['600106', '300204', '300113'] In : df Out: STK_Name ROIC mg_r STK_ID RPT_Date 002410 20111231 ??? 0.401 0.956 300204 20111231 ??? 0.375 0.881 300295 20111231 ???? 2.370 0.867 30...
Pros and cons to use Celery vs. RQ
13,440,875
27
2012-11-18T14:04:29Z
29,837,939
31
2015-04-24T02:54:53Z
[ "python", "web-applications", "redis", "scheduled-tasks", "celery" ]
Currently I'm working on python project that requires implement some background jobs (mostly for email sending and heavily database updates). I use Redis for task broker. So in this point I have two candidates: [Celery](http://celeryproject.org/) and [RQ](http://python-rq.org/). I had some experience with these job que...
Here is what I have found while trying to answer this exact same question. It's probably not comprehensive, and may even be inaccurate on some points. In short, RQ is designed to be simpler all around. Celery is designed to be more robust. They are both excellent. * Documentation. [RQ's documentation](http://python-r...
When I try to run vim in command line I get Python errors
13,441,820
9
2012-11-18T16:05:15Z
14,248,264
8
2013-01-09T23:21:07Z
[ "python", "vim", "terminal" ]
When I try running vim in the Terminal (so as to follow [@romainl's suggestion in my other question](http://stackoverflow.com/a/13438459/1622940)) I get lots of Python errors, which all boil down to: ``` IOError: invalid Python installation: unable to open /usr/include/python2.7/pyconfig.h (No such file or directory) ...
Just had the exact IOError while installing [spf13-vim](https://github.com/spf13/spf13-vim) on my dev machine... This fixes the problem: ``` $ sudo mkdir -p /usr/include/python2.7 $ sudo ln -s /System/Library/Frameworks/Python.framework/Versions/Current/include/python2.7/pyconfig.h /usr/include/python2.7/pyconfig.h `...
Regular Expression to extract parts of Twitter query
13,442,431
4
2012-11-18T17:11:40Z
13,442,494
7
2012-11-18T17:17:16Z
[ "python", "regex", "python-2.7" ]
I have the following string from which I want to extract the `q` and `geocode` values. ``` ?since_id=261042755432763393&q=salvia&geocode=39.862712%2C-75.33958%2C10mi ``` I've tried the following regular expression. ``` expr = re.compile('\[\=\](.*?)\[\&\]') vals = expr.match(str) ``` However, vals is `None`. I'm a...
No need for a regex (using Python 3): ``` >>> from urllib.parse import parse_qs >>> query = parse_qs(str[1:]) >>> query {'q': ['salvia'], 'geocode': ['39.862712,-75.33958,10mi'], 'since_id': ['261042755432763393']} >>> query['q'] ['salvia'] >>> query['geocode'] ['39.862712,-75.33958,10mi'] ``` Obviously, `str` contai...
How do I determine if sys.stdin is redirected from a file vs. piped from another process?
13,442,574
16
2012-11-18T17:25:18Z
13,443,424
21
2012-11-18T18:55:08Z
[ "python", "stdin", "io-redirection" ]
In a simple Python script intended to be run from the shell, can I reliably determine whether sys.stdin has been redirected from an actual file vs. piped from another process? I want to change runtime behavior depending on whether stdin is coming from a data file vs. streaming from another process via a pipe. As expe...
You're looking for [`stat`](http://docs.python.org/library/stat.html#module-stat) macros: ``` import os, stat mode = os.fstat(0).st_mode if stat.S_ISFIFO(mode): print "stdin is piped" elif stat.S_ISREG(mode): print "stdin is redirected" else: print "stdin is terminal" ```
Iterating over an unknown number of nested loops in python
13,443,006
14
2012-11-18T18:10:49Z
13,443,028
21
2012-11-18T18:12:15Z
[ "python", "list", "combinations" ]
I have a variable number of user-defined lists, each containing words. For example, there may be three lists like the following: ``` list1 = ["THE", "A"] list2 = ["ELEPHANT", "APPLE", "CAR"] list3 = ["WALKED", "DROVE", "SAT"] ``` What I want is to iterate over every combination in each list, checking each against a d...
[`itertools.product`](http://docs.python.org/2/library/itertools.html#itertools.product) does exactly what you want: ``` from itertools import product lists = [ ['THE', 'A'], ['ELEPHANT', 'APPLE', 'CAR'], ['WALKED', 'DROVE', 'SAT'] ] for items in product(*lists): print items ```
Python: setup.py missing: No such file or directory
13,443,472
6
2012-11-18T19:01:28Z
13,445,125
11
2012-11-18T22:07:48Z
[ "python", "osx", "python-2.7" ]
I tried to update the libxml2 & libxslt packages as mine are too old to run with lxml. I found a walkthrough [here](http://stackoverflow.com/a/9797504/1794223) and tried to update the package with the command ``` sudo python setup.py install ``` but what I got was this error message: ``` /opt/local/Library/Framework...
To make this a formal answer from my comment... setup.py is not part of the python installation location. It is included with the package that you wish to install. Change directories to the location of the source that you downloaded and then run the setup.py file.
Python + Django on Android
13,444,534
7
2012-11-18T21:01:29Z
13,445,259
9
2012-11-18T22:26:12Z
[ "android", "python", "django" ]
I am a Django developer and wanted to know if anyone has any idea of the possibilities of installing and developing on Django using an Android tablet such as the nexus 7. This seems like a reasonably powerful device, can be hooked up with a bluetooth keyboard, and has linux at the core of the OS. So - is it possible t...
We're developing [PythonAnywhere](https://www.pythonanywhere.com) to fill just this kind of niche. We tuned it to work with the iPad first. But it seems that the Nexus 7 is popular enough now that there might be enough demand to do the same thing for Android.
Implementing breadcrumbs in Python using Flask?
13,444,666
6
2012-11-18T21:15:23Z
13,637,060
9
2012-11-30T00:07:07Z
[ "python", "navigation", "flask", "breadcrumbs" ]
I want breadcrumbs for navigating my [Flask](http://flask.pocoo.org) app. An option could be to use a general Python module like [bread.py](http://russell.ballestrini.net/a-homegrown-python-bread-crumb-module/): > The bread object accepts a url string and grants access to the url > crumbs (parts) or url links (list of...
So you're after "path/history" breadcrumbs, rather than "location" breadcrumbs to use the terminology from the [wikipedia article](http://en.wikipedia.org/wiki/Breadcrumb_%28navigation%29)? If you want to have access to the user's history of visited links, then you're going to have to save them in a session. I've had ...
Replacing blank values (white space) with NaN in pandas
13,445,241
34
2012-11-18T22:22:39Z
13,445,630
18
2012-11-18T23:15:17Z
[ "python", "pandas" ]
I want to find all values in a Pandas dataframe that contain whitespace (any arbitrary amount) and replace those values with NaNs. Any ideas how this can be improved? Basically I want to turn this: ``` A B C 2000-01-01 -0.532681 foo 0 2000-01-02 1.490752 bar 1 2000-01-03 -1.387326 ...
How about: ``` d = d.applymap(lambda x: np.nan if isinstance(x, basestring) and x.isspace() else x) ``` The `applymap` function applies a function to every cell of the dataframe.
Replacing blank values (white space) with NaN in pandas
13,445,241
34
2012-11-18T22:22:39Z
21,942,746
40
2014-02-21T18:48:53Z
[ "python", "pandas" ]
I want to find all values in a Pandas dataframe that contain whitespace (any arbitrary amount) and replace those values with NaNs. Any ideas how this can be improved? Basically I want to turn this: ``` A B C 2000-01-01 -0.532681 foo 0 2000-01-02 1.490752 bar 1 2000-01-03 -1.387326 ...
I think `df.replace()` does the job: ``` df = pd.DataFrame([ [-0.532681, 'foo', 0], [1.490752, 'bar', 1], [-1.387326, 'foo', 2], [0.814772, 'baz', ' '], [-0.222552, ' ', 4], [-1.176781, 'qux', ' '], ], columns='A B C'.split(), index=pd.date_range('2000-01-01','2000-01-06')) p...
Python ctypes: how to free memory? Getting invalid pointer error
13,445,568
13
2012-11-18T23:06:48Z
13,452,473
16
2012-11-19T11:04:45Z
[ "c++", "python", "c", "ctypes" ]
I want to get some string from a C/C++ library with ctypes into python. My code looks like this: Code in lib: ``` const char* get(struct something *x) { [...] // buf is a stringstream return strdup(buf.str().c_str()); } void freeme(char *ptr) { free(ptr); } ``` Python code: ``` fillprototype(lib.ge...
As David Schwartz pointed out, if you set restype to `c_char_p`, ctypes returns a regular Python string object. A simple way to get around this is to use a `void *` and cast the result: string.c: ``` #include <stdlib.h> #include <string.h> #include <stdio.h> char *get(void) { char *buf = "Hello World"; char ...
Django: CSS Is not not working
13,446,325
3
2012-11-19T00:55:20Z
13,446,661
11
2012-11-19T01:48:51Z
[ "python", "html", "css", "django", "web" ]
I am still new to django and I am having problem with my CSS working. I have followed the direction from the link: [Django Static Link tutorial](https://docs.djangoproject.com/en/dev/howto/static-files/), on handling static files. But it is still not working. ## Settings ``` # Absolute path to the directory static ...
For Django to serve static files, you have to make sure you have a couple of settings. **STATIC\_URL** This setting specifies what url should static files map to under. You have that done already. **STATICFILES\_DIRS** This specifies all the folders on your system where Django should look for static files. The idea...
Python multiprocessing safely writing to a file
13,446,445
16
2012-11-19T01:13:12Z
13,530,258
34
2012-11-23T13:38:36Z
[ "python", "io", "multiprocessing", "mutex" ]
I am trying to solve a big numerical problem which involves lots of subproblems, and I'm using Python's multiprocessing module (specifically Pool.map) to split up different independent subproblems onto different cores. Each subproblem involves computing lots of sub-subproblems, and I'm trying to effectively memoize the...
@GP89 mentioned a good solution. Use a queue to send the writing tasks to a dedicated process that has sole write access to the file. All the other workers have read only access. This will eliminate collisions. Here is an example that uses apply\_async, but it will work with map too: ``` import multiprocessing as mp i...
Python Pandas: remove entries based on the number of occurrences
13,446,480
13
2012-11-19T01:20:07Z
13,447,176
16
2012-11-19T03:17:23Z
[ "python", "numpy", "python-2.7", "pandas" ]
I'm trying to remove entries from a data frame which occur less than 100 times. The data frame `data` looks like this: ``` pid tag 1 23 1 45 1 62 2 24 2 45 3 34 3 25 3 62 ``` Now I count the number of tag occurrences like this: ``` bytag = data.groupby('tag').aggregate(np.count_...
Edit: Thanks to @WesMcKinney for showing this much more direct way: ``` data[data.groupby('tag').pid.transform(len) > 1] ``` --- ``` import pandas import numpy as np data = pandas.DataFrame( {'pid' : [1,1,1,2,2,3,3,3], 'tag' : [23,45,62,24,45,34,25,62], }) bytag = data.groupby('tag').aggregate(np.coun...
Python Pandas: remove entries based on the number of occurrences
13,446,480
13
2012-11-19T01:20:07Z
18,357,933
16
2013-08-21T12:51:45Z
[ "python", "numpy", "python-2.7", "pandas" ]
I'm trying to remove entries from a data frame which occur less than 100 times. The data frame `data` looks like this: ``` pid tag 1 23 1 45 1 62 2 24 2 45 3 34 3 25 3 62 ``` Now I count the number of tag occurrences like this: ``` bytag = data.groupby('tag').aggregate(np.count_...
New in 0.12, groupby objects have a [`filter`](http://pandas.pydata.org/pandas-docs/dev/groupby.html#filtration) method, allowing you to do these types of operations: ``` In [11]: g = data.groupby('tag') In [12]: g.filter(lambda x: len(x) > 1) # pandas 0.13.1 Out[12]: pid tag 1 1 45 2 1 62 4 2 45 ...
Python 2.7 creating a multidimensional list
13,447,882
6
2012-11-19T04:56:18Z
13,448,022
9
2012-11-19T05:11:49Z
[ "python", "list", "python-2.7", "list-comprehension" ]
In Python I want an intuitive way to create a 3 dimensional list. I want an (n by n) list. So for n = 4 it should be: ``` x = [[[],[],[],[]],[[],[],[],[]],[[],[],[],[]],[[],[],[],[]]] ``` I've tried using: ``` y = [n*[n*[]]] y = [[[]]* n for i in range(n)] ``` Which both appear to be creating copies of a refer...
I think your list comprehension versions were very close to working. You don't need to do any list multiplication (which doesn't work with empty lists anyway). Here's a working version: ``` >>> y = [[[] for i in range(n)] for i in range(n)] >>> print y [[[], [], [], []], [[], [], [], []], [[], [], [], []], [[], [], []...
Python, return multiple arrays in new lines
13,448,060
3
2012-11-19T05:17:18Z
13,448,258
8
2012-11-19T05:37:49Z
[ "python" ]
I have 3 arrays, a1, a2, a3 I would like to return all three of them at once. I have `return a1, a2, a3` but it returns them all on the same line, I was wondering how I would return them each on a new line
Do you mean like this? ``` >>> def f(): ... a1 = [1, 2, 3] ... a2 = [4, 5, 6] ... a3 = [7, 8, 9] ... return a1, a2, a3 ... >>> f() ([1, 2, 3], [4, 5, 6], [7, 8, 9]) ``` You can unpack the return value like this ``` >>> b1, b2, b3 = f() >>> b1 [1, 2, 3] >>> b2 [4, 5, 6] >>> b3 [7, 8, 9] ``` Or print it on 3...
Pythons many ways of string formatting — are the older ones (going to be) deprecated?
13,451,989
49
2012-11-19T10:33:16Z
13,452,357
29
2012-11-19T10:57:05Z
[ "python", "string-formatting", "deprecated" ]
Python has at least five ways of formatting a string: ``` In [1]: world = "Earth" # method 1a In [2]: "Hello, %s" % world Out[2]: 'Hello, Earth' # method 1b In [3]: "Hello, %(planet)s" % {"planet": world} Out[3]: 'Hello, Earth' # method 2a In [4]: "Hello, {0}".format(world) Out[4]: 'Hello, Earth' # method 2b In [5...
The new [`.format()` method](http://docs.python.org/2/library/stdtypes.html#str.format) is meant to replace the old `%` formatting syntax. The latter has been de-emphasised, (but not officially deprecated *yet*). The method documentation states as much: > This method of string formatting is the new standard in Python ...
Pythons many ways of string formatting — are the older ones (going to be) deprecated?
13,451,989
49
2012-11-19T10:33:16Z
13,452,395
14
2012-11-19T11:00:00Z
[ "python", "string-formatting", "deprecated" ]
Python has at least five ways of formatting a string: ``` In [1]: world = "Earth" # method 1a In [2]: "Hello, %s" % world Out[2]: 'Hello, Earth' # method 1b In [3]: "Hello, %(planet)s" % {"planet": world} Out[3]: 'Hello, Earth' # method 2a In [4]: "Hello, {0}".format(world) Out[4]: 'Hello, Earth' # method 2b In [5...
Guido's latest position on this seems to be indicated here: [What’s New In Python 3.0](http://docs.python.org/3/whatsnew/3.0.html) > PEP 3101: A New Approach To String Formatting > > A new system for built-in string formatting operations replaces > the % string formatting operator. (However, the % operator is still...
Pythons many ways of string formatting — are the older ones (going to be) deprecated?
13,451,989
49
2012-11-19T10:33:16Z
13,454,823
28
2012-11-19T13:29:46Z
[ "python", "string-formatting", "deprecated" ]
Python has at least five ways of formatting a string: ``` In [1]: world = "Earth" # method 1a In [2]: "Hello, %s" % world Out[2]: 'Hello, Earth' # method 1b In [3]: "Hello, %(planet)s" % {"planet": world} Out[3]: 'Hello, Earth' # method 2a In [4]: "Hello, {0}".format(world) Out[4]: 'Hello, Earth' # method 2b In [5...
The `%` operator for string formatting is not deprecated, and is not going to be removed - despite the other answers. Every time the subject is raised on Python development list, there is strong controversy on which is better, but no controversy on whether to remove the classic way - it will stay. Despite being denot...
Pythons many ways of string formatting — are the older ones (going to be) deprecated?
13,451,989
49
2012-11-19T10:33:16Z
23,381,153
13
2014-04-30T06:30:30Z
[ "python", "string-formatting", "deprecated" ]
Python has at least five ways of formatting a string: ``` In [1]: world = "Earth" # method 1a In [2]: "Hello, %s" % world Out[2]: 'Hello, Earth' # method 1b In [3]: "Hello, %(planet)s" % {"planet": world} Out[3]: 'Hello, Earth' # method 2a In [4]: "Hello, {0}".format(world) Out[4]: 'Hello, Earth' # method 2b In [5...
Looking at the older Python docs and PEP 3101 there was a statement that the % operator will be deprecated and removed from the language in the future. The [following statement](https://docs.python.org/3.2/tutorial/inputoutput.html#old-string-formatting) was in the Python docs for Python 3.0, 3.1, and 3.2: > Since str...
What to use to do multiple correlation?
13,452,353
3
2012-11-19T10:56:52Z
13,456,112
8
2012-11-19T14:44:57Z
[ "python", "correlation", "statsmodels" ]
I am trying to use python to compute multiple linear regression and multiple correlation between a response array and a set of arrays of predictors. I saw the very simple example to compute multiple linear regression, which is easy. But how to compute multiple correlation with statsmodels? or with anything else, as an ...
You could certainly do this with statsmodels and pandas. Something like this might get you started ``` import pandas import statsmodels.api as sm from statsmodels.formula.api import ols data = pandas.DataFrame([["A", 4, 0, 1, 27], ["B", 7, 1, 1, 29], ["C", 6, 1, 0, ...
os.walk without hidden folders
13,454,164
18
2012-11-19T12:48:23Z
13,454,267
45
2012-11-19T12:54:02Z
[ "python", "linux", "os.walk" ]
I need to list all files with the containing directory path inside a folder. I tried to use `os.walk`, which obviously would be the perfect solution. However, it also lists hidden folders and files. I'd like my application not to list any hidden folders or files. Is there any flag you can use to make it not yield any ...
No, there is no option to `os.walk()` that'll skip those. You'll need to do so yourself (which is easy enough): ``` for root, dirs, files in os.walk(path): files = [f for f in files if not f[0] == '.'] dirs[:] = [d for d in dirs if not d[0] == '.'] # use files and dirs ``` Note the `dirs[:] =` slice assig...
Is it possible to import flask configuration values in modules without circular import?
13,454,507
11
2012-11-19T13:09:58Z
13,462,351
13
2012-11-19T21:14:14Z
[ "python", "flask", "circular-dependency", "python-module" ]
I'm using Flask with Blueprints to get a skeleton for my website and I'm having a problem using configuration classes deep in my application. Here's some dummy code that explains how I've set everything up: **websiteconfig.py** ``` class Config(object): pass class ProductionConfig(Config): DEBUG = False class ...
I believe you can use flask's current\_app idiom for that. <http://flask.pocoo.org/docs/api/#flask.current_app> ``` from flask import current_app def test(): return current_app.config.get('some_config_value') ```
Getting file extension in Django template
13,455,052
5
2012-11-19T13:42:42Z
13,455,711
14
2012-11-19T14:21:11Z
[ "python", "django" ]
I have model like this: ``` class File(models.Model): name = models.CharField(max_length=45) description = models.CharField(max_length=100, blank=True) file = models.FileField(upload_to='files') ``` I get all File objects in my view and according to the type of file, I would like to print appropriate a cl...
You're missing a `.get_extension` on your model? That's easy, just add it :-) You can have all sorts of methods on a model. So something like this: ``` class File(models.Model): name = models.CharField(max_length=45) description = models.CharField(max_length=100, blank=True) file = models.FileField(upload_...
Why can't I use `import *` in a function?
13,456,481
10
2012-11-19T15:06:27Z
13,456,584
20
2012-11-19T15:11:53Z
[ "python", "python-2.x" ]
This works as expected ``` def outer_func(): from time import * print time() outer_func() ``` I can define nested functions in the context fine and call them from other nested functions: ``` def outer_func(): def time(): return '123456' def inner_func(): print time() inner_fun...
The compiler has no way of knowing whether the time module exports objects named `time`. The free variables of nested functions are tied to closure cells at compile time. Closure cells themselves point to (local) variables defined in compiled code, as opposed to globals, which are not tied at all. See the [python data...
Splitting a string into a list (but not separating adjacent numbers) in Python
13,457,776
4
2012-11-19T16:14:15Z
13,457,869
8
2012-11-19T16:18:46Z
[ "python", "string", "list" ]
For example, I have: ``` string = "123ab4 5" ``` I want to be able to get the following list: ``` ["123","ab","4","5"] ``` rather than list(string) giving me: ``` ["1","2","3","a","b","4"," ","5"] ```
Find one or more adjacent digits (`\d+`), or if that fails find non-digit, non-space characters (`[^\d\s]+`). ``` >>> string = '123ab4 5' >>> import re >>> re.findall('\d+|[^\d\s]+', string) ['123', 'ab', '4', '5'] ``` If you don't want the letters joined together, try this: ``` >>> re.findall('\d+|\S', string) ['12...
get user profile in django
13,460,426
14
2012-11-19T19:07:54Z
13,460,819
41
2012-11-19T19:34:10Z
[ "python", "django", "django-views" ]
hello i'm new in python and django I need a view that get current user profile I know I shoud use get\_profile from User but I don't know how to use it . i read the django document and It didn't help me. this is what I found from doc: ``` from django.contrib.auth.models import User profile=request.user.get_profile() `...
Django's documentation says it all, specifically the part [Storing additional information about users](https://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users). First you need to define a model somewhere in your `models.py` with fields for the additional information of the user: *...
Apache ImportError: No module named _socket in wsgi deployment on Django
13,460,469
4
2012-11-19T19:10:46Z
13,653,516
12
2012-11-30T21:34:00Z
[ "python", "django", "mod-wsgi", "apache2.2" ]
I am using WSGI 3.3 for Python 2.7.3 (32bit) for Apache 2.2. I downloaded the wsgi from <http://code.google.com/p/modwsgi/downloads/detail?name=mod_wsgi-win32-ap22py27-3.3.so> and just renamed it and transferred it to the APACHE modules. I have been trying to deploy an application but keep on receiving the `ImportErro...
Although reinstalling python might have worked. I figured out that \_socket was a \_socket.pyd file located in the DLLs folder, by adding that to my pythonpath in windows I was able to make my application work. Thank you for everyone's help.
How to redirect all methods of a contained class in Python?
13,460,889
4
2012-11-19T19:39:06Z
13,462,244
9
2012-11-19T21:07:07Z
[ "python", "inheritance", "pandas", "composition" ]
How to implement the composition pattern? I have a class `Container` which has an attribute object `Contained`. I would like to redirect/allow access to all methods of `Contained` class from `Container` by simply calling `my_container.some_contained_method()`. Am I doing the right thing in the right way? I use somethi...
Caveats: * DataFrames have a lot of attributes. If a `DataFrame` attribute is a number, you probably just want to return that number. But if the `DataFrame` attribute is `DataFrame` you probably want to return a `Container`. What should we do if the `DataFrame` attribute is a `Series` or a descriptor? To implement `Co...
Monte Carlo Method in Python
13,461,567
6
2012-11-19T20:22:42Z
13,461,903
11
2012-11-19T20:44:22Z
[ "python", "montecarlo" ]
I've been attempting to use Python to create a script that lets me generate large numbers of points for use in the Monte Carlo method to calculate an estimate to Pi. The script I have so far is this: ``` import math import random random.seed() n = 10000 for i in range(n): x = random.random() y = random.rando...
If you're doing any kind of heavy duty numerical calculation, considering learning `numpy`. Your problem is essentially a one-linear with a numpy setup: ``` import numpy as np N = 10000 pts = np.random.random((N,2)) # Select the points according to your condition idx = (pts**2).sum(axis=1) < 1.0 print pts[idx], i...
making python and fortran friends
13,462,184
5
2012-11-19T21:03:06Z
13,462,640
10
2012-11-19T21:33:43Z
[ "python", "fortran", "f2py" ]
Assume we need to call fortran function, which returns some values, in python program. I found out that rewriting fortran code in such way: ``` subroutine pow2(in_x, out_x) implicit none real, intent(in) :: in_x !f2py real, intent(in, out) :: out_x real, intent(out) :: out_x out_x = in...
I think you just need to change your f2py function signature slightly (so that `out_x` is only `intent(out)` and `in_x` is only `intent(in)`): ``` subroutine pow2(in_x, out_x) implicit none real, intent(in) :: in_x !f2py real, intent(in) :: in_x real, intent(out) :: out_x !f2py real, intent(out) :: out...
Python 2.7 Counting number of dictionary items with given value
13,462,365
10
2012-11-19T21:14:46Z
13,462,397
18
2012-11-19T21:16:25Z
[ "python", "dictionary" ]
first question here, so i will get right to it: using python 2.7 I have a dictionary of items, the keys are an x,y coordinate represented as a tuple: (x,y) and all the values are Boolean values. I am trying to figure out a quick and clean method of getting a count of how many items have a given value. I do NOT need ...
This first part is mostly for fun -- I probably wouldn't use it in my code. ``` sum(d.values()) ``` will get the number of `True` values. (Of course, you can get the number of `False` values by `len(d) - sum(d.values())`). --- Slightly more generally, you can do something like: ``` sum(1 for x in d.values() if som...
Split a string around any characters not specified
13,462,587
4
2012-11-19T21:30:37Z
13,462,632
9
2012-11-19T21:33:24Z
[ "python", "regex", "string" ]
I am looking to be able to split a string into a list around anything that is not a numeral or a dot. Currently the split method only provides a way of doing a positive match for split, is a regex the best route to take in this situation? For example, given the string `"10.23, 10.13.21; 10.1 10.5 and 10.23.32"` This s...
In case you are thinking of `re.findall`: you can use `re.split` with an inverted version of your regex: ``` In [1]: import re In [2]: s = "10.23, 10.13.21; 10.1 10.5 and 10.23.32" In [3]: re.split(r'[^\d\.]+', s) Out[3]: ['10.23', '10.13.21', '10.1', '10.5', '10.23.32'] ```
Round an answer to 2 decimal places in Python
13,463,556
5
2012-11-19T22:34:39Z
13,463,634
9
2012-11-19T22:39:45Z
[ "python", "currency", "rounding" ]
The issue i am having is my rounding my results to 2 decimal places. My app gets the right results, however, i am having difficulty making the app round to the nearest decimal as you would with currency ``` cost = input("\nEnter the 12 month cost of the Order: ") cost = float(cost) print("\n12 Month Cost:", cost * ...
You should use a format specifier: ``` print("6 Month Cost: %.2fUSD" % (cost * .6)) ``` Even better, you shouldn't rely on floating point numbers at all and use the [`decimal`](http://docs.python.org/2/library/decimal.html) module instead, which gives you arbitrary precision and much more control over the rounding me...
TypeError: unhashable type: 'list' when using built-in set function
13,464,152
13
2012-11-19T23:19:01Z
13,464,194
15
2012-11-19T23:21:56Z
[ "python", "list", "duplicates" ]
I have a list containing multiple lists as its elements ``` eg: [[1,2,3,4],[4,5,6,7]] ``` If I use the built in set function to remove duplicates from this list, I get the error ``` TypeError: unhashable type: 'list' ``` The code I'm using is ``` TopP = sorted(set(TopP),reverse=True) ``` where TopP is a list just...
Sets require their items to be *hashable*. Out of types predefined by Python only the immutable ones, such as strings, numbers, and tuples, are hashable. Mutable types, such as lists and dicts, are not hashable because a change of their contents would change the hash and break the lookup code. Since you're sorting the...
pexpect setecho not working
13,464,759
5
2012-11-20T00:19:59Z
27,116,594
7
2014-11-25T00:12:40Z
[ "python", "cisco", "pexpect" ]
I am trying to telnet to Cisco Router and give commands using pexpect. Its working, but the sendline() repeats in the output. even after using setecho to False. Code is: ``` ''' Created on Nov 19, 2012 @author: Amit Barik ''' import pexpect hostname = 'hostname' login_cmd = 'telnet ' + hostname + '.net' username = ...
I know this is a super old question, but I'm responding since I had the same problem when interacting with network devices (not \*nix terminals) and I couldn't find anything on the web that helped. Since there aren't any detailed answers, I wanted to leave one behind for others. Pexpect has 3 logging methods (1. `logf...
Exposing `defaultdict` as a regular `dict`
13,465,681
12
2012-11-20T02:20:11Z
13,465,745
18
2012-11-20T02:29:33Z
[ "python", "python-3.x", "wrapper", "defaultdict" ]
I am using `defaultdict(set)` to populate an internal mapping in a very large data structure. After it's populated, the whole structure (including the mapping) is exposed to the client code. At that point, I don't want anyone modifying the mapping. And nobody does, intentionally. But sometimes, client code may by acci...
<http://docs.python.org/2/library/collections.html#collections.defaultdict> Says: > If the default\_factory attribute is None, this raises a KeyError > exception with the key as argument. What if you just set your defaultdict's default\_factory to None? E.g., ``` >>> d = defaultdict(int) >>> d['a'] += 1 >>> d defaul...
A faster strptime?
13,468,126
5
2012-11-20T07:05:15Z
13,468,161
19
2012-11-20T07:08:28Z
[ "python", "performance", "strptime" ]
I have code which reads vast numbers of dates in 'YYYY-MM-DD' format. Parsing all these dates, so that it can add one, two, or three days then write back in the same format is slowing things down quite considerably. ``` 3214657 14.330 0.000 103.698 0.000 trade.py:56(effective) 3218418 34.757 0.000 66...
Is factor 7 lot enough? ``` datetime.datetime.strptime(a, '%Y-%m-%d').date() # 8.87us datetime.date(*map(int, a.split('-'))) # 1.28us ``` **EDIT:** great idea with explicit slicing: ``` datetime.date(int(a[:4]), int(a[5:7]), int(a[8:10])) # 1.06us ``` that makes factor 8.
Can i use selenium with Scrapy without actual browser opening with python
13,468,755
2
2012-11-20T07:53:28Z
16,050,387
7
2013-04-17T02:26:10Z
[ "python", "selenium", "scrapy" ]
I want to do some web crawling with scrapy and python. I have found few code examples from internet where they use selenium with scrapy. I don't know much about `selenium` but only knows that it automates some web tasks. and browser actually opens and do stuff. but i don't want the actual browser to open but i want ev...
Use PhantomJS instead. You can do `browser = webdriver.PhantomJS()` in selenium v2.32.0.
Python 3: Demystifying encode and decode methods
13,469,591
11
2012-11-20T08:57:26Z
13,469,933
17
2012-11-20T09:17:07Z
[ "python", "unicode", "encoding", "python-3.x" ]
Let's say I have a string in Python: ``` >>> s = 'python' >>> len(s) 6 ``` Now I `encode` this string like this: ``` >>> b = s.encode('utf-8') >>> b16 = s.encode('utf-16') >>> b32 = s.encode('utf-32') ``` What I get from above operations is a bytes array -- that is, `b`, `b16` and `b32` are just arrays of bytes (ea...
First of all, [UTF-32](https://en.wikipedia.org/wiki/UTF-32) is a 4-byte encoding, so its BOM is a four byte sequence too: ``` >>> import codecs >>> codecs.BOM_UTF32 b'\xff\xfe\x00\x00' ``` And because different computer architectures treat byte orders differently (called [Endianess](http://en.wikipedia.org/wiki/Endi...
How to extend model on serializer level with django-rest-framework
13,471,083
4
2012-11-20T10:20:22Z
13,473,702
8
2012-11-20T12:57:51Z
[ "python", "django-rest-framework" ]
My model looks like this: ``` class MenuItem(models.Model): name = models.CharField(max_length=500) components = models.ManyToManyField(Component, through=MenuItemComponent) class Component(models.Model): name = models.CharField(max_length=500) class MenuItemComponent(models.Model): menuItem = models...
First, create a view that will return the MenuItemComponent instances that you're interested in. ``` class ListComponents(generics.ListAPIView): serializer_class = MenuItemComponentSerializer def get_queryset(self): """ Override .get_queryset() to filter the items returned by the list. ...
How to get user's local timezone other than server timezone(UTC) in python?
13,473,175
5
2012-11-20T12:24:33Z
13,473,318
8
2012-11-20T12:34:14Z
[ "python", "datetime", "openerp" ]
In OpenERP, when I try to print the current date and time, it always print the 'UTC' time. But I want to get time in the user timezone . Each user have different timezone.`For example 'CST6CDT'`, 'US/Pacific' or 'Asia/Calcutta'. So I need to get time in user timezone so that I can show the correct datetime in the repor...
Got it. ``` from datetime import datetime from pytz import timezone fmt = "%Y-%m-%d %H:%M:%S" # Current time in UTC now_utc = datetime.now(timezone('UTC')) print now_utc.strftime(fmt) # Convert to US/Pacific time zone now_pacific = now_utc.astimezone(timezone('US/Pacific')) print now_pacific.strftime(fmt) # Conver...
Converting a dictionary into a list
13,473,433
10
2012-11-20T12:41:21Z
13,473,515
24
2012-11-20T12:45:40Z
[ "python", "list", "dictionary" ]
Example: ``` something = { "1": { "2": { "3": { "4": {}, "5": {}, "7": {}, }, "8": { "9": {}, "10": {} }, "11": { "12": { "13":...
You'll need to use a function to flatten your structure: ``` def flatten(d): for key, value in d.iteritems(): yield key for sub in flatten(value): yield sub ``` (The `.iteritems()` should be replaced with `.items()` if you are using Python 3). On python 3.3 and newer, you can also use...
Calculate daily sums using python pandas
13,475,812
3
2012-11-20T14:54:13Z
13,475,925
12
2012-11-20T14:59:23Z
[ "python", "pandas" ]
I'm trying to calculate daily sums of values using pandas. Here's the test file - <http://pastebin.com/uSDfVkTS> This is the code I came up so far: ``` import numpy as np import datetime as dt import pandas as pd f = np.genfromtxt('test', dtype=[('datetime', '|S16'), ('data', '<i4')], delimiter=',') dates = [dt.date...
You can do it directly in Pandas: ``` s = pd.read_csv('test', header=None, index_col=0, parse_dates=True) d = s.groupby(lambda x: x.date()).aggregate(lambda x: sum(x) if len(x) >= 40 else np.nan) X.2 2012-01-01 1128 ```
Convert CSV to mongoimport-friendly JSON using Python
13,478,222
5
2012-11-20T16:59:48Z
13,479,969
9
2012-11-20T18:44:29Z
[ "python", "json", "csv", "geospatial", "mongoimport" ]
I have a 300 mb CSV with 3 million rows worth of city information from Geonames.org. I am trying to convert this CSV into JSON to import into MongoDB with mongoimport. The reason I want JSON is that it allows me to specify the "loc" field as an array and not a string for use with the geospatial index. The CSV is encode...
Python standard library (plus simplejson for decimal encoding support) has all you need: ``` import csv, simplejson, decimal, codecs data = open("in.csv") reader = csv.DictReader(data, delimiter=",", quotechar='"') with codecs.open("out.json", "w", encoding="utf-8") as out: for r in reader: for k, v in r.it...
Round float to x decimals?
13,479,163
13
2012-11-20T17:55:05Z
13,479,195
15
2012-11-20T17:56:40Z
[ "python", "math" ]
Is there a way to round a python float to x decimals? For example: ``` >>> x = roundfloat(66.66666666666, 4) 66.6667 >>>x = roundfloat(1.29578293, 6) 1.295783 ``` I've found ways to trim/truncate them (66.666666666 --> 66.6666), but not round (66.666666666 --> 66.6667).
Use the built-in function `round()`: ``` In [23]: round(66.66666666666,4) Out[23]: 66.6667 In [24]: round(1.29578293,6) Out[24]: 1.295783 ``` help on `round()`: > round(number[, ndigits]) -> floating point number > > Round a number to a given precision in decimal digits (default 0 > digits). This always returns a f...
Round float to x decimals?
13,479,163
13
2012-11-20T17:55:05Z
22,155,830
31
2014-03-03T19:43:37Z
[ "python", "math" ]
Is there a way to round a python float to x decimals? For example: ``` >>> x = roundfloat(66.66666666666, 4) 66.6667 >>>x = roundfloat(1.29578293, 6) 1.295783 ``` I've found ways to trim/truncate them (66.666666666 --> 66.6666), but not round (66.666666666 --> 66.6667).
I feel compelled to provide a counterpoint to Ashwini Chaudhary's answer. Despite appearances, the two-argument form of the `round` function *does not* round a Python float to a given number of decimal places, and it's often not the solution you want, even when you think it is. Let me explain... The ability to round a...
Python using basicConfig method to log to console and file
13,479,295
15
2012-11-20T18:01:40Z
13,479,500
7
2012-11-20T18:14:05Z
[ "python", "file", "logging", "console", "screen" ]
I don't know why this code prints to the screen, but not to the file? File "example1.log" is created, but nothing is written there. ``` #!/usr/bin/env python3 import logging logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(message)s', handlers=[logging.FileHandler...
I can't reproduce it on Python 3.3. The messages are written both to the screen and the `'example2.log'`. On Python <3.3 it creates the file but it is empty. The code: ``` from logging_tree import printout # pip install logging_tree printout() ``` shows that `FileHandler()` is not attached to the root logger on Pyt...
Python using basicConfig method to log to console and file
13,479,295
15
2012-11-20T18:01:40Z
23,681,578
14
2014-05-15T14:43:49Z
[ "python", "file", "logging", "console", "screen" ]
I don't know why this code prints to the screen, but not to the file? File "example1.log" is created, but nothing is written there. ``` #!/usr/bin/env python3 import logging logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(message)s', handlers=[logging.FileHandler...
Try this working fine(tested in python 2.7) for both **console and file** ``` # set up logging to file logging.basicConfig( filename='twitter_effect.log', level=logging.INFO, format= '[%(asctime)s] {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s', datefmt='%H:%M:%S' ) # set up logging to c...
How do I zip keys with individual values in my lists in python?
13,480,031
6
2012-11-20T18:48:37Z
13,480,132
12
2012-11-20T18:54:36Z
[ "python", "key", "dictionary" ]
I am importing a matrix, turning the first row into keys, and turning the rest of the rows into values. I want to zip the keys with each value and put them in a dictionary. ex: If I have the following: ``` k = ['a', 'b'] v = [[1,2], [3,4]] ``` I want to take each value in v (for x in v) and zip them (k and x) then ...
``` >>> [dict(zip(k, x)) for x in v] [{'a': 1, 'b': 2}, {'a': 3, 'b': 4}] ```
Run a Python script from Python prompt such that variables are loaded into the interactive environment
13,480,490
2
2012-11-20T19:19:09Z
13,480,504
7
2012-11-20T19:20:05Z
[ "python" ]
Say I have a (somewhat pointless) Python script ``` #!/usr/bin/python a = 5 ``` Is there a way to run this script from the interactive prompt such that after running if I type `a` I get ``` >>> a 5 ``` and not ``` >>> a Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'a' i...
Import it: ``` from yourscriptname import a ``` Each and every `.py` file in python is a module, and you can simply import it. If the file is called `foo.py`, import `foo`.
Threading in python using queue
13,481,276
17
2012-11-20T20:11:05Z
13,481,512
10
2012-11-20T20:25:38Z
[ "python", "multithreading" ]
I wanted to use threading in python to download lot of webpages and went through the following code which uses queues in one of the website. it puts a infinite while loop. Does each of thread run continuously with out ending till all of them are complete? Am I missing something. ``` #!/usr/bin/env python import Queue...
Setting the thread's to be `daemon` threads causes them to exit when the main is done. But, yes you are correct in that your threads will run continuously for as long as there is something in the `queue` else it will block. The documentation explains this detail [Queue docs](http://docs.python.org/2/library/queue.html...
Parsing unclosed `<br>` tags with BeautifulSoup
13,481,408
5
2012-11-20T20:19:08Z
13,481,540
7
2012-11-20T20:27:04Z
[ "python", "html", "beautifulsoup" ]
BeautifulSoup has logic for closing consecutive `<br>` tags that doesn't do quite what I want it to do. For example, ``` >>> from bs4 import BeautifulSoup >>> bs = BeautifulSoup('one<br>two<br>three<br>four') ``` The HTML would render as ``` one two three four ``` I'd like to parse it into a list of strings, `['one...
``` import bs4 as bs soup = bs.BeautifulSoup('one<br>two<br>three<br>four') print(soup.find_all(text=True)) ``` yields ``` [u'one', u'two', u'three', u'four'] ``` --- Or, using [lxml](http://codespeak.net/lxml/): ``` import lxml.html as LH doc = LH.fromstring('one<br>two<br>three<br>four') print(list(doc.itertext(...
sort a list of tuples alphabetically and by value
13,482,313
4
2012-11-20T21:18:19Z
13,482,368
9
2012-11-20T21:21:31Z
[ "python", "list", "sorting", "import", "tuples" ]
Bit of a python newbie, but I got the following list of tuples. I need a list of tuples whereby the tuples are sorted by value and if the value is the same, sorted alphabetically. Here's a sample: ``` #original list_of_medals = [('Sweden', 24), ('Germany', 16), ('Russia', 10), ('Ireland', 10), ('Spain', 9), ('Albania'...
In this instance, I'd use a lambda function as the `key` argument to `sort()`/`sorted()`: ``` In [59]: sorted(list_of_medals, key=lambda x:(-x[1],x[0])) Out[59]: [('Sweden', 24), ('Germany', 16), ('Ireland', 10), ('Russia', 10), ('Spain', 9), ('Albania', 8), ('Lithuania', 7), ('Iceland', 6), ('Italy', 5), ('...
Twisted reactor is stopped, but program doesn't end?
13,482,550
5
2012-11-20T21:33:22Z
13,484,046
8
2012-11-20T23:34:53Z
[ "python", "twisted" ]
So I'm writing a small script to use with Deluge. Deluge uses Twisted, and I really don't have a firm grasp on how it works. Normally I'd just look up more info on it, but getting started with Twisted would take a *long* time and is beyond the scope of this little project. So I figured I would just ask here. Now, I ha...
reactor handles sigint, sigterm itself (there might be a parameter of `reactor.run()` that disables that). Install `reactor.addSystemEventTrigger('before', 'shutdown', client.disconnect)` instead. See [twisted: catch keyboardinterrupt and shutdown properly](http://stackoverflow.com/q/3453451/4279).
When I use python requests to check a site, if the site redirects me to another page, will I know?
13,482,777
5
2012-11-20T21:47:44Z
13,482,990
8
2012-11-20T22:03:39Z
[ "python", "httplib", "python-requests" ]
What I mean is, if I go to "www.yahoo.com/thispage", and yahoo has set up a filter to redirect /thispage to /thatpage. So whenever someone goes to /thispage, s/he will land on /thatpage. If I use httplib/requests/urllib, will it know that there was a redirection? What error pages? Some sites redirect user to /errorpag...
With `requests`, you get a listing of any redirects in the `.history` attribute of the response object. It returns a Python list. See the [documentation](http://docs.python-requests.org/en/latest/user/quickstart/#redirection-and-history) for more.
How to get an actual Pyramid request when unit testing
13,484,061
4
2012-11-20T23:36:35Z
13,487,580
7
2012-11-21T06:27:21Z
[ "python", "unit-testing", "pyramid" ]
I have a Pyramid app that I'm still trying to learn. I'm supposed to write unit tests for it but I don't know how to build a request. I see that Pyramid has a test module with a `DummyRequest` but this is blank and obviously if I pass that into the views it will fail because it's not populated with the attributes that...
The thing to realize whenever you are unit testing (which is different from functional tests) is that you are testing a small "unit". This unit (your view in this case) does not require a "real" request, nor does it require a fully working system. That view has certain expectations of what an object calling itself a "r...
safe enough 8-character short unique random string
13,484,726
10
2012-11-21T00:52:03Z
13,484,764
17
2012-11-21T00:55:28Z
[ "python", "hash", "random", "cryptography" ]
I am trying to compute 8-character short unique random filenames for, let's say, thousands of files without probable name collision. Is this method safe enough? ``` base64.urlsafe_b64encode(hashlib.md5(os.urandom(128)).digest())[:8] ``` ## Edit To be clearer, I am trying to achieve simplest possible obfuscation of f...
Your current method should be safe enough, but you could also take a look into the [`uuid`](http://docs.python.org/2/library/uuid.html) module. e.g. ``` import uuid print str(uuid.uuid4())[:8] ``` Output: ``` ef21b9ad ```
safe enough 8-character short unique random string
13,484,726
10
2012-11-21T00:52:03Z
13,484,927
11
2012-11-21T01:14:53Z
[ "python", "hash", "random", "cryptography" ]
I am trying to compute 8-character short unique random filenames for, let's say, thousands of files without probable name collision. Is this method safe enough? ``` base64.urlsafe_b64encode(hashlib.md5(os.urandom(128)).digest())[:8] ``` ## Edit To be clearer, I am trying to achieve simplest possible obfuscation of f...
Is there a reason you can't use `tempfile` to generate the names? Functions like `mkstemp` and `NamedTemporaryFile` are absolutely guaranteed to give you unique names; nothing based on random bytes is going to give you that. If for some reason you don't actually want the file created yet (e.g., you're generating file...
Can't install Kivy: Cython/GCC error
13,485,364
16
2012-11-21T02:13:52Z
13,487,660
14
2012-11-21T06:35:01Z
[ "python", "c", "gcc", "cython", "kivy" ]
so I tried to install Kivy following the instructions from the official site: ``` $ sudo apt-get install python-setuptools python-pygame python-opengl \ python-gst0.10 python-enchant gstreamer0.10-plugins-good python-dev \ build-essential libgl1-mesa-dev libgles2-mesa-dev python-pip $ sudo pip install --upgrade c...
Just met the same error. Using of Cython 0.17.1 helps me: ``` sudo pip install Cython==0.17.1 ``` If you want not just fix problem you can go in depth and check what was changed between this two versions. <https://github.com/cython/cython/blob/master/CHANGES.rst#0172-2012-11-20> - here you can find related issues, bu...
Blender Python scripting, trying to prevent UI lock up while doing large calculations
13,485,720
5
2012-11-21T03:06:13Z
16,744,008
12
2013-05-24T21:40:38Z
[ "python", "blender" ]
I am working in blender doing a script for N number of objects. When running my script, it locks up the user interface while it is doing its work. I want to write something that prevents this from happening so i can see what is happening on the screen as well as use my custom UI to show a progress bar. Any ideas on how...
If you want to do large calculations in Blender, and still have a responsive UI you might want to check out model operators with python timers. It would be something like this: ``` class YourOperator(bpy.types.Operator): bl_idname = "youroperatorname" bl_label = "Your Operator" _updating = False _cal...
How to run FFMPEG commands in Django?
13,486,524
3
2012-11-21T04:49:04Z
13,487,094
8
2012-11-21T05:44:56Z
[ "python", "django", "video", "flv" ]
I've spent several weeks of my free time trying to figure out this issue or search for it to no avail and I'm not sure if it is a Python or Django issue and was wondering if anyone could guide me in the right direction. I understand uploading video files and querying them, but I am inexperienced in using FFMPEG with D...
You can use subprocess python module to call ffmpeg once the file is uploaded. ``` import subprocess subprocess.call('ffmpeg -i video.mp4 video.flv') # check the ffmpeg command line :) ``` ffmpeg is quite cpu intensive. You should be careful of this point on a real world web app. The subprocess call will block the ap...
How can i extract only text in scrapy selector in python
13,489,473
10
2012-11-21T08:51:21Z
13,490,664
29
2012-11-21T10:00:44Z
[ "python", "scrapy" ]
I have this code ``` site = hxs.select("//h1[@class='state']") log.msg(str(site[0].extract()),level=log.ERROR) ``` The ouput is ``` [scrapy] ERROR: <h1 class="state"><strong> 1</strong> <span> job containing <strong>php</strong> in <strong>region</strong> paying <strong>$30-40k per ye...
``` //h1[@class='state'] ``` in your above xpath you are selecting `h1` tag that has `class` attribute `state` so thats why its selecting everything that comes in `h1 element` if you just want to select text of `h1` tag all you have to do is ``` //h1[@class='state']/text() ``` if you want to select text of `h1` t...
Format number using LaTeX notation in Python
13,490,292
4
2012-11-21T09:41:10Z
13,490,601
12
2012-11-21T09:57:06Z
[ "python", "formatting", "latex" ]
Using format strings in Python I can easily print a number in "scientific notation", e.g. ``` >> print '%g'%1e9 1e+09 ``` What is the simplest way to format the number in LaTeX format, i.e. 1\times10^{+09}?
The [siunitx](http://ctan.org/pkg/siunitx) LaTeX package solves this for you by allowing you to use the python float value directly without resorting to parsing the resulting string and turning it into valid LaTeX. ``` >>> print "\\num{{{0:.2g}}}".format(1e9) \num{1e+09} ``` When the LaTeX document is compiled, the a...
How do I install PyAudio in virtualenv on Mac OS X 10.7
13,491,401
9
2012-11-21T10:37:54Z
13,493,974
18
2012-11-21T13:07:56Z
[ "python", "osx", "virtualenv", "pyaudio" ]
I have tried ``` easy_install pyaudio ``` and it doesn't work. I get the following: ``` Searching for pyaudio Reading http://pypi.python.org/simple/pyaudio/ Reading http://people.csail.mit.edu/hubert/pyaudio/ Best match: pyaudio 0.2.7 Downloading http://people.csail.mit.edu/hubert/pyaudio/packages/pyaudio-0.2.7.tar....
It seems that you have not installed Portaudio. You can get it from Macports or Homebrew. * `sudo port install portaudio` * `sudo brew install portaudio`
What's the difference between "()" and "[]" when generating in Python?
13,491,601
7
2012-11-21T10:49:34Z
13,491,654
10
2012-11-21T10:51:53Z
[ "python", "list", "tuples", "generator" ]
There is a list: nodes = [20, 21, 22, 23, 24, 25]. I used two ways to generate new 2-dimentional objects: ``` tour1 = (((a,b) for a in nodes )for b in nodes) tour2 = [[(a,b) for a in nodes ]for b in nodes] ``` The type of *tour1* is a generator while *tour2* is a list: ``` In [34]: type(tour1) Out[34]: <type 'gener...
The syntax for a tuple is not parentheses `()`, it's the comma `,`. You can create a tuple without parentheses: ``` x = 1, 2, 3 ``` If you want to create a tuple from a comprehension, just use the `tuple` constructor: ``` tuple(tuple((a,b) for a in nodes )for b in nodes) ```
What's the difference between "()" and "[]" when generating in Python?
13,491,601
7
2012-11-21T10:49:34Z
13,491,681
10
2012-11-21T10:53:08Z
[ "python", "list", "tuples", "generator" ]
There is a list: nodes = [20, 21, 22, 23, 24, 25]. I used two ways to generate new 2-dimentional objects: ``` tour1 = (((a,b) for a in nodes )for b in nodes) tour2 = [[(a,b) for a in nodes ]for b in nodes] ``` The type of *tour1* is a generator while *tour2* is a list: ``` In [34]: type(tour1) Out[34]: <type 'gener...
The fundamental difference is that the first is a generator expression, and the second is a list comprehension. The former only yields elements as they are required, whereas the latter always produces the entire list when the comprehension is run. For more info, see [Generator Expressions vs. List Comprehension](http:...
Unittest: assert right SystemExit code
13,491,724
3
2012-11-21T10:55:29Z
13,491,726
7
2012-11-21T10:55:29Z
[ "python", "unit-testing" ]
I am using [unittest](http://docs.python.org/3.3/library/unittest.html "unittest") to assert that my script raises the right `SystemExit` code. Based on the example from <http://docs.python.org/3.3/library/unittest.html#unittest.TestCase.assertRaises> ``` with self.assertRaises(SomeException) as cm: do_something(...
[SystemExit](http://docs.python.org/2/library/exceptions.html#exceptions.SystemExit) derives directly from BaseException and not StandardError, thus it does not have the attribute `error_code`. Instead of `error_code` you have to use the attribute `code`. The example would look like this: ``` with self.assertRaises(S...
Missing errorbars when using yscale('log') at matplotlib
13,491,829
8
2012-11-21T11:02:04Z
13,492,914
8
2012-11-21T12:08:17Z
[ "python", "matplotlib" ]
In some cases matplotlib shows plot with errorbars errorneously when using logarithmic scale. Suppose these data (within pylab for example): ``` s=[19.0, 20.0, 21.0, 22.0, 24.0] v=[36.5, 66.814250000000001, 130.17750000000001, 498.57466666666664, 19.41] verr=[0.28999999999999998, 80.075044597909169, 71.322124839818571...
The problem is that for some points `v-verr` is becoming negative, values <=0 cannot be shown on a logarithmic axis (`log(x)`, `x<=0` is undefined) To get around this you can use asymmetric errors and force the resulting values to be above zero for the offending points. At any point for which errors are bigger than va...
Missing errorbars when using yscale('log') at matplotlib
13,491,829
8
2012-11-21T11:02:04Z
22,601,015
12
2014-03-24T04:19:09Z
[ "python", "matplotlib" ]
In some cases matplotlib shows plot with errorbars errorneously when using logarithmic scale. Suppose these data (within pylab for example): ``` s=[19.0, 20.0, 21.0, 22.0, 24.0] v=[36.5, 66.814250000000001, 130.17750000000001, 498.57466666666664, 19.41] verr=[0.28999999999999998, 80.075044597909169, 71.322124839818571...
Switch to logarithmic scale, but with this command: ``` plt.yscale('log', nonposy='clip') ``` Analogously, for the x-axis: ``` plt.xscale('log', nonposx='clip') ``` Anyway, if you got a [dev version of matplotlib](https://github.com/matplotlib/matplotlib/tree/master) in the last half year, you would have this clipp...
What is the difference between url() and tuple for urlpatterns in Django?
13,491,922
4
2012-11-21T11:07:05Z
13,492,303
8
2012-11-21T11:26:57Z
[ "python", "django", "url" ]
So in Django the two lines of url code below work the same: ``` urlpatterns = patterns('', url(r'^login/$', 'django.contrib.auth.views.login'), (r'^login/$', 'django.contrib.auth.views.login') ) ``` AFAIK, the only difference is I can define `name='login'` so I can use it for reversing url. But besides this, ...
There is no difference whatsoever. Have a look at the `patterns` function in `django.conf.urls.__init__.py`, if your url is a `list` or `tuple` then it is wrapped up by the `url` function anyway before being appended to the list of available patterns.
Connecting to Microsoft SQL Server through pyODBC on Ubuntu
13,492,369
7
2012-11-21T11:31:27Z
13,828,929
8
2012-12-11T21:39:03Z
[ "python", "sql-server", "linux", "ubuntu", "pyodbc" ]
Am having an issue connecting to a Microsoft SQL Server instance from `pyODBC` within an `Ubuntu (12.10)` machine. The error I am getting back is: ``` pyodbc.Error: ('IM002', '[IM002] [unixODBC][Driver Manager]Data Source name not found, and no default driver specified (0) (SQLDriverConnect)') ``` The connection str...
It looks like you have gotten freeTDS to work correctly since you can use tsql. Have you tried to connect with isql? Look at this [howto](http://tryolabs.com/Blog/2012/06/25/connecting-sql-server-database-python-under-ubuntu/) for a detailed walk through. The part I think you need is in setting up unixodbc a little wa...
How to barplot Pandas dataframe columns aligning by sub-index?
13,492,530
4
2012-11-21T11:42:53Z
13,518,146
8
2012-11-22T18:15:40Z
[ "python", "matplotlib", "pandas" ]
I have a pandas dataframe `df` contains two stocks' financial ratio data : ``` >>> df ROIC ROE STK_ID RPT_Date 600141 20110331 0.012 0.022 20110630 0.031 0.063 20110930 0.048 0.103 20111231 0.063 0.122 20120331 0.017 0.033 20120630 0.032 ...
If you unstack STK\_ID, you can create side by side plots per RPT\_Date. ``` In [55]: dfu = df.unstack("STK_ID") In [56]: fig, axes = subplots(2,1) In [57]: dfu.plot(ax=axes[0], kind="bar") Out[57]: <matplotlib.axes.AxesSubplot at 0xb53070c> In [58]: dfu.plot(ax=axes[1]) Out[58]: <matplotlib.axes.AxesSubplot ...
Celery task with multiple decorators not auto registering task name
13,492,603
7
2012-11-21T11:47:51Z
13,492,661
17
2012-11-21T11:51:42Z
[ "python", "celery", "django-celery" ]
I'm having a task that looks like this ``` from mybasetask_module import MyBaseTask @task(base=MyBaseTask) @my_custom_decorator def my_task(*args, **kwargs): pass ``` and my base task looks like this ``` from celery import task, Task class MyBaseTask(Task): abstract = True default_retry_delay = 10 ...
Use the [`functools.wraps()` decorator](http://docs.python.org/2/library/functools.html#functools.wraps) to ensure that the wrapper returned by `my_custom_decorator` has the correct name: ``` from functools import wraps def my_custom_decorator(func): @wraps(func) def __inner(): return func() retur...
From hexadecimal to one's complement in Python
13,492,826
7
2012-11-21T12:02:52Z
13,492,849
20
2012-11-21T12:04:05Z
[ "python", "bit-manipulation", "ones-complement" ]
Is there an easy way to produce a one's complement in python? For instance, if you take the hex value `0x9E`, I need to convert it to `0x61`. I need to swap the binary 1's for 0's and 0's for 1's. It feels like this should be simple.
Just use [the XOR operator `^`](http://docs.python.org/2/reference/expressions.html#binary-bitwise-operations) against 0xFF: ``` >>> hex(0x9E ^ 0xFF) '0x61' ``` If you need to work with values larger than a byte, you could create the mask from the [`int.bit_length()` method](http://docs.python.org/2/library/stdtypes....
UnicodeEncodeError: 'ascii' codec can't encode characters
13,493,477
7
2012-11-21T12:38:33Z
13,493,603
20
2012-11-21T12:46:52Z
[ "python", "unicode", "elementtree" ]
I have a dict that's feed with url response. Like: ``` >>> d { 0: {'data': u'<p>found "\u62c9\u67cf \u591a\u516c \u56ed"</p>'} 1: {'data': u'<p>some other data</p>'} ... } ``` While using `xml.etree.ElementTree` function on this data values (`d[0]['data']`) I get the most famous error message: `UnicodeEncodeError: '...
You'll have to encode it manually, to UTF-8: ``` ElementTree.fromstring(d[0]['data'].encode('utf-8')) ``` as the API only takes encoded bytes as input. UTF-8 is a good default for such data. It'll be able to decode to unicode again from there: ``` >>> from xml.etree import ElementTree >>> p = ElementTree.fromstring...
Self syntax in python
13,494,786
4
2012-11-21T13:53:19Z
13,494,889
9
2012-11-21T13:58:45Z
[ "python", "class", "oop" ]
Whenever I'm defining a class which has a number of parameters I often find myself doing something like this ``` class myClass(object): def __init__(self,param1,param2,param3, ...): self.param1 = param1 self.param2 = param2 self.param3 = param3 ... ``` My question is: is there a smarte...
You could accept a variable number of named arguments and automatically set them, like this: ``` class MyClass(object): def __init__(self, **kwargs): # variable named arguments for k, v in kwargs.items(): setattr(self, k, v) # set the value of self.k to v, same as self.k = v test = MyClass(par...
Sublime Text 2 - running selected python code in the interpreter
13,495,494
13
2012-11-21T14:33:19Z
13,495,858
10
2012-11-21T14:52:33Z
[ "python", "interpreter", "sublimetext2" ]
While editing a python script in the Sublime Text editor, I would like to run the script line by line, or block after block in the embedded interpreter. Is there a convenient way how to do that? Perfect way for me would be: 1. select a few lines of code 2. hit a shortcut, which will run the selected code inside the i...
There are two choices I think, one can be using PdbSublimeTextSupport, available here: <http://pypi.python.org/pypi/PdbSublimeTextSupport> Or you can try SublimeREPL, that can run Python code: <https://github.com/wuub/SublimeREPL>
How do I make a class in Python behave with Sets?
13,495,943
2
2012-11-21T14:57:00Z
13,495,973
9
2012-11-21T14:58:47Z
[ "python", "set" ]
I have a class. ``` class Part: def __init__(self,name): self.name = name self.count = 0 def __hash__(self): return hash(self.name) def __lt__(self,other): return self.count < other.count def __eq__(self,other): return self.name == self.count ``` I create a bunc...
This looks wrong: ``` def __eq__(self,other): return self.name == self.count ``` Maybe you meant: ``` def __eq__(self,other): return self.name == other.name ```
How to I display why some tests where skipped while using py.test?
13,495,950
13
2012-11-21T14:57:28Z
13,496,073
20
2012-11-21T15:05:24Z
[ "python", "unit-testing", "py.test" ]
I am using `skipIf()` from `unittest` for skipping tests in certain conditions. ``` @unittest.skipIf(condition), "this is why I skipped them!") ``` How do I tell `py.test` to display skipping conditions? I know that for unittest I need to enable the verbose mode (`-v`) but the same parameter added to py.test increas...
When you run py.test, you can pass `-rsx` to report skipped tests. From `py.test --help`: ``` -r chars show extra test summary info as specified by chars (f)ailed, (E)error, (s)skipped, (x)failed, (X)passed. ``` Also see this part of the documentation about skipping: <http://pytest.org...
Python: How to generate a 12-digit random number?
13,496,087
7
2012-11-21T15:06:05Z
13,496,247
18
2012-11-21T15:14:30Z
[ "python" ]
In Python, how to generate a 12-digit random number? Is there any function where we can specify a range like `random.range(12)`? ``` import random random.randint() ``` The output should be a string with 12 digits in the range 0-9 (leading zeros allowed).
Whats wrong with a straightforward approach? ``` >>> import random >>> random.randint(100000000000,999999999999) 544234865004L ``` And if you want it with leading zeros, you need a string. ``` >>> "%0.12d" % random.randint(0,999999999999) '023432326286' ``` **Edit:** My own solution to this problem would be someth...
clean way to accomplish -- if x in [(0, 1, 2), (2, 0, 1), (1, 2, 0)]:?
13,497,170
4
2012-11-21T16:02:32Z
13,497,227
8
2012-11-21T16:04:22Z
[ "python" ]
If not, then a canonical name for a function? 'Cycle' makes sense to me, but that's taken. The example in the header is written for clarity and brevity. Real cases I'm working with have a lot of repetition. (e.g., I want [1, 1, 0, 0, 0, 2, 1] to "match" [0, 0, 2, 1, 1, 1, 0]) This type of thing is obscuring my algori...
You can get the cycles of the list with: ``` def cycles(a): return [ a[i:] + a[:i] for i in range(len(a)) ] ``` You can then check if b is a cycle of a with: ``` b in cycles(a) ``` If the length of the list is long, or if want to make multiple comparison to the same cycles, it may be beneficial (performance wis...
python: getting around division by zero
13,497,891
8
2012-11-21T16:39:01Z
13,497,931
13
2012-11-21T16:43:05Z
[ "python", "numpy", "division" ]
I have a big data set of floating point numbers. I iterate through them and evaluate np.log(x) for each of them. I get ``` RuntimeWarning: divide by zero encountered in log ``` I would like to get around this and return to 0 if this error occurs. I am thinking of define a new function: ``` def safe_ln(x): #retu...
Since the `log` for `x=0` is minus infinite, I'd simply check if the input value is zero and return whatever you want there: ``` def safe_ln(x): if x <= 0: return 0 return math.log(x) ``` **EDIT**: small edit: you should check for all values smaller than or equal to 0. **EDIT 2**: `np.log` is of cour...
python: getting around division by zero
13,497,891
8
2012-11-21T16:39:01Z
13,499,499
18
2012-11-21T18:13:01Z
[ "python", "numpy", "division" ]
I have a big data set of floating point numbers. I iterate through them and evaluate np.log(x) for each of them. I get ``` RuntimeWarning: divide by zero encountered in log ``` I would like to get around this and return to 0 if this error occurs. I am thinking of define a new function: ``` def safe_ln(x): #retu...
You are using a np function, so I can safely guess that you are working on a numpy array? Then the most efficient way to do this is to use the where function instead of a for loop ``` myarray= np.random.randint(10,size=10) result = np.where(myarray>0, np.log(myarray), 0) ``` otherwise you can simply use the log funct...
Python double underscore mangling
13,498,151
5
2012-11-21T16:52:49Z
13,498,227
10
2012-11-21T16:57:35Z
[ "python", "attributes", "python-3.x", "private-methods", "double-underscore" ]
I am a bit confused by this behavior (using python 3.2): ``` class Bar: pass bar = Bar() bar.__cache = None print(vars(bar)) # {'__cache': None} class Foo: def __init__(self): self.__cache = None foo = Foo() print(vars(foo)) # {'_Foo__cache': None} ``` I've read up a bit on how double...
Name mangling occurs during the evaluation of a `class` statement. In the case of `Bar`, the `__cache` attribute is not defined as part of the class, but rather added to a specific object after the fact. (Actually, that may not be entirely correct. Name mangling may occur during the evaluation of the `__new__` method;...
Using Python map() function with keyword arguments
13,499,824
18
2012-11-21T18:33:34Z
13,499,853
42
2012-11-21T18:35:32Z
[ "python", "map-function" ]
Here is the loop I am trying to use a map function on: ``` volume_ids = [1,2,3,4,5] ip = '172.12.13.122' for volume_id in volume_ids: my_function(volume_id, ip=ip) ``` is there a way I can do this? It would be trivial if it weren't for the `ip` parameter, but I'm not sure how to deal with that.
Use [`functools.partial()`](http://docs.python.org/2/library/functools.html#functools.partial): ``` from functools import partial mapfunc = partial(my_function, ip=ip) map(mapfunc, volume_ids) ``` `partial()` creates a new callable, that'll apply any arguments (including keyword arguments) to the wrapped function in...
Using Python map() function with keyword arguments
13,499,824
18
2012-11-21T18:33:34Z
13,499,992
8
2012-11-21T18:44:26Z
[ "python", "map-function" ]
Here is the loop I am trying to use a map function on: ``` volume_ids = [1,2,3,4,5] ip = '172.12.13.122' for volume_id in volume_ids: my_function(volume_id, ip=ip) ``` is there a way I can do this? It would be trivial if it weren't for the `ip` parameter, but I'm not sure how to deal with that.
Here is a lambda approach (not better, just different) ``` volume_ids = [1,2,3,4,5] ip = '172.12.13.122' map(lambda ids: my_function(ids, ip), volume_ids); ```
Scipy : fourier transform of a few selected frequencies
13,499,852
6
2012-11-21T18:35:30Z
13,500,782
7
2012-11-21T19:37:05Z
[ "python", "scipy", "fft" ]
I am using `scipy.fft` on a signal, with a moving window to plot the amplitudes of frequencies changing with time (here is [an example](http://www.presonus.com/uploads/products/media/images/PreSonus_Smaart_Spectra_in_VSL-copy.jpg), time is on X, frequency on Y, and amplitude is the color). However, only a few frequenc...
You're really looking to use the Goertzel Algorithm: <http://en.wikipedia.org/wiki/Goertzel_algorithm>. Basically, it's an FFT at a single point, and efficient if you only need a limited number of frequencies in a signal. If you have trouble pulling apart the algorithm from Wikipedia, ping back, and I'll help you. Also...
loading file in memory using Python
13,500,434
4
2012-11-21T19:14:20Z
13,500,510
8
2012-11-21T19:19:16Z
[ "python", "mmap" ]
I try to load a file in memory with this: ``` import mmap with open(path+fileinput+'example.txt', 'rb') as f: fileinput = mmap.mmap(f.fileno(), 0, prot=mmap.PROT_READ) ``` When I run the code the error: ``` AttributeError: 'module' object has no attribute 'PROT_READ' ```
The `PROT_READ` and `PROT_WRITE` are Unix-specific. You're likely looking for: ``` mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) ``` The [`mmap` page](http://docs.python.org/3/library/mmap.html) actually has different entries for Unix/Windows version.
How to pause and wait for command input in a python script
13,501,363
7
2012-11-21T20:15:25Z
13,501,373
9
2012-11-21T20:16:11Z
[ "python" ]
Is it possible to have a script like the following in python? ``` ... Pause -> Wait for the user to execute some commands in the terminal (e.g. to print the value of a variable, to import a library, or whatever). The script will keep waiting if the user does not input anything. -> Continue execution of the remainin...
if you are using python 2.x: `raw_input()` python 3.x: `input()` Example: ``` # do some stuff in script variable = raw_input('input something!: ') # do stuff with variable ```
Euler Project #3 in Python
13,503,320
3
2012-11-21T22:46:33Z
13,503,414
10
2012-11-21T22:56:04Z
[ "python" ]
I'm trying to solve the Project Euler problem 3 in Python: ``` The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? ``` I know my program is inefficient and oversized, but I just wanted to know why doesn't it work? Here's the code: ``` def check(z): # checks...
The reason is that a list in Python is limited to 536,870,912 elements (see [How Big can a Python Array Get?](http://stackoverflow.com/questions/855191/how-big-can-a-python-array-get)) and when you create the range in your example, the number of elements exceeds that number, causing the error. The fun of Project Euler...
Why is HttpsURLConnection.getServerCertificates() returning different results in Java6 vs Java7?
13,503,861
4
2012-11-21T23:42:14Z
13,511,365
8
2012-11-22T11:05:40Z
[ "java", "python", "ssl", "httpsurlconnection" ]
I have code like this: ``` // configure the SSLContext with a TrustManager SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(new KeyManager[0], new TrustManager[] {new DefaultTrustManager()}, new SecureRandom()); SSLContext.setDefault(ctx); URL url = new URL(urlS...
I would suspect this is due to Server Name Indication support introduced on the client side in Java 7. SNI allows the client to specify the host name within the SSL/TLS initial request, in particular to be able to host multiple host names on the same IP address/port with distinct certificates (what Apache Httpd calls ...
Compound boolean logic in python if
13,504,586
5
2012-11-22T01:15:10Z
13,504,632
8
2012-11-22T01:22:22Z
[ "python" ]
I am trying to test a basic premise in python and it always fails and I can't figure out why. My sys.argv looks like this: ``` ['test.py', 'test'] ``` And my code looks like this: ``` if len(sys.argv) > 1 and sys.argv[1] is 'test': print 'Test mode' ``` But the test is never true. I am sure that I am missing s...
As mentioned above, the main reason is your `test` comparison. Using `is` is different than using `==` as it compares if two *objects* are equal. In this case, you can verify that they are not equal by checking their ids: ``` import sys print id(sys.argv[1]) print id('test') ``` My output: ``` 140335994263232 14033...
Can't get PIL to correctly install on Ubuntu 12.04
13,505,621
5
2012-11-22T03:50:33Z
13,505,677
8
2012-11-22T03:57:34Z
[ "python", "python-imaging-library", "pip" ]
I'm using Ubuntu 12.04 and I'm in PIL-hell. I've tried every suggestion I can find online for ways to install PIL, but I have no luck. I know for a fact I have every dependency. I've tried all of the symlink methods. I've modified the setup.py file to ensure it finds the correct directories. I've also tried building fr...
the simplest way should be the following: ``` sudo apt-get install python-imaging ``` if you need to install in a virtualenv, or want the absolute latest version use pip. First install some stuff pil needs, then run the pip install: ``` sudo apt-get install libjpeg-dev libjpeg62 libjpeg62-dev zlib1g-dev libfreetype6...
Python Split path recursively
13,505,819
4
2012-11-22T04:16:34Z
13,505,966
8
2012-11-22T04:36:35Z
[ "python", "recursion", "path", "split", "tuples" ]
I am trying to split a path given as a string into sub-parts using the "/" as a delimiter **recursively** and passed into a tuple. For ex: "E:/John/2012/practice/question11" should be ('E:', 'John', '2012', 'practice', 'question11'). So I've passed every character excluding the "/" into a tuple but it is not how I wan...
Something like this ``` >>> import os >>> s = "E:/John/2012/practice/question11" >>> os.path.split(s) ('E:/John/2012/practice', 'question11') ``` Notice `os.path.split()` doesn't split up the whole path as `str.split()` would ``` >>> def rec_split(s): ... rest, tail = os.path.split(s) ... if rest == '': ... ...
How to use the function numpy.append
13,506,122
7
2012-11-22T04:55:25Z
13,506,148
13
2012-11-22T04:59:24Z
[ "python", "numpy", "append" ]
I have a problem using the function numpy.append. I wrote the following function as part of a larger piece of code, however, my error is reproduced in the folowing: ``` data = [ [ '3.5', '3', '0', '0', '15', '6', '441', 'some text', 'some more complicated data' ], [ ...
Unlike the list `append` method, numpy's `append` does not append in-place. It returns a new array with the extra elements appended. So you'd need to do `r = np.append(r, float(line[index]))`. Building up numpy arrays in this way is inefficient, though. It's better to just build your list as a Python list and then mak...