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 |
|---|---|---|---|---|---|---|---|---|---|
Can pandas automatically recognize dates? | 17,465,045 | 27 | 2013-07-04T08:08:39Z | 17,468,154 | 7 | 2013-07-04T10:38:47Z | [
"python",
"date",
"types",
"dataframe",
"pandas"
] | Today I was positively surprised by the fact that while reading data from a data file (for example) pandas is able to recognize types of values:
```
df = pandas.read_csv('test.dat', delimiter=r"\s+", names=['col1','col2','col3'])
```
For example it can be checked in this way:
```
for i, r in df.iterrows():
print... | pandas read\_csv method is great for parsing dates. Complete documentation at <http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.parsers.read_csv.html>
you can even have the different date parts in different columns and pass the parameter:
```
parse_dates : boolean, list of ints or names, list of lists,... |
Best way to structure a tkinter application | 17,466,561 | 32 | 2013-07-04T09:21:47Z | 17,466,968 | 11 | 2013-07-04T09:40:36Z | [
"python",
"tkinter"
] | The following is the overall structure of my typical python tkinter program.
```
def funA():
def funA1():
def funA12():
# stuff
def funA2():
# stuff
def funB():
def funB1():
# stuff
def funB2():
# stuff
def funC():
def funC1():
# stuff
de... | Putting each of your top-level windows into it's own separate class gives you code re-use and better code organization. Any buttons and relevant methods that are present in the window should be defined inside this class. Here's an example (taken from [here](http://stackoverflow.com/questions/16115378/tkinter-example-co... |
Best way to structure a tkinter application | 17,466,561 | 32 | 2013-07-04T09:21:47Z | 17,470,842 | 68 | 2013-07-04T12:52:50Z | [
"python",
"tkinter"
] | The following is the overall structure of my typical python tkinter program.
```
def funA():
def funA1():
def funA12():
# stuff
def funA2():
# stuff
def funB():
def funB1():
# stuff
def funB2():
# stuff
def funC():
def funC1():
# stuff
de... | I advocate an object oriented approach. This is the template that I start out with:
```
# Use Tkinter for python 2, tkinter for python 3
import Tkinter as tk
class MainApplication(tk.Frame):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self.parent =... |
python Tornado websockets how to send message every X seconds? | 17,466,847 | 10 | 2013-07-04T09:35:31Z | 17,468,469 | 9 | 2013-07-04T10:55:22Z | [
"python",
"websocket",
"tornado"
] | I am trying to cobble together a test which allows websockets clients to connect to a Tornado server and I want the Tornado server to send out a message to all clients every X seconds.
The reason I am doing this is because wbesockets connections are being silently dropped somewhere and I am wondering of periodic "ping... | Why don't you try write a scheduler inside it? :)
```
def schedule_func():
#DO SOMETHING#
#milliseconds
interval_ms = 15
main_loop = tornado.ioloop.IOLoop.instance()
sched = tornado.ioloop.PeriodicCallback(schedule_func,interval_ms, io_loop = main_loop)
#start your period timer
sched.start()
#start your loop
main... |
How to embed python code in batch script | 17,467,441 | 5 | 2013-07-04T10:02:39Z | 17,468,811 | 7 | 2013-07-04T11:12:08Z | [
"python",
"windows",
"bash",
"batch-file"
] | In bash, we can:
```
python - << EOF
import os
print 'hello'
EOF
```
to embed python code snippet in bash script.
But in Windows batch, this doesn't work - although I can still use python -c but that requires me to collpase my code into one line, which is something I try to avoid.
Is there a way to achieve this in ... | You could use a hybrid technic.
```
1>2# : ^
'''
@echo off
echo normal
echo batch code
echo Switch to python
python "%~f0"
exit /b
rem ^
'''
print "This is Python code"
```
The batch code is in a multiline string `'''` so this is invisible for python.
The batch parser doesn't see the python code, as it exits befor... |
How to embed python code in batch script | 17,467,441 | 5 | 2013-07-04T10:02:39Z | 29,881,143 | 9 | 2015-04-26T17:44:27Z | [
"python",
"windows",
"bash",
"batch-file"
] | In bash, we can:
```
python - << EOF
import os
print 'hello'
EOF
```
to embed python code snippet in bash script.
But in Windows batch, this doesn't work - although I can still use python -c but that requires me to collpase my code into one line, which is something I try to avoid.
Is there a way to achieve this in ... | Even more efficient, plus it passes all command-line arguments to and returns the exit code from the script:
```
@SETLOCAL ENABLEDELAYEDEXPANSION & python -x "%~f0" %* & EXIT /B !ERRORLEVEL!
# Your python code goes here...
```
Here's a break-down of what's happening:
* `@` prevents the script line from being printed... |
Django class-based view | 17,469,461 | 2 | 2013-07-04T11:45:17Z | 17,469,511 | 7 | 2013-07-04T11:47:52Z | [
"python",
"django",
"django-class-based-views"
] | # django
i'm new to django. as per in doc i'm creating a django app. while o'm using class-based view I got a error.
I didn't understand much about class based view. Can any one explain what's the different between normal view. Its the same poll app in the documentation page of Django
Here's my code:
```
class Detai... | `as_view` should be called, not referenced, according to the [docs](https://docs.djangoproject.com/en/dev/topics/class-based-views/#simple-usage-in-your-urlconf), your url should look like:
```
url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail')
```
Note the usage of parenthesis.
Also, you should rathe... |
How to round to two decimal places in Python 2.7? | 17,470,883 | 42 | 2013-07-04T12:54:52Z | 17,470,912 | 128 | 2013-07-04T12:56:17Z | [
"python",
"python-2.7"
] | Just wondering how i could round my code to two decimal places rather than the 10 or so it gives?
Thank you in advance.
```
print "financial return of outcome 1 =","$"+str(out1)
``` | Use the built-in function [`round()`](https://docs.python.org/2/library/functions.html#round):
```
>>> round(1.2345,2)
1.23
>>> round(1.5145,2)
1.51
>>> round(1.679,2)
1.68
```
Or built-in function [`format()`](https://docs.python.org/2/library/functions.html#format):
```
>>> format(1.2345, '.2f')
'1.23'
>>> format(... |
Python: Formatting a string using variable names placeholders | 17,471,439 | 4 | 2013-07-04T13:22:42Z | 17,471,509 | 8 | 2013-07-04T13:25:53Z | [
"python",
"string-formatting",
"iterable-unpacking"
] | Consider the following string building statement:
```
s="svn cp %s/%s/ %s/%s/" % (root_dir, trunk, root_dir, tag)
```
Using four `%s` can be confusing, so I prefer using variable names:
```
s="svn cp {root_dir}/{trunk}/ {root_dir}/{tag}/".format(**SOME_DICTIONARY)
```
When `root_dir`, `tag` and `trunk` are defined ... | You can use [`locals()`](http://docs.python.org/2/library/functions.html#locals) function
```
s="svn cp {root_dir}/{trunk}/ {root_dir}/{tag}/".format(**locals())
``` |
How to sum a list of numbers in python | 17,472,771 | 3 | 2013-07-04T14:26:15Z | 17,472,796 | 12 | 2013-07-04T14:27:42Z | [
"python",
"numbers",
"sum"
] | So first of all, I need to extract the numbers from a range of 455,111,451, to 455,112,000.
I could do this manually, there's only 50 numbers I need, but that's not the point.
I tried to:
```
for a in range(49999951,50000000):
print +str(a)
```
What should I do? | Use [`sum`](http://docs.python.org/2/library/functions.html#sum)
```
>>> sum(range(49999951,50000000))
2449998775L
```
---
It is a [builtin function](http://docs.python.org/2/library/functions.html), Which means you don't need to import anything or do anything special to use it. you should always consult the documen... |
Check if the filename contains a string Python | 17,473,093 | 2 | 2013-07-04T14:42:47Z | 17,473,147 | 7 | 2013-07-04T14:45:29Z | [
"python"
] | I am trying to find a way where the name of the file the program is reading will be checked if it contains any of the strings like below. I am not sure if that is the right way to go about it. The string is going to be a global variable as I have to use it later in the program
```
class Wordnet():
def __init__(se... | Try this:
```
def check_word_type(self, filename):
words = ['noun','verb','vrb','adj','adv'] #I am not sure if adj and adv are variables
self.word_type = ''
for i in words:
if i in filename:
self.word_type = str(i) #just make sure its string
return self.word_type
``` |
How to avoid the L in Python | 17,473,195 | 4 | 2013-07-04T14:48:16Z | 17,473,284 | 7 | 2013-07-04T14:53:26Z | [
"python",
"python-2.7",
"numbers"
] | ```
>>> sum(range(49999951,50000000))
2449998775L
```
Is there any possible way to avoid the L at the end of number? | You are looking at a Python literal representation of the number, which just indicates that it is a python `long` integer. *This is normal*. You do not need to worry about that `L`.
If you need to print such a number, the `L` will not normally be there.
What happens is that the Python interpreter prints the result of... |
How to sort python list of strings of numbers | 17,474,211 | 10 | 2013-07-04T15:47:21Z | 17,474,264 | 36 | 2013-07-04T15:51:05Z | [
"python"
] | I am trying to sort list of strings containing numbers
```
a = ["1099.0","9049.0"]
a.sort()
a
['1099.0', '9049.0']
b = ["949.0","1099.0"]
b.sort()
b
['1099.0', '949.0']
a
['1099.0', '9049.0']
```
But list `b` is sorting and not list `a` | You want to sort based on the `float` values (not string values), so try:
```
>>> b = ["949.0","1099.0"]
>>> b.sort(key=float)
>>> b
['949.0', '1099.0']
``` |
I'd like my code to flow with my terminal a little better | 17,474,524 | 2 | 2013-07-04T16:06:43Z | 17,474,544 | 7 | 2013-07-04T16:08:13Z | [
"python",
"linux",
"python-2.7"
] | So I have a fully functional py script running on Ubuntu 12.04, everything works great. Except I don't like my input methods, it's getting annoying as you'll see below. Before I type out the code, I should say that the code takes two images in a .img format and then does computations on them. Here's what I have:
```
i... | You want to parse the command line arguments instead of reading input after the program starts.
Use the [`argparse` module](http://docs.python.org/2/library/argparse.html) for that, or parse [`sys.argv`](http://docs.python.org/2/library/sys.html#sys.argv) yourself. |
Django DeleteView without confirmation template | 17,475,324 | 8 | 2013-07-04T17:03:57Z | 17,476,373 | 22 | 2013-07-04T18:29:39Z | [
"python",
"django"
] | I am using Django DeleteView in a template and I've created a url & view.
Is it possible to skip the process of loading the \_confirm\_delete template and just post the delete immediately. | `DeleteView` responds to `POST` and `GET`Â requests, `GET` request display confirmation template, while `POST` deletes instance.
You can send `POST` request, without confirmation with form like this:
```
<form method="POST" action="{% url "your_delete_url_name" %}">
{% csrf_token %}<input type="submit" value="DELE... |
dropping infinite values from dataframes in pandas? | 17,477,979 | 37 | 2013-07-04T20:55:20Z | 17,478,495 | 72 | 2013-07-04T21:50:51Z | [
"python",
"numpy",
"scipy",
"pandas"
] | what is the quickest/simplest way to drop nan and inf/-inf values from a pandas DataFrame without resetting `mode.use_inf_as_null`? I'd like to be able to use the `subset` and `how` arguments of `dropna`, except with `inf` values considered missing, like:
```
df.dropna(subset=["col1", "col2"], how="all", with_inf=True... | The simplest way would be to first [`replace`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html) infs to NaN:
```
df.replace([np.inf, -np.inf], np.nan)
```
and then use the [`dropna`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.dropna.html):
```
df.replac... |
How can I generate documentation for a Python property setter using Sphinx? | 17,478,040 | 6 | 2013-07-04T21:00:28Z | 17,522,081 | 8 | 2013-07-08T08:28:59Z | [
"python",
"properties",
"python-sphinx"
] | I have a Python class something like the following, with docstrings intended to be converted into documentation by [Sphinx](http://sphinx-doc.org/):
```
class Direction(object):
"""
A direction in which movement can be made.
"""
def __init__(self):
self._name = None
@property
def name(... | Sphinx ignores docstrings on property setters so all documentation for a property must be on the `@property` method.
Whilst Sphinx understands certain specific tags (e.g. `:param ...:`) it will accept any custom tags and will render them as labels for the text which follows them.
Therefore something like the followin... |
Make scatter plot from set of points in tuples | 17,478,779 | 3 | 2013-07-04T22:24:14Z | 17,478,866 | 9 | 2013-07-04T22:34:16Z | [
"python",
"matplotlib",
"set"
] | I have set of points in tuples, like this:
```
>>> s
set([(209, 147),
(220, 177),
(222, 181),
(225, 185),
(288, 173),
(211, 155),
(222, 182)])
```
What is the right way to do scatter plot of this set? | You can do:
```
x,y = zip(*s)
plt.scatter(x,y)
```
Or even in an "one-liner":
```
plt.scatter(*zip(*a))
```
[`zip()` can be used to pack and unpack arrays](http://stackoverflow.com/q/19339/832621) and when you call using `method(*list_or_tuple)`, each element in the list or tuple is passed as an argument. |
Iterating vs List Concatenation | 17,479,361 | 10 | 2013-07-04T23:51:06Z | 17,479,468 | 13 | 2013-07-05T00:08:42Z | [
"python",
"profiling",
"performance"
] | So there are two ways to take a list and add the members of a second list to the first. You can use list concatenation or your can iterate over it. You can:
```
for obj in list2:
list1.append(obj)
```
or you can:
```
list1 = list1 + list2
```
or
```
list1 += list2
```
My question is: which is faster, and why?... | `append` adds each item one at a time, which is the cause of its slowness, as well as the repeated function calls to `append`.
**However** in this case the `+=` operator is **not** syntactic sugar for the `+`. The `+=` operator does not actually create a new list then assign it back, it modifies the left hand operand ... |
Flask: request.json works but request.get_json() causes error code 500 | 17,479,774 | 2 | 2013-07-05T01:01:43Z | 17,492,081 | 8 | 2013-07-05T15:13:24Z | [
"python",
"flask"
] | The [documentation](http://flask.pocoo.org/docs/api/) says to use `request.get_json()`, but that causes the service to return an error:
```
Server returned HTTP response code: 500
```
calling `request.data` or `request.json` both work, however.
Stack trace:
```
Traceback (most recent call last):
File "/home/blake... | In Flask/wrappers.py the method `get_json()` is defined as method to the class `Request`.
However, the same file still contains the old, deprecated method `json()`. If you have an old version of flask, then a) update or b) use `request.json()` instead. |
Fitting a Weibull distribution using Scipy | 17,481,672 | 19 | 2013-07-05T05:29:10Z | 17,498,673 | 13 | 2013-07-06T01:15:23Z | [
"python",
"numpy",
"scipy",
"distribution",
"weibull"
] | I am trying to recreate maximum likelihood distribution fitting, I can already do this in Matlab and R, but now I want to use scipy. In particular, I would like to estimate the Weibull distribution parameters for my data set.
I have tried this:
```
import scipy.stats as s
import numpy as np
import matplotlib.pyplot a... | My guess is that you want to estimate the shape parameter and the scale of the Weibull distribution while keeping the location fixed. Fixing `loc` assumes that the values of your data and of the distribution are positive with lower bound at zero.
`floc=0` keeps the location fixed at zero, `f0=1` keeps the first shape ... |
Fitting a Weibull distribution using Scipy | 17,481,672 | 19 | 2013-07-05T05:29:10Z | 18,265,280 | 14 | 2013-08-16T03:18:35Z | [
"python",
"numpy",
"scipy",
"distribution",
"weibull"
] | I am trying to recreate maximum likelihood distribution fitting, I can already do this in Matlab and R, but now I want to use scipy. In particular, I would like to estimate the Weibull distribution parameters for my data set.
I have tried this:
```
import scipy.stats as s
import numpy as np
import matplotlib.pyplot a... | It is easy to verify which result is the true MLE, just need a simple function to calculate log likelihood:
```
>>> def wb2LL(p, x): #log-likelihood
return sum(log(stats.weibull_min.pdf(x, p[1], 0., p[0])))
>>> adata=loadtxt('/home/user/stack_data.csv')
>>> wb2LL(array([6.8820748596850905, 1.8553346917584836]), ad... |
Format string - spaces between every three digit | 17,484,631 | 4 | 2013-07-05T08:39:49Z | 17,484,665 | 13 | 2013-07-05T08:42:00Z | [
"python"
] | How to simple format string with decimal number for show it with spaces between every three digits?
I can make something like this:
```
some_result = '12345678,46'
' '.join(re.findall('...?', test[:test.find(',')]))+test[test.find(','):]
```
and result is:
```
'123 456 78,46'
```
but I want:
```
'12 345 678,46'
`... | This is a bit hacky, but:
```
format(12345678.46, ',').replace(',', ' ').replace('.', ',')
```
As described in [Format specification mini-language](http://docs.python.org/2/library/string.html#format-specification-mini-language), in a format\_spec:
> The ',' option signals the use of a comma for a thousands separato... |
How to just keep punctuation with a string in python? | 17,485,092 | 2 | 2013-07-05T09:06:18Z | 17,485,115 | 15 | 2013-07-05T09:07:41Z | [
"python",
"string"
] | I want create a catalog of all logs, so I just want keep all punctuation and remove all other chars which include CJK and others.
for example:
```
s = "aaa; sf = fa = bla http://wa"
```
expected output is
```
;==://
``` | You can use [`str.translate`](http://docs.python.org/2/library/stdtypes.html#str.translate):
```
>>> from string import letters, digits, whitespace, punctuation
>>> s = "aaa; sf = fa = bla http://wa"
>>> s.translate(None, letters+digits+whitespace)
';==://'
```
or `regex`:
```
>>> re.sub(r'[^{}]+'.format(punctuation... |
Python - Lazy loading of class attributes | 17,486,104 | 6 | 2013-07-05T09:59:45Z | 17,487,613 | 10 | 2013-07-05T11:15:51Z | [
"python"
] | Class foo has a bar. Bar is not loaded until it is accessed. Further accesses to bar should incur no overhead.
```
class Foo(object):
def get_bar(self):
print "initializing"
self.bar = "12345"
self.get_bar = self._get_bar
return self.bar
def _get_bar(self):
print "acce... | There are some problems with the current answers. The solution with a property requires that you specify an additional class attribute and has the overhead of checking this attribute on each look up. The solution with `__getattr__` has the issue that it hides this attribute until first access. This is bad for introspec... |
How can you bundle all your python code into a single zip file? | 17,486,578 | 11 | 2013-07-05T10:23:42Z | 17,616,626 | 14 | 2013-07-12T13:57:48Z | [
"python",
"setup.py",
"pypi"
] | It would be convenient when distributing applications to combine *all* of the eggs into a single zip file so that all you need to distribute is a single zip file and an executable (some custom binary that simply starts, loads the zip file's main function and kicks python off or similar).
I've seen some talk of doing t... | You can automate most of the work with regular python tools. Let's start with clean virtualenv.
```
[zart@feena ~]$ mkdir ziplib-demo
[zart@feena ~]$ cd ziplib-demo
[zart@feena ziplib-demo]$ virtualenv .
New python executable in ./bin/python
Installing setuptools.............done.
Installing pip...............done.
``... |
Can a Python package name start with a number? | 17,487,209 | 5 | 2013-07-05T10:54:59Z | 17,487,228 | 11 | 2013-07-05T10:55:45Z | [
"python"
] | I know that naming a Python module starting with a number is a bad idea, as stated in [this other question](http://stackoverflow.com/questions/9090079/in-python-how-to-import-filename-starts-with-a-number), but I'm wondering if is it legal to do so in a Python package, not module (aka file).
For example. I want to int... | No, it cannot. Python package and module names need to be [valid identifiers](http://docs.python.org/2/reference/lexical_analysis.html#identifiers):
```
identifier ::= (letter|"_") (letter | digit | "_")*
```
Identifiers *must* start with a letter or an underscore.
The [import statement](http://docs.python.org/2/re... |
import matplotlib.pyplot hangs | 17,490,444 | 41 | 2013-07-05T13:48:29Z | 24,982,107 | 76 | 2014-07-27T14:48:23Z | [
"python",
"matplotlib",
"python-import"
] | I'm trying to get matplotlib up and running on OS X 10.8.4. I've installed matplotlib and the dependencies (libping, freetype, numpy, scipy). I am able to import matplotlib just fine. However, if I try to import matplotlib.pyplot, it just hangs. There's no error, it's just that nothing happens.
```
>>> import matplotl... | You can fix the problem on Mac OS X Mavericks and Yosemite by doing the following:
```
cd ~/.matplotlib/
fc-list # Should take a couple minutes.
```
After `fc-list` finishes running you will be able to import the package using `import matplotlib.pyplot as plt`. This is the [github issue](https://github.com/matplotli... |
How can I search through a list in python for something that might not exist? | 17,493,102 | 2 | 2013-07-05T16:13:47Z | 17,493,115 | 10 | 2013-07-05T16:14:59Z | [
"python"
] | For example something like:
```
if l.index(a)== -1:
l += [a]
```
If I run something like this, I will get a value error.I am assuming this is not a new problem. | Why not just use:
```
if a not in some_list:
some_list.append(a)
``` |
Should I force Python type checking? | 17,493,159 | 7 | 2013-07-05T16:18:18Z | 17,504,280 | 8 | 2013-07-05T18:19:23Z | [
"python",
"types",
"semantics"
] | Perhaps as a remnant of my days with a strongly-typed language (Java), I often find myself writing functions and then forcing type checks. For example:
```
def orSearch(d, query):
assert (type(d) == dict)
assert (type(query) == list)
```
Should I keep doing this? what are the advantages to doing/not doing thi... | In most of the cases it would interfere with duck typing and with inheritance.
* *Inheritance:* You certainly intended to write something with the effect of
```
assert isinstance(d, dict)
```
to make sure that your code also works correctly with subclasses of `dict`. This is similar to the usage in Java, I t... |
Why Python returns a False statement when it shouldn't? | 17,493,219 | 3 | 2013-07-05T16:22:20Z | 17,493,242 | 11 | 2013-07-05T16:24:07Z | [
"python",
"equals",
"modulo"
] | Take this code for example:
```
print 2.0 == 2 #---> returns True
print 12 % 5 #---> returns 2
print ((12.0 / 5) - (12 / 5)) * 5 #---> returns 2.0
print ((12.0 / 5) - (12 / 5)) * 5 == 12 % 5 #---> returns False (What the hell happens here?)
``` | Because the first calculation does not return *exactly* 2.0:
```
>>> ((12.0 / 5) - (12 / 5)) * 5
1.9999999999999996
```
`print` limits floating point display to 12 significant digits only, causing the value to be rounded to 2.0. |
get intersection of list of sets | 17,495,257 | 7 | 2013-07-05T18:54:12Z | 17,495,274 | 19 | 2013-07-05T18:55:31Z | [
"python",
"list",
"set"
] | I want python to get the intersection of a list of sets.
For example, I have a function that returns `s` a list of sets following:
```
[set(0,1,3), set(1,3)]
```
As you can see the intersection of this is the set {1,3}. How can I get python to obtain the intersection? What I've been doing so far is iterating over th... | Use `set.intersection`:
```
>>> lis = [set((0,1,3)), set((1,3))]
>>> set.intersection(*lis)
set([1, 3])
```
For union use `set.union`:
```
>>> set.union(*lis)
set([0, 1, 3])
```
If [performance](http://stackoverflow.com/a/17350800/846892) matters then use this:
```
>>> from itertools import islice
>>> set.intersec... |
How to determine whether string is a number when the number is negative | 17,496,871 | 3 | 2013-07-05T21:06:57Z | 17,496,893 | 7 | 2013-07-05T21:09:26Z | [
"python"
] | I get the following result:
```
>>> x = '-15'
>>> print x.isdigit()
False
```
When I expect it to be `True`. There seems to be no built in function that returns `True` for a string of negative number. What is the recommend to detect it? | The recommended way would be to `try` it:
```
try:
x = int(x)
except ValueError:
print "{} is not an integer".format(x)
```
If you also expect decimal numbers, use `float()` instead of `int()`. |
Python: copying a list within a list | 17,497,067 | 18 | 2013-07-05T21:27:20Z | 17,497,086 | 18 | 2013-07-05T21:29:37Z | [
"python",
"list"
] | Hoping someone can help me here.
I'm very new to Python, and I'm trying to work out what I'm doing wrong.
I've already searched and found out that that Python variables can be linked so that changing one changes the other, and I have done numerous tests with the `id()` function to get to grips with this concept. But ... | `b = a[:]` creates a [shallow copy](http://en.wikipedia.org/wiki/Object_copy#Shallow_copy) of `a`, so changing the mutable lists within `b` still effects *those same lists* in `a`.
In other words, `a` and `b` do not point to the same list (which is why `a is not b`), but rather to two different lists which both *conta... |
Python: copying a list within a list | 17,497,067 | 18 | 2013-07-05T21:27:20Z | 17,497,089 | 13 | 2013-07-05T21:29:51Z | [
"python",
"list"
] | Hoping someone can help me here.
I'm very new to Python, and I'm trying to work out what I'm doing wrong.
I've already searched and found out that that Python variables can be linked so that changing one changes the other, and I have done numerous tests with the `id()` function to get to grips with this concept. But ... | You need to make a *deepcopy* of your list. `a[:]` only makes a *shallow copy* - [see docs](http://docs.python.org/2/library/copy.html)
You can use `copy.deepcopy` function:
```
>>> import copy
>>> a = [[0,0],[0,0]]
>>> b = copy.deepcopy(a)
>>> b
[[0, 0], [0, 0]]
>>> b[0][0]=1
>>> a
[[0, 0], [0, 0]]
``` |
BeautifulSoup - adding attribute to tag | 17,497,819 | 4 | 2013-07-05T22:55:46Z | 17,497,840 | 7 | 2013-07-05T22:58:18Z | [
"python",
"html",
"tags",
"attributes",
"beautifulsoup"
] | Question for you here, I'm trying to add an attribute to a tag here, wondering if I can use a BeautifulSoup method, or should use plain string manipulation.
An example would probably make this clear, as it's a weird explanation.
How the HTML Code looks now:
```
<option value="BC">BRITISH COLUMBIA</option>
```
How I... | Easy with BeautifulSoup :)
```
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup('<option value="BC">BRITISH COLUMBIA</option>')
>>> soup.find('option')['selected'] = ''
>>> print soup
<html><body><option selected="" value="BC">BRITISH COLUMBIA</option></body></html>
```
The attributes can be looked at as a ... |
Read every second line and print to new file | 17,497,866 | 5 | 2013-07-05T23:00:41Z | 17,497,895 | 9 | 2013-07-05T23:04:25Z | [
"python"
] | I am trying to read every second line in a CSV file and print it in a new file. Unfortunately i am getting a blank line which i am unable to remove.
```
lines = open( 'old.csv', "r" ).readlines()[::2]
file = open('new.csv', "w")
n = 0
for line in lines:
n += 1
if ((n % 2) == 1):
print >> file, line... | In answer to your question, your blank line is coming from:
```
print >> file, line
```
Using `print` like that automatically outputs a new line, either use `sys.stdout.write` or, use a trailing comma to suppress the newline character, eg:
```
print >> file, line,
```
Anyway, the better way to approach this overall... |
Why are there differences in Python time.time() and time.clock() on Mac OS X? | 17,498,199 | 4 | 2013-07-05T23:46:03Z | 17,498,239 | 7 | 2013-07-05T23:51:58Z | [
"python",
"osx",
"time"
] | I'm running Mac OS X 10.8 and get strange behavior for time.clock(), which some online sources say I should prefer over time.time() for timing my code. For example:
```
import time
t0clock = time.clock()
t0time = time.time()
time.sleep(5)
t1clock = time.clock()
t1time = time.time()
print t1clock - t0clock
print t1... | From the docs on [`time.clock`](http://docs.python.org/2/library/time.html#time.clock):
> On Unix, return the current processor time as a floating point number expressed in seconds. The precision, and in fact the very definition of the meaning of âprocessor timeâ, depends on that of the C function of the same name... |
Why are there differences in Python time.time() and time.clock() on Mac OS X? | 17,498,199 | 4 | 2013-07-05T23:46:03Z | 17,498,263 | 7 | 2013-07-05T23:57:20Z | [
"python",
"osx",
"time"
] | I'm running Mac OS X 10.8 and get strange behavior for time.clock(), which some online sources say I should prefer over time.time() for timing my code. For example:
```
import time
t0clock = time.clock()
t0time = time.time()
time.sleep(5)
t1clock = time.clock()
t1time = time.time()
print t1clock - t0clock
print t1... | Instead of using `time.time` or `time.clock` use `timeit.default_timer`. This will return `time.clock` when `sys.platform == "win32"` and `time.time` for all other platforms.
That way, your code will use the best choice of timer, independent of platform.
---
From timeit.py:
```
if sys.platform == "win32":
# On ... |
gevent/libevent.h:9:19: fatal error: event.h: No such file or directory | 17,498,256 | 19 | 2013-07-05T23:54:53Z | 17,498,363 | 11 | 2013-07-06T00:15:07Z | [
"python",
"virtualenv"
] | I was trying to work on Pyladies website on my local folder. I cloned the repo, (<https://github.com/pyladies/pyladies>) ! and created the virtual environment. However when I do the pip install -r requirements, I am getting this error
```
Installing collected packages: gevent, greenlet
Running setup.py install for gev... | I think you just forget to install the "libevent" in the environment. If you are on a OSX machine, please try to install brew here <http://mxcl.github.io/homebrew/> and use brew install libevent to install the dependency. If you are on an ubuntu machine, you can try apt-get to install the corresponding library. |
gevent/libevent.h:9:19: fatal error: event.h: No such file or directory | 17,498,256 | 19 | 2013-07-05T23:54:53Z | 17,837,130 | 45 | 2013-07-24T14:35:19Z | [
"python",
"virtualenv"
] | I was trying to work on Pyladies website on my local folder. I cloned the repo, (<https://github.com/pyladies/pyladies>) ! and created the virtual environment. However when I do the pip install -r requirements, I am getting this error
```
Installing collected packages: gevent, greenlet
Running setup.py install for gev... | I had the same problem and just as the other answer suggested I had to install "libevent". It's apparently not called "libevent-devel" anymore (apt-get couldn't find it) but doing:
```
$ apt-cache search libevent
```
listed a bunch of available packages.
```
$ apt-get install libevent-dev
```
worked for me. |
executing a while loop between defined time | 17,502,226 | 7 | 2013-07-06T10:53:03Z | 17,502,244 | 7 | 2013-07-06T10:55:09Z | [
"python"
] | I'm trying to execute a while loop only under a defined time like this, but the while loop continues its execution even when we are above the defined limit :
```
import datetime
import time
now = datetime.datetime.now()
minute = now.minute
while minute < 46 :
print "test"
time.sleep(5)
minute = now.minu... | You're not updating the value of `minute` inside while loop properly. You should recalculate the value of `now` in loop and then assign the new `now.minute` to `minute`.
```
while minute < 46 :
print "test"
time.sleep(5)
now = datetime.datetime.now()
minute = now.minute
``` |
Missing dll Error Whle installing Python 2.7 | 17,502,747 | 5 | 2013-07-06T12:01:39Z | 20,175,017 | 16 | 2013-11-24T13:28:07Z | [
"python",
"python-2.7",
"enthought"
] | I am trying to install python(epd\_free-7.3-2-win-x86) on my PC (windows 7 - 32bit) but not able to do so. it shows error which says a DLL is missing. searched every where but could not found. i have attached an image of error message dialog.

I also ... | Was facing the same problem in windows 8 - 64 bit ..
try doing this..
Go to **C:/Users//AppData/Local** .
right click on the folder **"Temp"**.
Go to **Properties**.
Go to **Security** Tab.
Click on **"Everyone"** and "**Edit"** the permission to **"full control"-> allow**.
Click apply.
try running the installer agai... |
uwsgi throws IO error caused by uwsgi_response_write_body_do broken pipe | 17,504,435 | 12 | 2013-07-06T15:39:56Z | 20,526,299 | 17 | 2013-12-11T17:46:06Z | [
"python",
"django",
"uwsgi"
] | My application deploy by uwsgi+django, I use gevent to do performance testing, it run 1200 request concurrently, uwsgi will throw IO error, the log information is:
```
uwsgi_response_write_body_do(): Broken pipe [core/writer.c line 260]
IOError: write error
```
Django 1.4.0
uwsgi: 1.9.13
python: 2.6
TCP Listen ... | This can happen when Nginx started a request to uwsgi but uwgsi took too long to respond, then Nginx closes the connection to uwsgi. When uwsgi finally finishes, it tries to give it's response back to Nginx, but nginx closed the connection earlier, so then uwsgi throws an I/O error.
So this could mean that your uwsgi ... |
Django error: needs to have a value for field "..." before this many-to-many relationship can be used | 17,505,935 | 26 | 2013-07-06T18:37:21Z | 17,514,360 | 30 | 2013-07-07T17:16:16Z | [
"python",
"django"
] | When saving a form I am getting this error:
"" needs to have a value for field "surveythread" before this many-to-many relationship can be used.
Models.py:
```
class SurveyResult(models.Model):
stay = models.OneToOneField(Stay, related_name='survey')
created = models.DateTimeField(default=datetime.now)
vo... | Ok, the code is slightly messy, I'm sure you'll be better off [tackling your problem with `ModelForms`](https://docs.djangoproject.com/en/dev/topics/forms/modelforms/). Seems to me the problem actually is the line:
```
s.survey = self.survey
```
because `s` object hasn't been written to the database yet, so accessing... |
How to convert a boolean array to an int array | 17,506,163 | 28 | 2013-07-06T19:08:19Z | 17,506,182 | 42 | 2013-07-06T19:10:26Z | [
"python",
"integer",
"boolean",
"type-conversion",
"scilab"
] | I use Scilab, and want to convert an array of booleans into an array of integers:
```
>>> x = np.array([4, 3, 2, 1])
>>> y = 2 >= x
>>> y
array([False, False, True, True], dtype=bool)
```
In Scilab I can use:
```
>>> bool2s(y)
0. 0. 1. 1.
```
or even just multiply it by 1:
```
>>> 1*y
0. 0. 1. ... | Numpy arrays have an `astype` method. Just do `y.astype(int)`.
Note that it might not even be necessary to do this, depending on what you're using the array for. Bool will be autopromoted to int in many cases, so you can add it to int arrays without having to explicitly convert it:
```
>>> x
array([ True, False, Tru... |
How to convert a boolean array to an int array | 17,506,163 | 28 | 2013-07-06T19:08:19Z | 17,506,220 | 9 | 2013-07-06T19:15:04Z | [
"python",
"integer",
"boolean",
"type-conversion",
"scilab"
] | I use Scilab, and want to convert an array of booleans into an array of integers:
```
>>> x = np.array([4, 3, 2, 1])
>>> y = 2 >= x
>>> y
array([False, False, True, True], dtype=bool)
```
In Scilab I can use:
```
>>> bool2s(y)
0. 0. 1. 1.
```
or even just multiply it by 1:
```
>>> 1*y
0. 0. 1. ... | The `1*y` method works in Numpy too:
```
>>> import numpy as np
>>> x = np.array([4, 3, 2, 1])
>>> y = 2 >= x
>>> y
array([False, False, True, True], dtype=bool)
>>> 1*y # Method 1
array([0, 0, 1, 1])
>>> y.astype(int) # Method 2
array([0, 0, 1, 1])
```
If you are asking for a way to... |
local variable 'count' referenced before assignment | 17,506,947 | 6 | 2013-07-06T20:43:05Z | 17,506,974 | 13 | 2013-07-06T20:45:49Z | [
"python",
"var"
] | ```
Truel=""
count = 0
finle_touch=False #true after it find the first 3 upperletter
# check if there is 1 lower letter after three upper letter
def one_lower(i):
count=0
if i == i.lower:
finle_touch=True
Truel=i
# check for 3 upper letter
def three_upper(s):
for i in s:
if count =... | Due to this line `count +=1` python thinks that `count` is a local variable and will not search the global scope when you used `if count == 3:`. That's why you got that error.
Use `global` statement to handle that:
```
def three_upper(s): #check for 3 upper letter
global count
for i in s:
```
From [docs](htt... |
Django-storages not detecting changed static files | 17,507,843 | 6 | 2013-07-06T22:59:39Z | 17,564,521 | 8 | 2013-07-10T07:13:19Z | [
"python",
"django",
"amazon-web-services",
"amazon-s3"
] | I'm using django-storages and amazon s3 for my static files. Following the documentation, I put these settings in my settings.py
```
STATIC_URL = 'https://mybucket.s3.amazonaws.com/'
ADMIN_MEDIA_PREFIX = 'https://mybucket.s3.amazonaws.com/admin/'
INSTALLED_APPS += (
'storages',
)
DEFAULT_FILE_STORAGE = 'storage... | collectstatic skips files if "target" file is "younger" than source file. Seems like amazon S3 storage returns wrong date for you file.
you could investigate [code][1] and debug server responses. Maybe there is a problem with timezone.
Or you could just pass --clear argument to collectstatic so that all files are del... |
Trying to count words in a string | 17,507,876 | 9 | 2013-07-06T23:04:57Z | 17,507,898 | 11 | 2013-07-06T23:09:05Z | [
"python",
"string",
"list",
"function",
"loops"
] | I'm trying to analyze the contents of a string. If it has a punctuation mixed in the word I want to replace them with spaces.
For example, If Johnny.Appleseed!is:a\*good&farmer is entered as an input then it should say there are 6 words, but my code only sees it as 0 words. I'm not sure how to remove an incorrect char... | # Simple loop based solution:
```
strs = "Johnny.Appleseed!is:a*good&farmer"
lis = []
for c in strs:
if c.isalnum() or c.isspace():
lis.append(c)
else:
lis.append(' ')
new_strs = "".join(lis)
print new_strs #print 'Johnny Appleseed is a good farmer'
new_strs.split() #prints [... |
Trying to count words in a string | 17,507,876 | 9 | 2013-07-06T23:04:57Z | 17,507,954 | 10 | 2013-07-06T23:21:34Z | [
"python",
"string",
"list",
"function",
"loops"
] | I'm trying to analyze the contents of a string. If it has a punctuation mixed in the word I want to replace them with spaces.
For example, If Johnny.Appleseed!is:a\*good&farmer is entered as an input then it should say there are 6 words, but my code only sees it as 0 words. I'm not sure how to remove an incorrect char... | Here's a one-line solution that doesn't require importing any libraries.
It replaces non-alphanumeric characters (like punctuation) with spaces, and then `split`s the string.
Inspired from "[Python strings split with multiple separators](http://stackoverflow.com/questions/1059559/python-strings-split-with-multiple-s... |
How to POST the data from a modal form of bootstrap? | 17,508,444 | 13 | 2013-07-07T01:13:44Z | 17,508,710 | 12 | 2013-07-07T02:22:06Z | [
"javascript",
"jquery",
"python",
"django",
"twitter-bootstrap"
] | I have a page using a `modal` to get the users email and I want to add it to a list of subscribers(which is a django model). Here is the modal code for that:
```
<div id="notifications" class="modal hide fade" role="dialog" ara-labelledby="Notification" aria-hidden="true">
<div class="modal-header">
<butto... | You need to handle it via `ajax` submit.
Something like this:
```
$(function(){
$('#subscribe-email-form').on('submit', function(e){
e.preventDefault();
$.ajax({
url: url, //this is the submit URL
type: 'GET', //or POST
data: $('#subscribe-email-form').serialize... |
How can I get Python working in an existing NetBeans? | 17,508,695 | 5 | 2013-07-07T02:16:10Z | 18,413,089 | 12 | 2013-08-23T22:58:41Z | [
"python",
"netbeans"
] | I'm running a standalone ZIP of NetBeans 7.3.1 and I am wondering if it is to get Python support going with this. I know there is a standalone download for Python support, but I was hoping I could get it going in my install. Is this possible? | Check this out: <https://blogs.oracle.com/geertjan/entry/python_in_netbeans_ide_7>
It provides decent plugins that allow for some python and jython dev functionality.
Edit:
In case you don't know how to add the plugin source in Netbeans you need to navigate to:
Tools > Plugins > Settings > click the "Add" button an... |
Submitting to a web form using python | 17,509,607 | 8 | 2013-07-07T05:41:23Z | 17,509,879 | 9 | 2013-07-07T06:40:59Z | [
"python",
"post",
"request",
"urllib2",
"urllib"
] | I have seen questions like this asked many many times but none are helpful
Im trying to submit data to a form on the web ive tried requests, and urllib and none have worked
for example here is code that should search for the [python] tag on SO:
```
import urllib
import urllib2
url = 'http://stackoverflow.com/'
# P... | If you want to pass `q` as a parameter in the URL using [`requests`](http://docs.python-requests.org/), use the `params` argument, not `data` (see [Passing Parameters In URLs](http://docs.python-requests.org/en/latest/user/quickstart.html#passing-parameters-in-urls)):
```
r = requests.get('http://stackoverflow.com', p... |
Python super() arguments: why not super(obj)? | 17,509,846 | 17 | 2013-07-07T06:36:15Z | 17,509,938 | 24 | 2013-07-07T06:53:17Z | [
"python",
"inheritance",
"super"
] | I am trying to understand when and how to use super() in Python correctly (either 2.7.x or 3.x)
on `>>> help(super)` the interpreter tells me how to call it:
```
class super(object)
| super(type) -> unbound super object
| super(type, obj) -> bound super object; requires isinstance(obj, type)
| super(type, type2... | The two-argument form is only needed in Python 2. The reason is that `self.__class__` always refers to the "leaf" class in the inheritance tree -- that is, the most specific class of the object -- but when you call `super` you need to tell it which implementation is currently being invoked, so it can invoke the next on... |
Django unique together constraint failure? | 17,510,261 | 9 | 2013-07-07T07:55:24Z | 17,510,291 | 10 | 2013-07-07T07:59:38Z | [
"python",
"django",
"postgresql"
] | Using Django 1.5.1. Python 2.7.3.
I wanted to do a unique together constraint with a foreign key field and a slug field. So in my model meta, I did
```
foreign_key = models.ForeignKey("self", null=True, default=None)
slug = models.SlugField(max_length=40, unique=False)
class Meta:
unique_together = ("foreign_key... | In Postgresql `NULL` isn't equal to any other `NULL`. Therefore the rows you create are not the same (from Postgres' perspective).
**Update**
You have a few ways to deal with it:
* Forbid the `Null` value for foreign key and use some default value
* Override the `save` method of your model to check that no such row ... |
Django South Error: "there is no enabled application matching 'myapp'" | 17,510,314 | 15 | 2013-07-07T08:04:11Z | 24,953,051 | 7 | 2014-07-25T09:59:38Z | [
"python",
"django",
"django-south"
] | So, I finally gave in and grabbed South. The problem is, every time I try to follow the tutorial and run
```
"python manage.py schemamigration myapp --initial"
```
I get an error
```
"There is no enabled application matching 'myapp'"
```
--Things I have tried--
I have tripple checked my settings file, running Impo... | This error can be misleading: it is thrown not when South tries to import the app, but when it tries to get the app's `models` module.
* perhaps it cannot import the application (because you didn't add its name to `INSTALLED_APPS`)
* perhaps it cannot import the `models` module, because the file `models.py` does not e... |
How can I add items to an empty set in python | 17,511,270 | 29 | 2013-07-07T10:22:11Z | 17,511,281 | 54 | 2013-07-07T10:23:05Z | [
"python",
"set"
] | I have the following procedure:
```
def myProc(invIndex, keyWord):
D={}
for i in range(len(keyWord)):
if keyWord[i] in invIndex.keys():
D.update(invIndex[query[i]])
return D
```
But I am getting the following error:
```
Traceback (most recent call last):
File "<stdin>", line... | `D = {}` is a dictionary not set.
```
>>> d = {}
>>> type(d)
<type 'dict'>
```
Use `D = set()`:
```
>>> d = set()
>>> type(d)
<type 'set'>
>>> d.update({1})
>>> d.add(2)
>>> d.update([3,3,3])
>>> d
set([1, 2, 3])
``` |
How can I add items to an empty set in python | 17,511,270 | 29 | 2013-07-07T10:22:11Z | 17,511,295 | 10 | 2013-07-07T10:24:19Z | [
"python",
"set"
] | I have the following procedure:
```
def myProc(invIndex, keyWord):
D={}
for i in range(len(keyWord)):
if keyWord[i] in invIndex.keys():
D.update(invIndex[query[i]])
return D
```
But I am getting the following error:
```
Traceback (most recent call last):
File "<stdin>", line... | ```
>>> d = {}
>>> D = set()
>>> type(d)
<type 'dict'>
>>> type(D)
<type 'set'>
```
What you've made is a dictionary and not a Set.
The `update` method in dictionary is used to update the new dictionary from a previous one, like so,
```
>>> abc = {1: 2}
>>> d.update(abc)
>>> d
{1: 2}
```
Whereas in sets, it is used... |
Fast string array - Cython | 17,511,309 | 5 | 2013-07-07T10:26:23Z | 17,511,714 | 7 | 2013-07-07T11:23:55Z | [
"python",
"arrays",
"string",
"cython"
] | Having following hypothetical code:
```
cdef extern from "string.h":
int strcmp(char* str1, char* str2)
def foo(list_str1, list_str2):
cdef unsigned int i, j
c_arr1 = ??
c_arr2 = ??
for i in xrange(len(list_str1)):
for j in xrange(len(list_str2)):
if not strcmp(c_arr1[i], c_arr... | Try following code. `to_cstring_array` function in the following code is what you want.
```
from libc.stdlib cimport malloc, free
from libc.string cimport strcmp
from cpython.string cimport PyString_AsString
cdef char ** to_cstring_array(list_str):
cdef char **ret = <char **>malloc(len(list_str) * sizeof(char *))... |
Python scikit-learn: exporting trained classifier | 17,511,968 | 26 | 2013-07-07T12:00:34Z | 17,512,093 | 44 | 2013-07-07T12:19:25Z | [
"python",
"scikit-learn"
] | I am using a DBN (deep belief network) from [nolearn](https://pypi.python.org/pypi/nolearn) based on scikit-learn.
I have already build a Network which can classify my data very well, now I am interested in exporting the model for deployment, but I don't know how (I am training the DBN every time I want predict someth... | You can use:
```
>>> from sklearn.externals import joblib
>>> joblib.dump(clf, 'my_model.pkl', compress=9)
```
And then later, on the prediction server:
```
>>> from sklearn.externals import joblib
>>> model_clone = joblib.load('my_model.pkl')
```
This is basically a Python pickle with an optimized handling for lar... |
CsvReader Next function | 17,513,438 | 2 | 2013-07-07T15:22:58Z | 17,513,447 | 10 | 2013-07-07T15:23:57Z | [
"python",
"csv"
] | i am given a csv file but i want to skip the first row of data and move on to the next. Here is my code:
```
def read_csv(inputfile):
return list(csv.reader(inputfile)) #<-----
def generate_xml(reader,outfile):
root = Element('Solution')
root.set('version','1.0')
tree = ElementTree(root)
h... | You have a *list*, not an iterator. Just slice it instead:
```
for row in reader[1:]:
```
or skip that first row when you still have an actual `csv.reader()` object:
```
def read_csv(inputfile):
reader = csv.reader(inputfile)
next(reader)
return list(reader)
```
You'd be better off returning the `reader... |
Python dictionary comprehension example | 17,513,890 | 4 | 2013-07-07T16:19:58Z | 17,513,951 | 10 | 2013-07-07T16:28:14Z | [
"python",
"dictionary",
"dictionary-comprehension"
] | I am trying to learn Python dictionary comprehension, and I think it is possible to do in one line what the following functions do. I wasn't able to make the `n+1` as in the first or avoid using `range()` as in the second.
Is it possible to use a counter that automatically increments during the comprehension, as in `t... | It's quite simple using the [`enumerate`](http://docs.python.org/3.3/library/functions.html#enumerate) function:
```
>>> L = ['a', 'b', 'c', 'd']
>>> {letter: i for i,letter in enumerate(L, start=1)}
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
```
Note that, if you wanted the inverse mapping, i.e. mapping `1` to `a`, `2` to `b`... |
list of dictionary Sorting in python | 17,514,769 | 2 | 2013-07-07T18:03:30Z | 17,514,797 | 8 | 2013-07-07T18:06:00Z | [
"python",
"sorting",
"python-2.7"
] | May be this is a duplicate. I didnt find same type of question
I have a list of dictionary, for example
```
mylist=[
{'month':'MAR2011','amount':90},
{'month':'MAR2013','amount':190},
{'month':'JUN2011','amount':290},
{'month':'AUG2011','amount':930},
{'month':'DEC2011','amount':30},
{'month':'... | Create a dictionary mapping month to an ordinal:
```
from calendar import month_abbr
month_to_index = {month.upper(): i for i, month in enumerate(month_abbr[1:])}
```
and use that to sort:
```
sorted(mylist, key=lambda d: month_to_index[d['month'][:3]])
```
Demo:
```
>>> from calendar import month_abbr
>>> month_... |
Add two lists of different lengths in python, start from the right | 17,521,145 | 5 | 2013-07-08T07:28:44Z | 17,521,272 | 13 | 2013-07-08T07:37:25Z | [
"python",
"coding-style"
] | I want to add two list of different length start from the right
Here's an example
```
[3, 0, 2, 1]
[8, 7]
```
Expected result:
```
[3, 0, 10, 8]
```
These list represent coefficient of polynomials
Here is my implementation
```
class Polynomial:
def __init__(self, coefficients):
self.coeffs = coefficie... | ```
>>> P = [3, 0, 2, 1]
>>> Q = [8, 7]
>>> from itertools import izip_longest
>>> [x+y for x,y in izip_longest(reversed(P), reversed(Q), fillvalue=0)][::-1]
[3, 0, 10, 8]
```
Obviously, if you choose a convention where the coefficients are ordered the opposite way, you can just use
```
P = [1, 2, 0, 3]
Q = [7, 8]
[x... |
Python list of identical sublists | 17,521,665 | 3 | 2013-07-08T08:03:25Z | 17,521,679 | 9 | 2013-07-08T08:04:10Z | [
"python",
"list"
] | I am trying to programmatically create a list containing `n` identical sublists:
```
>>> pos = [10,20]
>>> 3 * pos
[10, 20, 10, 20, 10, 20]
```
But what I want is `[[10,20], [10,20], [10,20]]`
Any clues? | ```
[[10, 20] for x in range(3)]
```
beware of
```
[[10, 20]] * 3
```
because it copies the same list 3 times |
Python: logging.streamhandler is not sending logs to stdout | 17,523,173 | 5 | 2013-07-08T09:26:26Z | 17,523,356 | 10 | 2013-07-08T09:36:38Z | [
"python",
"logging"
] | I want to use StreamHandler logging handler of python.
What i have tried is,
```
import logging
import sys
mylogger = logging.getLogger("mylogger")
h1 = logging.StreamHandler(stream=sys.stdout)
h1.setLevel(logging.DEBUG)
mylogger.addHandler(h1)
# now trying to log with the created logger
mylogger.debug("abcd") # <no... | You have to set the level of the logger, not only the level of the handler:
```
mylogger.setLevel(logging.DEBUG)
```
Here is a nice graphic of the logging workflow, where you can see that either the logger and the handler check for the log level:
<http://docs.python.org/2/howto/logging.html#logging-flow>
The defaul... |
How to create Password Field in Model django | 17,523,263 | 8 | 2013-07-08T09:31:30Z | 17,524,315 | 12 | 2013-07-08T10:25:58Z | [
"python",
"django",
"django-models",
"django-forms",
"django-templates"
] | i want to create password as password field in views. Please can someone help me? Thanks in advance
```
**models.py**
class User(models.Model):
username = models.CharField(max_length=100)
password = models.CharField(max_length=50)
**views.py**
class UserForm(ModelForm):
class Meta:... | Use widget as `PasswordInput`
```
from django import forms
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
``` |
How to create Password Field in Model django | 17,523,263 | 8 | 2013-07-08T09:31:30Z | 17,531,053 | 9 | 2013-07-08T15:59:04Z | [
"python",
"django",
"django-models",
"django-forms",
"django-templates"
] | i want to create password as password field in views. Please can someone help me? Thanks in advance
```
**models.py**
class User(models.Model):
username = models.CharField(max_length=100)
password = models.CharField(max_length=50)
**views.py**
class UserForm(ModelForm):
class Meta:... | You should create a `ModelForm` ([docs](https://docs.djangoproject.com/en/dev/topics/forms/modelforms/)), that has a field that uses the `PasswordInput` widget from the forms library. Here's what it would look like.
## models.py
```
from django import models
class User(models.Model):
username = models.CharField(m... |
Unicode or what in matplotlib? | 17,525,882 | 5 | 2013-07-08T11:50:48Z | 17,525,923 | 10 | 2013-07-08T11:52:41Z | [
"python",
"unicode",
"matplotlib",
"spyder"
] | Can't get the titles right in matplotlib:
`'technologieën in °C'` gives: `technologieÃn in ÃC`
possible solutions already tried:
`u'technologieën in °C`' doens't work and neither does: `# -*- coding: utf-8 -*-` at the beginning of the code-file.
Any solutions? | You need to pass in *unicode* text:
```
u'technologieën in °C'
```
Do make sure you use the `# -*- coding: utf-8 -*-` comment at the top, and make sure your text editor is actually using that codec. If your editor saves the file as Latin-1 encoded text, use that codec in the header, etc. The comment communicates to... |
How to set a max length for a python list/set? | 17,526,659 | 8 | 2013-07-08T12:30:45Z | 17,526,715 | 12 | 2013-07-08T12:33:22Z | [
"python",
"list",
"max",
"maxlength"
] | In c/c++, we could have:
```
maxnum = 10;
double xlist[maxnum];
```
How to set a maximum length for a python list/set? | You don't and do not need to.
Python lists grow and shrink dynamically as needed to fit their contents. Sets are implemented as a hash table, and like Python dictionaries grow and shrink dynamically as needed to fit their contents.
Perhaps you were looking for [`collections.deque`](http://docs.python.org/2/library/co... |
How to set a max length for a python list/set? | 17,526,659 | 8 | 2013-07-08T12:30:45Z | 17,535,702 | 7 | 2013-07-08T20:46:33Z | [
"python",
"list",
"max",
"maxlength"
] | In c/c++, we could have:
```
maxnum = 10;
double xlist[maxnum];
```
How to set a maximum length for a python list/set? | Here is extended version of python's `list`. It behaves like `list`, but will raise `BoundExceedError`, if length is exceeded (tried in python 2.7):
```
class BoundExceedError(Exception):
pass
class BoundList(list):
def __init__(self, *args, **kwargs):
self.length = kwargs.pop('length', None)
... |
How to convert a unicode list of tuples into utf-8 with python | 17,527,072 | 2 | 2013-07-08T12:48:58Z | 17,527,101 | 8 | 2013-07-08T12:50:14Z | [
"python",
"unicode",
"utf-8"
] | My function returns a tuple
which is then assigned to a variable x and appended to a list.
```
x = (u'string1', u'string2', u'string3', u'string4')
resultsList.append(x)
```
The function is called multiple times and final list consists of 20 tuples.
The strings within the tuple are in unicode and I would like to con... | Use a nested list comprehension:
```
encoded = [[s.encode('utf8') for s in t] for t in resultsList]
```
This produces a list of lists containing byte strings of UTF-8 encoded data.
If you were to print these lists, you'll see Python represent the contents of the Python byte strings as Python literal strings; with qu... |
No handlers could be found for logger "apscheduler.scheduler" | 17,528,363 | 9 | 2013-07-08T13:49:03Z | 17,551,794 | 25 | 2013-07-09T15:09:21Z | [
"python",
"scheduler"
] | ```
from apscheduler.scheduler import Scheduler
import os
class ListHref():
def __init__(self):
print 'In ListHref Class!'
self.name_hrefs = {}
self.name_img = {}
self.path = os.path.dirname(__file__)
print 'Out ListHref Class'
def other_function():...
def job(): #function na... | apscheduler is using the python [logging module](http://docs.python.org/2/library/logging.html) which needs to be initialized. Logging is a bit complicated (see the link) but the minimum is to:
```
import logging
logging.basicConfig()
```
basicConfig supports some common logging features but its worth figuring out so... |
Python convert set to string and vice versa | 17,528,374 | 6 | 2013-07-08T13:49:29Z | 17,528,406 | 7 | 2013-07-08T13:51:22Z | [
"python",
"string",
"python-2.7",
"set"
] | Set to string. Obvious:
```
>>> s = set([1,2,3])
>>> s
set([1, 2, 3])
>>> str(s)
'set([1, 2, 3])'
```
String to set? Maybe like this?
```
>>> set(map(int,str(s).split('set([')[-1].split('])')[0].split(',')))
set([1, 2, 3])
```
Extremely ugly. Is there better way to serialize/deserialize sets? | Use `repr` and `eval`:
```
>>> s = set([1,2,3])
>>> strs = repr(s)
>>> strs
'set([1, 2, 3])'
>>> eval(strs)
set([1, 2, 3])
```
Note that `eval` is not safe if the source of string is unknown, prefer `ast.literal_eval` for safer conversion:
```
>>> from ast import literal_eval
>>> s = set([10, 20, 30])
>>> lis = str(... |
Need help vectorizing code or optimizing | 17,529,342 | 4 | 2013-07-08T14:33:53Z | 17,626,907 | 8 | 2013-07-13T04:12:51Z | [
"python",
"optimization",
"numba"
] | I am trying to do a double integral by first interpolating the data to make a surface. I am using numba to try and speed this process up, but it's just taking too long.
[Here is my code,](https://github.com/wesleybowman/honours/blob/master/newStart/ee.py) with the images needed to run the code located at [here](https:... | Noting that your code has a quadruple-nested set of for loops, I focused on optimizing the inner pair. Here's the old code:
```
for i in xrange(K.shape[0]):
for j in xrange(K.shape[1]):
print(i,j)
'''create an r vector '''
r=(i*distX,j*distY,z)
for x in xrange(img.shape[0]):
... |
Why is this Python code running twice? | 17,530,046 | 6 | 2013-07-08T15:07:26Z | 17,530,276 | 9 | 2013-07-08T15:18:42Z | [
"python",
"python-2.7",
"python-requests"
] | I have a Python script with just these 2 lines:
```
import requests
print len(dir(requests))
```
It prints:
```
12
48
```
When I print the actual list `dir(requests)`, I get this:
```
['__author__', '__build__', '__builtins__', '__copyright__', '__doc__', '__file__', '__license__', '__name__', '__package__', '__pa... | You gave your script a name of a standard module or something else that is imported by the `requests` package. You created a circular import.
```
yourscript -> import requests -> [0 or more other modules] -> import yourscript -> import requests again
```
Because `requests` didn't *complete* importing the first time y... |
Can't import turtle module in Python 2.x and Python 3.x | 17,530,140 | 5 | 2013-07-08T15:12:13Z | 17,530,188 | 14 | 2013-07-08T15:14:48Z | [
"python",
"user-interface",
"turtle-graphics"
] | I want to play with [turtle](http://docs.python.org/2/library/turtle.html) module in Python. But when i do import turtle module, i've the following error:
```
$ python
Python 2.7.3 (default, Sep 26 2012, 21:51:14)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import ... | You've called a script `turtle.py`, which is shadowing the `turtle` module in the standard library. Rename it. |
n-grams in python, four, five, six grams? | 17,531,684 | 34 | 2013-07-08T16:35:31Z | 17,532,044 | 17 | 2013-07-08T16:54:06Z | [
"python",
"string",
"nltk",
"n-gram"
] | I'm looking for a way to split a text into n-grams.
Normally I would do something like:
```
import nltk
from nltk import bigrams
string = "I really like python, it's pretty awesome."
string_bigrams = bigrams(string)
print string_bigrams
```
I am aware that nltk only offers bigrams and trigrams, but is there a way to ... | I'm surprised that this hasn't shown up yet:
```
In [34]: sentence = "I really like python, it's pretty awesome.".split()
In [35]: N = 4
In [36]: grams = [sentence[i:i+N] for i in xrange(len(sentence)-N)]
In [37]: for gram in grams: print gram
['I', 'really', 'like', 'python,']
['really', 'like', 'python,', "it's"]... |
n-grams in python, four, five, six grams? | 17,531,684 | 34 | 2013-07-08T16:35:31Z | 17,547,860 | 63 | 2013-07-09T12:10:39Z | [
"python",
"string",
"nltk",
"n-gram"
] | I'm looking for a way to split a text into n-grams.
Normally I would do something like:
```
import nltk
from nltk import bigrams
string = "I really like python, it's pretty awesome."
string_bigrams = bigrams(string)
print string_bigrams
```
I am aware that nltk only offers bigrams and trigrams, but is there a way to ... | Great native python based answers given by other users. But here's the `NLTK` approach (just in case, the OP gets penalized for reinventing what's already existing in the `NLTK` library).
There is an ngram module (<http://www.nltk.org/_modules/nltk/model/ngram.html>) that people seldom use in NLTK. It's not because it... |
Division in Python 3 gives different result than in Python 2 | 17,531,874 | 2 | 2013-07-08T16:45:00Z | 17,531,903 | 7 | 2013-07-08T16:46:18Z | [
"python",
"python-3.x",
"python-2.x"
] | In the following code, I want to calculate the percent of G and C characters in a sequence. In Python 3 I correctly get `0.5`, but on Python 2 I get `0`. Why are the results different?
```
def gc_content(base_seq):
"""Return the percentage of G and C characters in base_seq"""
seq = base_seq.upper()
return ... | `/` is a different operator in Python 3; in Python 2 `/` alters behaviour when applied to 2 integer operands and returns the result of a floor-division instead:
```
>>> 3/2 # two integer operands
1
>>> 3/2.0 # one operand is not an integer, float division is used
1.5
```
Add:
```
from __future__ import division
``... |
PyImport_Import fails (returns NULL) | 17,532,371 | 3 | 2013-07-08T17:15:06Z | 17,543,639 | 7 | 2013-07-09T08:37:54Z | [
"python",
"c"
] | I am a newbie in python, so may be this is a silly question. I want to write simple c program with embedded python script. I have two files:
call-function.c:
```
#include <Python.h>
int main(int argc, char *argv[])
{
PyObject *pName, *pModule, *pDict, *pFunc, *pValue;
if (argc < 3)
... | I have resolved this issue by setting PYTHONPATH to `pwd`. Also module name (without .py) should be set for argv[1].
Thank you! |
Python - generate array of returns from function that changes its return value | 17,532,901 | 2 | 2013-07-08T17:49:13Z | 17,532,921 | 7 | 2013-07-08T17:50:11Z | [
"python"
] | What is a good pythonic way to generate an array of results from multiple function calls with a function that changes what it returns after each call? For example, say I have a function `foo` that returns `'callno-X'` each time it is called, and X is increased by 1 every time. I want to then be able to say something li... | Just use a list comprehension:
```
returnValues = [foo() for x in xrange(5)]
``` |
How to set Selenium Python WebDriver default timeout? | 17,533,024 | 19 | 2013-07-08T17:57:33Z | 17,536,547 | 47 | 2013-07-08T21:46:27Z | [
"python",
"firefox",
"selenium",
"timeout",
"selenium-webdriver"
] | Trying to find a good way to set a maximum time limit for command execution latency in Selenium Python WebDriver. Ideally, something like:
```
my_driver = get_my_driver()
my_driver.set_timeout(30) # seconds
my_driver.get('http://www.example.com') # stops / throws exception when time is over 30 seconds
```
would w... | The method to create a timeout for a page to load, in Python, is:
```
driver.set_page_load_timeout(30)
```
This will throw a `TimeoutException` whenever the page load takes more than 30 seconds. |
Installing a package to Canopy | 17,533,094 | 3 | 2013-07-08T18:02:01Z | 17,533,730 | 7 | 2013-07-08T18:41:18Z | [
"python",
"install",
"package",
"enthought",
"canopy"
] | I'm really new to coding, programming, Python, and just computers in general, so I need some help with Canopy. I've been having pretty consistent troubles installing any packages to Canopy; some stuff is in the internal package manager,but whenever it isn't, it's really confusing. I guess I'll list a specific installat... | The way I installed `astropy` is as follows.
1. Open Windows Terminal
2. Change Directory to `C:\Users\<USER NAME>\AppData\Local\Enthought\Canopy32\User\Scripts`
3. Type `easy_install.exe astropy`
4. Wait until the download completes, and restart Enthought.
 |
Why isn't the Dfunc(gradient) never called while using integrate.odeint in SciPy? | 17,533,751 | 6 | 2013-07-08T18:42:47Z | 17,538,834 | 10 | 2013-07-09T02:07:39Z | [
"python",
"scipy",
"odeint"
] | Can anyone provide an example of providing a jacobian to a `integrate.odeint` function in SciPy?.
I try to run this code from SciPy tutorial [odeint example](http://docs.scipy.org/doc/scipy-dev/reference/tutorial/integrate.html#ordinary-differential-equations-odeint) but seems that Dfunc (gradient) is never called.
``... | Under the hood, `scipy.integrate.odeint` uses the LSODA solver from the ODEPACK FORTRAN library. In order to deal with situations where the function you are trying to integrate is [stiff](http://en.wikipedia.org/wiki/Stiffness_%28mathematics%29), LSODA switches adaptively between two different methods for computing the... |
What is the use of __kwdefaults__ which is a function object attribute? | 17,533,929 | 6 | 2013-07-08T18:53:35Z | 17,534,006 | 7 | 2013-07-08T18:59:44Z | [
"python",
"python-3.x"
] | Function object has attributes `__defaults__` and `__kwdefaults__`. I see that if a function has some default arguments then they are put as a tuple to `__defaults__` but `__kwdefaults__` is `None`. When is used attribute `__kwdefaults__`? | ```
def foo(arg1, arg2, arg3, *args, kwarg1="FOO", kwarg2="BAR", kwarg3="BAZ"):
pass
print(foo.__kwdefaults__)
```
Output (Python 3):
```
{'kwarg1': 'FOO', 'kwarg2': 'BAR', 'kwarg3': 'BAZ'}
```
Since the `*args` would swallow all non-keyword arguments, the arguments after it have to be passed with keywords. See... |
What is the difference between NaN and None? | 17,534,106 | 32 | 2013-07-08T19:06:17Z | 17,534,682 | 30 | 2013-07-08T19:43:37Z | [
"python",
"numpy",
"pandas",
null
] | I am reading two columns of a csv file using pandas `readcsv()` and then assigning the values to a dictionary. The columns contain strings of numbers and letters. Occasionally there are cases where a cell is empty. In my opinion, the value read to that dictionary entry should be `None` but instead `nan` is assigned. Su... | NaN is used as a placeholder for [missing data *consistently* in pandas](http://pandas.pydata.org/pandas-docs/dev/gotchas.html#choice-of-na-representation), consistency is good. I usually read/translate NaN as **"missing"**. *Also see the ['working with missing data'](http://pandas.pydata.org/pandas-docs/dev/missing_da... |
TypeError: Missing 1 required positional argument: 'self' | 17,534,345 | 21 | 2013-07-08T19:21:42Z | 17,534,363 | 36 | 2013-07-08T19:23:06Z | [
"python",
"python-3.x"
] | I am new to python and have hit a wall. I followed several tutorials but cant get past the error:
```
Traceback (most recent call last):
File "C:\Users\Dom\Desktop\test\test.py", line 7, in <module>
p = Pump.getPumps()
TypeError: getPumps() missing 1 required positional argument: 'self'
```
I examined several t... | You need to instantiate a class instance here.
Use
```
p = Pump()
p.getPumps()
```
Small example -
```
>>> class TestClass:
def __init__(self):
print "in init"
def testFunc(self):
print "in Test Func"
>>> testInstance = TestClass()
in init
>>> testInstance.testFunc()
in Tes... |
TypeError: Missing 1 required positional argument: 'self' | 17,534,345 | 21 | 2013-07-08T19:21:42Z | 17,534,365 | 9 | 2013-07-08T19:23:10Z | [
"python",
"python-3.x"
] | I am new to python and have hit a wall. I followed several tutorials but cant get past the error:
```
Traceback (most recent call last):
File "C:\Users\Dom\Desktop\test\test.py", line 7, in <module>
p = Pump.getPumps()
TypeError: getPumps() missing 1 required positional argument: 'self'
```
I examined several t... | You need to initialize it first:
```
p = Pump().getPumps()
``` |
Generate random string from regex character set | 17,534,484 | 3 | 2013-07-08T19:31:43Z | 17,534,712 | 8 | 2013-07-08T19:45:44Z | [
"python",
"regex",
"string"
] | I assume there's some beautiful Pythonic way to do this, but I haven't quite figured it out yet. Basically I'm looking to create a testing module and would like a nice simple way for users to define a character set to pull from. I could potentially concatenate a list of the various charsets associated with string, but ... | Paul McGuire, author of [Pyparsing](http://pyparsing.wikispaces.com), has written an [inverse regex parser](http://pyparsing.wikispaces.com/file/view/invRegex.py), with which you could do this:
```
import invRegex
print(''.join(invRegex.invert('[a-z]')))
# abcdefghijklmnopqrstuvwxyz
```
If you do not want to install ... |
Mongodb replica set auto reconect don't work after down and up for nginx + uwsgi with several processes | 17,534,642 | 6 | 2013-07-08T19:41:54Z | 17,577,341 | 12 | 2013-07-10T17:40:35Z | [
"python",
"mongodb",
"pymongo",
"uwsgi",
"mongoengine"
] | Hi everyone I have next envirement for `python2.7.5`:
```
flask==0.10.1
flask-wtf==0.8.4
jinja2==2.7
werkzeug==0.9.1
flask-mongoengine==0.7.0
mongoengine==0.8.2
pymongo==2.5.2
uwsgi==1.9.13
```
and have next application 'app.py':
```
from flask import Flask
from flask.ext.mongoengine import Document, MongoEngine
fro... | Try using the uwsgi `--lazy-apps` option. MongoReplicaSetClient spawns a replicaset MonitorThread, and this thread does not survive the uwsgi worker process fork. `--lazy-apps` will initialize the pymongo MonitorThread in each worker process. |
Tkinter/Matplotlib backend conflict causes infinite mainloop | 17,535,766 | 7 | 2013-07-08T20:50:11Z | 17,535,868 | 7 | 2013-07-08T20:57:47Z | [
"python",
"matplotlib",
"tkinter"
] | Consider running the following code (note it is an extremely simplified version to demonstrate the problem):
```
import matplotlib.pyplot as plot
from tkinter import * #Tkinter if your on python 2
def main():
fig = plot.figure(figsize=(16.8, 8.0))
root = Tk()
w = Label(root, text="Close this and it will... | ```
import matplotlib
from tkinter import *
def main():
fig = matplotlib.figure.Figure(figsize=(16.8, 8.0))
root = Tk()
w = Label(root, text="Close this and it will not hang!")
w.pack()
root.mainloop()
print('Code *does* reach this point')
if __name__ == '__main__':
main()
```
When emb... |
How can i reduce memory usage of Scikit-Learn Vectorizers? | 17,536,394 | 3 | 2013-07-08T21:36:35Z | 17,536,682 | 8 | 2013-07-08T21:57:29Z | [
"python",
"numpy",
"machine-learning",
"scipy",
"scikit-learn"
] | TFIDFVectorizer takes so much memory ,vectorizing 470 MB of 100k documents takes over 6 GB , if we go 21 million documents it will not fit 60 GB of RAM we have.
So we go for HashingVectorizer but still need to know how to distribute the hashing vectorizer.Fit and partial fit does nothing so how to work with Huge Corpu... | I would strongly recommend you to use the [HashingVectorizer](http://scikit-learn.org/stable/modules/feature_extraction.html#vectorizing-a-large-text-corpus-with-the-hashing-trick) when fitting models on large dataset.
The `HashingVectorizer` is data independent, only the parameters from `vectorizer.get_params()` are ... |
Python/Django: how to assert that unit test result contains a certain string? | 17,536,916 | 11 | 2013-07-08T22:16:52Z | 17,540,673 | 9 | 2013-07-09T05:33:51Z | [
"python",
"json",
"django",
"unit-testing",
"assert"
] | In a python unit test (actually Django), what is the correct `assert` statement that will tell me if my test result contains a string of my choosing?
i.e., something like `self.assertContainsTheString(result, {"car" : ["toyota","honda"]})`
I want to make sure that my `result` contains at least the json object (or str... | ```
self.assertContains(result, "abcd")
```
I guess this is what you are looking for. You can modify it to work with json. |
Python/Django: how to assert that unit test result contains a certain string? | 17,536,916 | 11 | 2013-07-08T22:16:52Z | 29,205,547 | 11 | 2015-03-23T08:05:51Z | [
"python",
"json",
"django",
"unit-testing",
"assert"
] | In a python unit test (actually Django), what is the correct `assert` statement that will tell me if my test result contains a string of my choosing?
i.e., something like `self.assertContainsTheString(result, {"car" : ["toyota","honda"]})`
I want to make sure that my `result` contains at least the json object (or str... | You can write assertion about expected part of string in another string with a simple assertTrue + in python keyword :
```
self.assertTrue("expected_part_of_string" in my_longer_string)
``` |
Python/Django: how to assert that unit test result contains a certain string? | 17,536,916 | 11 | 2013-07-08T22:16:52Z | 36,021,102 | 18 | 2016-03-15T20:07:14Z | [
"python",
"json",
"django",
"unit-testing",
"assert"
] | In a python unit test (actually Django), what is the correct `assert` statement that will tell me if my test result contains a string of my choosing?
i.e., something like `self.assertContainsTheString(result, {"car" : ["toyota","honda"]})`
I want to make sure that my `result` contains at least the json object (or str... | To assert if a string is or is not a substring of another, you should use `assertIn` and `assertNotIn`:
```
# Passes
self.assertIn('bcd', 'abcde')
# AssertionError: 'bcd' unexpectedly found in 'abcde'
self.assertNotIn('bcd', 'abcde')
```
These are new since [Python 2.7](https://docs.python.org/2/library/unittest.htm... |
Java: String formatting with placeholders | 17,537,216 | 21 | 2013-07-08T22:45:35Z | 17,537,223 | 10 | 2013-07-08T22:46:09Z | [
"java",
"python",
"string",
"format",
"placeholder"
] | I am new to Java and am from Python. In Python we do string formatting like this:
```
>>> x = 4
>>> y = 5
>>> print("{0} + {1} = {2}".format(x, y, x + y))
4 + 5 = 9
>>> print("{} {}".format(x,y))
4 5
```
How do I replicate the same thing in Java? | Java has a [String.format](http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#format%28java.lang.String,%20java.lang.Object...%29) method that works similarly to this. [Here's an example of how to use it.](http://stackoverflow.com/a/3695253/61624) This is the [documentation reference](http://docs.oracle.com... |
Java: String formatting with placeholders | 17,537,216 | 21 | 2013-07-08T22:45:35Z | 17,537,310 | 43 | 2013-07-08T22:52:32Z | [
"java",
"python",
"string",
"format",
"placeholder"
] | I am new to Java and am from Python. In Python we do string formatting like this:
```
>>> x = 4
>>> y = 5
>>> print("{0} + {1} = {2}".format(x, y, x + y))
4 + 5 = 9
>>> print("{} {}".format(x,y))
4 5
```
How do I replicate the same thing in Java? | The [`MessageFormat`](http://docs.oracle.com/javase/7/docs/api/java/text/MessageFormat.html) class looks like what you're after.
```
System.out.println(MessageFormat.format("{0} + {1} = {2}", x, y, x + y));
``` |
How to install a package using the python-apt API | 17,537,390 | 11 | 2013-07-08T23:02:11Z | 17,538,002 | 22 | 2013-07-09T00:16:36Z | [
"python",
"apt"
] | I'm quite a newbie when it comes to Python, thus I beg foregiveness beforehand :). That said, I'm trying to make a script that, among other things, installs some Linux packages. First I tried to use subopen as explained [here](http://stackoverflow.com/questions/8481943/using-apt-get-install-xxx-inside-python-script). W... | It's recommended to use the `apt` module from the `python-apt` Debian package. This is a higher level wrapper around the underlying C/C++ `libapt-xxx` libraries and has a Pythonic interface.
Here's an example script which will install the `libjs-yui-doc` package:
```
#!/usr/bin/env python
# aptinstall.py
import apt
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.