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
Removing key values pairs from a list of dictionaries
13,254,241
6
2012-11-06T15:30:14Z
13,254,290
12
2012-11-06T15:33:05Z
[ "python", "list-comprehension" ]
I have a list of dictionaries such as: ``` [{'mykey1':'myvalue1', 'mykey2':'myvalue2'}, {'mykey1':'myvalue1a', 'mykey2':'myvalue2a'}] ``` I need to remove all key values pairs from all dictionaries where the key is equal to mykey1. I could do this by looping through and using the del statement, but I am wondering how...
If you really want to use a list comprehension, combine it with a dict comprehension: ``` [{k: v for k, v in d.iteritems() if k != 'mykey1'} for d in mylist] ``` Substitute `.iteritems()` for `.items()` if you are on python 3. On python 2.6 and below you should use: ``` [dict((k, v) for k, v in d.iteritems() if k !...
beautiful soup get children that are Tags (not Navigable Strings) from a Tag
13,255,308
8
2012-11-06T16:29:24Z
13,291,701
11
2012-11-08T15:08:30Z
[ "python", "beautifulsoup", "tree-traversal" ]
Beautiful soup documentation provides attributes .contents and .children to access the children of a given tag (a list and an iterable respectively), and includes both Navigable Strings and Tags. I want only the children of type Tag. I'm currently accomplishing this using list comprehension: ``` rows=[x for x in tabl...
thanks to [J.F.Sebastian](http://stackoverflow.com/users/4279/j-f-sebastian) , the following will work: ``` rows=table.tbody.find_all(True, recursive=False) ``` Documentation here: <http://www.crummy.com/software/BeautifulSoup/bs4/doc/#true> In my case, I needed actual rows in the table, so I ended up using the foll...
Pandas: Creating aggregated column in DataFrame
13,256,917
13
2012-11-06T18:17:32Z
13,257,677
16
2012-11-06T19:07:38Z
[ "python", "pandas" ]
With the DataFrame below as an example, ``` In [83]: df = pd.DataFrame({'A':[1,1,2,2],'B':[1,2,1,2],'values':np.arange(10,30,5)}) df Out[83]: A B values 0 1 1 10 1 1 2 15 2 2 1 20 3 2 2 25 ``` What would be a simple way to generate a new column containing some aggregation of the data ...
``` In [20]: df = pd.DataFrame({'A':[1,1,2,2],'B':[1,2,1,2],'values':np.arange(10,30,5)}) In [21]: df Out[21]: A B values 0 1 1 10 1 1 2 15 2 2 1 20 3 2 2 25 In [22]: df['sum_values_A'] = df.groupby('A')['values'].transform(np.sum) In [23]: df Out[23]: A B values sum_values_A 0...
Python function on the command line not working
13,257,491
4
2012-11-06T18:55:52Z
13,257,508
10
2012-11-06T18:57:16Z
[ "python", "command-line" ]
Consider this simple python: ``` def cube(x): return x*x*x; if __name__ == '__main__': print(cube(4)); ``` Works ok. But when I open up the python command line interpreter and do: ``` >>> def cube(x): return x*x*x; ... cube(4); ``` I get: ``` File "<stdin>", line 2 cube(4); ^ SyntaxEror: invalid ...
Try pressing enter one more time :) The ellipse in front of your `cube(4)` indicates that you are still defining your function. Also, you can remove the semicolon: ``` >>> def cube(x): return x*x*x ... >>> cube(4) 64 ```
python os.fdopen(os.open()) can't be used for writing?
13,257,748
5
2012-11-06T19:11:30Z
13,257,869
7
2012-11-06T19:20:29Z
[ "python" ]
This question has to do with the answer to [Write file with specific permissions in Python](http://stackoverflow.com/questions/5624359/write-file-with-specific-permissions-in-python) for opening a file for writing (in python) with specific permissions. The code in the answer looks like: ``` with os.fdopen(os.open('fo...
You must choose one of O\_RDONLY, O\_WRONLY or O\_RDWR as a "basic" mode argument to open(). You did not explicitly do so, so O\_RDONLY (zero on many systems) is assumed. Python's `os.fdopen` sees that you have specified a O\_RDONLY *and* O\_APPEND, which is a bit silly. Python complains about this combination with th...
Efficient scheduling of university courses
13,257,826
7
2012-11-06T19:17:07Z
13,258,093
8
2012-11-06T19:35:20Z
[ "python", "algorithm", "scheduling" ]
I'm currently working on a website that will allow students from my university to automatically generate valid schedules based on the courses they'd like to take. Before working on the site itself, I decided to tackle the issue of how to schedule the courses efficiently. A few clarifications: 1. Each course at our u...
Scheduling is a very famous [constraint satisfaction problem](http://en.wikipedia.org/wiki/Constraint_satisfaction_problem) that is generally [NP-Complete](http://en.wikipedia.org/wiki/NP-complete). A lot of work has been done on the subject, even in the same context as you: [Solving the University Class Scheduling Pro...
Missing bootstrap resources in Django-Rest-Framework
13,258,087
11
2012-11-06T19:34:36Z
13,258,729
12
2012-11-06T20:19:59Z
[ "python", "django-rest-framework" ]
I'm using the new [django-rest-framework 2.0](http://django-rest-framework.org/topics/rest-framework-2-announcement.html) and have been following the tutorial for creating a rest based API. The API is now complete, however I am having trouble getting the bootstrap resources to load, all return with a 404 Not Found from...
First up, I'm assuming that you mean the bootstrap static resources aren't loading for the browsable API? (Although I guess it could be that you're trying to use them elsewhere in your project?) If you're running with `DEBUG=True` they should be served automatically, but once you're running with `DEBUG=False` you need...
What is a simpler, more pythonic way of expressing the following?
13,258,197
3
2012-11-06T19:42:25Z
13,258,220
14
2012-11-06T19:43:47Z
[ "python" ]
``` return not a and not b ``` ^ how do I express this in a better format
[DeMorgan's Law](http://en.wikipedia.org/wiki/De_Morgan%27s_laws), perhaps? ``` return not (a or b) ``` I think it's sufficiently simple at that point
Alternatives to Dictionary in Python - Need to reference value by named key and iterate in insertion order
13,258,211
2
2012-11-06T19:43:27Z
13,258,275
7
2012-11-06T19:47:48Z
[ "python", "dictionary", "loops" ]
I am using Python and Django and messing around with returning JSON objects as Python dictonaries, but am not content because I can't iterate through my dictionary's elements in the order they were inserted. If I create a dictionary as follows: ``` measurements = { 'units': 'imperial', 'fit': request.POST[ 'fit' ...
You can use a [`collections.OrderedDict`](http://docs.python.org/2/library/collections.html#collections.OrderedDict) to preserve insertion order if you're using py2.7 or newer. **This is a part of the standard library**. For older versions, there's an [activestate recipe](http://code.activestate.com/recipes/576693/) fl...
Convert "unknown format" strings to datetime objects?
13,258,554
8
2012-11-06T20:05:55Z
13,258,582
14
2012-11-06T20:07:49Z
[ "python", "date", "date-conversion" ]
This is probably a very basic question but after reading documentation I still can't figure out how to do it... I have two strings in Python that contain dates of *unknown format*. I don't know what formats they are in, except I know that both are valid date-time expressions. For example, one of them might be in the I...
The [dateutil module](http://niemeyer.net/python-dateutil#head-a23e8ae0a661d77b89dfb3476f85b26f0b30349c) has a date parser which can parse date strings in many formats. For example, ``` In [13]: import dateutil.parser as parser In [14]: parser.parse("19970902T090000") Out[14]: datetime.datetime(1997, 9, 2, 9, 0) In...
Applying LIMIT and OFFSET to all queries in SQLAlchemy
13,258,934
20
2012-11-06T20:34:03Z
13,258,978
19
2012-11-06T20:37:06Z
[ "python", "sqlalchemy", "api-design" ]
I'm designing an API with SQLAlchemy (querying MySQL) and I would like to force all my queries to have page\_size (LIMIT) and page\_number (OFFSET) parameters. Is there a clean way of doing this with SQLAlchemy? Perhaps building a factory of some sort to create a custom Query object? Or maybe there is a good way to do...
Try adding a first, required argument, which must be a group of query filters. Thus, ``` # q({'id': 5}, 2, 50) def q(filters, page=0, page_size=None): query = session.query(...).filter_by(**filters) if page_size: query = query.limit(page_size) if page: query = query.offset(page*page_size) ...
List callbacks?
13,259,179
7
2012-11-06T20:49:53Z
13,259,435
11
2012-11-06T21:07:19Z
[ "python", "list", "callback" ]
Is there any way to make a `list` call a function every time the list is modified? For example: ``` >>>l = [1, 2, 3] >>>def callback(): print "list changed" >>>apply_callback(l, callback) # Possible? >>>l.append(4) list changed >>>l[0] = 5 list changed >>>l.pop(0) list changed 5 ```
Borrowing from the suggestion by @sr2222, here's my attempt. (I'll use a decorator without the syntactic sugar): ``` import sys _pyversion = sys.version_info[0] def callback_method(func): def notify(self,*args,**kwargs): for _,callback in self._callbacks: callback() return func(self,*...
returning a list of words after reading a file in python
13,259,288
5
2012-11-06T20:57:52Z
13,259,326
9
2012-11-06T21:00:26Z
[ "python", "string", "list" ]
I have a text file which is named `test.txt`. I want to read it and return a list of all words (with newlines removed) from the file. This is my current code: ``` def read_words(test.txt): open_file = open(words_file, 'r') words_list =[] contents = open_file.readlines() for i in range(len(contents)): ...
Replace the `words_list.append(...)` line in the for loop with the following: ``` words_list.extend(contents[i].split()) ``` This will split each line on whitespace characters, and then add each element of the resulting list to `words_list`. Or as an alternative method for rewriting the entire function as a list com...
returning a list of words after reading a file in python
13,259,288
5
2012-11-06T20:57:52Z
13,259,605
14
2012-11-06T21:21:12Z
[ "python", "string", "list" ]
I have a text file which is named `test.txt`. I want to read it and return a list of all words (with newlines removed) from the file. This is my current code: ``` def read_words(test.txt): open_file = open(words_file, 'r') words_list =[] contents = open_file.readlines() for i in range(len(contents)): ...
Depending on the size of the file, this seems like it would be as easy as: ``` with open(file) as f: words = f.read().split() ```
self deleting instance
13,259,933
9
2012-11-06T21:46:01Z
13,259,994
7
2012-11-06T21:50:20Z
[ "python" ]
Is it possible to make a class call `del()` for some instances under some condition? Or turn self into None? ``` class T: def __init__(self, arg1, arg2): condition=check_condition(arg1,arg2) if not condition: do_something(arg1) else: del(sel...
> I need do something like this to be sure that will never exist a kind of instance. If you simply want to prevent the creation of such an instance, raise an exception in `__init__()` whenever the condition is satisfied. This is standard protocol for signalling constructor failures. For further discussion, see [Pytho...
Python cos(90) and cos(270) not 0
13,260,296
4
2012-11-06T22:15:50Z
13,260,353
7
2012-11-06T22:20:47Z
[ "python", "math", "cos" ]
What is going on?? Testing out sin and cos functions to find out why I get so beautiful positioning on the wrong places when outputting my coordinates into a SVG file. So I made this test code, which I can predict what the answer is to find out why. Oddly nothing that effects the calculation it self adds this behavior...
Indeed, it is a very low number, awfully close to zero. Here's a great article which can help you understand the common challenges and pitfalls of floats: "[What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html)"
Create new class instance from class method
13,260,557
13
2012-11-06T22:38:53Z
13,260,566
17
2012-11-06T22:40:00Z
[ "python", "object", "copy" ]
I want to be able to create a new instance of an object by calling a method on an already instantiated object. For example, I have the object: `organism = Organism()` I want to be able to call `organism.reproduce()` and have two objects of type Organism. My method at this point looks like this: ``` class Organism(ob...
``` class Organism(object): def reproduce(self): #use self here to customize the new organism ... return Organism() ``` Another option -- if the instance doesn't matter: ``` class Organism(object): @classmethod def reproduce(cls): return cls() ``` This makes sure that Organisms pr...
Python 3.3, returning smallest value in a while loop
13,260,666
2
2012-11-06T22:48:39Z
13,260,705
9
2012-11-06T22:50:44Z
[ "python", "loops", "while-loop", "minimum" ]
I'm trying to return the smallest value for the square root of k using Newton's method. ``` k=float(input("Number? ")) x = k/2 def newton(x): while abs(x**(1/2)- k) >= 10**(-10): if k >= 0: x = (x+k/x)/(2) return x elif k < 0: raise ValueError ("Cannot take the ...
You need to place your `return` statement outside your loop, otherwise it will always return on the first iteration: ``` def newton(x): while abs(x**(1/2)- k) >= 10**(-10): if k >= 0: x = (x+k/x)/(2) elif k < 0: raise ValueError ("Cannot take the square root of a negative nu...
Convert a unixtime to a datetime object and back again (pair of time conversion functions that are inverses)
13,260,863
16
2012-11-06T23:05:08Z
13,260,981
26
2012-11-06T23:18:24Z
[ "python", "date", "datetime", "time", "dst" ]
I'm trying to write a pair of functions, `dt` and `ut`, that convert back and forth between normal unix time (seconds since 1970-01-01 00:00:00 UTC) and a Python datetime object. If `dt` and `ut` were proper inverses then this code would print the same timestamp twice: ``` import time, datetime # Convert a unix time...
You are correct that this behavior is related to daylight savings time. The easiest way to avoid this is to ensure you use a time zone without daylight savings, UTC makes the most sense here. [`datetime.datetime.utcfromtimestamp()`](http://docs.python.org/2/library/datetime.html#datetime.datetime.utcfromtimestamp) and...
pandas pivot dataframe to 3d data
13,261,175
3
2012-11-06T23:39:52Z
13,270,595
8
2012-11-07T13:16:49Z
[ "python", "pandas" ]
There seem to be a lot of possibilities to pivot flat table data into a 3d array but I'm somehow not finding one that works: Suppose I have some data with columns=['name', 'type', 'date', 'value']. When I try to pivot via ``` pivot(index='name', columns=['type', 'date'], values='value') ``` I get ``` ValueError: Buf...
`pivot` only supports using a single column to generate your columns. You probably want to use [`pivot_table`](http://pandas.pydata.org/pandas-docs/stable/reshaping.html#pivot-tables-and-cross-tabulations) to generate a pivot table using multiple columns e.g. ``` pandas.tools.pivot.pivot_table(your_dataframe, values='...
How to pass multiple values for a single URL parameter?
13,261,377
16
2012-11-07T00:07:15Z
13,261,403
26
2012-11-07T00:10:45Z
[ "python", "django", "url", "urlencode" ]
Is it possible to pass multiple values for a single URL parameter without using your own separator? What I want to do is that the backend expects an input parameter `urls` to have one or more values. It can me set to a single or multiple URLs. What is a way to set the urls parameter so it can have multiple values? I c...
``` http://.../?urls=foo&urls=bar&... ``` ... ``` request.GET.getlist('urls') ```
How to pass multiple values for a single URL parameter?
13,261,377
16
2012-11-07T00:07:15Z
13,261,408
7
2012-11-07T00:11:05Z
[ "python", "django", "url", "urlencode" ]
Is it possible to pass multiple values for a single URL parameter without using your own separator? What I want to do is that the backend expects an input parameter `urls` to have one or more values. It can me set to a single or multiple URLs. What is a way to set the urls parameter so it can have multiple values? I c...
The following is probably the best way of doing it - ie, don't specify a delimited list of URLs, rather, use the fact you can specify the same param name multiple times, eg: ``` http://example.com/?url=http://google.co.uk&url=http://yahoo.com ``` The URL list be then be used and retrieved via `request.GET.getlist('ur...
Find maximum value in a list of dictionaries
13,262,382
2
2012-11-07T02:30:53Z
13,262,404
8
2012-11-07T02:35:59Z
[ "python", "data-structures" ]
Given a data structure: ``` [ {'id':0, 'items': [ {'id': 0, name: "Tom1", age: 10}, {'id': 0, name: "Mark1", age: 15}, {'id': 0, name: "Pam1", age: 17} ] }, {'id':1, 'items': [ {'id': 1, name: "Tom12", age: 8}, {'id': 1, name: "Mark12", age: 3}...
Try this: ``` for dVals in yourData: print max(dVals['items'], key=lambda x:x['age']) ``` Or one-liner: ``` print [max(dVals['items'], key=lambda x: x['age']) for dVals in yourData] {'id': 0, 'age': 17, 'name': 'Pam1'} {'id': 1, 'age': 8, 'name': 'Tom12'} {'id': 2, 'age': 77, 'name': 'Pam13'} ```
OpenERP Unique Constraint
13,263,507
13
2012-11-07T05:18:58Z
13,263,587
14
2012-11-07T05:25:51Z
[ "python", "openerp" ]
I have a table in OpenERP/PostgreSQL with the following columns: `name` and `description`. I added the following validation for unique name: ``` _sql_constraints = [('unique_name', 'unique(name)', 'A record with the same name already exists.')] ``` It works fine but it is case sensitive. Currently, it accepts values...
For `case insensitive constraints` check out [HERE](http://archives.postgresql.org/pgsql-general/2005-09/msg00842.php) else you can always use Openerp Constraints instead of SQL . for openerp Constraints check the example ``` def _check_unique_insesitive(self, cr, uid, ids, context=None): sr_ids = self.search(cr...
Do multiprocessing pools give every process the same number of tasks, or are they assigned as available?
13,264,435
12
2012-11-07T06:41:49Z
13,264,865
17
2012-11-07T07:14:55Z
[ "python", "multiprocessing", "pool" ]
When you `map` an iterable to a `multiprocessing.Pool` are the iterations divided into a queue for each process in the pool at the start, or is there a common queue from which a task is taken when a process comes free? ``` def generate_stuff(): for foo in range(100): yield foo def process...
> So given this untested suggestion code; if there are 4 processes in the pool does each process get allocated 25 stuffs to do, or do the 100 stuffs get picked off one by one by processes looking for stuff to do so that each process might do a different number of stuffs, eg 30, 26, 24, 20. Well, the obvious answer is ...
TypeError: unhashable type: 'dict'
13,264,511
42
2012-11-07T06:47:24Z
13,264,725
81
2012-11-07T07:03:52Z
[ "python" ]
This piece of code is giving me an error `unhashable type: dict` can anyone explain me what is the solution ``` negids = movie_reviews.fileids('neg') def word_feats(words): return dict([(word, True) for word in words]) negfeats = [(word_feats(movie_reviews.words(fileids=[f])), 'neg') for f in negids] stopset = se...
You're trying to use a `dict` as a key to another `dict` or in a `set`. That does not work because the keys have to be hashable. As a general rule, only immutable objects (strings, integers, floats, frozensets, tuples of immutables) are hashable (though exceptions are possible). So this does not work: ``` >>> dict_key...
iterating over file object in Python does not work, but readlines() does but is inefficient
13,264,805
2
2012-11-07T07:10:22Z
13,264,832
8
2012-11-07T07:12:25Z
[ "python" ]
In the following code, if I use: ``` for line in fin: ``` It only executes for 'a' But if I use: ``` wordlist = fin.readlines() for line in wordlist: ``` Then it executes for a thru z. But `readlines()` reads the whole file at once, which I don't want. How to avoid this? ``` def avoids(): alphabet = 'abcdef...
the syntax `for line in fin` can only be used once. After you do that, you've exhausted the file and you can't read it again unless you "reset the file pointer" by `fin.seek(0)`. Conversely, `fin.readlines()` will give you a list which you can iterate over and over again. --- I think a simple refactor with [`Counter`...
How to enumerate enum members using SWIG
13,269,393
10
2012-11-07T12:02:33Z
13,406,244
8
2012-11-15T21:08:56Z
[ "c++", "python", "swig" ]
Can I expose a C++ `enum` to SWIG as a real entity rather than a set of constants so I can enumerate over them in python code?
I faced the same issue. I hope that SWIG soon supports C++11's `enum class`. Here's a hack that convinces SWIG to put enums in a structure: ``` #ifdef SWIG %rename(MyEnum) MyEnumNS; #endif struct MyEnumNS { enum Value { Value1, Value2, Value3 }; }; typedef MyEnumNS::Value MyEnum; ``` In `.cpp` code you now must...
cartesian product in pandas
13,269,890
20
2012-11-07T12:33:12Z
13,270,110
19
2012-11-07T12:47:36Z
[ "python", "pandas" ]
I have two pandas dataframes: ``` from pandas import DataFrame df1 = DataFrame({'col1':[1,2],'col2':[3,4]}) df2 = DataFrame({'col3':[5,6]}) ``` What is the best practice to get their cartesian product (of course without writing it explicitly like me)? ``` #df1, df2 cartesian product df_cartesian = DataFrame({'col1':...
If you have a key that is repeated for each row, then you can produce a cartesian product using merge (like you would in SQL). ``` from pandas import DataFrame, merge df1 = DataFrame({'key':[1,1], 'col1':[1,2],'col2':[3,4]}) df2 = DataFrame({'key':[1,1], 'col3':[5,6]}) merge(df1, df2,on='key')[['col1', 'col2', 'col3'...
Python QT ProgressBar
13,269,936
5
2012-11-07T12:36:22Z
13,275,347
7
2012-11-07T17:53:07Z
[ "python", "qt", "pyqt" ]
When using the following code my application stalls after a couple of seconds. And by stalls I mean hangs. I get a window from Windows saying wait or force close. I might add that this only happens when I click either inside the progress bar window or when I click outside of it so it loses focus. If I start the exampl...
You need to allow events to be processed whilst the loop is running so that the application can remain responsive. Even more importantly, for long-running tasks, you need to provide a way for the user to stop the loop once it's started. One simple way to do this is to start the loop with a timer, and then periodicall...
How to manually install a pypi module without pip/easy_install?
13,270,877
18
2012-11-07T13:34:55Z
13,271,241
33
2012-11-07T13:55:58Z
[ "python", "installation", "pip", "growl" ]
I want to use the [gntp module](https://github.com/kfdm/gntp) to display toaster-like notifications for a C/C++ software. I want to package all the dependencies for the soft to be self-executable on a another computer. The gntp module is only available through the pip installer, which cannot be used (The computer whic...
1. Download the package 2. unzip it if it is zipped 3. cd into the directory containing setup.py 4. If there are any installation instructions contained in documentation contianed herein, read and follow the instructions OTHERWISE 5. type in `python setup.py install` You may need administrator privileges for step 5...
Why is startswith slower than slicing
13,270,888
41
2012-11-07T13:35:27Z
13,271,036
8
2012-11-07T13:43:59Z
[ "python", "startswith" ]
Why is the implementation of [`startwith`](http://docs.python.org/2/library/stdtypes.html#str.startswith) slower than slicing? ``` In [1]: x = 'foobar' In [2]: y = 'foo' In [3]: %timeit x.startswith(y) 1000000 loops, best of 3: 321 ns per loop In [4]: %timeit x[:3] == y 10000000 loops, best of 3: 164 ns per loop ``...
`startswith` is more complex than slicing... ``` 2924 result = _string_tailmatch(self, 2925 PyTuple_GET_ITEM(subobj, i), 2926 start, end, -1); ``` This isn't a simple character compare loop for needle in beginning of haystack that's happening. We're looking at a for loop that is iterating through a vector/tuple (subo...
Why is startswith slower than slicing
13,270,888
41
2012-11-07T13:35:27Z
13,271,125
30
2012-11-07T13:48:59Z
[ "python", "startswith" ]
Why is the implementation of [`startwith`](http://docs.python.org/2/library/stdtypes.html#str.startswith) slower than slicing? ``` In [1]: x = 'foobar' In [2]: y = 'foo' In [3]: %timeit x.startswith(y) 1000000 loops, best of 3: 321 ns per loop In [4]: %timeit x[:3] == y 10000000 loops, best of 3: 164 ns per loop ``...
*Some* of the performance difference can be explained by taking into account the time it takes the `.` operator to do its thing: ``` >>> x = 'foobar' >>> y = 'foo' >>> sw = x.startswith >>> %timeit x.startswith(y) 1000000 loops, best of 3: 316 ns per loop >>> %timeit sw(y) 1000000 loops, best of 3: 267 ns per loop >>>...
Why is startswith slower than slicing
13,270,888
41
2012-11-07T13:35:27Z
13,271,349
24
2012-11-07T14:03:18Z
[ "python", "startswith" ]
Why is the implementation of [`startwith`](http://docs.python.org/2/library/stdtypes.html#str.startswith) slower than slicing? ``` In [1]: x = 'foobar' In [2]: y = 'foo' In [3]: %timeit x.startswith(y) 1000000 loops, best of 3: 321 ns per loop In [4]: %timeit x[:3] == y 10000000 loops, best of 3: 164 ns per loop ``...
The comparison isn't fair since you're only measuring the case where `startswith` returns `True`. ``` >>> x = 'foobar' >>> y = 'fool' >>> %timeit x.startswith(y) 1000000 loops, best of 3: 221 ns per loop >>> %timeit x[:3] == y # note: length mismatch 10000000 loops, best of 3: 122 ns per loop >>> %timeit x[:4] == y 1...
How to chain a Celery task that returns a list into a group?
13,271,056
10
2012-11-07T13:45:39Z
13,569,873
20
2012-11-26T17:20:55Z
[ "python", "celery" ]
I want to create a group from a list returned by a Celery task, so that for each item in the task result set, one task will be added to the group. Here's a simple code example to explain the use case. The `???` should be the result from the previous task. ``` @celery.task def get_list(amount): # In reality, fetch...
You can get this kind of behavior using an intermediate task. Here's a demonstration of creating a "map" like method that works like you've suggested. ``` from celery import task, subtask, group @task def get_list(amount): return [i for i in range(amount)] @task def process_item(item): # do stuff pass @...
What is the Python equivalent of map in Ruby and Javascript?
13,271,670
4
2012-11-07T14:23:51Z
13,271,746
11
2012-11-07T14:27:50Z
[ "python", "list", "map" ]
Say for example I want to split string `"12:30-14:40"` and have the result in a matrix like: `[["12","30"],["14","40"]]`. I can do this in JavaScript with: ``` "12:30-14:40".split("-").map(function(x) { return x.split(':'); }); ``` and in Ruby with: ``` "12:30-14:40".split("-").map{|x| x.split(":")} ``` What ...
You can do: ``` >>> [i.split(':') for i in "12:30-14:40".split('-')] [['12', '30'], ['14', '40']] ```
What is the Python equivalent of map in Ruby and Javascript?
13,271,670
4
2012-11-07T14:23:51Z
13,271,761
11
2012-11-07T14:28:42Z
[ "python", "list", "map" ]
Say for example I want to split string `"12:30-14:40"` and have the result in a matrix like: `[["12","30"],["14","40"]]`. I can do this in JavaScript with: ``` "12:30-14:40".split("-").map(function(x) { return x.split(':'); }); ``` and in Ruby with: ``` "12:30-14:40".split("-").map{|x| x.split(":")} ``` What ...
In Python and using map you will have something like: ``` In [1]: map(lambda x: x.split(":"), "12:30-14:40".split("-")) Out[1]: [['12', '30'], ['14', '40']] ``` Regards
Multiplying Numpy/Scipy Sparse and Dense Matrices Efficiently
13,272,453
9
2012-11-07T15:09:44Z
16,754,459
8
2013-05-25T22:26:38Z
[ "python", "performance", "numpy", "scipy", "sparse-matrix" ]
I'm working to implement the following equation: ``` X =(Y.T * Y + Y.T * C * Y) ^ -1 ``` Y is a (n x f) matrix and C is (n x n) diagonal one; n is about 300k and f will vary between 100 and 200. As part of an optimization process this equation will be used almost 100 million times so it has to be processed really fas...
The reason the dot product runs into memory issues when computing r = dot(C,Y) is because numpy's dot function does not have native support for handling sparse matrices. What is happening is numpy thinks of the sparse matrix C as a python object, and not a numpy array. If you inspect on small scale you can see the prob...
Bottle.py HTTP Auth?
13,272,528
9
2012-11-07T15:14:05Z
23,592,568
11
2014-05-11T12:23:44Z
[ "python", "http", "authentication", "bottle", "digest" ]
How can I get my bottle.py app (Running in Paste or Cherrypy) to do HTTP (basic or digest) authentication? - I need to secure it, but cant find a any HOWTOs.
bottle has a built in `auth_basic` decorator that can be used on a view: ``` from bottle import auth_basic, request, route def check(user, pw): # Check user/pw here and return True/False @route('/') @auth_basic(check) def home(): return { 'data': request.auth } ```
App Engine Python Development Server + Taskqueue + Backend
13,273,067
7
2012-11-07T15:42:01Z
13,389,505
8
2012-11-14T23:59:05Z
[ "python", "google-app-engine" ]
I'm using GAE Python 2.7 with the local development server. I have configured a backend ``` backends: - name: worker class: B1 options: dynamic ``` and I'm using the default taskqueue. Everything works fine and the backend and taskqueue are visible at the SDK console. Also the local development work starts withou...
It's a bug in [`taskqueue.py`](http://code.google.com/searchframe#Qx8E-7HUBTk/trunk/python/google/appengine/api/taskqueue/taskqueue.py&q=taskqueue.py%20package%3agoogleappengine%5C.googlecode%5C.com&l=827), it misses a case to distinguish between production and the development environment. In production, it does the r...
scikit-learn OpenMP libsvm
13,273,738
3
2012-11-07T16:17:09Z
13,275,267
8
2012-11-07T17:47:36Z
[ "python", "openmp", "libsvm", "scikit-learn" ]
I am using scikit-learn SVC to classify some data. I would like to increase the training performance. > clf = svm.SVC(cache\_size=4000, probability=True, verbose=True) Since sckikit-learn interfaces with libsvm and libsvm uses OpenMp I was hoping that: > export OMP\_NUM\_THREADS=16 would run on multiple cores. Unfo...
There is no OpenMP support in the current binding for libsvm in scikit-learn. However it is very likely that if you have performance issues with `sklearn.svm.SVC` should you use a more scalable model instead. If your data is high dimensional it might be linearly separable. In that case it is advised to first try simpl...
AWS glacier delete job
13,274,197
7
2012-11-07T16:42:34Z
13,275,014
9
2012-11-07T17:31:58Z
[ "python", "amazon-web-services", "boto", "amazon-glacier" ]
I have started a retrival job for an archive stored in one of my vaults on Glacier AWS. It turns out that I do not need to resurrect and download that archive any more. Is there a way to stop and/or delete my Glacier job? I am using boto and I cannot seem to find a suitable function. Thanks
The AWS Glacier service does not provide a way to delete a job. You can: * Initiate a job * Describe a job * Get the output of a job * List all of your jobs The Glacier service manages the jobs associated with an vault.
Replacing chars in a string in every way
13,274,976
4
2012-11-07T17:29:06Z
13,275,168
8
2012-11-07T17:41:15Z
[ "python" ]
I'm looking for help on a function that takes a string, and replaces every character in that string in every way. I'm not quite sure how to word my question so that it makes sense so I'll show you what it's supposed to do. ``` stars('1') returns ['*'] stars('12') returns ['*1', '1*', '**'] stars('123') returns ['*23...
I think the canonical approach in Python would be to use the `itertools` module: ``` >>> from itertools import product, cycle >>> s = 'abcde' >>> [''.join(chars) for chars in product(*zip(s, cycle('*')))] ['abcde', 'abcd*', 'abc*e', 'abc**', 'ab*de', 'ab*d*', 'ab**e', 'ab***', 'a*cde', 'a*cd*', 'a*c*e', 'a*c**', 'a*...
Can't get pytest to understand command-line arguments on setups
13,275,738
5
2012-11-07T18:20:24Z
15,422,896
14
2013-03-15T00:54:08Z
[ "python", "unit-testing", "testing", "command-line-arguments", "py.test" ]
So I have been trying to get pytest to run selenium tests on different environments based on some command-line argument. But it keeps throwing this error: ``` TypeError: setup_class() takes exactly 2 arguments (1 given) ``` It seems that it is understanding that `setup_class` takes 2 arguments, but `host` is not bein...
To access the command line options from inside the setup functions, you can use the pytest.config object. Here is an example... adapt as needed. ``` import pytest def setup_module(mod): print "Host is %s" % pytest.config.getoption('host') ```
In python, how does the following AutoVivification class work?
13,276,218
12
2012-11-07T18:52:10Z
13,276,466
16
2012-11-07T19:07:02Z
[ "python", "dictionary", "autovivification" ]
In searching for a way of working with nested dictionaries, I found the following code posted by [nosklo](http://stackoverflow.com/users/17160/nosklo), which I would like to have explained, please. ``` class AutoVivification(dict): """Implementation of perl's autovivification feature.""" def __getitem__(self, ...
Line by line: ``` class AutoVivification(dict): ``` We make a subclass of `dict`, so `AutoVivification` is a kind of `dict`, with some local changes. ``` def __getitem__(self, item): ``` The [`__getitem()__` hook](http://docs.python.org/2/reference/datamodel.html#object.__getitem__) is called whenever someone tries...
How can I get Python to use upper case letters to print hex values?
13,277,440
4
2012-11-07T20:14:07Z
13,277,449
12
2012-11-07T20:14:49Z
[ "python", "hex", "uppercase" ]
In Python v2.6 I can get hex for my integers in one of two ways: ``` print ("0x%x")%value print hex(value) ``` However, in both cases, the hexadecimal digits are lower case. How can I get these in upper case?
Capital X: ``` print "0x%X" % value ```
How does Python's seek function work?
13,278,748
5
2012-11-07T21:41:30Z
13,278,770
7
2012-11-07T21:43:13Z
[ "python", "seek" ]
If I have some file-like object and do the following: ``` F = open('abc', 'r') ... loc = F.tell() F.seek(loc-10) ``` What does seek do? Does is start at the beginning of the file and read `loc-10` bytes? Or is it smart enough just to back up 10 bytes?
It is OS- and libc-specific. the `file.seek()` operation is delegated to the `fseek(3)` C call for actual OS-level files.
How does Python's seek function work?
13,278,748
5
2012-11-07T21:41:30Z
13,278,792
7
2012-11-07T21:44:54Z
[ "python", "seek" ]
If I have some file-like object and do the following: ``` F = open('abc', 'r') ... loc = F.tell() F.seek(loc-10) ``` What does seek do? Does is start at the beginning of the file and read `loc-10` bytes? Or is it smart enough just to back up 10 bytes?
According to [Python 2.7's docs](http://docs.python.org/2.7/library/stdtypes.html?highlight=seek#file.seek): > `file.seek(offset[, whence])` > > Set the file’s current position, like stdio‘s fseek(). The whence > argument is optional and defaults to os.SEEK\_SET or 0 (absolute file > positioning); other values are...
comparing Python code for equivalence
13,278,864
9
2012-11-07T21:50:13Z
13,279,160
14
2012-11-07T22:12:34Z
[ "python" ]
Is there a reliable, automatic way (such as a command-line utility) to check if two Python files are **equivalent** modulo whitespace, semicolons, backslash continuations, comments, etc.? In other words, that they are identical to the interpreter? For example, this: ``` import sys sys.stdout.write('foo\n') sys.stdout...
Use the [`ast`](http://docs.python.org/2/library/ast.html) module. Example (for Python 2): ``` import ast x = r'''import sys sys.stdout.write('foo\n') sys.stdout.write('bar\n')''' y = r'''import sys sys.stdout.\ write('foo\n'); sys.stdout.\ write( 'bar\n') # This is an unnecessary comment''' xd = as...
How to obtain values of request variables using Python and Flask
13,279,399
22
2012-11-07T22:30:29Z
13,279,573
32
2012-11-07T22:44:34Z
[ "python", "variables", "request", "flask" ]
I'm wondering how to go about obtaining the value of a POST/GET request variable using Python with Flask. With Ruby, I'd do something like this: ``` variable_name = params["FormFieldValue"] ``` How would I do this with Flask?
I've only used flask a bit but basically you can get POST data using ``` myvar = request.form["myvar"] ``` and GET using ``` myvar = request.args.get("myvar") ```
How to obtain values of request variables using Python and Flask
13,279,399
22
2012-11-07T22:30:29Z
20,341,272
55
2013-12-03T01:40:01Z
[ "python", "variables", "request", "flask" ]
I'm wondering how to go about obtaining the value of a POST/GET request variable using Python with Flask. With Ruby, I'd do something like this: ``` variable_name = params["FormFieldValue"] ``` How would I do this with Flask?
If you want to retrieve POST data, ``` first_name = request.form.get("firstname") ``` If you want to retrieve GET (query string) data, ``` first_name = request.args.get("firstname") ``` Or if you don't care/know whether the value is in the query string or in the post data, ``` first_name = request.values.get("firs...
Automatically inserting a header in vim
13,279,520
8
2012-11-07T22:40:54Z
13,279,595
23
2012-11-07T22:46:13Z
[ "python", "command-line", "vim" ]
Is there a way to auto add a header when i open a new file in vim? My objective is to automatically add the shebang `"#! /usr/bin/python"` when i open a new file using the command `"vim test.py"`. If the file is already present, no header should be inserted.
Add this line in your configuration file: ``` autocmd BufNewFile *.py 0put =\"#!/usr/bin/python\<nl>\"|$ ```
How dangerous is setting self.__class__ to something else?
13,280,680
17
2012-11-08T00:31:33Z
13,280,789
12
2012-11-08T00:46:12Z
[ "python", "python-2.x" ]
Say I have a class, which has a number subclasses. I can instantiate the class. I can then set its `__class__` attribute to one of the subclasses. I have effectively changed the class type to the type of its subclass, on a live object. I can call methods on it which invoke the subclass's version of those methods. So,...
Here's a list of things I can think of that make this dangerous, in rough order from worst to least bad: * It's likely to be confusing to someone reading or debugging your code. * You won't have gotten the right `__init__` method, so you probably won't have all of the instance variables initialized properly (or even a...
How dangerous is setting self.__class__ to something else?
13,280,680
17
2012-11-08T00:31:33Z
13,281,122
8
2012-11-08T01:28:04Z
[ "python", "python-2.x" ]
Say I have a class, which has a number subclasses. I can instantiate the class. I can then set its `__class__` attribute to one of the subclasses. I have effectively changed the class type to the type of its subclass, on a live object. I can call methods on it which invoke the subclass's version of those methods. So,...
Assigning the `__class__` attribute is useful if you have a long time running application and you need to replace an old version of some object by a newer version of the same class without loss of data, e.g. after some `reload(mymodule)` and without reload of unchanged modules. Other example is if you implement persist...
average of a number of arrays with numpy without considering zero values
13,281,904
3
2012-11-08T03:21:25Z
13,281,981
11
2012-11-08T03:31:37Z
[ "python", "arrays", "numpy", "average" ]
I am working on numpy and I have a number of arrays with the same size and shape like: `a= [153 186 0 258] b=[156 136 156 0] c=[193 150 950 757]` I want to have average of the arrays, but I want the program to ignore the zero values in the computation. So, the resulting array for this example will be: `d=[167.333 157.3...
``` >>> import numpy as np >>> a = np.array([153, 186, 0, 258]) >>> b = np.array([156, 136, 156, 0]) >>> c = np.array([193, 150, 950, 757]) >>> [np.mean([x for x in s if x]) for s in np.c_[a, b, c]] [167.33333333333334, 157.33333333333334, 553.0, 507.5] ``` Or maybe a nicer alternative: ``` >>> A = np.vstack([a,b,c])...
What is the proper way of checking if element exists and is true in a python dictionary?
13,282,695
2
2012-11-08T04:58:11Z
13,282,712
14
2012-11-08T04:59:56Z
[ "python", "dictionary" ]
``` someDict = {'foo': True} if 'foo' in someDict and someDict['foo']: print 'success' ``` Following code works fine. I'm just wondering if there is a better/shorter way of checking if key exists and its value is true.
`someDict.get('foo')` This will return None if `foo` is not in `someDict`, otherwise it will return the value found. You can optionally pass a second argument which will be the value returned if it does not exist.
python sum the values of lists of list
13,283,689
4
2012-11-08T06:27:43Z
13,283,721
17
2012-11-08T06:31:05Z
[ "python", "list", "sum" ]
I have list of lists and i need to sum the inner lists, for example, ``` a = [[1,2,3], [2,1,4], [4,3,6]] ``` for my case, the len of a[i] is same, that is all the inner lists have same dimension. and i need the output as ``` result = [6,7,13] ``` what i did is: ``` result = [sum(a[i]) for i in range(len(a))] ``` ...
``` result = map(sum, a) ``` Is the way I would do it. Alternatively: ``` result = [sum(b) for b in a] ``` The second variation is the same as yours, except it avoids the unnecessary range statement. In Python, you can iterate over lists directly without having to keep a separate variable as an index.
How to share the global app object in flask?
13,284,858
11
2012-11-08T08:02:10Z
13,286,236
17
2012-11-08T09:34:18Z
[ "python", "flask" ]
I am using flask and trying to the following. I have defined a main.py file through which I want to run my app ie python main.py - ``` from flask import Flask from view import tags app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello World!' if __name__ == '__main__': app.run() ``` I hav...
First, I would suggest to take a look at Blueprints <http://flask.pocoo.org/docs/blueprints/> This will help to organize the app easily. Also take a look at <http://flask.pocoo.org/docs/api/#flask.current_app> flask.current\_app, the way how to get your app instance in other modules. This link also could be helpful o...
How to share the global app object in flask?
13,284,858
11
2012-11-08T08:02:10Z
13,291,806
8
2012-11-08T15:13:55Z
[ "python", "flask" ]
I am using flask and trying to the following. I have defined a main.py file through which I want to run my app ie python main.py - ``` from flask import Flask from view import tags app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello World!' if __name__ == '__main__': app.run() ``` I hav...
One way is to create an overall package and adding a `__init__.py` file under that where you declare all global variables. In your case for example, you can create something like: ``` myapplication/ * __init__.py * myviews/ * __init__.py * view.py * ...
How to bundle Python dependancies in IronWorker?
13,285,901
9
2012-11-08T09:14:31Z
14,278,696
13
2013-01-11T12:58:12Z
[ "python", "iron.io" ]
I'm writing a simple [IronWorker in Python](http://dev.iron.io/worker/languages/python/) to do some work with the AWS API. To do so I want to use the [boto library](https://github.com/boto/boto) which is distributed via PiPy. The boto library is not installed by default in the IronWorker runtime environment. How can ...
Newer iron\_worker version has native support of `pip` command. So, you need: ``` runtime "python" exec "something.py" pip "boto" pip "someotherpip" full_remote_build true ```
Django CreateView : Append ForeignKey to CustomForm Data
13,286,075
3
2012-11-08T09:24:09Z
13,286,466
11
2012-11-08T09:48:03Z
[ "python", "django", "foreign-keys", "form-data", "create-view" ]
I have a CreateView as follows: ``` class ResumeCreateView(CreateView): model = Resume def form_valid(self, request, form): candidate = Candidate.objects.get(user=self.request.user) self.object = form.save(commit=False) self.object.candidate = candidate self.object.save() ...
You will have to define a `modelForm` with `candidate` as excluded field and then set it in `form_valid()` method. ``` class ResumeForm(forms.ModelForm): class Meta: model = Resume exclude = ('candidate',) class ResumeCreateView(CreateView): form_class = ResumeForm model = Resume def ...
Is there a way to use PhantomJS in Python?
13,287,490
135
2012-11-08T10:46:54Z
13,287,548
70
2012-11-08T10:49:59Z
[ "python", "phantomjs" ]
I want to use [PhantomJS](http://phantomjs.org/) in [Python](http://www.python.org/). I googled this problem but couldn't find proper solutions. I find `os.popen()` may be a good choice. But I couldn't pass some arguments to it. Using `subprocess.Popen()` may be a proper solution for now. I want to know whether there...
PhantomJS recently [dropped Python support](http://phantomjs.org/release-1.5.html) altogether. However, PhantomJS now embeds [Ghost Driver](https://github.com/detro/ghostdriver). A new project has since stepped up to fill the void: [`ghost.py`](http://ghost-py.readthedocs.org/en/latest/). You probably want to use that...
Is there a way to use PhantomJS in Python?
13,287,490
135
2012-11-08T10:46:54Z
13,933,894
9
2012-12-18T13:17:44Z
[ "python", "phantomjs" ]
I want to use [PhantomJS](http://phantomjs.org/) in [Python](http://www.python.org/). I googled this problem but couldn't find proper solutions. I find `os.popen()` may be a good choice. But I couldn't pass some arguments to it. Using `subprocess.Popen()` may be a proper solution for now. I want to know whether there...
Here's how I test javascript using PhantomJS and Django: **mobile/test\_no\_js\_errors.js**: ``` var page = require('webpage').create(), system = require('system'), url = system.args[1], status_code; page.onError = function (msg, trace) { console.log(msg); trace.forEach(function(item) { c...
Is there a way to use PhantomJS in Python?
13,287,490
135
2012-11-08T10:46:54Z
15,699,761
257
2013-03-29T08:23:16Z
[ "python", "phantomjs" ]
I want to use [PhantomJS](http://phantomjs.org/) in [Python](http://www.python.org/). I googled this problem but couldn't find proper solutions. I find `os.popen()` may be a good choice. But I couldn't pass some arguments to it. Using `subprocess.Popen()` may be a proper solution for now. I want to know whether there...
The easiest way to use PhantomJS in python is via Selenium. The simplest installation method is 1. Install [NodeJS](http://nodejs.org/) 2. Using Node's package manager install phantomjs: `npm -g install phantomjs` 3. install selenium (in your virtualenv, if you are using that) After installation, you may use phantom ...
Is there a way to use PhantomJS in Python?
13,287,490
135
2012-11-08T10:46:54Z
16,353,876
31
2013-05-03T07:39:39Z
[ "python", "phantomjs" ]
I want to use [PhantomJS](http://phantomjs.org/) in [Python](http://www.python.org/). I googled this problem but couldn't find proper solutions. I find `os.popen()` may be a good choice. But I couldn't pass some arguments to it. Using `subprocess.Popen()` may be a proper solution for now. I want to know whether there...
Now since the GhostDriver comes bundled with the PhantomJS, it has become even more convenient to use it through Selenium. I tried the Node installation of PhantomJS, as suggested by Pykler, but in practice I found it to be slower than the standalone installation of PhantomJS. I guess standalone installation didn't pr...
Have MySQLdb installed, works outside of virtualenv but inside it doesn't exist. How to resolve?
13,288,013
9
2012-11-08T11:17:21Z
13,288,095
11
2012-11-08T11:22:10Z
[ "python", "virtualenv", "mysql-python" ]
I'm using the most recent versions of all software (Django, Python, virtualenv, MySQLdb) and I can't get this to work. When I run "import MySQLdb" in the python prompt from outside of the virtualenv, it works, inside it says "ImportError: No module named MySQLdb". I'm trying to learn Python and Linux web development. ...
If you have created the virtualenv with the `--no-site-packages` switch (the default), then system-wide installed additions such as MySQLdb are not included in the virtual environment packages. You need to install MySQLdb with the `pip` command installed with the virtualenv. Either activate the virtualenv with the `bi...
Performance effect of using print statements in Python script
13,288,185
6
2012-11-08T11:28:26Z
13,288,938
7
2012-11-08T12:15:09Z
[ "python", "console", "text-files" ]
I have a Python script that process a huge text file (with around 4 millon lines) and writes the data into two separate files. I have added a print statement, which outputs a string for every line for debugging. I want to know how bad it could be from the performance perspective? If it is going to very bad, I can rem...
Tried doing it in a very simple script just for fun, the difference is quite staggering: In large.py: ``` target = open('target.txt', 'w') for item in xrange(4000000): target.write(str(item)+'\n') print item ``` Timing it: ``` [gp@imdev1 /tmp]$ time python large.py real 1m51.690s user 0m10.531s sys ...
How can I send keyboard commands (hold,release,simultanous) with a python script?
13,289,777
3
2012-11-08T13:26:20Z
13,290,031
7
2012-11-08T13:38:37Z
[ "python", "keyboard-events", "sendkeys", "virtual-keyboard" ]
I want to send virtually the command like this: ``` when keypress=="a" #if entered key is "a" send {ALT+TAB} # send ALT and TAB simultaneously sleep(2) #wait for 2 sec send {"I love my Country",0.1} #send all strings at 0.1 sec wait key_down...
I know how to do it with ctypes. For example for Alt-Tab (it is a lot of boilerplate code, I know) : ``` import ctypes import time SendInput = ctypes.windll.user32.SendInput PUL = ctypes.POINTER(ctypes.c_ulong) class KeyBdInput(ctypes.Structure): _fields_ = [("wVk", ctypes.c_ushort), ("wScan", ct...
Elementwise if elif function in python using arrays
13,290,557
7
2012-11-08T14:06:41Z
13,290,684
8
2012-11-08T14:14:12Z
[ "python", "arrays", "if-statement", "numpy", "definition" ]
I have a definition ``` def myfunc(a, b): if a < (b*10): result = a*2 else: result = a*(-1) return result ``` Now this obviously works perfectly when I feed in my `a` and `b` values one by one using for loops, however it takes forever (I've simplified the definition a wee bit) and I know f...
You could use [np.where](http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html): ``` def myfunc(a, b): return np.where(a < b*10, a*2, -a) ``` For example, ``` In [48]: a = np.array([1, 5, 50, 500]) In [49]: b = 1 In [50]: myfunc(a, b) Out[50]: array([ 2, 10, -50, -500]) ``` Note the output...
convert double to float in Python
13,291,539
4
2012-11-08T15:00:43Z
13,291,643
9
2012-11-08T15:05:46Z
[ "python", "floating-point", "double" ]
In a Python program, I have these two values: ``` v1 = 0.00582811585976 v2 = 0.00582811608911 ``` My **hypothesis** is that v1 is a 64-bits floating point value, and v2 is v1 converted to a 32-bits floating point value. How can I **verify** this? Details: The first value comes from a hardware board that calculates...
You can use the [struct module](http://docs.python.org/2/library/struct.html) to play with numerical representations: ``` import struct >>> struct.unpack("f", struct.pack("f", 0.00582811585976)) (0.005828116089105606,) ```
Running django project without django installation
13,291,576
5
2012-11-08T15:02:26Z
13,292,260
7
2012-11-08T15:37:11Z
[ "python", "mysql", "django" ]
I have developed a project with **Django framework(python and mysql DB)** in Linux OS(Ubuntu 12.04), I want to run this project in localhost in **another machine** with Linux(Ubuntu 12.04) without installing Django here, is it possible **run a django project without django installation.** Is there any way to run so? T...
In order to be able to use regular Django, it has to be installed since you have to be able to do `import django`. However it is never a good idea to install Django as a system-level Python package. It is always best to work with virtualenvs. They allows you to work on multiple projects where each project might require...
Python subtracting two date strings
13,293,009
6
2012-11-08T16:15:24Z
13,293,199
7
2012-11-08T16:25:00Z
[ "python", "string", "subtraction" ]
I have two strings containing a date like so" ``` start_date = 'Sun Sep 16 16:05:15 +0000 2012' end_date = 'Sun Sep 17 23:55:20 +0000 2012' ``` I need to perform: `end_date - start_date` It should return the number of seconds separating the end and start dates. This data is extracted from the twitter api. This is wh...
Here is the full answer: ``` from datetime import datetime start_date = 'Sun Sep 16 16:05:15 +0000 2012' end_date = 'Sun Sep 17 23:55:20 +0000 2012' def __datetime(date_str): return datetime.strptime(date_str, '%a %b %d %H:%M:%S +0000 %Y') start = __datetime(start_date) end = __datetime(end_date) delta = end ...
How would I stop a while loop after n amount of time?
13,293,269
24
2012-11-08T16:28:02Z
13,293,316
33
2012-11-08T16:30:41Z
[ "python", "python-2.7" ]
how would I stop a while loop after 5 minutes if it does not achieve what I want it to achieve. ``` while true: test = 0 if test == 5: break test = test - 1 ``` This code throws me in an endless loop.
Try the following: ``` import time timeout = time.time() + 60*5 # 5 minutes from now while True: test = 0 if test == 5 or time.time() > timeout: break test = test - 1 ``` You may also want to add a short sleep here so this loop is not hogging CPU (for example `time.sleep(1)` at the beginning or ...
How would I stop a while loop after n amount of time?
13,293,269
24
2012-11-08T16:28:02Z
13,293,360
13
2012-11-08T16:32:47Z
[ "python", "python-2.7" ]
how would I stop a while loop after 5 minutes if it does not achieve what I want it to achieve. ``` while true: test = 0 if test == 5: break test = test - 1 ``` This code throws me in an endless loop.
Try this module: <http://pypi.python.org/pypi/interruptingcow/> ``` from interruptingcow import timeout try: with timeout(60*5, exception=RuntimeException): while true: test = 0 if test == 5: break test = test - 1 except RuntimeException: pass ``` Re...
How would I stop a while loop after n amount of time?
13,293,269
24
2012-11-08T16:28:02Z
24,305,739
12
2014-06-19T11:41:58Z
[ "python", "python-2.7" ]
how would I stop a while loop after 5 minutes if it does not achieve what I want it to achieve. ``` while true: test = 0 if test == 5: break test = test - 1 ``` This code throws me in an endless loop.
You do not need to use the while True loop in this case. There is much simpler way to use the time condition directly: ``` import time timeout_start = time.time() # timeout variable can be omitted, if you use specific value in the while condition timeout = 300 # [seconds] while time.time() < timeout_start + timeo...
ValueError: object too deep for desired array
13,293,731
4
2012-11-08T16:52:00Z
13,298,003
11
2012-11-08T21:19:50Z
[ "python", "numpy", "scipy" ]
``` """ ___ """ from scipy.optimize import root import numpy as np LENGTH = 3 def process(x): return x[0, 0] + x[0, 1] * 5 def draw(process, length): """ """ X = np.matrix(np.random.normal(0, 10, (length, 2))) y = np.matrix([process(x) for x in X]) y += np.random.normal(3, 1, len(y)) retur...
The problem is that fsolve and root do not accept matrixes as return value of the objective function. For example this is a solution of above problem: ``` def maximum_likelyhood(y, X): def objective(b): b = np.matrix(b).T return np.transpose(np.array((X.T * (y - X * b))))[0] x0 = (1, 1) re...
Working with files too big to be stored in memory?
13,293,994
3
2012-11-08T17:04:25Z
13,294,035
8
2012-11-08T17:06:34Z
[ "python", "sqlite3", "large-files", "dbm" ]
I have a 20 gb file which looks like the following: ``` Read name, Start position, Direction, Sequence ``` Note that read names are not neccessarily unique. E.g. a snippet of my file would look like ``` Read1, 40009348, +, AGTTTTCGTA Read2, 40009349, -, AGCCCTTCGG Read1, 50994530, -, AGTTTTCGTA ``` I want to be ab...
[SQLite is able](https://www.sqlite.org/whentouse.html) to do both 1) and 2). I recommend you try it and report any problems you encounter. > With the default page size of 1024 bytes, an SQLite database is limited in size to 2 terabytes (241 bytes). And even if it could handle larger databases, SQLite stores the enti...
Can you "stream" images to ffmpeg to construct a video, instead of saving them to disk?
13,294,919
22
2012-11-08T17:57:14Z
13,298,538
27
2012-11-08T21:58:29Z
[ "python", "image", "stream", "ffmpeg", "python-imaging-library" ]
My work recently involves programmatically making videos. In python, the typical workflow looks something like this: ``` import subprocess, Image, ImageDraw for i in range(frames_per_second * video_duration_seconds): img = createFrame(i) img.save("%07d.png" % i) subprocess.call(["ffmpeg","-y","-r",str(frames...
Ok I got it working. thanks to LordNeckbeard suggestion to use image2pipe. I had to use jpg encoding instead of [png because image2pipe with png doesn't work on my verision of ffmpeg](https://ffmpeg.org/trac/ffmpeg/ticket/1272). The first script is essentially the same as your question's code except I implemented a sim...
How can I replace all the NaN values with Zero's in a column of a pandas dataframe
13,295,735
101
2012-11-08T18:50:39Z
13,295,801
179
2012-11-08T18:54:27Z
[ "python", "pandas" ]
I have a dataframe as below ``` itm Date Amount 67 420 2012-09-30 00:00:00 65211 68 421 2012-09-09 00:00:00 29424 69 421 2012-09-16 00:00:00 29877 70 421 2012-09-23 00:00:00 30990 71 421 2012-09-30 00:00:00 61303 72 485 2012-09-09 00:00:00 71781 73 485 2012-09-1...
I believe `DataFrame.fillna()` will do this for you. Link to Docs for [a dataframe](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html) and for [a Series](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.fillna.html). Example: ``` In [7]: df Out[7]: 0 ...
How can I replace all the NaN values with Zero's in a column of a pandas dataframe
13,295,735
101
2012-11-08T18:50:39Z
30,587,837
11
2015-06-02T05:13:34Z
[ "python", "pandas" ]
I have a dataframe as below ``` itm Date Amount 67 420 2012-09-30 00:00:00 65211 68 421 2012-09-09 00:00:00 29424 69 421 2012-09-16 00:00:00 29877 70 421 2012-09-23 00:00:00 30990 71 421 2012-09-30 00:00:00 61303 72 485 2012-09-09 00:00:00 71781 73 485 2012-09-1...
I just wanted to provide a bit of an update/special case since it looks like people still come here. If you're using a multi-index or otherwise using an index-slicer the inplace=True option may not be enough to update the slice you've chosen. For example in a 2x2 level multi-index this will not change any values (as of...
Using File Extension Wildcards in os.listdir(path)
13,297,406
15
2012-11-08T20:37:30Z
13,297,537
24
2012-11-08T20:49:46Z
[ "python" ]
I have a directory of files that I am trying to parse using Python. I wouldn't have a problem if they were all the same extension, but for whatever reason they are created with sequential numeric extensions after their original extension. For example: `foo.log foo.log.1 foo.log.2 bar.log bar.log.1 bar.log.2 etc.` On to...
Maybe the [glob](http://docs.python.org/2/library/glob.html) module can help you: ``` import glob listing = glob.glob('C:/foo/bar/foo.log*') for filename in listing: # do stuff ```
Parsing variable data out of a javascript tag using python
13,298,201
9
2012-11-08T21:33:57Z
13,298,240
19
2012-11-08T21:36:34Z
[ "python", "html", "json", "beautifulsoup", "python-requests" ]
I am scraping some websites using BeautifulSoup and Requests. There is one page that I am examining that has its data inside of a `<script language="JavaScript" type="text/javascript">` tag. It looks like this: ``` <script language="JavaScript" type="text/javascript"> var page_data = { "default_sku" : "SKU12345", ...
If you use BeautifulSoup to get the contents of the `<script>` tag, the [`json` module](http://docs.python.org/2/library/json.html) can do the rest with a bit of string magic: ``` jsonValue = '{%s}' % (textValue.split('{', 1)[1].rsplit('}', 1)[0],) value = json.loads(jsonValue) ``` The `.split()` and `.rsplit()` co...
Plotting a histogram using python and quickdraw
13,298,375
2
2012-11-08T21:46:47Z
13,305,092
9
2012-11-09T09:15:27Z
[ "python", "quickdraw" ]
I need help writing a program that reads about 300 lines from a text file and takes the grades from a specific assignment (column A1) and then uses the grades from that assignment to plot a histogram in quickdraw. ``` ID , Last, First, Lecture, Tutorial, A1, A2, A3, A4, A5 8959079, Moore, Maria, L01, T03, 9.0, 8.5, 8...
[Quickdraw](http://pages.cpsc.ucalgary.ca/QuickDraw/docs/index.html) doesn't support drawing graphs out of the box, All the rectangles, the grid, the text has to be mapped yourself. A much better way is to used python library that already exist. Don't try to reinvent the wheel. **Example 1 Quickdraw Solution** ``` #!...
How do I import a pre-existing python project into Eclipse?
13,298,630
13
2012-11-08T22:04:42Z
13,298,723
9
2012-11-08T22:10:40Z
[ "python", "eclipse" ]
I am using eclipse for python. How do I import an existing project into eclipse in the current workspace. Thanks
New Project Dont use default Location Browse to existing project location ... if its an existing eclipse project with project files that have correct paths for your system you can just open the .proj file ...
How do I import a pre-existing python project into Eclipse?
13,298,630
13
2012-11-08T22:04:42Z
31,423,129
7
2015-07-15T06:38:12Z
[ "python", "eclipse" ]
I am using eclipse for python. How do I import an existing project into eclipse in the current workspace. Thanks
In my case when i am trying to import my existing perforce project , it gives error no project found on windows machine. On linux i was able to import project nicely. For Eclipse Kepler, i have done like below. 1. Open eclipse in pydev perspective. 2. Create a new pydev project in your eclipse workspace with the same...
Remove newline from file in python
13,298,907
20
2012-11-08T22:23:49Z
13,298,933
34
2012-11-08T22:25:10Z
[ "python", "string" ]
I'm trying to remove all new line characters from a string. I've read up on how to do it, but it seems that I for some reason am unable to do so. Here is step by step what I am doing: ``` string1 = "Hello \n World" string2 = string1.strip('\n') print string2 ``` And I'm still seeing the newline character in the outpu...
`strip` only removes characters from the beginning or end of a string. You want to use `replace`: ``` str2 = str.replace("\n", "") ```
Python functions call by reference
13,299,427
10
2012-11-08T23:01:21Z
13,299,557
15
2012-11-08T23:13:03Z
[ "python" ]
In some languages you can pass a parameter by reference or value by using a special reserved word like **ref** or **val**. When you pass a parameter to a Python function it never alters the value of the parameter on leaving the function.The only way to do this is by using the **global** reserved word (or as i understan...
You can not pass a simple primitive by reference in Python, but you can do things like: ``` def foo(y): y[0] = y[0]**2 x = [5] foo(x) print x[0] ``` That is a weird way to go about it, however. Note that in Python, you can also return more than one value, making some of the use cases for pass by reference less imp...
Python functions call by reference
13,299,427
10
2012-11-08T23:01:21Z
13,300,388
15
2012-11-09T00:35:47Z
[ "python" ]
In some languages you can pass a parameter by reference or value by using a special reserved word like **ref** or **val**. When you pass a parameter to a Python function it never alters the value of the parameter on leaving the function.The only way to do this is by using the **global** reserved word (or as i understan...
OK, I'll take a stab at this. Python passes by object reference, which is different from what you'd normally think of as "by reference" or "by value". Take this example: ``` def foo(x): print x bar = 'some value' foo(bar) ``` So you're creating a string object with value 'some value' and "binding" it to a variab...
Python - Need to loop through directories looking for TXT files
13,299,731
2
2012-11-08T23:30:25Z
13,299,851
9
2012-11-08T23:40:30Z
[ "python" ]
I am a total Python Newb I need to loop through a directory looking for .txt files, and then read and process them individually. I would like to set this up so that whatever directory the script is in is treated as the root of this action. For example if the script is in /bsepath/workDir, then it would loop over all o...
``` import os, fnmatch def findFiles (path, filter): for root, dirs, files in os.walk(path): for file in fnmatch.filter(files, filter): yield os.path.join(root, file) ``` Use it like this, and it will find all text files somewhere within the given path (recursively): ``` for textFile in findF...
for/if loops and a scope of the variable in python
13,299,908
2
2012-11-08T23:46:25Z
13,299,949
7
2012-11-08T23:49:41Z
[ "python", "scope" ]
I am confused about the scope of the variable in python. Here is a toy example of what I am trying to do: ``` a = True enumerated_set = enumerate(['tic','tac','toe']) for i,j in enumerated_set: if a == True: print j ``` The result I get is: ``` tic tac toe ``` now, `print a` returns ``` `True` ``` a...
It is actually not a problem with your boolean. That is always `True`. `enumerated_set` is a generator. Once you cycle through it, it is exhausted. You would need to create a new one. ``` In [9]: enumerated_set = enumerate(['tic','tac','toe']) In [10]: enumerated_set.next() Out[10]: (0, 'tic') In [11]: enumerated_s...
Non-Integer Class Labels Scikit-Learn
13,300,160
10
2012-11-09T00:11:41Z
13,303,821
16
2012-11-09T07:22:50Z
[ "python", "svm", "scikit-learn" ]
Quick SVM question for scikit-learn. When you train an SVM, it's something like ``` from sklearn import svm s = svm.SVC() s.fit(training_data, labels) ``` Is there any way for `labels` to be a list of a non-numeric type? For instance, if I want to classify vectors as 'cat' or 'dog,' without having to have some kind o...
Passing strings as classes directly is on my todo, but it is not supported in the SVMs yet. For the moment, we have the [LabelEncoder](http://scikit-learn.org/dev/modules/generated/sklearn.preprocessing.LabelEncoder.html#sklearn.preprocessing.LabelEncoder) that can do the book keeping for you. [edit]This should work n...
IPython Maintain namespace after run
13,300,306
12
2012-11-09T00:27:17Z
13,300,775
12
2012-11-09T01:20:22Z
[ "python", "ipython" ]
I've tried to look everywhere for a simple, simple way to regain MATLAB-like functionality: when I run a script, I want ipython to maintain the namespace of my functions. Simple as that. I have a main function, and then I have a function sim\_loop() that has the code I'm trying to debus. sim\_loop() has a large array t...
To run a script in the main ipython namespace: ``` ipython script.py ``` Of course this just runs and exits. If you want to run the script in the main ipython namespace and then drop into the REPL: ``` ipython -i script.py ``` If you're already inside ipython and you want to run the script in the existing main ipyt...
Trouble Installing Pygame on Mac OSX
13,300,585
7
2012-11-09T00:59:25Z
13,300,989
8
2012-11-09T01:49:30Z
[ "python", "osx", "pygame" ]
Here is my error message: ``` Python 2.7.2 (default, Jun 20 2012, 16:23:33) [GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import pygame Traceback (most recent call last): File "<stdin>", line 1, in <module> Imp...
The instructions differ if you have a 32-bit proccessor or a 64-bit one. Users of 32-bit processors should just download and install the binary labeled pygame-1.9.1release-python.org-32bit-py2.7-macosx10.3.dmg on the [pygame download page](http://pygame.org/download.shtml). Users of 64-bit processors should follow the ...
numpy.nextafter decrementing instead of incrementing
13,300,984
7
2012-11-09T01:48:18Z
13,301,106
8
2012-11-09T02:08:14Z
[ "python", "numpy", "posix", "c99" ]
I fell on a weird case. I tried either of the three solutions posted here from Pyson: [Increment a python floating point value by the smallest possible amount](http://stackoverflow.com/questions/6063755/increment-a-python-floating-point-value-by-the-smallest-possible-amount). All three solutions display a weird behavio...
From the docs (emphasis mine): ``` nextafter(x1, x2[, out]) Return the next representable floating-point value after x1 **in the direction of x2 element-wise**. ``` The second argument isn't a direction given by +/-1, it's the value to aim toward. ``` In [12]: a = 1.1589832404270294929915507964324206113815307617187...
How to load the foreign keys elements in Tastypie
13,301,206
6
2012-11-09T02:18:46Z
13,301,739
9
2012-11-09T03:35:15Z
[ "python", "django", "tastypie" ]
In my Django model, I have 10 fields and there are 3 fields which are foreign keys. In my JSON data which is received from a GET request, I am getting all the fields but not the foreign keys. I have also done this, but I am still not getting those fields in the JSON data: ``` DataFields = MyData._meta.get_all_field_n...
You'll want to create [related resources](http://django-tastypie.readthedocs.org/en/latest/tutorial.html#creating-more-resources) for your foreign key fields and embed them in `MyResource`. If you make the embedded resource `full=True`, it'll dehydrate it when fetching `MyResource`, otherwise it'll embed it as the rela...
change the values of an array from nan to zero
13,301,262
3
2012-11-09T02:25:54Z
13,301,277
9
2012-11-09T02:27:45Z
[ "python", "arrays", "numpy" ]
I have an array A on python that has some nan values created by numpy.nan. I want to set all the nan values to zero using `A[A==numpy.nan] = 0`. It doesn't change the array at all. Why is that?
You want [`np.isnan`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.isnan.html): ``` A[np.isnan(A)] = 0 ``` The problem with your code is that (according to IEEE), `nan` doesn't equal anything -- even itself. As a side note, there's also * `np.isinf` -> (+/- infinity) * `np.isfinite` -> (not infinity or...
How to run standalone files in PyCharm
13,301,469
14
2012-11-09T02:56:04Z
16,985,124
8
2013-06-07T13:17:32Z
[ "python", "pycharm" ]
I'm doing small time project development using PyCharm. I use Pycharm for its intellisense features. As I develop each piece of code, I like to run it occasionally to test it. All I need at the point of development is to be able to run the file. However, when I right click and try to run a standalone file, PyCharm trie...
I just came across the same problem. It was because it had a class called TestClass in the file. I changed the name of the class and then I was able to run the file as normal.
How to run standalone files in PyCharm
13,301,469
14
2012-11-09T02:56:04Z
19,694,299
11
2013-10-30T21:39:55Z
[ "python", "pycharm" ]
I'm doing small time project development using PyCharm. I use Pycharm for its intellisense features. As I develop each piece of code, I like to run it occasionally to test it. All I need at the point of development is to be able to run the file. However, when I right click and try to run a standalone file, PyCharm trie...
You can simply choose the 'Run' entry in the context menu for the file in the Project view: ![enter image description here](http://i.stack.imgur.com/3g5LH.png) This will run the file exactly as if you had entered python from the command line, in the directory containing the file. The first time you do this an entr...
How to add extra object to tasty pie return json in python django
13,302,240
7
2012-11-09T04:46:00Z
16,304,070
17
2013-04-30T15:54:44Z
[ "python", "django", "tastypie" ]
In Django project i get two objects when i receive the JSON response `data.meta` and `data.objects` This is my Resource ``` class MyResource(ModelResource): def dehydrate(self, bundle): bundle.data["absolute_url"] = bundle.obj.get_absolute_url() bundle.data['myfields'] = MyDataFields retu...
a better approach IMHO would be to use [alter\_list\_data\_to\_serialize](http://django-tastypie.readthedocs.io/en/latest/resources.html?#Resource.alter_list_data_to_serialize), the function made to override/add fields to the data before making the response: ``` def alter_list_data_to_serialize(self, request, data...
how to access the class variable by string in Python?
13,303,100
6
2012-11-09T06:19:57Z
13,303,121
12
2012-11-09T06:22:13Z
[ "python", "class", "variables" ]
The codes are like this: ``` class Test: a = 1 def __init__(self): self.b=2 ``` When I make an instance of `Test`, I can access its instance variable `b` like this(using the string "b"): ``` test = Test() a_string = "b" print test.__dict__[a_string] ``` But it doesn't work for `a` as `self.__dict__`...
``` getattr(test, a_string) ``` plus some more characters so I can post it.