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
Python.h header file missing on Mac OS X 10.6
16,454,129
2
2013-05-09T04:01:56Z
16,454,614
12
2013-05-09T04:52:24Z
[ "python", "xcode", "osx", "osx-snow-leopard", "header-files" ]
I'm trying to access a shared C library in Python with `ctypes` on Mac OS X 10.6.8 with Python 2.7.4. To do this, I need to `#include <Python.h>` in my C code. If I try to compile a C script that only has that one include statement in it, call it "sample.c", I get: ``` $ gcc -shared -o sample.so sample.c sample.c:1:20...
Python is a framework on Mac OS X so you need to, ``` #include <Python/Python.h> ``` You also need to call `gcc` with the `-framework` argument to actually do anything inside C, ``` gcc -shared -o sample.so sample.c -framework Python ```
Python Count Elements in a List of Objects with Matching Attributes
16,455,777
10
2013-05-09T06:30:01Z
16,455,812
16
2013-05-09T06:32:17Z
[ "python", "list", "object", "attributes", "count" ]
I am trying to find a simple and fast way of counting the number of Objects in a list that match a criteria. e.g. ``` class Person: def __init__(self, Name, Age, Gender): self.Name = Name self.Age = Age self.Gender = Gender # List of People PeopleList = [Person("Joan", 15, "F"), ...
``` class Person: def __init__(self, Name, Age, Gender): self.Name = Name self.Age = Age self.Gender = Gender >>> PeopleList = [Person("Joan", 15, "F"), Person("Henry", 18, "M"), Person("Marg", 21, "F")] >>> sum(p.Gender == "F" for p in PeopleList) 2 >>> sum(p...
How to disable Django's CSRF validation?
16,458,166
36
2013-05-09T09:07:09Z
16,458,216
106
2013-05-09T09:10:17Z
[ "python", "django" ]
I have commented out csrf processor and middleware lines in `settings.py`: ``` 122 123 TEMPLATE_CONTEXT_PROCESSORS = ( 124 'django.contrib.auth.context_processors.auth', 125 # 'django.core.context_processors.csrf', 126 'django.core.context_processors.request', 127 'django.core.context_processors.static...
If you just need some views not to use CSRF, you can use `@csrf_exempt`: ``` from django.views.decorators.csrf import csrf_exempt @csrf_exempt def my_view(request): return HttpResponse('Hello world') ``` You can find more examples and other scenarios here: * <https://docs.djangoproject.com/en/1.9/ref/csrf/#edge...
Python equivalent of zip for dictionaries
16,458,340
17
2013-05-09T09:18:22Z
16,458,780
16
2013-05-09T09:41:07Z
[ "python", "dictionary", "iterator" ]
If I have these two lists: ``` la = [1, 2, 3] lb = [4, 5, 6] ``` I can iterate over them as follows: ``` for i in range(min(len(la), len(lb))): print la[i], lb[i] ``` Or more pythonically ``` for a, b in zip(la, lb): print a, b ``` --- What if I have two dictionaries? ``` da = {'a': 1, 'b': 2, 'c': 3} d...
There is no built-in function or method that can do this. However, you could easily define your own. ``` def common_entries(*dcts): for i in set(dcts[0]).intersection(*dcts[1:]): yield (i,) + tuple(d[i] for d in dcts) ``` This builds on the "manual method" you provide, but, like `zip`, can be used for any...
How do I pass a PK or slug to a DetailView using RequestFactory in Django?
16,459,264
18
2013-05-09T10:08:26Z
16,483,135
33
2013-05-10T13:12:53Z
[ "python", "django", "unit-testing", "django-views" ]
I'm trying to use [RequestFactory](https://docs.djangoproject.com/en/1.5/topics/testing/advanced/#module-django.test.client) to test a DetailView with the following test case: ``` def test_device_homepage(self): request = self.factory.get('/devices/1/', {'pk': 1}) response = DeviceView.as_view()(request) ...
Thanks to the #django channel on Freenode IRC, I found the following method is the correct one to pass parameters all the way through to the view: ``` response = DeviceView.as_view()(request, pk=1) ``` I hope this helps somebody else attempting to use RequestFactory to test DetailView or DeleteView etc
pip: Could not find an activated virtualenv (required)
16,460,313
15
2013-05-09T11:07:11Z
16,460,480
37
2013-05-09T11:17:41Z
[ "python", "osx-mountain-lion", "virtualenv", "pip" ]
I am trying to instal virtualenv and/or virtualenvwrapper on a mac osx 10.8.3 I have been fighting with python for the last two days. Finally I was able to install python 2.7.4 using brew. Before I had virtualenv installed using easy\_install. Then I tried to uninstall it, trying to get my computer in the same situati...
Open your `~/.bashrc` file and see if this line is there - ``` export PIP_REQUIRE_VIRTUALENV=true ``` It might be causing the trouble. If it's there, change it to `false` and run - ``` source ~/.bashrc ``` If not, run `export PIP_REQUIRE_VIRTUALENV=false` from terminal.
imshow() function not working
16,460,442
20
2013-05-09T11:15:10Z
16,464,822
28
2013-05-09T14:56:05Z
[ "python", "matplotlib" ]
I'm working on a program in python with packages numpy,scipy and matplotlib.pyplot. This is my code: ``` import matplotlib.pyplot as plt from scipy import misc im=misc.imread("photosAfterAverage/exampleAfterAverage1.jpg") plt.imshow(im, cmap=plt.cm.gray) ``` for some reason the image isn't showing up (checked if I go...
You need to call `plt.show()` to display the image. Or use `ipython --pylab` for an interactive shell that is `matplotlib` aware.
sort() and reverse() functions do not work
16,460,616
4
2013-05-09T11:23:59Z
16,460,627
30
2013-05-09T11:24:35Z
[ "python", "list", "sorting" ]
I was trying to test how the lists in python works according to a tutorial I was reading. When I tried to use `list.sort()` or `list.reverse()`, the interpreter gives me `None`. Please let me know how I can get a result from these two methods: ``` a = [66.25, 333, 333, 1, 1234.5] print(a.sort()) print(a.reverse()) ``...
`.sort()` and `.reverse()` change the list *in place* and return `None` See the [mutable sequence documentation](http://docs.python.org/2/library/stdtypes.html#mutable-sequence-types): > The `sort()` and `reverse()` methods modify the list in place for economy of space when sorting or reversing a large list. To remind...
How to clear a multiprocessing queue in python
16,461,459
4
2013-05-09T12:09:07Z
16,462,765
20
2013-05-09T13:16:34Z
[ "python", "multiprocessing" ]
I just want to know how to clear a multiprocessing queue in python like a normal python queue. For instance: ``` from multiprocessing import Queue # multiprocessing queue from Queue import Queue # normal queue multi_q = Queue() normal_q = Queue() multi_q.clear() # or multi_q.queue.clear...
So, I take look at Queue class, and you may to try this code: ``` while not some_queue.empty(): some_queue.get() # as docs say: Remove and return an item from the queue. ```
Displaying ASCII-art in TKinter
16,461,843
2
2013-05-09T12:31:51Z
16,462,031
7
2013-05-09T12:41:53Z
[ "python", "tkinter" ]
I am trying to develop an offline version of Candy box (solely for personal use only) using Tkinter and the ASCII art won't display properly on Tkinter Canvas. This is the way I'd like it to be displayed: ``` """ .---. | '.| __ | ___.--' ) _.-'_` _%%%_/ .-'%%% a: a %%% %% L %...
1. Align text to left (center is default) 2. Backslash at the line end have a special meaning in python: it wraps long lines. Use [raw strings](http://docs.python.org/2/reference/lexical_analysis.html#string-literals) ``` from tkinter import * text = r""" .---. | '.| __ | ___.--' ) _.-'...
Selenium Expected Conditions - possible to use 'or'?
16,462,177
9
2013-05-09T12:49:16Z
16,464,305
9
2013-05-09T14:32:59Z
[ "python", "selenium" ]
I'm using Selenium 2 / WebDriver with the Python API, as follows: ``` from selenium.webdriver.support import expected_conditions as EC # code that causes an ajax query to be run WebDriverWait(driver, 10).until( EC.presence_of_element_located( \ (By.CSS_SELECTOR, "div.some_result"))); ``` I want to wait for **ei...
I did it like this: ``` class AnyEc: """ Use with WebDriverWait to combine expected_conditions in an OR. """ def __init__(self, *args): self.ecs = args def __call__(self, driver): for fn in self.ecs: try: if fn(driver): return True except:...
memoize to disk - python - persistent memoization
16,463,582
13
2013-05-09T14:00:05Z
16,464,555
15
2013-05-09T14:44:21Z
[ "python", "memoization" ]
Is there a way to memoize the output of a function to disk? I have a function ``` def getHtmlOfUrl(url): ... # expensive computation ``` and would like to do something like: ``` def getHtmlMemoized(url) = memoizeToFile(getHtmlOfUrl, "file.dat") ``` and then call getHtmlMemoized(url), so as to do the expensive ...
Python offers a very elegant way to do this - decorators. Basically, a decorator is a function that wraps another function to provide additional functionality without changing the function source code. Your decorator can be written like this: ``` import json def persist_to_file(file_name): def decorator(original...
Why is reversing a list with slicing slower than reverse iterator
16,465,046
5
2013-05-09T15:07:18Z
16,465,067
10
2013-05-09T15:08:33Z
[ "python" ]
There are at least two ways to reverse a list in Python, but the iterator approach is much faster (at least in Python 2.7.x). I want to understand what contributes to this speed difference. ``` >>> x = range(1000) >>> %timeit x[::-1] 100000 loops, best of 3: 2.99 us per loop >>> %timeit reversed(x) 10000000 loops, bes...
That's because `reversed` returns an [`iterator`](http://docs.python.org/2/glossary.html#term-iterator) while slicing returns a whole list. ``` >>> lis = range(10) >>> lis[::-1] [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] >>> reversed(lis) <listreverseiterator object at 0x909dd0c> ``` You've to use `list()` to convert that iterat...
How yield catches StopIteration exception?
16,465,313
6
2013-05-09T15:20:31Z
16,473,009
11
2013-05-09T23:47:37Z
[ "python", "yield", "stopiteration" ]
Why in the example function terminates: ``` def func(iterable): while True: val = next(iterable) yield val ``` but if I take off yield statement function will raise StopIteration exception? **EDIT:** Sorry for misleading you guys. I know what generators are and how to use them. Of course when I s...
To answer your question about where the `StopIteration` gets caught in the `gen` generator created inside of `itertools.tee`: it doesn't. It is up to the consumer of the `tee` results to catch the exception as they iterate. First off, it's important to note that a generator function (which is any function with a `yiel...
Need the path for particular files using os.walk()
16,465,399
5
2013-05-09T15:25:32Z
16,465,439
17
2013-05-09T15:27:48Z
[ "python", "shapefile", "os.walk" ]
I'm trying to perform some geoprocessing. My task is to locate all shapefiles within a directory, and then find the full path name for that shapefile within the directory. I can get the name of the shapefile, but I don't know how to get the full path name for that shapefile. ``` shpfiles = [] for path, subdirs, files ...
`os.walk` gives you the path to the directory as the first value in the loop, just use `os.path.join()` to create full filename: ``` shpfiles = [] for dirpath, subdirs, files in os.walk(path): for x in files: if x.endswith(".shp"): shpfiles.append(os.path.join(dirpath, x)) ``` I renamed `path`...
Normalizing Unicode
16,467,479
18
2013-05-09T17:21:56Z
16,467,505
34
2013-05-09T17:23:37Z
[ "python", "unicode", "python-3.x" ]
Is there a standard way, in Python, to normalize a unicode string, so that it only comprehends the simplest unicode entities that can be used to represent it ? I mean, something which would translate a sequence like `['LATIN SMALL LETTER A', 'COMBINING ACUTE ACCENT']` to `['LATIN SMALL LETTER A WITH ACUTE']` ? See wh...
The `unicodedata` module offers a [`.normalize()` function](http://docs.python.org/2/library/unicodedata.html#unicodedata.normalize), you want to normalize to the NFC form: ``` >>> unicodedata.normalize('NFC', u'\u0061\u0301') u'\xe1' >>> unicodedata.normalize('NFD', u'\u00e1') u'a\u0301' ``` NFC, or 'Normal Form Com...
Django custom manager get_queryset() not working
16,468,571
6
2013-05-09T18:26:38Z
16,469,061
10
2013-05-09T18:55:20Z
[ "python", "django", "python-2.7", "django-models" ]
I can't make my custom manager work... ``` class PublicArtigoManager(models.Manager): def get_queryset(self): return super(PublicArtigoManager, self).get_queryset().filter(data_publicacao__lte=timezone.now()).filter(permissao__lte=3) class Artigo(models.Model): ... objects = models.Manager() p...
I'm sure the problem is the `get_query_set` method. [This is the doc for version 1.5](https://docs.djangoproject.com/en/1.5/topics/db/managers/) managers and it says: > You can override a Manager‘s base QuerySet by overriding the Manager.get\_query\_set() method. get\_query\_set() should return a QuerySet with the p...
Render form errors with the label rather than field name
16,469,380
10
2013-05-09T19:14:33Z
16,469,790
8
2013-05-09T19:40:52Z
[ "python", "django", "django-forms" ]
I would like to list all form errors together using {{ form.errors }} in the template. This produces a list of form fields and nested lists of the errors for each field. However, the literal name of the field is used. The generated html with an error in a particular field might look like this. ``` <ul class="errorlist...
I don't see a simple way to do this. The errors attribute of the form actually returns an `ErrorDict`, a class defined in `django.forms.utils` - it's a subclass of `dict` that knows to produce that ul rendering of itself as its unicode representation. But the keys are actually the field names, and that's important to ...
Render form errors with the label rather than field name
16,469,380
10
2013-05-09T19:14:33Z
22,345,167
9
2014-03-12T07:53:11Z
[ "python", "django", "django-forms" ]
I would like to list all form errors together using {{ form.errors }} in the template. This produces a list of form fields and nested lists of the errors for each field. However, the literal name of the field is used. The generated html with an error in a particular field might look like this. ``` <ul class="errorlist...
I know this has already been answered but, I ran across the same scenario and found there is a simple way to use the label: ``` {% if form.errors %} <ul class="user-msg error"> {% for field in form %} {% for error in field.errors %} <li> {% if field != '__all__' %} ...
matplotlib:plot a line closed
16,469,996
2
2013-05-09T19:53:24Z
16,470,091
7
2013-05-09T19:58:33Z
[ "python", "matplotlib" ]
I plot a figure as below: ``` plt.plot(lon,lat,'ro-') plt.show() ``` ![enter image description here](http://i.stack.imgur.com/P5mJx.png) but the lines aren't closed. How can I make them closed as polygons? thank you
Use `matplotlib.pyplot.fill(lon,lat,fill=False)` instead of `plot()`. See <http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.fill> for details. The color string refers to the interior, so to use red for the polygon, use ``` plt.fill(lon, lat, edgecolor='r', fill=False) ``` and continue to use `plot()` to p...
pySerial 2.6: specify end-of-line in readline()
16,470,903
6
2013-05-09T20:51:58Z
16,961,872
10
2013-06-06T12:17:16Z
[ "python", "serial-port", "pyserial" ]
I am sending commands to Eddie using pySerial. I need to specify a carriage-return in my readline, but pySerial 2.6 got rid of it... Is there a workaround? Here are the [Eddie command set](https://www.parallax.com/sites/default/files/downloads/550-28990-Eddie-Command-Set-v1.2.pdf#page=2) is listed on the second and th...
I'm having the same issue and implemented my own readline() function which I copied and modified from the serialutil.py file found in the pyserial package. The serial connection is part of the class this function belongs to and is saved in attribute 'self.ser' ``` def _readline(self): eol = b'\r' leneol = len...
How can I compare a unicode type to a string in python?
16,471,332
14
2013-05-09T21:21:17Z
16,471,461
13
2013-05-09T21:29:53Z
[ "python", "unicode", "python-2.7", "list-comprehension" ]
I am trying to use a list comprehension that compares string objects, but one of the strings is utf-8, the byproduct of json.loads. Scenario: ``` us = u'MyString' # is the utf-8 string ``` Part one of my question, is why does this return False? : ``` us.encode('utf-8') == "MyString" ## False ``` Part two - how can ...
You must be looping over the wrong data set; just loop directly over the JSON-loaded dictionary, there is no need to call `.keys()` first: ``` data = json.loads(response) myList = [item for item in data if item == "number1"] ``` You may want to use `u"number1"` to avoid implicit conversions between Unicode and byte s...
OperationalError: (OperationalError) (2003, "Can't connect to MySQL server on '192.168.129.139' (111)") None None
16,472,175
5
2013-05-09T22:26:57Z
16,472,795
9
2013-05-09T23:24:41Z
[ "python", "mysql", "sql", "sqlalchemy" ]
I am trying to create a remote database using mysql on an Ubuntu machine running 12.04. It has a root user with remote login enabled and no password.I have started the server. output of ``` sudo netstat -tap | grep mysql ``` shows ``` tcp 0 0 localhost:mysql *:* LISTEN ...
Looks like mysql is configured to listen only on localhost. You can test this by running `telnet 192.168.129.139 3306` from your client machine. Most probable reason - mysqld is configured to do so. Please try to follow [Configuration step described here](https://help.ubuntu.com/12.04/serverguide/mysql.html): Edit ...
Why is this returning an extra none?
16,472,516
2
2013-05-09T22:56:08Z
16,472,548
7
2013-05-09T22:59:54Z
[ "python" ]
``` def hotel_cost(nights): return nights * 140 bill = hotel_cost(5) def add_monthly_interest(balance): return balance * (1 + (0.15 / 12)) def make_payment(payment, balance): new_balance2 = balance - payment new_balance = add_monthly_interest(new_balance2) print "You still owe: " + str(new_balan...
It doesn't return that. It returns `None`, because that's what any function returns if you don't have a return statement. Meanwhile, it prints out "You still owe: 607.5", because that's what's in your print statement. (By "it" here, I'm assuming you're referring to the function call `make_payment(100, bill)`.) My gu...
Matrix multiplication in pandas
16,472,729
2
2013-05-09T23:18:13Z
16,473,007
7
2013-05-09T23:47:30Z
[ "python", "pandas" ]
I have numeric data stored in two DataFrames x and y. The inner product from numpy works but the dot product from pandas does not. ``` In [63]: x.shape Out[63]: (1062, 36) In [64]: y.shape Out[64]: (36, 36) In [65]: np.inner(x, y).shape Out[65]: (1062L, 36L) In [66]: x.dot(y) ---------------------------------------...
Not only must the shapes of `x` and `y` be correct, but also the column names of `x` must match the index names of `y`. Otherwise this code in `pandas/core/frame.py` will raise a ValueError: ``` if isinstance(other, (Series, DataFrame)): common = self.columns.union(other.index) if (len(common) > len(self.colum...
numpy vstack vs. column_stack
16,473,042
10
2013-05-09T23:51:59Z
16,473,086
29
2013-05-09T23:58:07Z
[ "python", "numpy" ]
What exactly is the difference between numpy vstack and column\_stack. Reading through the documentation, it looks as if column\_stack is an implementation of vstack for 1D arrays. Is it a more efficient implementation? Otherwise, I cannot find a reason for just having vstack.
I think the following code illustrates the difference nicely: ``` >>> np.vstack(([1,2,3],[4,5,6])) array([[1, 2, 3], [4, 5, 6]]) >>> np.column_stack(([1,2,3],[4,5,6])) array([[1, 4], [2, 5], [3, 6]]) >>> np.hstack(([1,2,3],[4,5,6])) array([1, 2, 3, 4, 5, 6]) ``` I've included `hstack` for compari...
Python Visual Debugger
16,473,278
4
2013-05-10T00:22:41Z
16,474,706
7
2013-05-10T03:27:05Z
[ "python", "debugging" ]
I know there are a thousand posts on debugging in Python but I can't find what I am looking for....a visual debugger. For example: ``` one@localhost ~ $ cat duh.py import pdb class Coordinate(object): pdb.set_trace() def __init__(self, x, y): self.x = x self.y = y def __repr__(self...
That pdb debugging doesn't look like fun. I can see why you don't like it. Fortunately, there *are* some visual Python debuggers out there. The two that I use most often are commercial products, but they are both well worth the cost. They are [Komodo IDE](http://www.activestate.com/komodo-ide) and [IntelliJ IDEA](http...
How do I post JSON via HTTP in Ruby after conversion from Python?
16,474,985
6
2013-05-10T04:01:36Z
16,475,537
15
2013-05-10T05:07:51Z
[ "python", "ruby", "json" ]
I yield - I've tried for hours to crack this nut but can't figure it out. I'm too new to Ruby (and have no Python background!) to translate this and then post my JSON data to a site that requires user/pass, and then get the response data. This is the Python code: ``` r = requests.post('https://keychain.oneid.com/vali...
Use the [rest-client](https://github.com/rest-client/rest-client) gem or just use `Net::HTTP`. Ruby code(version 1.9.3): ``` require 'net/http' require 'json' require 'uri' uri = URI('https://keychain.oneid.com/validate/') req = Net::HTTP::Post.new uri.path # ruby 2.0: req = Net::HTTP::Post.new uri req.basic_auth 'u...
Rename a dictionary key
16,475,384
131
2013-05-10T04:52:30Z
16,475,408
11
2013-05-10T04:54:44Z
[ "python", "dictionary", "ordereddictionary" ]
Is there a way to rename a dictionary key, without reassigning its value to a new name and removing the old name key; and without iterating through dict key/value? In case of OrderedDict, do the same, while keeping that key's position.
Using a check for `newkey!=oldkey`, this way you can do: ``` if newkey!=oldkey: dictionary[newkey] = dictionary[oldkey] del dictionary[oldkey] ```
Rename a dictionary key
16,475,384
131
2013-05-10T04:52:30Z
16,475,444
229
2013-05-10T04:58:21Z
[ "python", "dictionary", "ordereddictionary" ]
Is there a way to rename a dictionary key, without reassigning its value to a new name and removing the old name key; and without iterating through dict key/value? In case of OrderedDict, do the same, while keeping that key's position.
For a regular dict, you can use: ``` mydict[new_key] = mydict.pop(old_key) ``` For an OrderedDict, I think you must build an entirely new one using a comprehension. ``` >>> OrderedDict(zip('123', 'abc')) OrderedDict([('1', 'a'), ('2', 'b'), ('3', 'c')]) >>> oldkey, newkey = '2', 'potato' >>> OrderedDict((newkey if k...
Rename a dictionary key
16,475,384
131
2013-05-10T04:52:30Z
29,629,919
15
2015-04-14T14:23:49Z
[ "python", "dictionary", "ordereddictionary" ]
Is there a way to rename a dictionary key, without reassigning its value to a new name and removing the old name key; and without iterating through dict key/value? In case of OrderedDict, do the same, while keeping that key's position.
best method in 1 line: ``` >>> d = {'test':[0,1,2]} >>> d['test2'] = d.pop('test') >>> d {'test2': [0, 1, 2]} ```
Python tkinter with ttk calendar
16,475,852
4
2013-05-10T05:37:35Z
16,476,647
13
2013-05-10T06:45:42Z
[ "python", "tkinter", "ttk" ]
I am using [this](http://svn.python.org/projects/sandbox/trunk/ttk-gsoc/samples/ttkcalendar.py) code to create a simple calendar on my Tkinter. When i put a calendar on my main root window, the calendar appear just fine. So, i decided to put another button that will create a Tkinter toplevel window and put 1 more calen...
Author of this widget used one unnecessary action: this widget set minimal size of **root** window, and he assumed that it is the only window in a program (it isn't bug, it's feature). 1.In method `def __place_widgets(self)`: ``` self._calendar = ttk.Treeview(show='', selectmode='none', height=7) ``` should be: ```...
How to insert pandas dataframe via mysqldb into database?
16,476,413
9
2013-05-10T06:29:10Z
16,477,603
25
2013-05-10T07:58:51Z
[ "python", "mysql", "pandas", "mysql-python" ]
I can connect to my local mysql database from python, and I can create, select from, and insert individual rows. My question is: can I directly instruct mysqldb to take an entire dataframe and insert it into an existing table, or do I need to iterate over the rows? In either case, what would the python script look li...
### Update: There is now a `to_sql` method, which is the preferred way to do this, rather than `write_frame`: ``` df.to_sql(con=con, name='table_name_for_df', if_exists='replace', flavor='mysql') ``` *Also note: the syntax may change in pandas 0.14...* You can set up the connection with [MySQLdb](http://mysql-pytho...
Convert Unicode data to int in python
16,476,484
15
2013-05-10T06:33:29Z
16,476,496
30
2013-05-10T06:34:30Z
[ "python", "unicode", "python-2.7", "casting" ]
I am getting values passed from url as : ``` user_data = {} if (request.args.get('title')) : user_data['title'] =request.args.get('title') if(request.args.get('limit')) : user_data['limit'] = request.args.get('limit') ``` Then using it as ``` if 'limit' in user_data : limit = user_data['limit'] condit...
`int(limit)` returns the value converted into an integer, and doesn't change it in place as you call the function (which is what you are expecting it to). This is because strings are *immutable*, in Python. Do this instead: ``` limit = int(limit) ``` Or when definiting `limit`: ``` if 'limit' in user_data : lim...
How to iterate over rows in a DataFrame?
16,476,924
146
2013-05-10T07:04:49Z
16,476,974
241
2013-05-10T07:07:58Z
[ "python", "pandas", "rows", "dataframe" ]
I have a DataFrames from pandas: ``` import pandas as pd inp = [{'c1':10, 'c2':100}, {'c1':11,'c2':110}, {'c1':12,'c2':120}] df = pd.DataFrame(inp) print df ``` Output: ``` c1 c2 0 10 100 1 11 110 2 12 120 ``` Now I want to iterate over the rows of the above frame. For every row I want to be able to acce...
[iterrows](http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.iterrows.html) is a generator which yield both index and row ``` In [18]: for index, row in df.iterrows(): ....: print row['c1'], row['c2'] ....: 10 100 11 110 12 120 ```
How to iterate over rows in a DataFrame?
16,476,924
146
2013-05-10T07:04:49Z
30,566,899
13
2015-06-01T06:24:44Z
[ "python", "pandas", "rows", "dataframe" ]
I have a DataFrames from pandas: ``` import pandas as pd inp = [{'c1':10, 'c2':100}, {'c1':11,'c2':110}, {'c1':12,'c2':120}] df = pd.DataFrame(inp) print df ``` Output: ``` c1 c2 0 10 100 1 11 110 2 12 120 ``` Now I want to iterate over the rows of the above frame. For every row I want to be able to acce...
You can also use `df.apply()` to iterate over rows and access multiple columns for a function. [docs: DataFrame.apply()](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html) ``` def valuation_formula(x, y): return x * y * 0.5 df['price'] = df.apply(lambda row: valuation_formula(row[...
How to iterate over rows in a DataFrame?
16,476,924
146
2013-05-10T07:04:49Z
32,680,162
21
2015-09-20T13:52:48Z
[ "python", "pandas", "rows", "dataframe" ]
I have a DataFrames from pandas: ``` import pandas as pd inp = [{'c1':10, 'c2':100}, {'c1':11,'c2':110}, {'c1':12,'c2':120}] df = pd.DataFrame(inp) print df ``` Output: ``` c1 c2 0 10 100 1 11 110 2 12 120 ``` Now I want to iterate over the rows of the above frame. For every row I want to be able to acce...
While `iterrows()` is a good option, sometimes `itertuples()` can be much faster: ``` df = pd.DataFrame({'a': randn(1000), 'b': randn(1000),'N': randint(100, 1000, (1000)), 'x': 'x'}) %timeit [row.a * 2 for idx, row in df.iterrows()] # => 10 loops, best of 3: 50.3 ms per loop %timeit [row[1] * 2 for row in df.itertu...
Java vs Python HMAC-SHA256 Mismatch
16,477,737
11
2013-05-10T08:09:18Z
16,556,423
8
2013-05-15T03:38:17Z
[ "java", "android", "python", "hmac" ]
Based on recent feedback and findings on this problem, I've rewritten the question to get rid of noise. I have 2 separate code paths, one in Java (Android), one and Python which accomplish the following for the purposes of negotiating a pairing between an Android device and a Python/Django. Java: * Generate a syncKe...
Your Python code is wrong. I can reproduce, in Python, the answer you got in Java. If I use your inputs: ``` >>> preshared_key_hex b'f8250b0d5960444e4de6ecc3a78900bb941246a1dece7848fc72b90092ab3ecd0c1c8e36fddba501ef92e72c95b47e07f98f7fd9cb63da75c008a3201124ea5d' >>> concat_hex b'824C1EE9EF507B52EA28362C71BD4AD512A5F8...
How to find dictionary key with the lowest value where key is in a list
16,478,369
2
2013-05-10T08:49:02Z
16,478,396
8
2013-05-10T08:50:28Z
[ "python" ]
I'm trying to get the key with the lowest value in a dictionary where the key is in a separate list. I also fear that initializing my variable "key" in the way I am might cause trouble in the future, even though I don't think it will. ``` d = { "a":3, "b":2, "c":7 } l = ["a","b"] key = l[0] for c in l: key = c if...
Use the `key` parameter to the [`min()` function](http://docs.python.org/2/library/functions.html#min) to pick out a lowest key: ``` min(l, key=d.__getitem__) ``` The `key` parameter must be a callable that maps items in the input list to a value by which you want to pick the minimum item. In your example, `'b'` is t...
Receiving Import Error: No Module named ***, but has __init__.py
16,480,898
5
2013-05-10T11:07:08Z
16,481,047
7
2013-05-10T11:16:52Z
[ "python", "python-3.x", "importerror" ]
I understand that this question has been asked several times but after reading them, and making the suggested fixes, I'm still stumped. My project structure is as follows: ``` Project | src | root - has __init__.py | nested - has __init__.py | ...
Try adding a `sys.path.append` to the list of your imports. ``` sys.path.append("/Project/src/") import root import root.nested.tests ```
Find out into how many values a return value will be unpacked
16,481,156
4
2013-05-10T11:24:43Z
16,481,975
8
2013-05-10T12:12:42Z
[ "python" ]
I have a function, and when it is called, I'd like to know what the return value is going to be assigned to - specifically when it is unpacked as a tuple. So: ``` a = func() # n = 1 ``` vs. ``` a, b, c = func() # n = 3 ``` I want to use the value of `n` in `func`. There must be some magic with `inspect` o...
Adapted from <http://code.activestate.com/recipes/284742-finding-out-the-number-of-values-the-caller-is-exp/>: ``` import inspect import dis def expecting(offset=0): """Return how many values the caller is expecting""" f = inspect.currentframe().f_back.f_back i = f.f_lasti + offset bytecode = f.f_code...
Disabled field is considered for validation in WTForms and Flask
16,481,924
10
2013-05-10T12:09:37Z
16,576,294
14
2013-05-15T22:51:39Z
[ "python", "flask", "jinja2", "wtforms" ]
I have some fields in page disabled as for example:(using jinja2 templating system) ``` <html> <body> <form action="" method=POST> {{ form.name(disabled=True) }} {{ form.title }} -- submit button -- </form> </body> </html> ``` Field is disabled in the form as expected. In my views.py: On doing validate\_...
This is actually an interesting problem, and the way WTForms solves it is intentionally something that requires explicitness, because it has to do with security and not allowing users to fake input. So the intent is, that "managers" cannot edit the name, while "admins" can. At first glance this seems obvious, just di...
Convert a numpy array to a CSV string and a CSV string back to a numpy array
16,482,895
6
2013-05-10T13:01:40Z
16,483,149
14
2013-05-10T13:13:41Z
[ "python", "csv", "python-2.7", "numpy" ]
I have to convert a numpy array of floats to a string (to store in a SQL DB) and then also convert the same string back into a numpy float array. This is how I'm going to a string ([based on this article](http://www.skymind.com/~ocrow/python_string/)) ``` VIstring = ''.join(['%.5f,' % num for num in VI]) VIstring= VI...
First you should use `join` this way to avoid the last comma issue: ``` VIstring = ','.join(['%.5f' % num for num in VI]) ``` Then to read it back, use `numpy.fromstring`: ``` np.fromstring(VIstring, sep=',') ```
pjsip new-call error ... Unable to find default audio device (PJMEDIA_EAUD_NODEFDEV)
16,483,635
3
2013-05-10T13:39:22Z
20,977,176
8
2014-01-07T16:45:48Z
[ "c++", "python", "c", "sip", "pjsip" ]
I get this error when I try to establish a new call from pjsip: `pjsua_aud.c ..Error retrieving default audio device parameters: Unable to find default audio device (PJMEDIA_EAUD_NODEFDEV) [status=420006] Exception: Object: {Account <sip:192.168.0.2:54496>}, operation=make_call(), error=Unable to find default audio de...
This happens when the **development packages** are not installed. From your error message i can tell that [libasound-development-package](http://packages.debian.org/sid/libasound2-dev) is not installed. Do as following: ``` sudo apt-get install libasound2-dev ``` Pay attention that pjsip would still fail to set the d...
Is it possible to use argsort in descending order
16,486,252
41
2013-05-10T15:57:47Z
16,486,299
38
2013-05-10T16:00:21Z
[ "python", "numpy" ]
Consider the following code: ``` avgDists = [1, 8, 6, 9, 4] ids = np.array(avgDists).argsort()[:n] ``` This gives me indices of the `n` smallest elements. Is it possible to use this same `argsort` in descending order to get the indices of `n` highest elements ?
Just like Python, in that `[::-1]` reverses the array returned by `argsort()` and `[:n]` gives that last n elements: ``` >>> avgDists=np.array([1, 8, 6, 9, 4]) >>> n=3 >>> ids = avgDists.argsort()[::-1][:n] >>> ids array([3, 1, 2]) ``` The advantage of this method is that `ids` is a [view](http://docs.scipy.org/doc/n...
Is it possible to use argsort in descending order
16,486,252
41
2013-05-10T15:57:47Z
16,486,305
28
2013-05-10T16:00:38Z
[ "python", "numpy" ]
Consider the following code: ``` avgDists = [1, 8, 6, 9, 4] ids = np.array(avgDists).argsort()[:n] ``` This gives me indices of the `n` smallest elements. Is it possible to use this same `argsort` in descending order to get the indices of `n` highest elements ?
How about simply ``` (-np.array(avgDists)).argsort()[:n] ``` *edit:* The suggestion in dawg's answer is arguably better, because it avoids calculating the negation of the array (which creates a copy): ``` np.array(avgDists).argsort()[::-1][:n] ``` These answers both give equivalent results. However, it should be n...
Python pandas: select columns with all zero entries in dataframe
16,486,762
5
2013-05-10T16:28:05Z
16,486,950
8
2013-05-10T16:37:44Z
[ "python", "dataframe", "pandas" ]
Given a dataframe how to find out all the columns that only have 0 as the values?
I'd simply compare the values to 0 and use `.all()`: ``` >>> df = pd.DataFrame(np.random.randint(0, 2, (2, 8))) >>> df 0 1 2 3 4 5 6 7 0 0 0 0 1 0 0 1 0 1 1 1 0 0 0 1 1 1 >>> df == 0 0 1 2 3 4 5 6 7 0 True True True False True True False Tru...
Django Admin shows escaped HTML even when allow_tags=True
16,488,186
4
2013-05-10T17:59:59Z
16,492,757
10
2013-05-11T01:00:28Z
[ "python", "django", "python-2.7", "django-admin" ]
I have the following code for the model and admin. The question column contains HTML content such as URL and image tags. However the admin still shows the raw HTML content and not formatted content. The model and the admin code is below: Model ``` class question(models.Model): question_id = models.AutoField(prima...
Is that your code exactly? You have `formatqn.allow_tags=True` indented inside the `def formatqn` method after the return so it won't execute never, try to write the model with that line unindented like this: ``` class QuestionAdmin(admin.ModelAdmin): list_display = ('question_id','formatqn') list_per_page = 1...
Plotting log-binned network degree distributions
16,489,655
7
2013-05-10T19:38:00Z
16,490,678
9
2013-05-10T20:54:16Z
[ "python", "numpy", "matplotlib", "networkx", "scientific-computing" ]
I have often encountered and made long-tailed degree distributions/histograms from complex networks like the figures below. They make the heavy end of these tails, well, very heavy and crowded from many observations: ![Classic long-tailed degree distribution](http://i.stack.imgur.com/R7RzP.png) However, many publicat...
Use [log binning](http://arxiv.org/pdf/1011.1533.pdf) ([see also](http://arxiv.org/pdf/0706.1062.pdf)). Here is code to take a `Counter` object representing a histogram of degree values and log-bin the distribution to produce a sparser and smoother distribution. ``` import numpy as np def drop_zeros(a_list): retur...
How to make SQLAlchemy in Tornado to be async?
16,491,564
31
2013-05-10T22:17:09Z
16,503,103
59
2013-05-12T00:44:41Z
[ "python", "python-2.7", "sqlalchemy", "tornado" ]
How to make `SQLAlchemy` in `Tornado` to be `async` ? I found example for MongoDB on [async mongo example](http://emptysquare.net/blog/refactoring-tornado-code-with-gen-engine/) but I couldn't find anything like `motor` for `SQLAlchemy`. Does anyone know how to make `SQLAlchemy` queries to execute with `tornado.gen` ( ...
ORMs are poorly suited for explicit asynchronous programming, that is, where the programmer must produce explicit callbacks anytime something that uses network access occurs. A primary reason for this is that ORMs make extensive use of the [lazy loading](http://www.martinfowler.com/eaaCatalog/lazyLoad.html) pattern, wh...
How to make SQLAlchemy in Tornado to be async?
16,491,564
31
2013-05-10T22:17:09Z
26,925,528
19
2014-11-14T08:06:20Z
[ "python", "python-2.7", "sqlalchemy", "tornado" ]
How to make `SQLAlchemy` in `Tornado` to be `async` ? I found example for MongoDB on [async mongo example](http://emptysquare.net/blog/refactoring-tornado-code-with-gen-engine/) but I couldn't find anything like `motor` for `SQLAlchemy`. Does anyone know how to make `SQLAlchemy` queries to execute with `tornado.gen` ( ...
I had this same issue in the past and I couldn't find a reliable Async-MySQL library. However there is a cool solution using [**Asyncio**](https://docs.python.org/3/library/asyncio.html) + **Postgres**. You just need to use the [**aiopg**](http://aiopg.readthedocs.org/en/stable/index.html) library, which comes with SQL...
Newcomer error in parsing tweet json UnicodeEncodeError: 'charmap' codec can't encode characters in position 13-63: character maps to <undefined>
16,491,789
3
2013-05-10T22:39:38Z
16,491,862
8
2013-05-10T22:48:10Z
[ "python", "list" ]
I'm trying to follow the Intro to Data Sci coursera class. But I have run into a problem while trying to parse json response from twitter I am trying to retreive the text from the json that is in the following format. ``` {u'delete': {u'status': {u'user_id_str': u'702327198', u'user_id': 702327198, u'id': 33277217869...
All of your conversion, etc. is correct. The problem is just trying to `print` it to stdout. (Usually, you run into problems with accented, east-Asian, etc. characters; here it seems to be with the `…` ellipsis character, but it's the same problem.) If you're running this in a terminal window (DOS prompt, etc.), yo...
Parsing JSON with python: blank fields
16,492,292
6
2013-05-10T23:45:26Z
16,492,333
8
2013-05-10T23:51:38Z
[ "python", "json", "parsing", "python-2.7" ]
I'm having problems while parsing a JSON with python, and now I'm stuck. The problem is that the entities of my JSON are not always the same. The JSON is something like: ``` "entries":[ { "summary": "here is the sunnary", "extensions": { "coordinates":"coords", "address":"address", "name":"name" "telepho...
Use `dict.get` instead of `[]`: ``` entries['extensions'].get('telephone', '') ``` Or, simply: ``` entries['extensions'].get('telephone') ``` `get` will return the second argument (default, `None`) instead of raising a `KeyError` when the key is not found.
Parsing JSON with python: blank fields
16,492,292
6
2013-05-10T23:45:26Z
16,492,357
7
2013-05-10T23:55:43Z
[ "python", "json", "parsing", "python-2.7" ]
I'm having problems while parsing a JSON with python, and now I'm stuck. The problem is that the entities of my JSON are not always the same. The JSON is something like: ``` "entries":[ { "summary": "here is the sunnary", "extensions": { "coordinates":"coords", "address":"address", "name":"name" "telepho...
If the data is missing in only one place, then [*dict.get*](http://docs.python.org/2.7/library/stdtypes.html#dict.get) can be used to fill-in missing the missing value: ``` tel = d['entries'][0]['extensions'].get('telelphone', '') ``` If the problem is more widespread, you can have the JSON parser use a [*defaultdict...
Colorplot of 2D array matplotlib
16,492,830
13
2013-05-11T01:19:13Z
16,492,880
18
2013-05-11T01:29:00Z
[ "python", "numpy", "matplotlib", "plot" ]
So, I thought this was going to be really simple, but I've been having a lot of difficult finding exactly what I'm looking for in a comprehensible example. Basically I want to make phase plots, so assuming I have a 2d array, how can I get matplotlib to convert this to a plot that I can attach titles, axes, and legends...
I'm afraid your posted example is not working, since X and Y aren't defined. So instead of `pcolormesh` let's use `imshow`: ``` import numpy as np import matplotlib.pyplot as plt H = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]) # added some comma...
Python list anomalous memory usage
16,492,851
7
2013-05-11T01:22:12Z
16,492,862
8
2013-05-11T01:25:21Z
[ "python", "list", "memory" ]
I'm working on a project that involves accessing data from a large list that's kept in memory. Because the list is quite voluminous (millions of lines) I keep an eye on how much memory is being used. I use OS X so I keep Activity Monitor open as I create these lists. I've noticed that the amount of memory used by a li...
Both functions make a list of 6000000 references. ``` sizeof(thelist) ≅ sizeof(reference_to_a_python_object) * 6000000 ``` First list contains 6000000 references to the same one tuple of three floats. Second list contains references to 6000000 different tuples containing 18000000 different floats. ![enter image d...
Stop a main thread from child thread
16,493,042
2
2013-05-11T02:00:34Z
16,494,559
7
2013-05-11T06:41:52Z
[ "python", "multithreading", "exception" ]
I am writing a python program, In main function I am starting a thread which runs continuously. After starting the the thread the main function enters a while loop where it takes user input continuously. If there is a exception in child thread I want to end the main function also. What is the best way to do that? Than...
Having a thread "controlling" its parent is not a good practice. It makes more sense for the main thread to manage/monitor/control the threads it starts. So my suggestion is that your main thread starts 2 threads: the one you already have, which at some point finishes/raises an exception, and one reading user input. T...
How to store dictionary in HDF5 dataset
16,494,669
7
2013-05-11T07:01:53Z
16,495,691
8
2013-05-11T09:31:17Z
[ "python", "h5py" ]
I have a dictionary, where key is datetime object and value is tuple of integers: ``` >>> d.items()[0] (datetime.datetime(2012, 4, 5, 23, 30), (14, 1014, 6, 3, 0)) ``` I want to store it in HDF5 dataset, but if I try to just dump the dictionary h5py raises error: > TypeError: Object dtype dtype('object') has no nati...
I found two ways to this: **I)** transform datetime object to string and use it as dataset name ``` h = h5py.File('myfile.hdf5') for k, v in d.items(): h.create_dataset(k.strftime('%Y-%m-%dT%H:%M:%SZ'), data=np.array(v, dtype=np.int8)) ``` where data can be accessed by quering key strings (datasets name). For ex...
how to apply a mask from one array to another array?
16,495,298
12
2013-05-11T08:34:46Z
16,495,529
9
2013-05-11T09:06:57Z
[ "python", "numpy" ]
I've read the masked array documentation several times now, searched everywhere and feel thoroughly stupid. I can't figure out for the life in me how to apply a mask from one array to another. Example: ``` import numpy as np y = np.array([2,1,5,2]) # y axis x = np.array([1,2,3,4]) # x axis m = np.m...
Why not simply ``` import numpy as np y = np.array([2,1,5,2]) # y axis x = np.array([1,2,3,4]) # x axis m = np.ma.masked_where(y>2, y) # filter out values larger than 5 print list(m) print np.ma.compressed(m) # mask x the same way m_ = np.ma.masked_where(y>2, x) # filter out values larger than ...
Strange conversion in Python logic expressions
16,496,546
6
2013-05-11T11:21:27Z
16,496,573
7
2013-05-11T11:24:20Z
[ "python", "python-2.7" ]
I noticed a strange behavior of Python 2.7 logic expressions: ``` >>> 0 and False 0 >>> False and 0 False >>> 1 and False False >>> False and 1 False ``` and with True in place of False ``` >>> 0 and True 0 >>> True and 0 0 >>> 1 and True True >>> True and 1 1 ``` Are there any rules when Python convert logical sta...
Nothing is being converted; the Python boolean logic operators instead *short circuit*. See the [boolean operators documentation](http://docs.python.org/2/reference/expressions.html#boolean-operations): > The expression `x and y` first evaluates `x`; if `x` is false, its value is returned; otherwise, `y` is evaluated...
Start server in current directory (php/apache)
16,498,411
3
2013-05-11T14:56:06Z
16,498,446
13
2013-05-11T14:58:50Z
[ "php", "python", "osx", "apache", "terminal" ]
Apparently, you can start a temporary server with Python, by using: ``` python -m SimpleHTTPServer ``` Is there a way to do this for PHP and Apache? e.g. one command which will serve the current folder as the localhost? On Mac.
You can start PHP development server in versions 5.4 and above with: ``` php -S localhost:8008 ``` I don't think Apache supports anything similar (being itself a web server), but PHP dev server is enough for testing scripts, including serving static contents.
Better pythonic idiom for this repeated piece code pattern
16,499,851
4
2013-05-11T17:26:45Z
16,499,880
9
2013-05-11T17:29:13Z
[ "python", "design-patterns", "idioms", "readability" ]
I find myself using this code pattern quite a bit, and every time I do I think there might be a better, clearer way of expressing myself: ``` do_something = True # Check a lot of stuff / loops for thing in things: .... if (thing == 'something'): do_something = False break if (do_something): ...
Python `for` loops can have an `else` block, which is executed if those loop is not broken out of: ``` for thing in things: ... if (thing == 'something'): break else: ... # Do something ``` This code will work in the same way as yours, but doesn't need a flag. I think this fits your criteria for s...
CSRF Exempt Failure - APIView csrf django rest framework
16,501,770
8
2013-05-11T21:12:11Z
17,424,074
14
2013-07-02T11:12:49Z
[ "python", "django", "django-rest-framework" ]
I have the following code: The problem is when I try to access user-login/ I get an error: "CSRF Failed: CSRF cookie not set." What can I do? I am using the django rest framework. ``` urls.py: url(r'^user-login/$', csrf_exempt(LoginView.as_view()), name='user-login'), views.py: class LoginView(APIView):...
I assume you use the django rest framework [SessionBackend](http://django-rest-framework.org/api-guide/authentication.html#sessionauthentication). This backend does a [implicit CSRF check](https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/authentication.py#L119) You can avoid this by: ``...
CSRF Exempt Failure - APIView csrf django rest framework
16,501,770
8
2013-05-11T21:12:11Z
28,300,473
9
2015-02-03T13:45:36Z
[ "python", "django", "django-rest-framework" ]
I have the following code: The problem is when I try to access user-login/ I get an error: "CSRF Failed: CSRF cookie not set." What can I do? I am using the django rest framework. ``` urls.py: url(r'^user-login/$', csrf_exempt(LoginView.as_view()), name='user-login'), views.py: class LoginView(APIView):...
Actually, better way to disable csrf check inside SessionAuthentication is: ``` from rest_framework.authentication import SessionAuthentication as OriginalSessionAuthentication class SessionAuthentication(OriginalSessionAuthentication): def enforce_csrf(self, request): return ```
Python property decorator not working, why?
16,502,133
2
2013-05-11T21:59:18Z
16,502,188
14
2013-05-11T22:06:21Z
[ "python", "python-2.7" ]
For some reason the 'obj.\_max\_value' and 'obj.\_current\_value' are not getting set. I have looked at many tutorials and it seems that I am doing it correctly. Does anyone know why it is not working? See code: <https://gist.github.com/matthew-campbell/5561562> (Python 2.7) --- Update: ``` class Progress(): @p...
The `property` decorator doesn't work with old-style classes. Inherit your class from `object` to get a new-style class: ``` class Progress(object): # ... ```
global variable inside main function python
16,502,377
4
2013-05-11T22:37:32Z
16,502,408
7
2013-05-11T22:44:21Z
[ "python", "scope" ]
I wanted to define a global variable in main, i.e., a variable that can be used by any function I call from the main function. Is that possible? What'd be a good way to do this? Thanks!
What you want is not possible\*. You can just create a variable in the global namespace: ``` myglobal = "UGHWTF" def main(): global myglobal # prevents creation of a local variable called myglobal myglobal = "yu0 = fail it" anotherfunc() def anotherfunc(): print myglobal ``` DON'T DO THIS. The whol...
Read Specific Columns from csv file with Python csv
16,503,560
67
2013-05-12T02:10:37Z
16,503,661
58
2013-05-12T02:34:02Z
[ "python", "csv" ]
I'm trying to parse through a csv file and extract the data from only specific columns. Example csv: ``` ID | Name | Address | City | State | Zip | Phone | OPEID | IPEDS | 10 | C... | 130 W.. | Mo.. | AL... | 3.. | 334.. | 01023 | 10063 | ``` I'm trying to capture only specific columns, say `ID`, `Name`, `Zip` and `...
``` import csv from collections import defaultdict columns = defaultdict(list) # each value in each column is appended to a list with open('file.txt') as f: reader = csv.DictReader(f) # read rows into a dictionary format for row in reader: # read a row as {column1: value1, column2: value2,...} for (k,...
Read Specific Columns from csv file with Python csv
16,503,560
67
2013-05-12T02:10:37Z
16,503,807
66
2013-05-12T03:06:30Z
[ "python", "csv" ]
I'm trying to parse through a csv file and extract the data from only specific columns. Example csv: ``` ID | Name | Address | City | State | Zip | Phone | OPEID | IPEDS | 10 | C... | 130 W.. | Mo.. | AL... | 3.. | 334.. | 01023 | 10063 | ``` I'm trying to capture only specific columns, say `ID`, `Name`, `Zip` and `...
The only way you would be getting the last column from this code is if you don't include your print statement **in** your `for` loop. This is most likely the end of your code: ``` for row in reader: content = list(row[i] for i in included_cols) print content ``` You want it to be this: ``` for row in reader: ...
Read Specific Columns from csv file with Python csv
16,503,560
67
2013-05-12T02:10:37Z
21,045,966
7
2014-01-10T13:46:04Z
[ "python", "csv" ]
I'm trying to parse through a csv file and extract the data from only specific columns. Example csv: ``` ID | Name | Address | City | State | Zip | Phone | OPEID | IPEDS | 10 | C... | 130 W.. | Mo.. | AL... | 3.. | 334.. | 01023 | 10063 | ``` I'm trying to capture only specific columns, say `ID`, `Name`, `Zip` and `...
You can use `numpy.loadtext(filename)`. For example if this is your database `.csv`: ``` ID | Name | Address | City | State | Zip | Phone | OPEID | IPEDS | 10 | Adam | 130 W.. | Mo.. | AL... | 3.. | 334.. | 01023 | 10063 | 10 | Carl | 130 W.. | Mo.. | AL... | 3.. | 334.. | 01023 | 10063 | 10 | Adolf | 130 W.. | Mo.. |...
Numpy: Difference between a[i][j] and a[i,j]
16,505,000
9
2013-05-12T07:07:05Z
16,505,058
10
2013-05-12T07:15:11Z
[ "python", "list", "numpy" ]
Coming from a Lists background in Python and that of programming languages like C++/Java, one is used to the notation of extracting elements using `a[i][j]` approach. But in `NumPy`, one usually does `a[i,j]`. Both of these would return the same result. What is the fundamental difference between the two and which shou...
The main difference is that `a[i][j]` first creates a view onto `a[i]` and then indexes into that view. On the other hand, `a[i,j]` indexes directly into `a`, making it faster: ``` In [9]: a = np.random.rand(1000,1000) In [10]: %timeit a[123][456] 1000000 loops, best of 3: 586 ns per loop In [11]: %timeit a[123,456]...
How exactly does the python any() function work?
16,505,456
32
2013-05-12T08:18:52Z
16,505,478
16
2013-05-12T08:21:39Z
[ "python" ]
In the python docs page for [`any`](http://docs.python.org/2/library/functions.html#any), the equivalent code for the `any()` function is given as: ``` def any(iterable): for element in iterable: if element: return True return False ``` How does this function know what element I wanna test...
`(x > 0 for x in list)` in that function call creates a generator expression eg. ``` >>> nums = [1, 2, -1, 9, -5] >>> genexp = (x > 0 for x in nums) >>> for x in genexp: print x True True False True False ``` Which `any` uses, and shortcircuits on encountering the first object that evaluates `True`
How exactly does the python any() function work?
16,505,456
32
2013-05-12T08:18:52Z
16,505,590
55
2013-05-12T08:38:56Z
[ "python" ]
In the python docs page for [`any`](http://docs.python.org/2/library/functions.html#any), the equivalent code for the `any()` function is given as: ``` def any(iterable): for element in iterable: if element: return True return False ``` How does this function know what element I wanna test...
First off, if you just used `any(lst)`, then you see that `lst` is the iterable, a list of some items. If it contained `[0, False, '', 0.0, [], {}]`, all of which have boolean values of `False`, then `any(lst)` would be `False`. If `lst` contained `[-1, -2, 10, -4, 20]`, all of which evaluate to `True`, then `any(lst)`...
Get Timezone from City in Python/Django
16,505,501
7
2013-05-12T08:25:28Z
16,519,004
16
2013-05-13T09:41:36Z
[ "python", "django" ]
Using `pytz`, I am able to get a list of timezones like so: ``` >>> from pytz import country_timezones >>> print(' '.join(country_timezones('ch'))) Europe/Zurich >>> print(' '.join(country_timezones('CH'))) Europe/Zurich ``` Given that I am getting both Country and City fields from the user, how can I go about determ...
`pytz` is a wrapper around IANA Time Zone Database (Olson database). It does not contain data to map an arbitrary city in the world to the timezone it is in. You might need a geocoder such as [`geopy`](https://github.com/geopy/geopy) that can translate a place (e.g., a city name) to its coordinates (latitude, longitud...
Generating a dense matrix from a sparse matrix in numpy python
16,505,670
22
2013-05-12T08:50:46Z
16,505,766
40
2013-05-12T09:03:53Z
[ "python", "arrays", "numpy", "scipy", "sparse-matrix" ]
I have a Sqlite database that contains following type of schema: ``` termcount(doc_num, term , count) ``` This table contains terms with their respective counts in the document. like ``` (doc1 , term1 ,12) (doc1, term 22, 2) . . (docn,term1 , 10) ``` This matrix can be considered as sparse matrix as each documents ...
``` from scipy.sparse import csr_matrix A = csr_matrix([[1,0,2],[0,3,0]]) >>>A <2x3 sparse matrix of type '<type 'numpy.int64'>' with 3 stored elements in Compressed Sparse Row format> >>> A.todense() matrix([[1, 0, 2], [0, 3, 0]]) >>> A.toarray() array([[1, 0, 2], [0, 3, 0]]) ...
What's the logic behind this python global scoping magic?
16,507,965
4
2013-05-12T13:37:23Z
16,507,969
7
2013-05-12T13:37:54Z
[ "python", "programming-languages", "scope", "lexical-scope" ]
I was messing around with the scoping in python and found something that I think is rather strange: ``` g = 5 def foo(a): if a: global g g = 10 else: g = 20 print("global g: ",g) foo(False) print("global g: ",g) # 20?! What? foo(True) print("global g: ",g) ``` My believe was that ...
The [`global`](http://docs.python.org/2/reference/simple_stmts.html#the-global-statement) keyword is used by the python *compiler* to mark a name in the function scope as global. As soon as you use it anywhere in the function, that name is no longer a local name. Note that `if` does not introduce a new scope, only fu...
Does fp.readlines() close a file?
16,508,271
2
2013-05-12T14:13:51Z
16,508,298
9
2013-05-12T14:17:32Z
[ "python", "file-io" ]
In python I'm seeing evidence that fp.readlines() is closing the file when I try to access the fp later in the program. Can you confirm this behavior, do I need to re-open the file again later if I also want to read from it again? [Is the file closed?](http://stackoverflow.com/questions/16405926/is-the-file-closed) is...
Once you have read a file, the file pointer has been moved to the end and no more lines will be 'found' beyond that point. Re-open the file or seek back to the start: ``` sent_file.seek(0) ``` Your file is *not* closed; a closed file raises an exception when you attempt to access it: ``` >>> fileobj = open('names.t...
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2
16,508,539
24
2013-05-12T14:44:33Z
16,508,962
43
2013-05-12T15:33:17Z
[ "python" ]
I am creating XML file in Python and there's a field on my XML that I put the contents of a text file. I do it by ``` f = open ('myText.txt',"r") data = f.read() f.close() root = ET.Element("add") doc = ET.SubElement(root, "doc") field = ET.SubElement(doc, "field") field.set("name", "text") field.text = data tree =...
You need to decode data from input string into unicode, before using it, to avoid encoding problems. ``` field.text = data.decode("utf8") ```
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2
16,508,539
24
2013-05-12T14:44:33Z
20,768,795
9
2013-12-25T03:32:48Z
[ "python" ]
I am creating XML file in Python and there's a field on my XML that I put the contents of a text file. I do it by ``` f = open ('myText.txt',"r") data = f.read() f.close() root = ET.Element("add") doc = ET.SubElement(root, "doc") field = ET.SubElement(doc, "field") field.set("name", "text") field.text = data tree =...
I was running into a similar error in pywikipediabot. The `.decode` method is a step in the right direction but for me it didn't work without adding `'ignore'`: ``` fix_encoding = lambda s: s.decode('utf8', 'ignore') ```
Hide external modules when importing a module (e.g. regarding code-completion)
16,509,012
9
2013-05-12T15:37:45Z
22,379,179
8
2014-03-13T12:48:57Z
[ "python", "code-completion", "python-import" ]
I have several modules in one package (a kind of a toolkit), which I use in my projects. The structure looks like this: ``` the_toolkit: __init__.py basic_io.py simple_math.py matrix_kit.py ... ``` Now when I use `IPython` or the code completion in `VIM` after importing a module from the package w...
I had the same problem, and solved it by adding a leading underscore to all my imports. It doesn't look brilliant, but it achieves what you're after. ``` from __future__ import division as _division import numpy as _np import pandas as _pd ``` Only the stuff that starts without an underscore is imported when you impo...
ugettext and ugettext_lazy functions not recognized by makemessages in Python Django
16,509,160
4
2013-05-12T15:51:45Z
16,510,454
14
2013-05-12T18:00:13Z
[ "python", "django", "internationalization" ]
I'm working with Django 1.5.1 and I'm experiencing some "strange behaviour" with translations. I'm using `ugettext` and `ugettext_lazy` in the same Python file. If I organize the imports as: ``` from django.utils.translation import ugettext as trans from django.utils.translation import ugettext_lazy as _ ``` or ``` ...
Django command utility makemessages internally calls [xgettext](https://www.gnu.org/savannah-checkouts/gnu/gettext/manual/html_node/xgettext-Invocation.html) program like this: ``` cmd = ( 'xgettext -d %s -L Python %s %s --keyword=gettext_noop ' '--keyword=gettext_lazy --keyword=ngettext_lazy:1,2 ' '--keyw...
python, storing dictionaries inside a dataframe
16,510,492
5
2013-05-12T18:05:03Z
16,510,526
7
2013-05-12T18:08:57Z
[ "python", "dictionary", "dataframe", "pandas" ]
I've built a pandas dataframe which is storing a simple dictionary in each cell. For example: ``` {'Sales':0,'Revenue':0} ``` I can retrieve a specific value from the dataframe via: ``` df[columnA][index100]['Revenue'] ``` But now I'd like to plot a graph of all the Revenue values from the dictionaries in `columnA`...
A simple way to get all the Revenue values from a column A is `df[columnA].map(lambda v: v['Revenue'])`. Depending on what you're doing, life may indeed be easier if you tweak your structure a bit. For instance, you could use a hierarchical index with "Sales" and "Revenue" as the keys in one level.
Correct way to try/except using Python requests module?
16,511,337
78
2013-05-12T19:44:44Z
16,511,493
165
2013-05-12T20:00:33Z
[ "python", "request", "python-requests" ]
``` try: r = requests.get(url, params={'s': thing}) except requests.ConnectionError, e: print e #should I also sys.exit(1) after this? ``` Is this correct? Is there a better way to structure this? Will this cover all my bases?
Have a look at the Requests [exception docs](http://docs.python-requests.org/en/latest/user/quickstart/#errors-and-exceptions). In short: > In the event of a network problem (e.g. DNS failure, refused connection, etc), Requests will raise a **`ConnectionError`** exception. > > In the event of the rare invalid HTTP res...
Using Extensions with Selenium (Python)
16,511,384
7
2013-05-12T19:49:13Z
16,512,012
9
2013-05-12T21:02:36Z
[ "python", "google-chrome", "selenium", "selenium-webdriver" ]
I am currently using Selenium to run instances of Chrome to test web pages. Each time my script runs, a clean instance of Chrome starts up (clean of extensions, bookmarks, browsing history, etc). I was wondering if it's possible to run my script with Chrome extensions. I've tried searching for a Python example, but not...
You should use chrome webdriver [options](http://selenium-python.readthedocs.org/en/latest/api.html#selenium.webdriver.chrome.webdriver.WebDriver) to set a list of extensions to load. Here's an example: ``` import os from selenium import webdriver from selenium.webdriver.chrome.options import Options executable_path...
No attribute 'SMTP', error when trying to send email in Python
16,512,256
6
2013-05-12T21:32:25Z
16,512,275
28
2013-05-12T21:34:36Z
[ "python", "email", "smtp", "attributeerror" ]
I am trying to send an email in Python: ``` import smtplib fromaddr = '......................' toaddrs = '......................' msg = 'Spam email Test' username = '.......' password = '.......' server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() server.login(username, password...
Python already has an [`email` module](http://docs.python.org/2/library/email.html). Your script's name is `email.py`, which is preventing `smtplib` from importing the built-in `email` module. Rename your script to something other than `email.py` and the problem will go away.
Logging into SAML/Shibboleth authenticated server using python
16,512,965
10
2013-05-12T23:11:13Z
16,646,366
14
2013-05-20T09:24:40Z
[ "python", "login", "saml", "saml-2.0", "shibboleth" ]
I'm trying to login my university's server via python, but I'm entirely unsure of how to go about generating the appropriate HTTP POSTs, creating the keys and certificates, and other parts of the process I may be unfamiliar with that are required to comply with the SAML spec. I can login with my browser just fine, but ...
Basically what you have to understand is the workflow behind a SALM authentication process. Unfortunately, there is no PDF out there which seems to really provide a good help in finding out what kind of things the browser does when accessing to a SAML protected website. Maybe you should take a look to something like t...
Where do classes get their default '__dict__' attributes from?
16,513,029
7
2013-05-12T23:23:14Z
16,515,220
8
2013-05-13T05:10:43Z
[ "python", "class" ]
If we compare the lists generated by applying the `dir()` built-in to the object superclass and to a 'dummy', bodyless class, such as ``` class A(): pass ``` we find that the A class has three attributes `('__dict__', '__module__' and '__weakref__')` that are not present in the object class. Where does the A cla...
* The `__dict__` attribute is created by the internal code in `type.__new__`. The class's metaclass may influence the eventual content of `__dict__`. If you are using `__slots__`, you will have no `__dict__` attribute. * `__module__` is set when the class is compiled, so the instance inherits this attribute from the cl...
python. if var == False
16,513,573
2
2013-05-13T00:59:13Z
16,513,591
15
2013-05-13T01:01:15Z
[ "python", "if-statement" ]
In python you can write an if statement as follows ``` var = True if var: print 'I\'m here' ``` is there any way to do the opposite without the ==, eg ``` var = False if !var: print 'learnt stuff' ```
Python uses `not` instead of `!` for negation. Try ``` if not var: print "learnt stuff" ``` instead
How to run multiple lines using python -c
16,513,811
3
2013-05-13T01:38:50Z
16,513,826
8
2013-05-13T01:41:34Z
[ "python" ]
I need to use `python -c` to remotely run some code, it works when I use: ``` python -c "a=4;print a" 4 ``` Or ``` python -c "if True:print 'ye'" ``` But `python -c "a=4;if a<5:print 'ye'"` will generate an error: ``` File "<string>", line 1 a=4;if a<5:print 'ye' SyntaxError: invalid syntax ``` What shoul...
Enclose it in single quotes and use multiple lines: ``` python -c ' a = 4 if a < 5: print "ye" ' ``` If you need a single quote in the code, use this horrible construct: ``` python -c ' a = 4 if a < 5: print '\''ye'\'' ' ``` This works because most UNIX shells will not interpret anything between single quot...
How to get attributes in the order they are declared in a Python class?
16,514,286
5
2013-05-13T03:01:00Z
16,514,323
10
2013-05-13T03:07:09Z
[ "python", "metaclass" ]
As described in [PEP435](http://www.python.org/dev/peps/pep-0435/), an `enum` can be defined this way: ``` class Color(Enum): red = 1 green = 2 blue = 3 ``` And the resulting `enum members` of `Color` can be iterated in definition order: `Color.red, Color.green, Color.blue`. This reminds me of `Form` in ...
In Python 3, you can customize the namespace that a class is declared in with the metaclass. For example, you can use an `OrderedDict`: ``` from collections import OrderedDict class EnumMeta(type): def __new__(mcls, cls, bases, d): print(d) return type.__new__(mcls, cls, bases, d) @classmeth...
How to normalize a list of positive and negative decimal number to a specific range
16,514,443
3
2013-05-13T03:28:08Z
16,514,676
11
2013-05-13T04:01:07Z
[ "python", "list", "range", "normalize" ]
I have a list of decimal numbers as follows: ``` [-23.5, -12.7, -20.6, -11.3, -9.2, -4.5, 2, 8, 11, 15, 17, 21] ``` I need to normalize this list to fit into the range `[-5,5]`. How can I do it in python?
To get the range of input is very easy: ``` old_min = min(input) old_range = max(input) - old_min ``` Here's the tricky part. You can multiply by the new range and divide by the old range, but that almost guarantees that the top bucket will only get one value in it. You need to expand your output range so that the to...
Set or update dictionary entries code pattern in Python
16,514,586
3
2013-05-13T03:48:49Z
16,514,621
7
2013-05-13T03:53:20Z
[ "python", "design-patterns", "dictionary" ]
Given a dict with the following format: ``` dict_list = {key0: [list0,list1], key1: [list0,list1], ...} ``` I am currently updating `dict_list` in the following manner: ``` for key in list_of_possibly_new_keys: if key not in dict_list.keys(): dict_list[key] = [list0, list1] else: dict_list[key][0]....
Unless this is homework, why can't you use a `defaultdict` here? ``` from collections import defaultdict dict_list = defaultdict(list) for key in list_of_possibly_new_keys: dict_list[key] += [list0, list1] ``` Updated for your example: ``` >>> from collections import defaultdict >>> dict_list = defaultdict(lamb...
Python Tkinter Notebook widget
16,514,617
3
2013-05-13T03:52:37Z
16,515,424
12
2013-05-13T05:33:03Z
[ "python", "widget", "tkinter" ]
Using [this python recipe](http://code.activestate.com/recipes/541092-tknotebook/), i have created a notebook like widget on my Tk window. It all works fine until i tried to add an image into each tab. When i add image into the tab, the text i initially set were no longer shown. I am wondering if i can make the text (i...
Label reference: [`compound`](http://effbot.org/tkinterbook/label.htm#Tkinter.Label.config-method) > Controls how to combine text and image in the label. By default, if an image or bitmap is given, it is drawn instead of the text. If this option is set to **CENTER**, the text is drawn on top of the image. If this opti...
Saving a stream while playing it using LibVLC
16,515,099
17
2013-05-13T04:56:09Z
16,758,988
7
2013-05-26T11:56:37Z
[ "c++", "python", "c", "video-streaming", "libvlc" ]
Using [LibVLC](http://wiki.videolan.org/Developers_Corner), I'm trying to save a stream while playing it. This is the python code: ``` import os import sys import vlc if __name__ == '__main__': filepath = <either-some-url-or-local-path> movie = os.path.expanduser(filepath) if 'http://' not in filepath: ...
## Idea: The basic idea is simple enough. You have to duplicate the output stream and redirect it to a file. This is done, as [Maresh](http://stackoverflow.com/a/16758264/961781) correctly pointed out, using the **sout=#duplicate{...}** directive. ## Working Solution: The following solution works on my machine ™. ...
How to specify 2 keys in python sorted(list)?
16,515,737
16
2013-05-13T06:06:01Z
16,515,763
26
2013-05-13T06:08:22Z
[ "python", "list", "sorting", "key" ]
How do I sort a list of strings by `key=len` first then by `key=str`? I've tried the following but it's not giving me the desired sort: ``` >>> ls = ['foo','bar','foobar','barbar'] >>> >>> for i in sorted(ls): ... print i ... bar barbar foo foobar >>> >>> for i in sorted(ls, key=len): ... print i ... foo ba...
Define a key function that returns a tuple in which the first item is `len(str)` and the second one is the string itself. Tuples are then compared lexicographically. That is, first the lengths are compared; if they are equal then the strings get compared. ``` In [1]: ls = ['foo','bar','foobar','barbar'] In [2]: sorte...
How to specify 2 keys in python sorted(list)?
16,515,737
16
2013-05-13T06:06:01Z
16,516,036
12
2013-05-13T06:29:46Z
[ "python", "list", "sorting", "key" ]
How do I sort a list of strings by `key=len` first then by `key=str`? I've tried the following but it's not giving me the desired sort: ``` >>> ls = ['foo','bar','foobar','barbar'] >>> >>> for i in sorted(ls): ... print i ... bar barbar foo foobar >>> >>> for i in sorted(ls, key=len): ... print i ... foo ba...
The answer from *root* is correct, but you don't really need a *lambda*: ``` >>> def key_function(x): return len(x), str(x) >>> sorted(['foo','bar','foobar','barbar'], key=key_function) ['bar', 'foo', 'barbar', 'foobar'] ``` In addtion, there is a alternate approach takes advantage of sort stability which le...
Writes, Deletes, but won't read text file
16,516,312
2
2013-05-13T06:51:45Z
16,516,334
9
2013-05-13T06:53:18Z
[ "python" ]
I just started learning python today. This is a simple script to either read, write one line to, or delete a text file. It writes and deletes just fine, but when choosing the 'r' (read) option i just get the error: > IOError: [Errno 9] Bad file descriptor What am I missing here...? ``` from sys import argv script, ...
You've opened the file in write mode, so you can't perform read on it. And secondly `'w'` automatically truncates the file, so your truncate operation is useless. You can use `r+` mode here: ``` target = open(filename, 'r+') ``` > 'r+' opens the file for both reading and writing Use the `with` statement while openin...
Pandas: Using Unix epoch timestamp as Datetime index
16,517,240
8
2013-05-13T07:56:59Z
16,517,273
13
2013-05-13T07:58:26Z
[ "python", "numpy", "pandas", "time-series" ]
My application involves dealing with data (contained in a CSV) which is of the following form: ``` Epoch (number of seconds since Jan 1, 1970), Value 1368431149,20.3 1368431150,21.4 .. ``` Currently i read the CSV using numpy loadtxt method (can easily use read\_csv from Pandas). Currently for my series i am converti...
Convert them to `datetime64[s]`: ``` np.array([1368431149, 1368431150]).astype('datetime64[s]') # array([2013-05-13 07:45:49, 2013-05-13 07:45:50], dtype=datetime64[s]) ```
Output pyodbc cursor results as python dictionary
16,519,385
19
2013-05-13T10:02:02Z
16,523,148
42
2013-05-13T13:22:23Z
[ "python", "dictionary", "cursor", "pyodbc", "pypyodbc" ]
How do I serialize pyodbc cursor output (from `.fetchone`, `.fetchmany` or `.fetchall`) as a Python dictionary? I'm using bottlepy and need to return dict so it can return it as JSON.
If you don't know columns ahead of time, use [cursor.description](https://code.google.com/p/pyodbc/wiki/Cursor#description) to build a list of column names and [zip](http://docs.python.org/2/library/functions.html#zip) with each row to produce a list of dictionaries. Example assumes connection and query are built: ```...
python regex: to match space character or end of string
16,519,744
3
2013-05-13T10:21:53Z
16,520,099
9
2013-05-13T10:40:25Z
[ "python", "regex" ]
I want to match space chars or end of string in a text. ``` import re uname='abc' assert re.findall('@%s\s*$' % uname, '@'+uname) assert re.findall('@%s\s*$' % uname, '@'+uname+' '+'aa') assert not re.findall('@%s\s*$' % uname, '@'+uname+'aa') ``` The pattern is not right. How to use python?
`\s*$` is incorrect: this matches "zero or more spaces *followed by* the end of the string", rather than "one or more spaces *or* the end of the string". For this situation, I would use `(?:\s+|$)` (inside a raw string, as others have mentioned). The `(?:)` part is just about separating that subexpression so that the ...
Python syntax for "if a or b or c but not all of them"
16,522,111
111
2013-05-13T12:30:20Z
16,522,142
223
2013-05-13T12:32:16Z
[ "python", "if-statement" ]
I have a python script that can receive either zero or three command line arguments. (Either it runs on default behavior or needs all three values specified.) What's the ideal syntax for something like: ``` if a and (not b or not c) or b and (not a or not c) or c and (not b or not a): ``` ?
How about: ``` conditions = [a, b, c] if any(conditions) and not all(conditions): ... ``` Other variant: ``` if 1 <= sum(map(bool, conditions)) <= 2: ... ```