title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
How to filter the DataFrame rows of pandas by "within"/"in"?
12,065,885
146
2012-08-22T03:16:56Z
12,065,904
210
2012-08-22T03:21:12Z
[ "python", "pandas" ]
I have a Python pandas DataFrame `rpt`: ``` rpt <class 'pandas.core.frame.DataFrame'> MultiIndex: 47518 entries, ('000002', '20120331') to ('603366', '20091231') Data columns: STK_ID 47518 non-null values STK_Name 47518 non-null values RPT_Date 47518 non-null val...
Use the `isin` method. `rpt[rpt['STK_ID'].isin(stk_list)]`.
How to filter the DataFrame rows of pandas by "within"/"in"?
12,065,885
146
2012-08-22T03:16:56Z
19,295,726
21
2013-10-10T12:26:29Z
[ "python", "pandas" ]
I have a Python pandas DataFrame `rpt`: ``` rpt <class 'pandas.core.frame.DataFrame'> MultiIndex: 47518 entries, ('000002', '20120331') to ('603366', '20091231') Data columns: STK_ID 47518 non-null values STK_Name 47518 non-null values RPT_Date 47518 non-null val...
you can also use ranges by using: ``` b = df[(df['a'] > 1) & (df['a'] < 5)] ```
How to filter the DataFrame rows of pandas by "within"/"in"?
12,065,885
146
2012-08-22T03:16:56Z
26,724,725
50
2014-11-03T22:49:27Z
[ "python", "pandas" ]
I have a Python pandas DataFrame `rpt`: ``` rpt <class 'pandas.core.frame.DataFrame'> MultiIndex: 47518 entries, ('000002', '20120331') to ('603366', '20091231') Data columns: STK_ID 47518 non-null values STK_Name 47518 non-null values RPT_Date 47518 non-null val...
`isin()` is ideal if you have a list of exact matches, but if you have a list of partial matches or substrings to look for, you can filter using the [`str.contains`](http://pandas.pydata.org/pandas-docs/dev/generated/pandas.core.strings.StringMethods.contains.html) method and regular expressions. For example, if we wa...
How to filter the DataFrame rows of pandas by "within"/"in"?
12,065,885
146
2012-08-22T03:16:56Z
29,108,799
19
2015-03-17T20:12:10Z
[ "python", "pandas" ]
I have a Python pandas DataFrame `rpt`: ``` rpt <class 'pandas.core.frame.DataFrame'> MultiIndex: 47518 entries, ('000002', '20120331') to ('603366', '20091231') Data columns: STK_ID 47518 non-null values STK_Name 47518 non-null values RPT_Date 47518 non-null val...
You can also directly [query](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.query.html) your DataFrame for this information. ``` rpt.query('STK_ID in (600809,600141,600329)') ``` Or similarly search for ranges: ``` rpt.query('60000 < STK_ID < 70000') ```
How to convert a str to a single element list in python
12,066,054
2
2012-08-22T03:46:12Z
12,066,068
9
2012-08-22T03:48:28Z
[ "python" ]
I have a str variable: `var_1 = "hello"` , and I want to convert it to a single element list, I try this: ``` >>> list(var_1) ['h', 'e', 'l', 'l', 'o'] ``` which is not the `['hello']` that I want. How do I do that?
Just put square brackets ``` >>> var_1 = "hello" >>> [var_1] ['hello'] ```
Python:Some special method for escaping single quotes and double quotes from a string variable
12,066,756
3
2012-08-22T05:26:31Z
12,066,822
9
2012-08-22T05:32:40Z
[ "python", "sqlite", "sqlite3", "python-2.7" ]
I am inputting a variable of datatype string in Sqlite database with my Python script.So whenever i am inserting that value i am getting Sqlite error: ``` sqlite3.OperationalError: near "s": syntax error ``` My variable string is something like this: ``` file_path=r'James Bond 007 - 07 - On Her Majesty's Secret Serv...
You're doing it wrong. ``` cursor.execute("INSERT ... (?, ?, ?)", (var1, var2, var3)) ```
Does Django have an equivalent of Rails's "bundle install"?
12,069,336
8
2012-08-22T08:42:54Z
12,069,483
9
2012-08-22T08:51:56Z
[ "python", "django" ]
One thing I like about Rails projects is that when deploying to a remote server, if everything is set up correctly you can just do: ``` $: bundle install ``` And the system will install the various dependencies (ruby gems) needed to run the project. Is there something similar for Python/Django?
You can freeze requirements. This generates a list of all the Python modules that your project needs. I believe `bundle` is similar in concept. For example: ``` virtualenv --no-site-packages myproject_env # create a blank Python virtual environment source myproject_env/bin/activate # activate it (myproject_env)$ pip ...
AssertionError: incompatible sizes: argument 'height' must be length 2 or scalar (Matplotlib, Python 2.7, drawing charts)
12,069,624
8
2012-08-22T09:01:43Z
12,070,344
11
2012-08-22T09:41:15Z
[ "python", "matplotlib" ]
A new day brought new problem with Python, unfortunately :/ I have a file generated by my other app written in Java. This app generates files with some data, it's kind a random stuff 'cause I'm not able to say how many rows each file would have. Example file looks like this: ``` 3 Sat Jan 21 00:00:00 2012 7 Sun M...
It's because dates only has 2 values. The length of dates and the length of values must be the same for matplotlib to know what to do. If values was a scalar then all the bars would have the same height
Why is datetime.strptime not working in this simple example?
12,070,193
30
2012-08-22T09:32:41Z
12,070,240
13
2012-08-22T09:35:10Z
[ "python", "string", "datetime", "type-conversion", "datetime-format" ]
I'm using [strptime](http://docs.python.org/library/datetime.html#datetime.datetime.strptime) to convert a date string into a `datetime`. According to the linked page, formatting like this should work: ``` >>> # Using datetime.strptime() >>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M") ``` My code is: ...
You are importing the module datetime, which doesn't have a `strptime` function. That module *does* have a `datetime` object with that method though: ``` import datetime dtDate = datetime.datetime.strptime(sDate, "%m/%d/%Y") ``` Alternatively you can import the `datetime` object from the module: ``` from datetime i...
Why is datetime.strptime not working in this simple example?
12,070,193
30
2012-08-22T09:32:41Z
12,070,426
31
2012-08-22T09:45:59Z
[ "python", "string", "datetime", "type-conversion", "datetime-format" ]
I'm using [strptime](http://docs.python.org/library/datetime.html#datetime.datetime.strptime) to convert a date string into a `datetime`. According to the linked page, formatting like this should work: ``` >>> # Using datetime.strptime() >>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M") ``` My code is: ...
You should be using `datetime.datetime.strptime`. Note that very old versions of Python (2.4 and older) don't have `datetime.datetime.strptime`; use [`time.strptime`](http://docs.python.org/library/time.html#time.strptime) in that case.
Setting hadoop parameters with boto?
12,071,436
7
2012-08-22T10:48:48Z
12,071,437
13
2012-08-22T10:48:48Z
[ "python", "boto", "elastic-map-reduce" ]
I am trying to enable bad input skipping on my Amazon Elastic MapReduce jobs. I am following the wonderful recipe described here: <http://devblog.factual.com/practical-hadoop-streaming-dealing-with-brittle-code> The link above says that I need to somehow set the following configuration parameters on an EMR job: ``` ...
After many hours of struggling, reading code, and experimentation, here is the answer: You need to add a new BootstrapAction, like so: ``` params = ['-s','mapred.skip.mode.enabled=true', '-s', 'mapred.skip.map.max.skip.records=1', '-s', 'mapred.skip.attempts.to.start.skipping=2', '-s', '...
Work with bytes in python
12,073,115
3
2012-08-22T12:26:14Z
12,073,219
7
2012-08-22T12:30:53Z
[ "python", "bytearray" ]
I have to get bytes array and send it into socket. The structure looks like: 1 byte + 2 bytes + 2 bytes. First byte is number '5', second 2 bytes should be taken from variable `first`, third 2 bytes should be taken from variable `second`. What's the right way to do this in python? ``` id = 5 # Fill as 1 byte fi...
Use the [`struct` module](http://docs.python.org/py3k/library/struct.html): ``` >>> import struct >>> id, first, second = 5, 42, 58 >>> struct.pack('>bhb', id, first, second) b'\x05\x00*:' ``` You may want to figure out if your data is a) little or big endian and b) is signed or unsigned; the example above use big-en...
TypeError: 'generator' object is not callable
12,074,726
4
2012-08-22T13:53:58Z
12,074,749
9
2012-08-22T13:55:07Z
[ "python", "generator", "yield" ]
I have a generator defined like this: ``` def lengths(x): for k, v in x.items(): yield v['time_length'] ``` And it works, calling it with ``` for i in lengths(x): print i ``` produces: ``` 3600 1200 3600 300 ``` which are the correct numbers. However, when I call it like so: ``` somefun(lengths(...
You don't need to call your generator, remove the `()` brackets. You are probably confused by the fact that you use the same name for the variable inside the function as the name of the generator; the following will work too: ``` def somefun(lengen): for length in lengen: if not is_blahblah(length): retur...
How hard to reverse engineer .pyd files?
12,075,042
11
2012-08-22T14:10:52Z
12,075,208
8
2012-08-22T14:20:23Z
[ "python", "reverse-engineering", "pyc", "pyd" ]
After reading [How do I protect python code?](http://stackoverflow.com/questions/261638/how-do-i-protect-python-code) , I decided to try a really simple extension module on Windows. I compiled my own extension module on Linux before, but this is the first time I compiled it on Windows. I was expecting to get a .dll fil...
They are, as you already found out, equivalent to DLL files with a certain structure. In principle, they are equally hard to reverse-engineer, they are machine code, need very little metadata, and the code may have been optimized beyond recognition. However, the required structure, and knowing that many functions will...
flask-login: can't understand how it works
12,075,535
42
2012-08-22T14:36:56Z
12,081,788
43
2012-08-22T21:38:17Z
[ "python", "mysql", "flask-login" ]
I'm trying to understand how [`Flask-Login`](https://flask-login.readthedocs.org/en/latest/) works. I see in their documentation that they use a pre-populated list of users. I want to play with a database-stored users list. However, I don't understand some things in this [`Flask-Login`](https://flask-login.readthedoc...
Flask-login doesn't actually have a user backend, it just handles the session machinery to help you login and logout users. You have to tell it (by decorating methods), what represents a user and it is also up to you to figure out how to know if a user is "active" or not (since being "active" can mean different things ...
How to deal with time values over 24 hours in python?
12,075,562
3
2012-08-22T14:37:43Z
12,075,654
8
2012-08-22T14:42:19Z
[ "python", "date", "time", "format" ]
I'm dealing with a large amount of data that has both values and times(in strings). I am converting the string time values into datetime values with the following code: ``` time = datetime.datetime.strptime(time, " %H:%M:%S.%f") ``` The only problem is that some of my data has the format: 24:00:00.004. So some of ...
The `%H` parameter can only parse values in the range 0-23. You'll have to manually deal with those specific time stamps: ``` try: time = datetime.datetime.strptime(time, " %H:%M:%S.%f") except ValueError: time = time.replace(' 24', ' 23') time = datetime.datetime.strptime(time, " %H:%M:%S.%f") tim...
Most pythonic way to get the previous element
12,076,270
8
2012-08-22T15:16:09Z
12,076,386
25
2012-08-22T15:22:05Z
[ "python", "iterator" ]
I would like an `enumerate`-like functional on iterators which yields the pair `(previous_element, current_element)`. That is, given that `iter` is ``` i0, i1, i1, ... ``` I would like `offset(iter)` to yield ``` (None, i0), (i0, i1), (i1, i2) ... ```
What about the simple (obvious) solution? ``` def offset(iterable): prev = None for elem in iterable: yield prev, elem prev = elem ```
Most pythonic way to get the previous element
12,076,270
8
2012-08-22T15:16:09Z
12,076,426
8
2012-08-22T15:24:17Z
[ "python", "iterator" ]
I would like an `enumerate`-like functional on iterators which yields the pair `(previous_element, current_element)`. That is, given that `iter` is ``` i0, i1, i1, ... ``` I would like `offset(iter)` to yield ``` (None, i0), (i0, i1), (i1, i2) ... ```
To put more itertools on the table: ``` from itertools import tee, izip, chain def tee_zip(iterable): a, b = tee(iterable) return izip(chain([None], a), b) ```
are user defined classes mutable
12,076,445
10
2012-08-22T15:24:58Z
12,076,539
15
2012-08-22T15:29:52Z
[ "python", "class", "immutability", "mutable" ]
Say I want to create a class for `car`, `tractor` and `boat`. All these classes have an instance of `engine` and I want to keep track of all the engines in a single list. If I understand correctly if the motor object is mutable i can store it as an attribute of `car` and also the same instance in a list. I cant track ...
User classes are considered mutable. Python doesn't have (absolutely) private attributes, so you can always change a class by reaching into the internals. For using your class as a key in a `dict` or storing them in a `set`, you can define a [`.__hash__()` method](http://docs.python.org/reference/datamodel.html#object...
Jinja Templates - Format a float as comma-separated currency
12,078,571
18
2012-08-22T17:41:59Z
12,080,621
33
2012-08-22T20:07:09Z
[ "python", "flask", "jinja" ]
I'm trying to format a float as comma-separated currency. E.g. `543921.9354` becomes `$543,921.94`. I'm using the `format` filter in Jinja templates, which seems to mimic the `%` operator in Python rather than the Python `format` function? How can I accomplish this formatting in Jinja? Is it possible using the `format...
Write a [custom filter](http://jinja.pocoo.org/docs/api/#custom-filters) for that. If you are using python 2.7, it can look like this: ``` def format_currency(value): return "${:,.2f}".format(value) ```
Jinja Templates - Format a float as comma-separated currency
12,078,571
18
2012-08-22T17:41:59Z
31,158,813
14
2015-07-01T10:29:26Z
[ "python", "flask", "jinja" ]
I'm trying to format a float as comma-separated currency. E.g. `543921.9354` becomes `$543,921.94`. I'm using the `format` filter in Jinja templates, which seems to mimic the `%` operator in Python rather than the Python `format` function? How can I accomplish this formatting in Jinja? Is it possible using the `format...
Update: Using Jinja2 and Python 3, this worked quite nicely in the template without having to define any custom code: ``` {{ "${:,.2f}".format(543921.9354) }} ``` I'm not sure exactly what the dependencies are to have this work, but IMHO anyone else reading this answer would do well to at least try it before worrying...
How do you unit test a Celery task?
12,078,667
43
2012-08-22T17:47:52Z
12,080,924
21
2012-08-22T20:29:48Z
[ "python", "unit-testing", "celery" ]
The Celery documentation [mentions testing Celery within Django](http://docs.celeryproject.org/projects/django-celery/en/2.4/cookbook/unit-testing.html) but doesn't explain how to test a Celery task if you are not using Django. How do you do this?
Depends on what exactly you want to be testing. * Test the task code directly. Don't call "task.delay(...)" just call "task(...)" from your unit tests. * Use [CELERY\_ALWAYS\_EAGER](http://docs.celeryproject.org/en/latest/configuration.html#celery-always-eager). This will cause your tasks to be called immediately at t...
How do you unit test a Celery task?
12,078,667
43
2012-08-22T17:47:52Z
12,080,984
27
2012-08-22T20:33:59Z
[ "python", "unit-testing", "celery" ]
The Celery documentation [mentions testing Celery within Django](http://docs.celeryproject.org/projects/django-celery/en/2.4/cookbook/unit-testing.html) but doesn't explain how to test a Celery task if you are not using Django. How do you do this?
It is possible to test tasks synchronously using any unittest lib out there. I normaly do 2 different test sessions when working with celery tasks. The first one (as I'm suggesting bellow) is completely synchronous and should be the one that makes sure the algorithm does what it should do. The second session uses the w...
How do you unit test a Celery task?
12,078,667
43
2012-08-22T17:47:52Z
21,041,324
33
2014-01-10T10:05:23Z
[ "python", "unit-testing", "celery" ]
The Celery documentation [mentions testing Celery within Django](http://docs.celeryproject.org/projects/django-celery/en/2.4/cookbook/unit-testing.html) but doesn't explain how to test a Celery task if you are not using Django. How do you do this?
I use this: ``` with mock.patch('celeryconfig.CELERY_ALWAYS_EAGER', True, create=True): ... ``` Docs: <http://docs.celeryproject.org/en/latest/configuration.html#celery-always-eager> CELERY\_ALWAYS\_EAGER lets you run your task synchronous, and you don't need a celery server.
Error R14 (Memory quota exceeded) Not visible in New Relic
12,079,582
5
2012-08-22T18:52:59Z
12,085,512
12
2012-08-23T05:53:09Z
[ "python", "django", "heroku" ]
Keep getting a Error R14 (Memory quota exceeded) on Heroku. Profiling the memory on the django app locally I don't see any issues. We've installed New Relic, and things seem to be fine there, except for one oddity: <http://screencast.com/t/Uv1W3bjd> Memory use hovers around 15mb per dyno, but for some reason the 'dy...
I BELIEVE I may have found the issue. Based on [posts](http://www.askthepony.com/blog/2011/07/getting-django-on-heroku-prancing-8-times-faster/) like [these](http://v3.mike.tig.as/blog/2012/02/13/deploying-django-on-heroku/) I thought that I should have somewhere in the area of 9-10 gunicorn workers. I believe this is...
Make virtualenv inherit specific packages from your global site-packages
12,079,607
91
2012-08-22T18:54:52Z
19,459,977
104
2013-10-18T22:25:01Z
[ "python", "virtualenv" ]
I'm looking for a way to make a virtualenv which will contain just some libraries (which i chose) of the base python installation. To be more concrete, I'm trying to import my matplotlib to virtualenv during the creation of virtualenv. It can't be installed efficiently with pip or easy\_install since it misses some fo...
Create the environment with `virtualenv --system-site-packages` . Then, activate the virtualenv and when you install things use `pip install --ignore-installed` or `pip install -I` . That way pip will install what you've requested locally even though a system-wide version exists. Your python interpreter will look first...
Quiver plot arrow aspect ratio
12,079,842
8
2012-08-22T19:10:54Z
12,125,682
8
2012-08-25T21:10:08Z
[ "python", "velocity", "matplotlib" ]
I am having some issues with Matplotlib's quiver plot. Given a velocity vector field, I want to plot the velocity vectors on top of the stream lines. The vectors are not tangent to the stream function as expected. To calculate the stream function, I use a Python translated version of Dr. Pankratov's Matlab code availa...
Plot your quiver [(doc)](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.quiver) using ``` pylab.quiver(x, y, u, v, angles='xy', scale_units='xy', scale=10) ``` `angles='uv'` sets the angle of vector by `atan2(u,v)`, `angles='xy'` draws the vector from `(x,y)` to `(x+u, y+v)`
Python list doesn't reflect variable change
12,080,552
10
2012-08-22T20:01:41Z
12,080,644
31
2012-08-22T20:09:19Z
[ "python", "list", "variables" ]
When I write this code: ``` polly = "alive" palin = ["parrot", polly] print(palin) polly = "dead" print(palin) ``` I thought it would output this: ``` "['parrot', 'alive']" "['parrot', 'dead']" ``` However, it doesn't. How do I get it to output that?
Python variables hold references to *values*. Thus, when you define the `palin` list, you pass in the value referenced by `polly`, not the variable itself. You should imagine values as balloons, with variables being threads tied to those balloons. `"alive"` is a balloon, `polly` is just a thread to that balloon, and t...
python, % and mysql statements
12,080,786
2
2012-08-22T20:20:30Z
12,080,810
7
2012-08-22T20:22:21Z
[ "python" ]
I am trying to execute a mysql query, which needs to contain % characters... While building the query, I run into a problem of python using % and trying to stick it as a variable: ``` statmt="select id from %s WHERE `email` LIKE %blah%" % (tbl) self.cursor.execute(statmt) ``` This naturally barfs with: ``` statmt="s...
When needing a literal `%` inside a Python formatting expression, use `%%`: ``` statmt="select id from %s WHERE `email` LIKE '%%blah%%'" % (tbl) ``` See the documentation [section 5.6.2. String Formatting Operations](http://docs.python.org/library/stdtypes.html#string-formatting-operations) for more information.
Python, the same "for" for two lists
12,081,145
2
2012-08-22T20:44:08Z
12,081,163
13
2012-08-22T20:45:06Z
[ "python", "arrays", "list" ]
I have two lists ``` a: a, b, c, d, e b: blue, white, brown, yellow, red ``` I need a to become blue's key in a dictonary, so i need to do this: ``` dictonary[a]="blue" ``` but how do I do it using the same for...
Use [`zip()`](http://docs.python.org/library/functions.html#zip) to merge `a` and `b`: ``` dict(zip(a, b)) ``` Because the `dict()` constructor also can take a sequence of (key, value) pairs no for loops are needed at all.
Python module to change system date and time
12,081,310
10
2012-08-22T20:58:22Z
12,292,874
17
2012-09-06T04:12:25Z
[ "python", "date", "time" ]
How can I change System Date, Time, Timezone in Python? Is there any module available for this? 1. I don't want to execute any system commands 2. I want one common solution, which should work on both Unix and Windows.
``` import sys import datetime time_tuple = ( 2012, # Year 9, # Month 6, # Day 0, # Hour 38, # Minute 0, # Second 0, # Millisecond ) def _win_set_time(time_tuple): import pywin32 # http://t...
python mysql delete statement not working
12,082,360
3
2012-08-22T22:38:37Z
12,082,392
8
2012-08-22T22:41:47Z
[ "python" ]
here I am trying to remove any users which containt a " in their email/username. ``` def removeQuote(self, tbl,record): """ Updates the record """ statmt="select id from %s WHERE `email` LIKE '%%\"%%'" % (tbl) self.cursor.execute(statmt) rows=list(self.cursor.fetchal...
You need to commit the change, using the commit() method on the connection object. Most DBAPI interfaces use implicit transactions. Also, don't use string formatting for SQL query generation! It will open you up to SQL injections: **UNSAFE!!** ``` # What happens if id = "1'; DROP DATABASE somedb" ? delstatmt = "DELE...
Override function declaration in autodoc for sphinx
12,082,570
7
2012-08-22T23:03:45Z
12,087,750
8
2012-08-23T08:34:53Z
[ "python", "documentation", "python-sphinx" ]
I have a module that goes something like this: ``` #!/usr/bin/env python #: Documentation here. #: blah blah blah foobar = r'Some really long regex here.' def myfunc(val=foobar): '''Blah blah blah''' pass ``` ...and I have a `.rst` file that goes something like this: ``` :mod:`my_module` Module -----------...
You have a module-level variable that is used as the default value of a keyword argument in a function. Sphinx displays the value (instead of the name) of that variable in the function signature. This problem is discussed in [another question](http://stackoverflow.com/q/7228797/407651), and the OP has also submitted [a...
Bug in Python Regex? (re.sub with re.MULTILINE)
12,082,886
5
2012-08-22T23:43:14Z
12,083,038
13
2012-08-23T00:01:48Z
[ "python", "regex" ]
I'm noticing some odd behavior in Python's Regex library, and I'm not sure if I'm doing something wrong. If I run a regex on it using `re.sub()`, with `re.MULTILINE`. It seems to only replace the first few occurrences. It replaces all occurrences if I turn off `re.MULTILINE`, use `re.subn(..., count = 0, flags = re.MU...
Use ``` re.sub(pattern, replace, text, flags=re.MULTILINE) ``` instead of ``` re.sub(pattern, replace, text, re.MULTILINE) ``` which is equivalent to ``` re.sub(pattern, replace, text, count=re.MULTILINE) ``` which is a bug in your code. See [re.sub()](http://docs.python.org/library/re.html#re.sub)
PyQt: updating GUI from a callback
12,083,034
3
2012-08-23T00:00:45Z
12,083,625
8
2012-08-23T01:37:33Z
[ "python", "multithreading", "user-interface", "pyqt" ]
Using Python3 and PyQt4 I have a function (**run**) that takes as an input a callable to provide status updates. ``` class Windows(QtGui.QWidget): # Creates a widget containing: # - a QLineEdit (status_widget) # - a button, connected to on_run_clicked def on_run_clicked(self): def update(text)...
I don't know the specific reason why one class works and the other doesn't - nor do I really know the difference between using Python threading vs. Qt's threading...however, I can tell you that it is very tempremental if you don't set it up properly. Namely, you cannot (or at the very least, should not) modify GUI obje...
python urllib2 urlopen response
12,083,231
17
2012-08-23T00:32:02Z
12,083,328
24
2012-08-23T00:47:26Z
[ "python", "urllib2", "urlopen" ]
python urllib2 urlopen response: ``` <addinfourl at 1081306700 whose fp = <socket._fileobject object at 0x4073192c>> ``` expected: {"token":"mYWmzpunvasAT795niiR"}
You need to bind the resultant file-like object to a variable, otherwise the interpreter just dumps it via `repr`: ``` >>> import urllib2 >>> urllib2.urlopen('http://www.google.com') <addinfourl at 18362520 whose fp = <socket._fileobject object at 0x106b250>> >>> >>> f = urllib2.urlopen('http://www.google.com') >>> f...
Is it possible to determine with NDB if model is persistent in the datastore or not?
12,083,254
11
2012-08-23T00:35:44Z
12,096,066
10
2012-08-23T16:20:45Z
[ "python", "google-app-engine" ]
I am in process of migration from `db.Model` to `ndb.Model`. The only issue that I have to solve before finish this migration is that there is no `Model.is_saved` method. I have used `db.Model.is_saved` in my application to determine if sharded counters must be updated on `put`/`delete`, to check for conflicted keys on...
To get the same kind of state in NDB you would need a combination of post-get-hook and post-put-hook to set a flag. Here's a working example: ``` class Employee(ndb.Model): <properties here> saved = False # class variable provides default value @classmethod def _post_get_hook(cls, key, future): obj = fu...
python 2.5 encoding
12,086,953
2
2012-08-23T07:43:51Z
12,087,064
7
2012-08-23T07:51:05Z
[ "python", "character-encoding", "utf8-decode" ]
``` # -*- coding: utf-8 -*- from pyquery import PyQuery as pq from urllib import urlencode from urllib2 import Request,urlopen def sendRequest(url, data = None, headersOnly = False): headers = { 'User-Agent' : 'Mozilla/5.0 (X11; U; Linux i686; en-US;)' } request = Request(url, data, headers) return ur...
You need to specify an encoding for your source code, or use a character escape instead. ``` # -*- coding: utf-8 -*- ``` or ``` print 'caf\xc3\xa9' # UTF-8 representation of e accent egu. ``` You probably want to use a Unicode literal though (here with a unicode escape character): ``` print u'caf\u00e9' ``` Pleas...
Should I add a trailing comma after the last argument in a function call?
12,087,742
4
2012-08-23T08:34:26Z
12,087,814
8
2012-08-23T08:38:44Z
[ "python", "function", "coding-style", "parameter-passing" ]
What is better to do? ``` self.call(1, True, "hi") ``` or ``` self.call(1, True, "hi",) ``` And what in the following cases: ``` self.call( 1, True, "hi" ) ``` or ``` self.call( 1, True, "hi", ) ``` ? Reasons for adding a trailing comma in data structures are familiar to me, but what ab...
In data structures, the trailing comma is "useful" for making it easier to add items: ``` a = [ 1, 2, 3, ] ``` is easier to change into ``` a = [ 1, 2, 3, 4, 5, ] ``` because you don't have to edit the line that says `3,`. But there is no such benefit in func...
Should I add a trailing comma after the last argument in a function call?
12,087,742
4
2012-08-23T08:34:26Z
17,492,103
10
2013-07-05T15:14:37Z
[ "python", "function", "coding-style", "parameter-passing" ]
What is better to do? ``` self.call(1, True, "hi") ``` or ``` self.call(1, True, "hi",) ``` And what in the following cases: ``` self.call( 1, True, "hi" ) ``` or ``` self.call( 1, True, "hi", ) ``` ? Reasons for adding a trailing comma in data structures are familiar to me, but what ab...
I think there's no technical reason to avoid trailing slashes in function calls, but some people probably do find them distracting. Some may stop and say, "Hmmm, I wonder if that's really supposed to be there?" I hesitate to call this a benefit, but one *effect* of using trailing slashes in conjunction with an indente...
Pythonic way to sorting list of namedtuples by field name
12,087,905
24
2012-08-23T08:44:13Z
12,087,992
27
2012-08-23T08:48:23Z
[ "python", "sorting", "namedtuple", "field-names" ]
I want to sort a list of named tuples without having to remember the index of the fieldname. My solution seems rather awkward and was hoping someone would have a more elegant solution. ``` from operator import itemgetter from collections import namedtuple Person = namedtuple('Person', 'name age score') seq = [ Pe...
``` from operator import attrgetter from collections import namedtuple Person = namedtuple('Person', 'name age score') seq = [Person(name='nick', age=23, score=100), Person(name='bob', age=25, score=200)] ``` Sort list by name ``` sorted(seq, key=attrgetter('name')) ``` Sort list by age ``` sorted(seq, key=...
Pythonic way to sorting list of namedtuples by field name
12,087,905
24
2012-08-23T08:44:13Z
12,088,018
30
2012-08-23T08:50:12Z
[ "python", "sorting", "namedtuple", "field-names" ]
I want to sort a list of named tuples without having to remember the index of the fieldname. My solution seems rather awkward and was hoping someone would have a more elegant solution. ``` from operator import itemgetter from collections import namedtuple Person = namedtuple('Person', 'name age score') seq = [ Pe...
``` sorted(seq, key=lambda x: x.name) sorted(seq, key=lambda x: x.age) ```
python list concatenation efficiency
12,088,089
8
2012-08-23T08:54:14Z
12,088,747
9
2012-08-23T09:34:36Z
[ "python", "list" ]
What is the most efficient way to concatenate two lists `list_a` and `list_b` when: * `list_b` items have to be placed before `list_a` items * the result must be placed in `list_a` I have 4 possibilities in mind: ``` # 1 list_a = list_b + list_a # 2 for item in list_b: list_a.insert(0, item) # 3 for item in se...
Here's a graph of how the timings used in the answer of BigYellowCactus develop as the length of the lists increase. The vertical axis is the time required to initialize both lists and insert one in front of the other, in usec. The horizontal axis is the number of items in the lists. ![Asymptotic behaviour of the poss...
Listing available com ports with Python
12,090,503
28
2012-08-23T11:25:30Z
14,224,477
58
2013-01-08T21:38:10Z
[ "python", "pyserial" ]
I am searching for a simple method to list all available com port on a PC. I have found this method but it is windows specific : [Listing serial (COM) ports on Windows?](http://stackoverflow.com/questions/1205383/listing-serial-com-ports-on-windows) I am using python 3 with pyserial on an win7 (windows seven) PC. I ...
This is the code I use. Successfully tested on Windows 8.1 x64, Windows 10 x64, Mac OS X 10.9.x / 10.10.x / 10.11.x and Ubuntu 14.04 / 14.10 / 15.04 / 15.10 with both Python 2 and Python 3. ``` import sys import glob import serial def serial_ports(): """ Lists serial port names :raises EnvironmentError...
Listing available com ports with Python
12,090,503
28
2012-08-23T11:25:30Z
24,720,101
8
2014-07-13T06:21:25Z
[ "python", "pyserial" ]
I am searching for a simple method to list all available com port on a PC. I have found this method but it is windows specific : [Listing serial (COM) ports on Windows?](http://stackoverflow.com/questions/1205383/listing-serial-com-ports-on-windows) I am using python 3 with pyserial on an win7 (windows seven) PC. I ...
A possible refinement to Thomas's excellent answer is to have Linux and possibly OSX also try to open ports and return only those which could be opened. This is because Linux, at least, lists a boatload of ports as files in /dev/ which aren't connected to anything. If you're running in a terminal, /dev/tty is the termi...
parsing json formatted requests in appengine
12,091,028
3
2012-08-23T11:57:37Z
12,091,446
10
2012-08-23T12:19:32Z
[ "python", "google-app-engine" ]
been working on an appengine app lately. i would like to parse json data contained in requests to the app. how do i use the request object of the requesthandler class to achieve this? below is a snippet of the code to show what i want to achieve ``` import cgi import webapp2 import datamethods from google.appengine....
You have to parse the incoming json string in an object. After this you can access the attributes. ``` import json # Now you can import json instead of simplejson .... jsonstring = self.request.body jsonobject = json.loads(jsonstring) ```
'negative' pattern matching in python
12,091,065
5
2012-08-23T11:59:56Z
12,091,566
18
2012-08-23T12:25:43Z
[ "python", "regex" ]
My inupt is: ``` OK SYS 10 LEN 20 12 43 1233a.fdads.txt,23 /data/a11134/a.txt 3232b.ddsss.txt,32 /data/d13f11/b.txt 3452d.dsasa.txt,1234 /data/c13af4/f.txt . ``` Now, I want to get everything except "`OK SYS 10 LEN 20`" and last dot `"."` : ``` 1233a.fdads.txt,23 /data/a11134/a.txt 3232b.ddsss.txt,32 /data/d13f11/b....
See it [in action](http://regexr.com?31u07): ``` matchObj = re.search("^(?!OK|\\.).*", item) ``` Don't forget to put `.*` after negative look-ahead, otherwise you couldn't get any match ;-)
matplotlib: inset axes for multiple boxplots
12,091,471
5
2012-08-23T12:20:54Z
12,096,155
13
2012-08-23T16:25:12Z
[ "python", "plot", "matplotlib", "zoom", "boxplot" ]
I have a few boxplots in matplotlib that I want to zoom in on a particular y-range ([0,0.1]) using [inset axes](http://matplotlib.sourceforge.net/mpl_toolkits/axes_grid/users/overview.html). It is not clear to me from the [example](http://matplotlib.sourceforge.net/mpl_toolkits/axes_grid/examples/inset_locator_demo2.py...
The `loc` determines the location of the zoomed axis, 1 for `upper right`, 2 for `upper left` and so on. I modified the example code slightly to generate multiple zoomed axis. ``` import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes from mpl_toolkits.axes_grid1.inset_loc...
python closure with assigning outer variable inside inner function
12,091,973
13
2012-08-23T12:49:05Z
12,092,094
20
2012-08-23T12:56:24Z
[ "python", "closures", "scope", "python-2.x" ]
I've got this piece of code: ``` #!/usr/bin/env python def get_match(): cache=[] def match(v): if cache: return cache cache=[v] return cache return match m = get_match() m(1) ``` if I run it, it says: ``` UnboundLocalError: local variable 'cache' referenced before assignment ``` but if I do...
The problem is that the variable `cache` is not in the scope of the function match. This is not a problem if you only want to read it as in your second example, but if you're assigning to it, python interprets it as a local variable. If you're using python 3 you can use the `nonlocal` keyword to solve this problem - fo...
python closure with assigning outer variable inside inner function
12,091,973
13
2012-08-23T12:49:05Z
12,092,178
7
2012-08-23T13:00:37Z
[ "python", "closures", "scope", "python-2.x" ]
I've got this piece of code: ``` #!/usr/bin/env python def get_match(): cache=[] def match(v): if cache: return cache cache=[v] return cache return match m = get_match() m(1) ``` if I run it, it says: ``` UnboundLocalError: local variable 'cache' referenced before assignment ``` but if I do...
Accessing a variable is different from assigning it. You have a similar situation with global variables. You can access them in any function, but if you try to assign to it without the `global` statement, it will redeclare it in the local context. Unfortunately for local functions there is no equivalent of the `globa...
Python Write bytes to file
12,092,527
24
2012-08-23T13:19:53Z
12,092,564
51
2012-08-23T13:22:00Z
[ "python" ]
I have a function that returns a string. The string contains carriage returns and new line feeds (0x0D, 0x0A). However when I write to a file it contains only the new line feeds. Is there a way to get the output to include the carriage return and the new line feed. ``` msg = function(arg1, arg2, arg3) f = open('/tmp/o...
If you want to write bytes then you should open the file in binary mode. ``` f = open('/tmp/output', 'wb') ```
How to implement band-pass Butterworth filter with Scipy.signal.butter
12,093,594
32
2012-08-23T14:09:52Z
12,233,959
54
2012-09-02T06:41:24Z
[ "python", "scipy", "signal-processing", "digital-filter" ]
UPDATE: To my surprise, while looking for this same topic almost two years later, I found a Scipy Recipe based in this question! So, for anyone interested, go straight to: <http://wiki.scipy.org/Cookbook/ButterworthBandpass> --- I'm having a hard time to achieve what seemed initially a simple task of implementing a...
You could skip the use of buttord, and instead just pick an order for the filter and see if it meets your filtering criterion. To generate the filter coefficients for a bandpass filter, give butter() the filter order, the cutoff frequencies `Wn=[low, high]` (expressed as the fraction of the Nyquist frequency, which is ...
Passing more kwargs into a function than initially set
12,093,726
3
2012-08-23T14:16:33Z
12,093,751
14
2012-08-23T14:17:47Z
[ "python", "kwargs" ]
Is there a way to send more kwargs into a function than is called for in the function call? Example: ``` def mydef(a, b): print a print b mydict = {'a' : 'foo', 'b' : 'bar'} mydef(**mydict) # This works and prints 'foo' and 'bar' mybigdict = {'a' : 'foo', 'b' : 'bar', 'c' : 'nooooo!'} mydef(**mybigdict) ...
No, unless the function definition allows for more parameters (using the `**kwargs` catch-all syntax), you cannot call a method with more arguments than it has defined. You *can* introspect the function and remove any arguments it won't accept however: ``` import inspect mybigdict = {'a2' : 'foo', 'b2' : 'bar', 'c2'...
How do I check for valid Git branch names?
12,093,748
10
2012-08-23T14:17:31Z
12,093,994
21
2012-08-23T14:31:12Z
[ "python", "regex", "git", "githooks" ]
I'm developing a [`git` `post-receive` hook in Python](https://github.com/alexchamberlain/githooks/blob/master/post-receive.d/jekyll-build). Data is supplied on `stdin` with lines similar to ``` ef4d4037f8568e386629457d4d960915a85da2ae 61a4033ccf9159ae69f951f709d9c987d3c9f580 refs/heads/master ``` The first hash is t...
Let's dissect the various rules and build regex parts from them: 1. They can include slash `/` for hierarchical (directory) grouping, but no slash-separated component can begin with a dot `.` or end with the sequence `.lock`. ``` # must not contain /. (?!.*/\.) # must not end with .lock (?<!\.lock)$ ...
Reading files in a particular order in python
12,093,940
10
2012-08-23T14:28:19Z
12,093,995
21
2012-08-23T14:31:19Z
[ "python", "file", "order" ]
Lets say I have three files in a folder: file9.txt, file10.txt and file11.txt and i want to read them in this particular order. Can anyone help me with this? Right now I am using the code ``` import glob, os for infile in glob.glob(os.path.join( '*.txt')): print "Current File Being Processed is: " + infile ``` a...
Files on the filesystem are not sorted. You can sort the resulting filenames yourself using the [`sorted()` function](http://docs.python.org/library/functions.html#sorted): ``` for infile in sorted(glob.glob('*.txt')): print "Current File Being Processed is: " + infile ``` Note that the `os.path.join` call in you...
Python: 'module' object is not callable
12,094,613
2
2012-08-23T15:00:00Z
12,094,643
7
2012-08-23T15:01:28Z
[ "python", "exception" ]
I have an exception class defined ``` #####UNIQUE CONSTRAINT EXCEPTION#########################################################3 class UniqueConstraintException (Exception): def __init__(self, value): self.value = value def __str__(self): return repr('Failed unique property. Property name: ' +...
This is why you want to keep your module names lower-cased. :-) ``` from exception.UniqueConstraintException import UniqueConstraintException ``` You imported the module, no the class defined inside of the module.
Python - tuple unpacking in dict comprehension
12,094,764
8
2012-08-23T15:08:14Z
12,094,807
12
2012-08-23T15:10:26Z
[ "python", "dictionary", "iterable-unpacking", "dictionary-comprehension" ]
I'm trying to write a function that turns strings of the form `'A=5, b=7'` into a dict `{'A': 5, 'b': 7}`. The following code snippets are what happen inside the main `for` loop - they turn a single part of the string into a single dict element. This is fine: ``` s = 'A=5' name, value = s.split('=') d = {name: int(va...
In your code, `s.split('=')` will return the list: `['A', '5']`. When iterating over that list, a single string gets returned each time (the first time it is `'A'`, the second time it is `'5'`) so you can't unpack that single string into 2 variables. You could try: `for name,value in [s.split('=')]` More likely, you ...
Python - tuple unpacking in dict comprehension
12,094,764
8
2012-08-23T15:08:14Z
12,094,956
7
2012-08-23T15:18:59Z
[ "python", "dictionary", "iterable-unpacking", "dictionary-comprehension" ]
I'm trying to write a function that turns strings of the form `'A=5, b=7'` into a dict `{'A': 5, 'b': 7}`. The following code snippets are what happen inside the main `for` loop - they turn a single part of the string into a single dict element. This is fine: ``` s = 'A=5' name, value = s.split('=') d = {name: int(va...
Some people tend to believe you'll go to hell for using `eval`, but... ``` s = 'A=5, b=7' eval('dict(%s)' % s) ``` Or better, to be safe (thanks to mgilson for pointing it out): ``` s = 'A=5, b=7' eval('dict(%s)' % s, {'__builtins__': None, 'dict': dict}) ```
NDB not clearing memory during a long request
12,095,259
6
2012-08-23T15:35:16Z
12,108,891
9
2012-08-24T11:50:09Z
[ "python", "google-app-engine", "memory-leaks", "task-queue", "app-engine-ndb" ]
I am currently offloading a long running job to a TaskQueue to calculate connections between NDB entities in the Datastore. Basically this queue handles several lists of entity keys that are to be related to another `query` by the `node_in_connected_nodes` function in the `GetConnectedNodes` node: ``` class GetConnec...
We had similar issues (with long running requests). We solved them by turning-off the default ndb cache. You can read more about it [here](https://developers.google.com/appengine/docs/python/ndb/cache)
using django session inside templates
12,096,440
3
2012-08-23T16:43:36Z
12,096,980
8
2012-08-23T17:22:01Z
[ "python", "django", "django-templates", "django-sessions" ]
``` # views.py def like(request,option="food",restaurant = 1): if request.is_ajax: like = '%s_like' % str(option) if 'restaurants' in request.session: if restaurant not in request.session['restaurants']: request.session['restaurants'][restaurant] = {} x = requ...
You might not have "django.core.context\_processors.request" in your settings.TEMPLATE\_CONTEXT\_PROCESSORS. You can try to print {{ request }} in the template, if it shows nothing then you don't have it. You can also check it with ./manage.py shell: ``` from django.conf import settings print settings.TEMPLATE_CONTE...
How to return multiple values in render_template in Flask
12,096,522
13
2012-08-23T16:49:10Z
12,096,776
26
2012-08-23T17:07:24Z
[ "python", "mongodb", "flask" ]
I am using Flask(as framework) and MongoDB(as database server). Right now, all i can do is just pass one argument that i got from the database: ``` @app.route('/im/', methods=['GET', 'POST']) def im_research(user=None): error = None if request.method == 'POST': if request.form['user']: user...
You can pass multiple parameters to the view. You can pass all your local variable ``` @app.route('/') def index(): content = """ teste """ user = "Hero" return render_template('index.html', **locals()) ``` or just pass your data ``` def index() : return render_template('index.html', obj = "object...
fast numpy addnan
12,096,684
7
2012-08-23T17:01:05Z
12,096,964
9
2012-08-23T17:20:55Z
[ "python", "optimization", "numpy", null, "scientific-computing" ]
I would like to add thousands of 4D arrays element wise and accounting for nans. A simple example using 1D arrays would be: ``` X = array([4,7,89,nan,89,65, nan]) Y = array([0,5,4, 9, 8, 100,nan]) z = X+Y print z = array([4,12,93,9,97,165,nan]) ``` I've written a simple for loop around this but it takes forever - no...
Here is one possibility: ``` >>> x = np.array([1, 2, np.nan, 3, np.nan, 4]) ... y = np.array([1, np.nan, 2, 5, np.nan, 8]) >>> x = np.ma.masked_array(np.nan_to_num(x), mask=np.isnan(x) & np.isnan(y)) >>> y = np.ma.masked_array(np.nan_to_num(y), mask=x.mask) >>> (x+y).filled(np.nan) array([ 2., 2., 2., 8., nan,...
Python - parallel commands
12,097,406
5
2012-08-23T17:52:30Z
12,097,555
10
2012-08-23T18:02:35Z
[ "python" ]
How do I run several python commands in parallel in a python script ? As a simple example I have several sleep commands: ``` time.sleep(4) time.sleep(6) time.sleep(8) ``` I want all the above to be executed in parallel. I expect the control back when 8 seconds have passed (which is the max of all the sleeps above). T...
One simple example, using multiprocessing: ``` import multiprocessing as mp import time pool = mp.Pool(3) results = pool.map(time.sleep, [4, 6, 8] ) ``` This spawns separate processes instead of creating separate threads in the same process as demonstrated in the answer by Steven Rumbalski. multiprocessing sidesteps...
What is a more efficient way to pass variables from Template to View in Django?
12,097,475
9
2012-08-23T17:57:24Z
12,097,609
21
2012-08-23T18:06:37Z
[ "python", "django", "templates", "view" ]
My question involves passing variables from the template to view in Django. I know of passing variables in the URL and through a form. The problem I have with the first one is that the url could be manipulated which is not what I want. Is there anyway to prevent that? Right now this is what I have as a band-aid: ```...
There are broadly 3 ways to hold onto this kind of information: ## Session (my suggestion for your situation) Just stuff the data you want into the `request.session` dictionary; it'll persist per-user, and you can access it easily: ``` # view1 request.session['name1'] = male_results request.session['userid1'] = male...
Specifying widget for model form extra field (Django)
12,097,825
16
2012-08-23T18:22:47Z
12,097,900
20
2012-08-23T18:28:32Z
[ "python", "django", "django-forms", "extra" ]
I have to add extra field to my model form. My approach is: ``` class MyForm(forms.ModelForm): extra_field = forms.CharField() class Meta: model = MyModel widgets = { #Does not work 'extra_field': forms.Textarea(attrs={'placeholder': u'Bla bla'}), } ``` But it s...
It doesn't matter if it's an extra field. This works: ``` class FooForm(forms.ModelForm): class Meta: model = People widgets = { 'name': forms.Textarea(attrs={'placeholder': u'Bla bla'}), } ``` This doesn't: ``` class FooForm(forms.ModelForm): name = forms.CharField() ...
Check if a function returns false in Python
12,097,929
10
2012-08-23T18:30:25Z
12,097,968
17
2012-08-23T18:33:13Z
[ "python", "function", "if-statement" ]
In python, I am currently doing this: ``` if user_can_read(request.user, b) == False: ``` Is there any other way of checking if the function returns `False`?
You could just use ``` if user_can_read(request.user, b): ## do stuff ``` If `user_can_read` returns *anything* (except 0, False, etc), it will be considered True, and do stuff. And the negation: `if not user_can_read(request.user, b)`
How to iterate a loop based on a user's input?
12,098,155
4
2012-08-23T18:46:15Z
12,098,174
7
2012-08-23T18:48:05Z
[ "python", "user-interface", "user-input" ]
I'm new here, but look here often for help. Anyways, I am trying to use tkSimpleDialog.askinteger() to ask for how many files the user needs to read into the program. I want to read the files in based on the integer that the user inputs in a for loop. I would index the file names f[1] through f[n] for the file names. A...
Assuming `NumDates` is an integer, you're looking for the range function: ``` for dates in range(NumDates): ... ``` In python 2.x, you can use `xrange` instead. This doesn't create an intermediate list so many people prefer it. In python 3, `xrange` was renamed `range` and the former range function which returns ...
How do you set a default value for a WTForms SelectField?
12,099,741
16
2012-08-23T20:48:18Z
12,100,214
14
2012-08-23T21:25:59Z
[ "python", "flask", "wtforms" ]
When attempting to set the default value of a SelectField with WTForms, I pass in value to the 'default' parameter like so. ``` class TestForm(Form): test_field = SelectField("Test: ", choices=[(1, "Abc"), (2, "Def")], default=2) ``` I have also tried the following. ``` class TestForm(Form): test_field = SelectF...
The first way you posted is correct, and it works for me. The only explanation for it not working can be that you are running an older version of WTForms, it worked for me on 1.0.1
How do you set a default value for a WTForms SelectField?
12,099,741
16
2012-08-23T20:48:18Z
17,019,796
10
2013-06-10T08:32:40Z
[ "python", "flask", "wtforms" ]
When attempting to set the default value of a SelectField with WTForms, I pass in value to the 'default' parameter like so. ``` class TestForm(Form): test_field = SelectField("Test: ", choices=[(1, "Abc"), (2, "Def")], default=2) ``` I have also tried the following. ``` class TestForm(Form): test_field = SelectF...
I believe this problem is caused by the `Field`'s `data` attribute overriding the `default` with something that WTForms doesn't understand (e.g. a DB model object -- it expects an `int`). This would happen if you have populated your form in the constructor like so: ``` form = PostForm(obj=post) ``` the solution is to...
How do you set a default value for a WTForms SelectField?
12,099,741
16
2012-08-23T20:48:18Z
28,686,468
8
2015-02-24T00:52:52Z
[ "python", "flask", "wtforms" ]
When attempting to set the default value of a SelectField with WTForms, I pass in value to the 'default' parameter like so. ``` class TestForm(Form): test_field = SelectField("Test: ", choices=[(1, "Abc"), (2, "Def")], default=2) ``` I have also tried the following. ``` class TestForm(Form): test_field = SelectF...
There are a few ways to do this. Your first code snippet is indeed correct. If you want to do this in a View dynamically though, you can also do: ``` form = TestForm() form.test_field.default = some_default_id form.process() ```
How to extract slides from a video using python
12,100,072
5
2012-08-23T21:15:25Z
12,100,266
10
2012-08-23T21:30:59Z
[ "python", "video", "image-processing", "video-capture", "video-processing" ]
I have a video training course supplied as AVI files. Most of the screens are shown as slides with a mouse pointer moving around on them. I'd like to capture a screenshot of the slide automatically when the screen changes (ignoring when the image changes a small amount due to the mouse pointer moving around.) I want ...
A tool like [ffmpeg](http://ffmpeg.org/) is suited for extracting images from a video. From the manual: ``` ffmpeg -i foo.avi -r 1 -s WxH -f image2 foo-%03d.jpeg ``` This will extract one video frame per second from the video and will output them in files named `foo-001.jpeg`, `foo-002.jpeg`, etc. Images will be res...
pandas: set values with (row, col) indices
12,100,497
13
2012-08-23T21:50:36Z
12,100,543
10
2012-08-23T21:54:44Z
[ "python", "pandas" ]
`pandas` offers the ability to look up by lists of row and column indices, ``` In [49]: index = ['a', 'b', 'c', 'd'] In [50]: columns = ['one', 'two', 'three', 'four'] In [51]: M = pandas.DataFrame(np.random.randn(4,4), index=index, columns=columns) In [52]: M Out[52]: one two three four a -...
I'm not sure I follow you, but do you use `DataFrame.ix` to select/set individual elements: ``` In [79]: M Out[79]: one two three four a -0.277981 1.500188 -0.876751 -0.389292 b -0.705835 0.108890 -1.502786 -0.302773 c 0.880042 -0.056620 -0.550164 -0.409458 d 0.704202 0.619031 0.274018 -1...
Prevent pandas from automatically infering type in read_csv
12,101,113
12
2012-08-23T22:54:04Z
12,117,333
7
2012-08-24T22:15:41Z
[ "python", "pandas" ]
I have a #-separated file with three columns: the first is integer, the second looks like a float, but isn't, and the third is a string. I attempt to load this directly into python with `pandas.read_csv` ``` In [149]: d = pandas.read_csv('resources/names/fos_names.csv', sep='#', header=None, names=['int_field', 'floa...
I think your best bet is to read the data in as a record array first using numpy. ``` # what you described: In [15]: import numpy as np In [16]: import pandas In [17]: x = pandas.read_csv('weird.csv') In [19]: x.dtypes Out[19]: int_field int64 floatlike_field float64 # what you don't want? str_field ...
Prevent pandas from automatically infering type in read_csv
12,101,113
12
2012-08-23T22:54:04Z
12,992,260
9
2012-10-20T20:12:00Z
[ "python", "pandas" ]
I have a #-separated file with three columns: the first is integer, the second looks like a float, but isn't, and the third is a string. I attempt to load this directly into python with `pandas.read_csv` ``` In [149]: d = pandas.read_csv('resources/names/fos_names.csv', sep='#', header=None, names=['int_field', 'floa...
I'm planning to add explicit column dtypes in the upcoming file parser engine overhaul in pandas 0.10. Can't commit myself 100% to it but it should be pretty simple with the new infrastructure coming together (http://wesmckinney.com/blog/?p=543).
Multiple ping script in Python
12,101,239
13
2012-08-23T23:09:43Z
12,101,320
19
2012-08-23T23:21:56Z
[ "python", "networking", "ping" ]
I'm unable to find any good easy to learn documentation on python and networking. In this instance, I'm just trying to make a easy script which I can ping a number of remote machines. ``` for ping in range(1,10): ip="127.0.0."+str(ping) os.system("ping -c 3 %s" % ip) ``` A simple script like that will ping the ...
Try `subprocess.call`. It saves the return value of the program that was used. According to my ping manual, it returns 0 on success, 2 when pings were sent but no reply was received and any other value indicates an error. ``` # typo error in import import subprocess for ping in range(1,10): address = "127.0.0." ...
Keep track of instances in python
12,101,958
9
2012-08-24T00:55:21Z
12,102,163
19
2012-08-24T01:30:10Z
[ "python", "class", "dictionary", "self", "instances" ]
Toward the end of a program I'm looking to load a specific variable from all the instances of a class into a dictionary. For example: ``` class Foo(): __init__(self): x = {} foo1 = Foo() foo2 = Foo() foo...etc. ``` Let's say the number of instances will vary and I want the x dict from each instance of Foo()...
One way to keep track of instances is with a class variable: ``` class A(object): instances = [] def __init__(self, foo): self.foo = foo A.instances.append(self) ``` At the end of the program, you can create your dict like this: ``` foo_vars = {id(instance): instance.foo for instance in A.in...
Keep track of instances in python
12,101,958
9
2012-08-24T00:55:21Z
12,102,666
18
2012-08-24T03:03:44Z
[ "python", "class", "dictionary", "self", "instances" ]
Toward the end of a program I'm looking to load a specific variable from all the instances of a class into a dictionary. For example: ``` class Foo(): __init__(self): x = {} foo1 = Foo() foo2 = Foo() foo...etc. ``` Let's say the number of instances will vary and I want the x dict from each instance of Foo()...
@JoelCornett's answer covers the basics perfectly. This is a slightly more complicated version, which might help with a few subtle issues. If you want to be able to access all the "live" instances of a given class, subclass the following (or include equivalent code in your own base class): ``` from weakref import Wea...
How can I suppress the newline after a print statement?
12,102,749
32
2012-08-24T03:23:33Z
12,102,758
57
2012-08-24T03:24:41Z
[ "python", "python-3.x" ]
I read that to suppress the newline after a print statement you can put a comma after the text. The example [here](http://stackoverflow.com/a/4390955/1343005) looks like Python 2. **How can it be done in Python 3?** For example: ``` for item in [1,2,3,4]: print(item, " ") ``` What needs to change so that it prin...
The question asks: "**How can it be done in Python 3?**" Use this construct with Python 3.x: ``` for item in [1,2,3,4]: print(item, " ", end="") ``` This will generate: ``` 1 2 3 4 ``` See this [Python doc](http://docs.python.org/release/3.0.1/whatsnew/3.0.html) for more information: ``` Old: print x, ...
No errors logged with failed Postgres/Psycopg2 copy_from
12,103,218
8
2012-08-24T04:36:38Z
12,103,274
12
2012-08-24T04:45:42Z
[ "python", "database", "postgresql", "psycopg2" ]
The following code does not elicit an error. But it doesn't put any values in my database either. Have taken all constraints off the table except index on Primary Key. The two fields are both strings. Any ideas? The most confusing thing is that no errors get logged. ``` conn = psycopg2.connect("dbname=<mydbname> user=...
I struggled with this one too. Some hidden knowledge is that you have to do an: ``` output.seek(0) #put the position of the buffer at the beginning ``` after your `write`, or if you're moving from database to database, after you do a `copy_to`. It's easy to forget that `StringIO` objects have all the same methods an...
Calculating nth fibonacci number using the formulae in python
12,103,861
5
2012-08-24T05:58:16Z
12,103,893
10
2012-08-24T06:01:22Z
[ "python", "fibonacci" ]
I am calculating the n-th fibonacci number using (a) a linear approach, and (b) [this](http://en.wikipedia.org/wiki/Fibonacci_number#Closed-form_expression) expression Python code: ``` 'Different implementations for computing the n-th fibonacci number' def lfib(n): 'Find the n-th fibonacci number iteratively' ...
You are indeed seeing rounding errors. The matrix form is the more accurate *and* much faster algorithm. [Literateprograms.org](http://en.literateprograms.org/Fibonacci_numbers_%28Python%29) lists a good implementation, but it also lists the following algorithm based on Lucas numbers: ``` def powLF(n): if n == 1:...
getting error distributionNotFound
12,105,815
6
2012-08-24T08:35:38Z
12,105,921
11
2012-08-24T08:43:42Z
[ "python", "celery" ]
I have installed celeryD and redis on my system. when i am running the command using `celery`. iam getting the following error. ``` Traceback (most recent call last): File "/usr/local/bin/celeryd", line 5, in <module> from pkg_resources import load_entry_point File "/usr/lib/python2.7/dist-packages/pkg_resou...
There's a package called [python-dateutil](http://pypi.python.org/pypi/python-dateutil) that isn't installed. It should be available on the PYTHONPATH that's active when you call celeryd. Python dateutil is installable from [PyPi](http://pypi.python.org/pypi/). Assuming you have [pip](http://pypi.python.org/pypi/pip...
Is there anything to be gained from short variable names?
12,106,515
9
2012-08-24T09:21:10Z
12,106,556
19
2012-08-24T09:23:49Z
[ "python", "interpreted-language" ]
Is there anything to be gained memorywise and speedwise by having shorter variable-names in a language like python? And if so, what kind of situations would it be reasonable to consider this? **Note** I'm in no way advocating short variable names, I'm just wondering, please **(re)read** the question. **Note 2** Ple...
No. No. No. No. No. # No. Use readable names, not short names. The performance difference is absolutely neglegible. --- ``` $ python -m timeit "i = 5" "i *= i" 10000000 loops, best of 3: 0.0938 usec per loop $ python -m timeit "is_there_anything_to_be_gained_from_short_variable_names = 5" "is_there_anything_to_be_...
Is there anything to be gained from short variable names?
12,106,515
9
2012-08-24T09:21:10Z
12,107,102
12
2012-08-24T09:56:19Z
[ "python", "interpreted-language" ]
Is there anything to be gained memorywise and speedwise by having shorter variable-names in a language like python? And if so, what kind of situations would it be reasonable to consider this? **Note** I'm in no way advocating short variable names, I'm just wondering, please **(re)read** the question. **Note 2** Ple...
There's a problem with "like python", because not all interpreted languages are the same. With a purely-interpreted language it would have more of an impact than with one like Python that has a pre-compile step. Strictly this isn't a language difference (you could have one Javascript engine that precompiles, and one t...
Digital sum, Python
12,106,989
4
2012-08-24T09:49:02Z
12,107,072
9
2012-08-24T09:54:15Z
[ "python", "python-3.x" ]
I need to write a code that counts the sum of the digits of a number, these is the exact text of the problem:The digital sum of a number n is the sum of its digits. Write a recursive function digitalSum(n) that takes a positive integer n and returns its digital sum. For example, digitalSum(2019) should return 12 becaus...
Try this: ``` def digitalSum(n): if n < 10 : return n return n % 10 + digitalSum( n // 10 ) ``` **Edit:** The logic behind this algorithm is that for every call of the recursive function, we chop off the number's last digit and add it to the sum. First we obtain the last digit with `n % 10` and then w...
Python quicksort - List comprehension vs Recursion (partition routine)
12,107,790
6
2012-08-24T10:38:13Z
12,108,092
9
2012-08-24T10:58:59Z
[ "python", "sorting", "optimization", "quicksort", "tail-recursion" ]
I watched the talk Three Beautiful Quicksorts and was messing around with quicksort. My implementation in python was very similar to c (select pivot, partition around it and recursing over smaller and larger partitions). Which I thought wasn't *pythonic*. So this is the implementation using list comprehension in pytho...
1. *Why is list comprehension so much faster?* Because list comprehension implies C loop which is much faster than slow general way of using Python's `for` block. 2. *Some enlightenment on the limit on recursion in python. I first set it to 100000 in what cases should I be careful?* In case you run out of memor...
How to "see" the structure of an object in python
12,109,102
4
2012-08-24T12:04:32Z
12,109,118
9
2012-08-24T12:05:56Z
[ "python", "object", "introspection", "tweepy" ]
I am wokring in python 2.7. I have been experimenting with the [tweepy](http://tweepy.github.com/) package. There is an object called the tweepy.models.status object, whose function is defined here: <https://github.com/tweepy/tweepy/blob/master/tweepy/models.py>. I have a function that looks like this: ``` def on...
You could iterate over `status.__dict__.items()`: ``` for k,v in status.__dict__.items(): #same thing as `vars(status)` print k,v ``` The above approach won't work if the class uses `__slots__` and doesn't have a slot for `__dict__`. Classes with `__slots__` are quite rare though, so it's unlikely to be a proble...
Is there a cross-OS GUI framework that supports embedding HTML pages?
12,109,795
9
2012-08-24T12:54:20Z
12,135,297
24
2012-08-27T01:20:23Z
[ "c#", "javascript", "python", "tidesdk" ]
I want to develop a desktop app to be used cross-system (win, mac, linux), is there a GUI framework that would allow me to write code once for all 3 platforms and have a fully-scriptable embedded web component? I need it to have an API to communicate between app and webpage javascript. I know C#, JavaScript and a lit...
There is also [TideSDK](http://tidesdk.org) formally known as Titanium. This provides a WebKit HTML/JavaScript widget that does pretty much everything you could want, including running the Chrome developer tools. --- **EDIT** below. Consolidating my update with feedback from the TideSDK developers: [TideSDK](http://...
Is there a cross-OS GUI framework that supports embedding HTML pages?
12,109,795
9
2012-08-24T12:54:20Z
12,190,496
8
2012-08-30T05:38:28Z
[ "c#", "javascript", "python", "tidesdk" ]
I want to develop a desktop app to be used cross-system (win, mac, linux), is there a GUI framework that would allow me to write code once for all 3 platforms and have a fully-scriptable embedded web component? I need it to have an API to communicate between app and webpage javascript. I know C#, JavaScript and a lit...
as cited, TideSDK (http://www.tidesdk.org/) is an option (the better at the moment for me) you could also go with the same idea XUL Runner (https://developer.mozilla.org/en-US/docs/XULRunner), Adobe AIR (http://www.adobe.com/devnet/air/air-sdk-download.html) ( here: <http://www.adobe.com/devnet/air.html> is the tutoria...
How should I indicate that a test hasn't been written yet in Python?
12,110,610
4
2012-08-24T13:41:57Z
12,110,690
8
2012-08-24T13:47:07Z
[ "python", "unit-testing", "tdd" ]
I'm doing TDD using Python and the `unittest` module. In NUnit you can `Assert.Inconclusive("This test hasn't been written yet")`. So far I haven't been able to find anything similar in Python to indicate that "These tests are just placeholders, I need to come back and actually put the code in them." Is there a Pytho...
With the [new and updated unittest module](http://www.voidspace.org.uk/python/articles/unittest2.shtml) you can skip tests: ``` @skip("skip this test") def testSomething(self): pass # TODO def testBar(self): self.skipTest('We need a test here, really') def testFoo(self): raise SkipTest('TODO: Write a tes...
Python variable variables without eval?
12,111,358
2
2012-08-24T14:29:15Z
12,111,399
10
2012-08-24T14:31:19Z
[ "python", "variables", "eval", "variable-variables" ]
Is there is a way to access variables using a variable string in python? For instance, I would like a neater way than using `eval` for the following: ``` def toggleListButtons (self): buttons = ["flip", "remove", "removeAll", "delete", "deleteAll", "loadDirectory"] for button in buttons: eval("self." +...
What you're looking for is the [getattr()](http://docs.python.org/library/functions.html#getattr) built-in function. There is also [hasattr()](http://docs.python.org/library/functions.html#hasattr) and [setattr()](http://docs.python.org/library/functions.html#setattr). ``` button = getattr(self, 'flipButton') button.s...
capturing dis.dis results
12,111,717
11
2012-08-24T14:49:11Z
12,111,817
17
2012-08-24T14:55:30Z
[ "python", "python-2.7" ]
Is there any way to get the output of `dis.dis()` without redirecting `sys.stdout`? I have tried: ``` out=str(dis.dis()) ``` and ``` out="""""" out+=str(dis.dis()) ``` However I soon found out that it returns `None`. Is there any way to fix this?
Unfortunately, in Python versions before 3.4 the `dis` module uses print statements to stdout, so it won't return anything directly useful. Either you have to re-implement the `dis`, `disassemble` and `disassemble_string` functions, or you temporarily replace `sys.stdout` with an alternative to capture the output: ```...
Python: derived classes access dictionary of base class in the same memory location
12,111,816
5
2012-08-24T14:55:29Z
12,111,845
10
2012-08-24T14:57:07Z
[ "python", "inheritance", "dictionary" ]
I'm wondering why a dictionary, that is defined in a base class and is accessed from derived classes, is obviously present only in one memory location. A short example: ``` class BaseClass: _testdict = dict() _testint = 0 def add_dict_entry(self): self._testdict["first"] = 1 def increment(sel...
It's because `_testdict` is a class variable: it's defined only once, when the class is initially constructed. If you want it to be separate for each instance, make it an instance variable: ``` class BaseClass: _testint = 0 def __init__(self): self._testdict = dict() def add_dict_entry(self): ...
A value in a list, python
12,112,200
4
2012-08-24T15:18:40Z
12,112,248
12
2012-08-24T15:21:39Z
[ "python", "python-3.x" ]
Every character in the English language has a percentage of occurrence, these are the percentages: ``` A B C D E F G H I .0817 .0149 .0278 .0425 .1270 .0223 .0202 .0609 .0697 J K L M N O P Q R .0015 .0077 ...
letterGoodness is better as a dictionary, then you can just do: ``` sum(letterGoodness.get(c,0) for c in yourstring.upper()) # #^.upper for defensive programming ``` To convert `letterGoodness` from your list to a dictonary, you can do: ``` import string letterGoodness = d...
How to automatically destroy django test database
12,113,050
21
2012-08-24T16:15:23Z
12,113,633
25
2012-08-24T16:54:31Z
[ "python", "database", "django", "testing", "hudson" ]
I'm currently trying to automate django tests using hudson, and am struggling to find an option that will automatically destroy the test database if it already exists (typically it will ask for confirmation to destroy it, which the automatic testing obviously cannot provide for). Any suggestions would be much apprecia...
Use --help to see the docs of the test command: ``` >>> ./manage.py test --help Usage: ./manage.py test [options] [appname ...] Runs the test suite for the specified applications, or the entire site if no apps are specified. [...] --noinput Tells Django to NOT prompt the user for input of any ...
Elementwise operations over tuples in Python
12,113,252
5
2012-08-24T16:27:53Z
12,113,366
8
2012-08-24T16:35:19Z
[ "python", "python-3.x" ]
Are there any built-in functions that allow elementwise operations over tuples in Python 3? If not, what is the "pythonic" way to perform these operations? Example: I want to take the percent difference between `a` and `b` and compare them to some threshold `th`. ``` >>> a = (1, 2, 4) >>> b = (1.1, 2.1, 4.1) >>> # co...
There is no builtin way, but there is a pretty simple way: ``` [f(aItem, bItem) for aItem, bItem in zip(a, b)] ``` . . . where `f` is the function you want to apply elementwise. For your case: ``` [100*abs(aItem - bItem)/aItem < 3 for aItem, bItem in zip(a, b)] ``` If you find yourself doing this a lot, especially ...
Run os.system() multiple times simultaneously in Python?
12,114,655
2
2012-08-24T18:16:37Z
12,114,669
8
2012-08-24T18:17:58Z
[ "python", "multithreading" ]
I've written the following short python script to download flv videos using cclive on a Fedora 17 system. ``` urls = [line.strip() for line in open("urls.txt")] for url in urlstoget: os.system('cclive %s' % url) ``` It works fine but the videos are limited to about 80kbps. I have a 39 to download and would like t...
use either `threading` or `multiprocessing`. Here's an example using multiprocessing: ``` def retrieve_url(url): os.system('cclive %s' % url) pool = multiprocessing.Pool(4) pool.map(retrieve_url, list_of_urls) ``` And a link to another SO question: [Python - parallel commands](http://stackoverflow.com/q/1209740...
Calling a class method upon creation of Python classes
12,115,357
4
2012-08-24T19:13:40Z
12,115,402
9
2012-08-24T19:17:01Z
[ "python", "class-method", "initializer" ]
I'd like to automatically run some code upon class creation that can call other class methods. I have not found a way of doing so from within the class declaration itself and end up creating a `@classmethod` called `__clsinit__` and call it from the defining scope immediately after the class declaration. Is there a met...
You can do this with a [**metaclass**](http://docs.python.org/reference/datamodel.html#customizing-class-creation) or a [**class decorator**](http://docs.python.org/whatsnew/2.6.html#pep-3129-class-decorators). A class decorator (since 2.6) is probably easier to understand: ``` def call_clsinit(cls): cls._clsinit...
Celery Error 'No such transport: amqp'
12,115,692
3
2012-08-24T19:44:46Z
12,115,697
7
2012-08-24T19:45:13Z
[ "python", "virtualenv", "celery", "pip", "kombu" ]
Celery was working fine, one day the command-line worker failed to start up with the following trace: ``` Traceback (most recent call last): File "/home/buildslave/venv/bin/celery", line 9, in <module> load_entry_point('celery==3.0.7', 'console_scripts', 'celery')() File "/home/buildslave/venv/local/lib/python...
The problem appears to be due to an upgrade to celery 3.0.7. The following resolved the issue for me: ``` pip install kombu==2.4.0 ``` *Note: this appears to have been resolved by kombu==2.4.3 per <https://github.com/celery/kombu/commit/c3b7a0d885fef3a43b76af0881fee6b5d012923f>*
Python 2.7.3 . . . Write .jpg/.png image file?
12,116,524
2
2012-08-24T20:55:15Z
12,116,606
10
2012-08-24T21:02:38Z
[ "python", "image", "file", "text", "fwrite" ]
So I have a .jpg/.png and I opened it up in Text Edit which I provided below: **Is there anyway I can save these exotic symbols to a string in Python to later write that to a file to produce an image?** I tried to import a string that had the beta symbol in it and I got an error that send Non-ASCII so I am assuming t...
What you are looking at in your text edit is a binary file, trying to represent it all in human readable characters. Just open the file as binary in python: ``` with open('picture.png', 'rb') as f: data = f.read() with open('picture_out.png', 'wb') as f: f.write(data) ```
How can I require my python script's argument to be a float between 0.0-1.0 using argparse?
12,116,685
4
2012-08-24T21:08:38Z
12,117,065
12
2012-08-24T21:43:54Z
[ "python", "command-line-arguments", "argparse" ]
I'd like to use `argparse` on Python 2.7 to require that one of my script's parameters be between the range of 0.0 and 1.0. Does `argparse.add_argument()` support this?
The `type` parameter to `add_argument` just needs to be a callable object that takes a string and returns a converted value. You can write a wrapper around `float` that checks its value and raises an error if it is out of range. ``` def restricted_float(x): x = float(x) if x < 0.0 or x > 1.0: raise arg...