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 |
|---|---|---|---|---|---|---|---|---|---|
Erase whole array Python | 3,499,233 | 19 | 2010-08-17T04:01:30Z | 3,499,241 | 30 | 2010-08-17T04:03:08Z | [
"python",
"arrays",
"erase"
] | How do I erase a whole array, leaving it with no items?
I want to do this so I can store new values in it (a new set of 100 floats) and find the minimum.
Right now my program is reading the minimum from sets before I think because it is appending itself with the previous set still in there. I use .append by the way. | Note that `list` and [`array`](http://docs.python.org/library/array.html) are different classes. You can do:
```
del mylist[:]
```
This will actually modify your existing list. David's answer creates a new list and assigns it to the same variable. Which you want depends on the situation (e.g. does any other variable ... |
How do I prevent fixtures from conflicting with django post_save signal code? | 3,499,791 | 36 | 2010-08-17T06:19:59Z | 3,500,009 | 53 | 2010-08-17T06:57:18Z | [
"python",
"django",
"signals",
"fixtures",
"django-signals"
] | In my application, I want to create entries in certain tables when a new user signs up. For instance, I want to create a userprofile which will then reference their company and some other records for them. I implemented this with a post\_save signal:
```
def callback_create_profile(sender, **kwargs):
# check if we... | I think I figured out a way to do this. There is a 'raw' parameter in the kwargs passed in along with signals so I can replace my test above with this one:
```
if (kwargs.get('created', True) and not kwargs.get('raw', False)):
```
Raw is used when loaddata is running. This seems to do the trick.
It is mentioned here... |
How do I prevent fixtures from conflicting with django post_save signal code? | 3,499,791 | 36 | 2010-08-17T06:19:59Z | 11,409,794 | 11 | 2012-07-10T08:53:18Z | [
"python",
"django",
"signals",
"fixtures",
"django-signals"
] | In my application, I want to create entries in certain tables when a new user signs up. For instance, I want to create a userprofile which will then reference their company and some other records for them. I implemented this with a post\_save signal:
```
def callback_create_profile(sender, **kwargs):
# check if we... | This is an old question, but the solution I've found most straightforward is to use the 'raw' argument, passed by load data, and decorate the listener functions, for example:
```
from functools import wraps
def disable_for_loaddata(signal_handler):
@wraps(signal_handler)
def wrapper(*args, **kwargs):
... |
How to extract url GET parameter from <a> tag, from the full html text | 3,500,895 | 3 | 2010-08-17T09:05:52Z | 3,501,044 | 7 | 2010-08-17T09:24:45Z | [
"python",
"html",
"regex"
] | So I have an html page. It's full of various tags, most of them have sessionid GET parameter in their href attribute. Example:
```
...
<a href="struct_view_distrib.asp?sessionid=11692390">
...
<a href="SHOW_PARENT.asp?sessionid=11692390">
...
<a href="nakl_view.asp?sessionid=11692390">
...
<a href="move_sum_to_7300001... | This does not use regexes, but anyway, this is what you would do in Python 2.6:
```
from BeautifulSoup import BeautifulSoup
import urlparse
soup = BeautifulSoup(html)
links = soup.findAll('a', href=True)
for link in links:
href = link['href']
url = urlparse.urlparse(href)
params = urlparse.parse_qs(url.query)
... |
How can I use meta-dot (M-.) in python with emacs? | 3,501,040 | 16 | 2010-08-17T09:24:19Z | 3,503,683 | 9 | 2010-08-17T14:45:48Z | [
"python",
"emacs",
"ropemacs",
"pymacs",
"rope"
] | Is there an equivalent of slime for python?
For example, if I position the cursor on foo() and do M-. (jump to definition) I would like to see the source definition of the function foo
This should work regardless of whether foo is in
1) the local project directory
2) in some ~/.virtualenvs/bar/lib/site-packages
3)... | To avoid the -e you can use etags and with a find you recursively add the py file:
```
find . -type f -name '*.py' | xargs etags
``` |
Checking whether a variable is an integer or not | 3,501,382 | 412 | 2010-08-17T10:15:08Z | 3,501,408 | 471 | 2010-08-17T10:18:16Z | [
"python"
] | How do I check whether a variable is an integer? | If you need to do this, do
```
isinstance( <var>, int )
```
unless you are in Python 2.x in which case you want
```
isinstance( <var>, ( int, long ) )
```
Do not use `type`. It is almost never the right answer in Python, since it blocks all the flexibility of polymorphism. For instance, if you subclass `int`, your ... |
Checking whether a variable is an integer or not | 3,501,382 | 412 | 2010-08-17T10:15:08Z | 3,501,414 | 23 | 2010-08-17T10:19:03Z | [
"python"
] | How do I check whether a variable is an integer? | ```
>>> isinstance(3, int)
True
```
See [here](http://docs.python.org/library/functions.html#isinstance) for more.
Note that this does not help if you're looking for `int`-like attributes. In this case you may also want to check for `long`:
```
>>> isinstance(3L, (long, int))
True
```
I've seen checks of this kind ... |
Checking whether a variable is an integer or not | 3,501,382 | 412 | 2010-08-17T10:15:08Z | 3,646,519 | 34 | 2010-09-05T15:08:59Z | [
"python"
] | How do I check whether a variable is an integer? | If you *really* need to check then it's better to use [abstract base classes](http://docs.python.org/library/numbers.html#module-numbers) rather than concrete classes. For an integer that would mean:
```
>>> import numbers
>>> isinstance(3, numbers.Integral)
True
```
This doesn't restrict the check to just `int`, or ... |
Checking whether a variable is an integer or not | 3,501,382 | 412 | 2010-08-17T10:15:08Z | 9,266,979 | 39 | 2012-02-13T19:45:59Z | [
"python"
] | How do I check whether a variable is an integer? | All proposed answers so far seem to miss the fact that a double (floats in python are actually doubles) can also be an integer (if it has nothing after the decimal point). I use the built-in `is_integer()` method on doubles to check this.
Example (to do something every xth time in a for loop):
```
for index in range(... |
Checking whether a variable is an integer or not | 3,501,382 | 412 | 2010-08-17T10:15:08Z | 15,560,515 | 11 | 2013-03-22T00:14:40Z | [
"python"
] | How do I check whether a variable is an integer? | Why not try something like:
```
if x%1 == 0:
``` |
Checking whether a variable is an integer or not | 3,501,382 | 412 | 2010-08-17T10:15:08Z | 20,436,858 | 8 | 2013-12-07T02:33:03Z | [
"python"
] | How do I check whether a variable is an integer? | it's really astounding to see such a heated discussion coming up when such a basic, valid and, i believe, mundane question is being asked.
some people have pointed out that type-checking against `int` (and `long`) might loose cases where a big decimal number is encountered. quite right.
some people have pointed out t... |
Checking whether a variable is an integer or not | 3,501,382 | 412 | 2010-08-17T10:15:08Z | 29,913,046 | 13 | 2015-04-28T07:30:50Z | [
"python"
] | How do I check whether a variable is an integer? | Rather than over complicate things, why not just a simple
```
if type(var) is int:
``` |
Break/Decompose complex and compound sentences in nltk | 3,501,436 | 6 | 2010-08-17T10:22:29Z | 3,508,201 | 8 | 2010-08-18T01:06:00Z | [
"python",
"nlp",
"nltk"
] | Is there a way to decompose complex sentences into simple sentences in nltk or other natural language processing libraries?
For example:
The park is so wonderful when the sun is setting and a cool breeze is blowing ==> The sun is setting. a cool breeze is blowing. The park is so wonderful. | This is much more complicated than it seems, so you're unlikely to find a perfectly clean method.
However, using the English parser in [OpenNLP](http://opennlp.sourceforge.net/), I can take your example sentence and get a following grammar tree:
```
(S
(NP (DT The) (NN park))
(VP
(VBZ is)
(ADJP ... |
How to assign a local file to the FileField in Django? | 3,501,588 | 16 | 2010-08-17T10:48:36Z | 3,502,356 | 26 | 2010-08-17T12:27:27Z | [
"python",
"django",
"filefield"
] | I was trying to assign a file from my disk to the FileField, but I have this error:
AttributeError: 'str' object has no attribute 'open'
My python code:
```
pdfImage = FileSaver()
pdfImage.myfile.save('new', open('mytest.pdf').read())
```
and my models.py
```
class FileSaver(models.Model):
myfile = models.Fil... | Django uses it's own [file type](http://docs.djangoproject.com/en/dev/topics/files/#the-file-object) (with a sightly enhanced functionality). Anyway Django's file type works like a [decorator](http://en.wikipedia.org/wiki/Decorator_pattern), so you can simply wrap it around existing file objects to meet the needs of th... |
how to make a 3d effect on bars in matplotlib? | 3,501,771 | 4 | 2010-08-17T11:15:18Z | 3,506,588 | 11 | 2010-08-17T20:19:17Z | [
"python",
"3d",
"matplotlib",
"bar-chart"
] | I have a very simple basic bar's graphic like this one

but i want to display the bars with some 3d effect, like this

I just want the bars to have that 3d effect...my code is:
```
fig = Figure(figsize=(4.6,4))
ax1 = fig.ad... | I certainly understand your reason for needing a 3d bar plot; i suspect that's why they were created.
The libraries ('toolkits') in Matplotlib required to create 3D plots are *not* third-party libraries, etc., rather they are *included in the base Matplotlib installation*.
(This is true for the current stable version,... |
How to bind self events in Tkinter Text widget after it will binded by Text widget? | 3,501,849 | 8 | 2010-08-17T11:25:30Z | 3,513,906 | 15 | 2010-08-18T15:43:46Z | [
"python",
"events",
"text",
"binding",
"tkinter"
] | I want to bind self events after `Text` widget class bindings, in order to change the text of the widget when my binding function is called. My binding, for example `self.text.bind("<Key>", self.callback)`, is called before the content in Text widget changes. | What is happening in your case is that your binding to print the value happens before the class binding, and it's the class binding that actually takes user input and puts it in the widget. There are several ways to solve this problem. You could bind to `<KeyRelease>` instead of `<KeyPress>`, or you could use the built... |
Is it good design to create a module-wide logger in python? | 3,502,558 | 5 | 2010-08-17T12:51:23Z | 3,502,604 | 7 | 2010-08-17T12:57:01Z | [
"python",
"logging",
"coding-style",
"import"
] | When coding python, I use the logging module a lot.
After some bad experiences and reading articles like [this one](http://plope.com/Members/chrism/import_time_side_effectsrism/import_time_side_effects), I try to prevent import-time executed code wherever possible.
However, for the sake of simplicity, I tend to get m... | It's fine. I even use the same variable name `logger`. Any logging is better than no logging, but I find it's nice practise to *only* expose the logger variable, keep the module hidden away so your code only references the logger, and hence the namespace you've designated for the module.
If you later need to refine th... |
Emulating Bash 'source' in Python | 3,503,719 | 41 | 2010-08-17T14:49:31Z | 3,503,781 | 13 | 2010-08-17T14:55:33Z | [
"python",
"bash"
] | I have a script that looks something like this:
```
export foo=/tmp/foo
export bar=/tmp/bar
```
Every time I build I run 'source init\_env' (where init\_env is the above script) to set up some variables.
To accomplish the same in Python I had this code running,
```
reg = re... | Rather than having your Python script source the bash script, it would be simpler and more elegant to have a wrapper script source `init_env` and then run your Python script with the modified environment.
```
#!/bin/bash
source init_env
/run/python/script.py
``` |
Emulating Bash 'source' in Python | 3,503,719 | 41 | 2010-08-17T14:49:31Z | 3,505,826 | 52 | 2010-08-17T18:45:52Z | [
"python",
"bash"
] | I have a script that looks something like this:
```
export foo=/tmp/foo
export bar=/tmp/bar
```
Every time I build I run 'source init\_env' (where init\_env is the above script) to set up some variables.
To accomplish the same in Python I had this code running,
```
reg = re... | The problem with your approach is that you are trying to interpret bash scripts. First you just try to interpret the export statement. Then you notice people are using variable expansion. Later people will put conditionals in their files, or process substitutions. In the end you will have a full blown bash script inter... |
Emulating Bash 'source' in Python | 3,503,719 | 41 | 2010-08-17T14:49:31Z | 7,198,338 | 16 | 2011-08-25T23:21:40Z | [
"python",
"bash"
] | I have a script that looks something like this:
```
export foo=/tmp/foo
export bar=/tmp/bar
```
Every time I build I run 'source init\_env' (where init\_env is the above script) to set up some variables.
To accomplish the same in Python I had this code running,
```
reg = re... | Using pickle:
```
import os, pickle
# For clarity, I moved this string out of the command
source = 'source init_env'
dump = '/usr/bin/python -c "import os,pickle;print pickle.dumps(os.environ)"'
penv = os.popen('%s && %s' %(source,dump))
env = pickle.loads(penv.read())
os.environ = env
```
Updated:
This uses json, s... |
Assign output of os.system to a variable and prevent it from being displayed on the screen | 3,503,879 | 120 | 2010-08-17T15:03:57Z | 3,503,909 | 176 | 2010-08-17T15:06:22Z | [
"python"
] | I want to assign the output of a command I run using `os.system` to a variable and prevent it from being output to the screen. But, in the below code ,the output is sent to the screen and the value printed for `var` is 0, which I guess signifies whether the command ran successfully or not. Is there any way to assign th... | From "[Equivalent of Bash Backticks in Python](http://stackoverflow.com/questions/1410976/equivalent-of-backticks-in-python)", which I asked a long time ago, what you may want to use is `popen`:
```
os.popen('cat /etc/services').read()
```
---
I'm told that `subprocess` is a much better way to solve this, so here's ... |
Assign output of os.system to a variable and prevent it from being displayed on the screen | 3,503,879 | 120 | 2010-08-17T15:03:57Z | 3,504,078 | 33 | 2010-08-17T15:22:32Z | [
"python"
] | I want to assign the output of a command I run using `os.system` to a variable and prevent it from being output to the screen. But, in the below code ,the output is sent to the screen and the value printed for `var` is 0, which I guess signifies whether the command ran successfully or not. Is there any way to assign th... | The commands module is a reasonably high-level way to do this:
```
import commands
status, output = commands.getstatusoutput("cat /etc/services")
```
status is 0, output is the contents of /etc/services. |
Assign output of os.system to a variable and prevent it from being displayed on the screen | 3,503,879 | 120 | 2010-08-17T15:03:57Z | 3,504,154 | 80 | 2010-08-17T15:29:42Z | [
"python"
] | I want to assign the output of a command I run using `os.system` to a variable and prevent it from being output to the screen. But, in the below code ,the output is sent to the screen and the value printed for `var` is 0, which I guess signifies whether the command ran successfully or not. Is there any way to assign th... | You might also want to look at the `subprocess` module, which was built to replace the whole family of Python `popen`-type calls.
```
import subprocess
output = subprocess.check_output("cat /etc/services", shell=True)
```
The advantage it has is that there is a ton of flexibility with how you invoke commands, where t... |
Assign output of os.system to a variable and prevent it from being displayed on the screen | 3,503,879 | 120 | 2010-08-17T15:03:57Z | 23,796,709 | 9 | 2014-05-22T02:06:21Z | [
"python"
] | I want to assign the output of a command I run using `os.system` to a variable and prevent it from being output to the screen. But, in the below code ,the output is sent to the screen and the value printed for `var` is 0, which I guess signifies whether the command ran successfully or not. Is there any way to assign th... | I know this has already been answered, but I wanted to share a potentially better looking way to call Popen via the use of `from x import x` and functions:
```
from subprocess import PIPE, Popen
def cmdline(command):
process = Popen(
args=command,
stdout=PIPE,
shell=True
)
return ... |
Make Python ignore .pyc files | 3,503,970 | 16 | 2010-08-17T15:11:37Z | 3,504,003 | 11 | 2010-08-17T15:14:57Z | [
"python",
"pyc"
] | Is there a way to make Python ignore any .pyc files that are present and always interpret all the code (including imported modules) directly? Google hasn't turned up any answers, so I suspect not, but it seemed worth asking just in case.
(Why do I want to do this? I have a large pipeline of Python scripts which are ru... | It's not exactly what you asked for, but would removing the existing .pyc files and then not creating any more work for you? In that case, you could use the -B option:
```
>python --help
usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-... |
Make Python ignore .pyc files | 3,503,970 | 16 | 2010-08-17T15:11:37Z | 3,504,066 | 11 | 2010-08-17T15:21:35Z | [
"python",
"pyc"
] | Is there a way to make Python ignore any .pyc files that are present and always interpret all the code (including imported modules) directly? Google hasn't turned up any answers, so I suspect not, but it seemed worth asking just in case.
(Why do I want to do this? I have a large pipeline of Python scripts which are ru... | You *could* use the standard Python library's imp module to reimplement `__builtins__.__import__`, which is the hook function called by `import` and `from` statement. In particular, the [imp.load\_module](http://docs.python.org/library/imp.html#imp.load_module) function can be used to load a `.py` even when the corresp... |
twisted + gtk: should I run GUI things in threads, or in the reactor thread? | 3,504,739 | 7 | 2010-08-17T16:29:47Z | 3,509,723 | 10 | 2010-08-18T07:10:13Z | [
"python",
"multithreading",
"gtk",
"twisted",
"pygtk"
] | From what I understand about twisted, nothing running in the reactor thread should block. All blocking activities should be delegated to other threads, to fire callbacks back into the reactor thread when they're done.
So does this apply to gtk things as well? For example, I want to display a "connection failed" messag... | Your problem doesn't actually have anything to do with threads and GUIs. You should always use Twisted and GTK from the same thread: there's no need to do otherwise.
Your problem is that you are using `gtk.Dialog.run()`. This is an API that you should never use, Twisted or not. It runs a re-entrant main loop, which ca... |
Using RSA in Python | 3,504,955 | 15 | 2010-08-17T16:58:39Z | 3,506,652 | 35 | 2010-08-17T20:27:06Z | [
"python",
"rsa",
"pycrypto"
] | I am using RSA to encrypt/decrypt my session keys in Python. I am using Pycrypto library. After generating the keypair, I want to extract the private key and public key from that generated key and store them in different files. How can I do this? I can see the has Private method which can tell that the generated keypai... | If you want to get according parts from they key, there is `key` attribute for that:
```
>>> from Crypto.PublicKey import RSA
>>> RSAkey = RSA.generate(1024)
>>> getattr(RSAkey.key, 'n')
13773...L
>>> getattr(RSAkey.key, 'p')
11731...L
>>> getattr(RSAkey.key, 'q')
11740...L
```
Available components are 'n', 'e', 'd',... |
Python: Undo a Python file readline() operation so file pointer is back in original state | 3,505,479 | 13 | 2010-08-17T18:02:31Z | 3,505,524 | 23 | 2010-08-17T18:08:23Z | [
"python",
"file-io"
] | I'm browsing through a Python file pointer of a text file in read-only mode using file.readline() looking for a special line. Once I find that line I want to pass the file pointer to a method that is expecting the file pointer to be at the START of that readline (not right after it.)
How do I essentially undo one file... | You have to remember the position by calling `file.tell()` before the readline and then calling `file.seek()` to rewind. Something like:
```
fp = open('myfile')
last_pos = fp.tell()
line = fp.readline()
while line != '':
if line == 'SPECIAL':
fp.seek(last_pos)
other_function(fp)
break
last_pos = fp.tel... |
Python: Undo a Python file readline() operation so file pointer is back in original state | 3,505,479 | 13 | 2010-08-17T18:02:31Z | 3,505,538 | 10 | 2010-08-17T18:09:56Z | [
"python",
"file-io"
] | I'm browsing through a Python file pointer of a text file in read-only mode using file.readline() looking for a special line. Once I find that line I want to pass the file pointer to a method that is expecting the file pointer to be at the START of that readline (not right after it.)
How do I essentially undo one file... | You record the starting point of the line with `thefile.tell()` before you call `readline`, and get back to that point, if you need to, with `thefile.seek`.
```
>>> with open('bah.txt', 'w') as f:
... f.writelines('Hello %s\n' % i for i in range(5))
...
>>> with open('bah.txt') as f:
... f.readline()
... x = f.... |
in python how do I convert a single digit number into a double digits string? | 3,505,831 | 16 | 2010-08-17T18:46:47Z | 3,505,854 | 32 | 2010-08-17T18:49:57Z | [
"python",
"string",
"numbers",
"digits"
] | So say i have
a = 5
i want to print it as a string '05' | `print "%02d"%a` is the python 2 variant
python 3 uses a somewhat more verbose formatting system:
```
"{0:0=2d}".format(a)
```
The relevant doc link for python2 is: <http://docs.python.org/2/library/string.html#format-specification-mini-language>
For python3, it's <http://docs.python.org/3/library/string.html#strin... |
in python how do I convert a single digit number into a double digits string? | 3,505,831 | 16 | 2010-08-17T18:46:47Z | 3,505,998 | 10 | 2010-08-17T19:07:34Z | [
"python",
"string",
"numbers",
"digits"
] | So say i have
a = 5
i want to print it as a string '05' | ```
a = 5
print '%02d' % a
# output: 05
```
The '%' operator is called [string formatting](http://docs.python.org/library/stdtypes.html#string-formatting) operator when used with a string on the left side. `'%d'` is the formatting code to print out an integer number (you will get a type error if the value isn't numeri... |
Static class members python | 3,506,150 | 12 | 2010-08-17T19:24:27Z | 3,506,218 | 12 | 2010-08-17T19:31:49Z | [
"python",
"static",
"static-variables"
] | So I'm using static class members so I can share data between class methods and static methods of the same class (there will only be 1 instantiation of the class). I understand this fine, but I'm just wondering when the static members get initialized? Is it on import? On the first use of the class? Because I'm going to... | They will be initialized at class definition time, which will happen at import time if you are importing the class as part of a module. This assuming a "static" class member definition style like this:
```
class Foo:
bar = 1
print Foo.bar # prints '1'
```
Note that, this being a static class member, there is no ... |
Java Replacement | 3,506,252 | 3 | 2010-08-17T19:35:31Z | 3,506,284 | 14 | 2010-08-17T19:40:56Z | [
"java",
"python",
"qt",
"programming-languages",
"replace"
] | I may be posting a premature question, and maybe I'm just freaking out for no reason, but the way Oracle is handling Java is not very promising. I am a nerd who fell in love with Java from the first sight... and use it all the time in my personal/freelance projects but now I am thinking of a replacement. I am fluent in... | Not so long ago, I decided to explore away from the JVM. I set foot on python, and even though i'm nowhere near the expert/ guru level, I dont regret it. Didn't choose C# (considered it) because I consider it to be more of the same. I alredy know (and like a lot) C++, so python seemed like something new, which is what ... |
Bottle and Json | 3,506,705 | 22 | 2010-08-17T20:33:47Z | 3,506,753 | 39 | 2010-08-17T20:39:32Z | [
"python",
"json",
"bottle"
] | How do I go about returning json data from a bottle request handler. I see a dict2json method in the bottle src but I am not sure how to use it.
What is in the documentation:
```
@route('/spam')
def spam():
return {'status':'online', 'servertime':time.time()}
```
Gives me this when I bring up the page:
```
<htm... | Simply return a dict. Bottle handles the conversion to JSON for you.
> Even dictionaries are allowed. They are converted to json and returned with Content-Type header set to application/json. To disable this feature (and pass dicts to your middleware) you can set bottle.default\_app().autojson to False.
```
@route('/... |
Django admin and MongoDB, possible at all? | 3,506,809 | 18 | 2010-08-17T20:47:29Z | 4,824,175 | 11 | 2011-01-28T02:12:21Z | [
"python",
"django",
"django-admin",
"mongodb"
] | I'm building a simple short URL service, ala bitly, for our company use. And I would like to use mongodb to store the data, but I will need some kind of simple interface to add/edit short url to long url mappings.
The mongo documents will be very simple, something like this:
```
{
shortUrlSlug: 'pbbs',
fullUrl: '... | I have confirmed that django-nonrel project does support the admin interface. I did have a problem where the default SITE\_ID was picked up as a number, which is not allowed as a primary key in MongoDB. I resolved this by setting:
SITE\_ID = '4d421623b0207acdc500001d'
in my settings.py
I got the number by printing t... |
Django admin and MongoDB, possible at all? | 3,506,809 | 18 | 2010-08-17T20:47:29Z | 5,256,626 | 9 | 2011-03-10T07:21:21Z | [
"python",
"django",
"django-admin",
"mongodb"
] | I'm building a simple short URL service, ala bitly, for our company use. And I would like to use mongodb to store the data, but I will need some kind of simple interface to add/edit short url to long url mappings.
The mongo documents will be very simple, something like this:
```
{
shortUrlSlug: 'pbbs',
fullUrl: '... | I have used django-nonrel with [mongodb-engine](https://github.com/django-mongodb-engine/mongodb-engine) and it works well. Django admin also works with standard model fields. But if you are using listfield and dictfield, you would need to do some hacking. |
How can I strip comment tags from HTML using BeautifulSoup? | 3,507,283 | 9 | 2010-08-17T21:53:18Z | 3,507,360 | 46 | 2010-08-17T22:07:06Z | [
"python",
"beautifulsoup"
] | I have been playing with BeautifulSoup, which is great. My end goal is to try and just get the text from a page. I am just trying to get the text from the body, with a special case to get the title and/or alt attributes from `<a>` or `<img>` tags.
So far I have this `EDITED & UPDATED CURRENT CODE`:
```
soup = Beautif... | Straight from the [documentation for BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/documentation.html#Removing+elements), you can easily strip comments (or anything) using `extract()`:
```
from BeautifulSoup import BeautifulSoup, Comment
soup = BeautifulSoup("""1<!--The loneliest number-->
... |
Python: How to check if a unicode string contains a cased character? | 3,508,490 | 7 | 2010-08-18T02:18:06Z | 3,508,515 | 7 | 2010-08-18T02:25:05Z | [
"python",
"unicode",
"uppercase",
"lowercase"
] | I'm doing a filter wherein I check if a unicode (utf-8 encoding) string contains no uppercase characters (in all languages). It's fine with me if the string doesn't contain any cased character at all.
For example: 'Hello!' will not pass the filter, but "!" should pass the filter, since "!" is not a cased character.
I... | ```
import unicodedata as ud
def contains_cased(u):
return any(ud.category(c)[0] == 'L' for c in u)
``` |
Is there a time limit to Cron jobs in Google Apps? | 3,508,565 | 6 | 2010-08-18T02:41:16Z | 12,668,114 | 14 | 2012-10-01T05:51:51Z | [
"python",
"google-app-engine",
"cron"
] | I have created a cron job to scan rss/atom feeds but want to know if there is a timeout on this.
The documentation says that requests are limited to 30 seconds; is a cron job a regular request that is subject to this restriction?
Should I break the job up into one scan per cron job just to be on the safe side, or is ... | Cron jobs are subject to a 10 minute deadline, not 30 seconds.
See [App Engine version 1.4 release page](http://googleappengine.blogspot.com/2010/12/happy-holidays-from-app-engine-team-140.html):
> No more 30-second limit for background work - With this release, weâve
> significantly raised this limit for offline r... |
python one-liner | 3,508,766 | 2 | 2010-08-18T03:33:21Z | 3,508,979 | 19 | 2010-08-18T04:30:06Z | [
"python",
"sum"
] | I want a one-liner solution In Python of the following code but how?
```
total = 0
for ob in self.oblist:
total+=sum(v.amount for v in ob.anoutherob)
```
It returns total value. I want it one liner , plz any one help me | No need to double up on the `sum()` calls
```
total = sum(v.amount for ob in self.oblist for v in ob.anotherob)
``` |
How to remove list of words from a list of strings | 3,510,846 | 9 | 2010-08-18T09:52:47Z | 3,510,894 | 7 | 2010-08-18T09:58:58Z | [
"python",
"regex",
"list-comprehension",
"stop-words"
] | Sorry if the question is bit confusing. This is similar to [this question](http://stackoverflow.com/questions/2553668/how-to-remove-list-of-words-from-strings)
I think this the above question is close to what I want, but in Clojure.
There is [another](http://stackoverflow.com/questions/3136689/find-and-replace-string... | Here is my stab at it. This uses regular expressions.
```
import re
pattern = re.compile("(of|the|in|for|at)\W", re.I)
phrases = ['of New York', 'of the New York']
map(lambda phrase: pattern.sub("", phrase), phrases) # ['New York', 'New York']
```
Sans `lambda`:
```
[pattern.sub("", phrase) for phrase in phrases]
`... |
How to remove list of words from a list of strings | 3,510,846 | 9 | 2010-08-18T09:52:47Z | 3,511,518 | 12 | 2010-08-18T11:25:18Z | [
"python",
"regex",
"list-comprehension",
"stop-words"
] | Sorry if the question is bit confusing. This is similar to [this question](http://stackoverflow.com/questions/2553668/how-to-remove-list-of-words-from-strings)
I think this the above question is close to what I want, but in Clojure.
There is [another](http://stackoverflow.com/questions/3136689/find-and-replace-string... | Without regexp you could do like this:
```
places = ['of New York', 'of the New York']
noise_words_set = {'of', 'the', 'at', 'for', 'in'}
stuff = [' '.join(w for w in place.split() if w.lower() not in noise_words_set)
for place in places
]
print stuff
``` |
Factory pattern in Python | 3,511,027 | 17 | 2010-08-18T10:19:32Z | 3,511,113 | 9 | 2010-08-18T10:31:54Z | [
"python",
"design-patterns",
"factory",
"factory-pattern"
] | I'm currently implementing the Factory design pattern in Python and I have a few questions.
1. Is there any way to prevent the direct instantiation of the actual concrete classes? For example, if I have a VehicleFactory that spawns Vehicles, I want users to just use that factory, and prevent anyone from accidentally i... | 1. Don't expose the class (for example make it private `__MyClass`, or obvious that you don't want it used directly `_MyClass`). This way it can only be instantiated via the factory function.
2. Perhaps you should review the use of keyword arguments, and inheritance. It sounds like you may be overlooking these, which w... |
Factory pattern in Python | 3,511,027 | 17 | 2010-08-18T10:19:32Z | 3,511,165 | 22 | 2010-08-18T10:39:15Z | [
"python",
"design-patterns",
"factory",
"factory-pattern"
] | I'm currently implementing the Factory design pattern in Python and I have a few questions.
1. Is there any way to prevent the direct instantiation of the actual concrete classes? For example, if I have a VehicleFactory that spawns Vehicles, I want users to just use that factory, and prevent anyone from accidentally i... | Be Pythonic. Don't overcomplicate your code with "enterprise" language (like Java) solutions that add unnecessary levels of abstraction.
Your code should be simple, and intuitive. You shouldn't need to delegate to another class to instantiate another. |
Python (1..n) syntax? | 3,511,699 | 6 | 2010-08-18T11:47:38Z | 3,511,887 | 13 | 2010-08-18T12:11:26Z | [
"python",
"sage"
] | I see in the code on this [Sage wiki page](http://wiki.sagemath.org/interact) the following code:
```
@interact
def _(order=(1..12)):
```
Is this `(1..n)` syntax unique to Sage or is it something in Python? Also, what does it do? | It's Sage-specific. You can use `preparse` to see how it is desugared to:
```
sage: preparse("(1..12)")
'(ellipsis_iter(Integer(1),Ellipsis,Integer(12)))'
```
See [here](http://www.sagemath.org/doc/reference/sage/misc/misc.html#sage.misc.misc.ellipsis_iter) for documentation of `ellipsis_iter`, [here](http://www.sage... |
Python (1..n) syntax? | 3,511,699 | 6 | 2010-08-18T11:47:38Z | 3,513,869 | 9 | 2010-08-18T15:40:15Z | [
"python",
"sage"
] | I see in the code on this [Sage wiki page](http://wiki.sagemath.org/interact) the following code:
```
@interact
def _(order=(1..12)):
```
Is this `(1..n)` syntax unique to Sage or is it something in Python? Also, what does it do? | There was a Python PEP to add this notation to Python, but it was rejected. Robert Bradshaw decided to implement it anyways, but for the Sage preparser. He implemented the following:
* (a..b) -- like xrange, so an iterator
* [a..b] -- list, including endpoints
* [a,b,..,c] -- arithmetic progression |
Using xlrd to read Excel xls file containing Chinese and/or Hindi characters | 3,511,743 | 3 | 2010-08-18T11:53:30Z | 3,517,806 | 7 | 2010-08-19T00:25:38Z | [
"python",
"xls",
"cjk",
"xlrd",
"hindi"
] | <http://scienceoss.com/read-excel-files-from-python/comment-page-1/#comment-1051>
From the above link, I used this utility to read an XLS file. If the XLS file contains different language characters like Chinese or Hindi, it does not output them correctly. Is there a workaround for this?
After Googling, I found this:... | [dis]claimer: I'm the author of xlrd.
"""If the xls contains different language characters like chine or hindi.It does not output the exact wordings.Is there a work around for this.."""
The encoding\_override argument is (as explained in the documentation) used ONLY for OLD files (produced by Excels earlier than Exce... |
Does this PyList_Append(list, Py_BuildValue(...)) leak? | 3,512,414 | 8 | 2010-08-18T13:11:25Z | 3,512,476 | 12 | 2010-08-18T13:18:36Z | [
"python",
"c"
] | Does this leak?:
```
static PyObject* foo(PyObject* self, PyObject* args){
PyObect* list = PyList_New(0);
for(int i = 0; i < 100; i++)
// leak? does PyList_Append increment ref of the temporary?
PyList_Append(list, Py_BuildValue("i", 42));
return list;
}
```
Though, I suppose it's better ... | `PyList_Append` does indeed increment the reference counter, so, yes, the first example will leak. `PyList_SetItem` does not, making it a weird exception.
The second option will be slightly more efficient because the list will be allocated to excatly the right size and Python does have to dynamically resize it as item... |
webpy: How to serve JSON | 3,513,446 | 19 | 2010-08-18T14:58:36Z | 3,514,653 | 53 | 2010-08-18T17:05:56Z | [
"python",
"web.py"
] | Is it possible to use webpy to serve JSON?
I built my website and I need to serve some information in JSON to interact with the Javascript on some pages.
I try to look for answers in the documentation, but I'm not able to find anything.
Thanks,
Giovanni | I wouldn't think you'd have to do any thing overly "special" for web.py to serve JSON.
```
import web
import json
class index:
def GET(self):
pyDict = {'one':1,'two':2}
web.header('Content-Type', 'application/json')
return json.dumps(pyDict)
``` |
(Unintentionally) skipping items when iterating over a list | 3,513,531 | 3 | 2010-08-18T15:06:32Z | 3,513,598 | 8 | 2010-08-18T15:12:13Z | [
"python",
"list"
] | I have a list and I want to remove from it the items that don't appear in another list. I've tried the following:
```
for w in common:
for i in range(1,n):
if not w in words[i]:
common.remove(w)
```
However, this fails to remove some of the items. Adding print statements
```
for w... | I think you can simplify your statement with something like this:
```
filtered = filter(lambda x: x in words, common)
```
That's checking each element in common for it's presence in words and removing based on it. You may need to try `x not in words` depending on what you're desired result is, but I think that should... |
Pythonic way to split a list into first and rest? | 3,513,947 | 30 | 2010-08-18T15:48:04Z | 3,514,009 | 22 | 2010-08-18T15:53:31Z | [
"python"
] | I think in Python 3 I'll be able to do:
```
first, *rest = l
```
which is exactly what I want, but I'm using 2.6. For now I'm doing:
```
first = l[0]
rest = l[1:]
```
This is fine, but I was just wondering if there's something more elegant. | ```
first, rest = l[0], l[1:]
```
Basically the same, except that it's a oneliner. Tuple assigment rocks.
This is a bit longer and less obvious, but generalized for all iterables (instead of being restricted to sliceables):
```
i = iter(l)
first = next(i) # i.next() in older versions
rest = list(i)
``` |
Pythonic way to split a list into first and rest? | 3,513,947 | 30 | 2010-08-18T15:48:04Z | 3,514,129 | 11 | 2010-08-18T16:06:02Z | [
"python"
] | I think in Python 3 I'll be able to do:
```
first, *rest = l
```
which is exactly what I want, but I'm using 2.6. For now I'm doing:
```
first = l[0]
rest = l[1:]
```
This is fine, but I was just wondering if there's something more elegant. | You can do
```
first = l.pop(0)
```
and then `l` will be the rest. It modifies your original list, though, so maybe itâs not what you want. |
What is wrong with this Python game code? | 3,514,154 | 4 | 2010-08-18T16:09:36Z | 3,514,165 | 12 | 2010-08-18T16:11:22Z | [
"python"
] | ```
import random
secret = random.randint (1,99)
guess = 0
tries = 0
print ("AHOY! I'm the Dread Pirate Roberts, and I have a secret!")
print ("It is a number from 1 to 99. I'll give you 6 tries. ")
while guess != secret and tries < 6:
guess = input ("What's yer guess? ")
if guess < secret:
print ("T... | ```
guess = input ("What's yer guess? ")
```
Calling `input` gives you back a `string`, not an `int`. When you then compare `guess` using `<`, you need an `int` in order to compare a numerical value. Try doing something along the lines of:
```
try:
guess = int(input("What's yer guess? "))
except ValueError:
#... |
Validating an XMPP jid with python? | 3,514,342 | 8 | 2010-08-18T16:30:39Z | 3,519,699 | 20 | 2010-08-19T07:42:24Z | [
"python",
"validation",
"xmpp"
] | What is the correct way to validate an xmpp jid? The syntax is described [here:](http://xmpp.org/rfcs/rfc3920.html#addressing), but I don't really understand it. Also, it seems pretty complicated, so using a library to do it would seem like a good idea.
I'm currently using xmpppy, but I can't seem to find how to valid... | First off, the current best reference for JIDs is [RFC 6122](http://tools.ietf.org/html/rfc6122).
I was just going to give you the regex in here, but got a little carried away, and implemented all of the spec:
```
import re
import sys
import socket
import encodings.idna
import stringprep
# These characters aren't al... |
How to use C extensions in python to get around GIL | 3,514,495 | 7 | 2010-08-18T16:46:37Z | 3,514,615 | 7 | 2010-08-18T16:59:21Z | [
"python",
"python-c-extension"
] | I want to run a cpu intensive program in Python across multiple cores and am trying to figure out how to write C extensions to do this. Are there any code samples or tutorials on this? | Take a look at [multiprocessing](http://docs.python.org/library/multiprocessing.html). It's an often overlooked fact that not globally sharing data, and not cramming loads of threads into a single process is what operating systems prefer.
If you still insist that your CPU intensive behaviour requires threading, take a... |
How to use C extensions in python to get around GIL | 3,514,495 | 7 | 2010-08-18T16:46:37Z | 3,514,684 | 8 | 2010-08-18T17:10:45Z | [
"python",
"python-c-extension"
] | I want to run a cpu intensive program in Python across multiple cores and am trying to figure out how to write C extensions to do this. Are there any code samples or tutorials on this? | You can already break a Python program into multiple processes. The OS will already allocate your processes across all the cores.
Do this.
```
python part1.py | python part2.py | python part3.py | ... etc.
```
The OS will assure that part uses as many resources as possible. You can trivially pass information along t... |
How to completely remove Python from a Windows machine? | 3,515,673 | 32 | 2010-08-18T18:59:12Z | 3,515,928 | 11 | 2010-08-18T19:32:59Z | [
"python",
"installation",
"uninstall"
] | I installed both Python 2.7 and Python 2.6.5. I don't know what went wrong, but nothing related to Python seems to work any more. e.g. "setup.py install" for certain packages don't recognize the "install" parameter and other odd phenomena...
I would like to completely remove Python from my system.
I tried running th... | You will also have to look in your system path. Python puts itself there and does not remove itself: <http://www.computerhope.com/issues/ch000549.htm>
Your problems probably started because your python path is pointing to the wrong one. |
How to completely remove Python from a Windows machine? | 3,515,673 | 32 | 2010-08-18T18:59:12Z | 18,430,403 | 13 | 2013-08-25T15:08:32Z | [
"python",
"installation",
"uninstall"
] | I installed both Python 2.7 and Python 2.6.5. I don't know what went wrong, but nothing related to Python seems to work any more. e.g. "setup.py install" for certain packages don't recognize the "install" parameter and other odd phenomena...
I would like to completely remove Python from my system.
I tried running th... | Here's the steps (my non-computer-savvy girlfriend had to figure this one out for me, but unlike all the far more complicated processes one can find online, this one works)
1. Open Control Panel
2. Click "Uninstall a Program"
3. Scroll down to Python and click uninstall for each version you don't want anymore.
This w... |
Python print statements being buffered with > output redirection | 3,515,757 | 10 | 2010-08-18T19:11:18Z | 3,515,882 | 22 | 2010-08-18T19:28:18Z | [
"python",
"linux"
] | I'm doing print statements in python. I'm executing my script like so:
```
python script.py > out.log nohup &
```
The print statements are not all showing up in `out.log` but the program is finishing ok.
That line of code is in an `.sh` file
I execute by doing `./script.sh`
**Update:** The log does get all the data... | When stdout is sent to a tty it will be line buffered and will be flushed every line, but when redirected to a file or pipe it'll be fully buffered and will only be flushed periodically when you overrun the buffer.
You'll have to add `sys.stdout.flush()` calls after each line if you want the output to be immediately v... |
Run Process and Don't Wait | 3,516,007 | 17 | 2010-08-18T19:41:54Z | 3,516,106 | 16 | 2010-08-18T19:51:13Z | [
"python",
"windows"
] | I'd like to run a process and not wait for it to return. I've tried spawn with P\_NOWAIT and subprocess like this:
```
app = "C:\Windows\Notepad.exe"
file = "C:\Path\To\File.txt"
pid = subprocess.Popen([app, file], shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE).pid
```
However, the console window remains... | This call doesn't wait for the child process to terminate (on Linux). Don't ask me what `close_fds` does; I wrote the code some years ago. (BTW: The documentation of `subprocess.Popen` is confusing, IMHO.)
```
proc = Popen([cmd_str], shell=True,
stdin=None, stdout=None, stderr=None, close_fds=True)
```
*... |
Run Process and Don't Wait | 3,516,007 | 17 | 2010-08-18T19:41:54Z | 6,700,359 | 12 | 2011-07-14T21:50:01Z | [
"python",
"windows"
] | I'd like to run a process and not wait for it to return. I've tried spawn with P\_NOWAIT and subprocess like this:
```
app = "C:\Windows\Notepad.exe"
file = "C:\Path\To\File.txt"
pid = subprocess.Popen([app, file], shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE).pid
```
However, the console window remains... | I finally got this to work. I'm running "Python 2.6.6 (r266:84297, Aug 24 2010, 18:13:38) [MSC v.1500 64 bit (AMD64)] win32". Here's how I had to code it:
```
from subprocess import Popen
DETACHED_PROCESS = 0x00000008
cmd = [
sys.executable,
'c:\somepath\someprogram.exe',
parm1,
parm2,
... |
Coming from C, how should I learn Python? | 3,516,560 | 12 | 2010-08-18T20:49:49Z | 3,516,607 | 13 | 2010-08-18T20:55:54Z | [
"python",
"c"
] | I've got a good grasp on C, my first programming language. I know a reasonable number of tricks and techniques and have written quite a few programs, mostly for scientific stuff. Now I'd like to branch out and understand OOP, and Python seems like a good direction to go.
I've seen several questions on how to learn Pyt... | I learned everything I know about Python from the official documentation: <http://docs.python.org/>
And it's free. |
Coming from C, how should I learn Python? | 3,516,560 | 12 | 2010-08-18T20:49:49Z | 3,516,618 | 9 | 2010-08-18T20:57:13Z | [
"python",
"c"
] | I've got a good grasp on C, my first programming language. I know a reasonable number of tricks and techniques and have written quite a few programs, mostly for scientific stuff. Now I'd like to branch out and understand OOP, and Python seems like a good direction to go.
I've seen several questions on how to learn Pyt... | [dive into python](http://diveintopython.net/) is a good place to start
fire up an interpreter, IPython is even better than the plain Python interpreter
use dir() and help() to poke around
and don't forget to read through the [official docs](http://docs.python.org) at least once |
Coming from C, how should I learn Python? | 3,516,560 | 12 | 2010-08-18T20:49:49Z | 3,516,905 | 24 | 2010-08-18T21:34:59Z | [
"python",
"c"
] | I've got a good grasp on C, my first programming language. I know a reasonable number of tricks and techniques and have written quite a few programs, mostly for scientific stuff. Now I'd like to branch out and understand OOP, and Python seems like a good direction to go.
I've seen several questions on how to learn Pyt... | I knew C before I knew Python. No offence intended, but I don't think that your C knowledge is that big a deal. Unless you read very, very slowly, just set out to learn Python. It won't take that long to skim through the material you're familiar with, and it's not as if a Python tutorial aimed at C programmers will mak... |
Python Remove Parts of string by index | 3,516,571 | 8 | 2010-08-18T20:50:48Z | 3,516,590 | 12 | 2010-08-18T20:53:19Z | [
"python",
"string"
] | I have a string
```
string='texttexttextblahblah",".'
```
and what I want to do is cut of some of the rightmost characters by indexing and assign it to `string` so that `string` will be equal to `texttexttextblahblah"`
I've looked around and found how to print by indexing, but not how to reassign that actual variabl... | Just reassign what you printed to the variable.
```
>>> string='texttexttextblahblah",".'
>>> string = string[:-3]
>>> string
'texttexttextblahblah"'
>>>
```
Also, avoid using names of libraries or builtins (`string`) for variables
Unless you know exactly how many `text` and `blah`'s you'll have, use `.find()` as Br... |
When parsing html why do I need item.text sometimes and item.text_content() others | 3,517,461 | 5 | 2010-08-18T23:09:33Z | 3,518,170 | 7 | 2010-08-19T01:56:35Z | [
"python",
"html",
"parsing",
"lxml"
] | Still learning lxml. I discovered that sometimes I cannot get to the text of an item from a tree using item.text. If I use item.text\_content() I am good to go. I am not sure I see why yet. Any hints would be appreciated
Okay I am not sure exactly how to provide an example without making you handle a file:
here is so... | Accordng to [the docs](http://lxml.de/lxmlhtml.html#html-element-methods) the `text_content` method:
> Returns the text content of the element, including the text content of
> its children, with no markup.
So for example,
```
import lxml.html as lh
data = """<a><b><c>blah</c></b></a>"""
doc = lh.fromstring(data)
pri... |
Python raw literal string | 3,517,802 | 6 | 2010-08-19T00:24:33Z | 3,517,827 | 26 | 2010-08-19T00:29:57Z | [
"python",
"string"
] | ```
str = r'c:\path\to\folder\' # my comment
```
IDE: Eclipse, Python2.6
When the last character in the string is backslash, it seems will escape the last single quote and treat my comment as part of the string. But the raw string suppose to ignore all escape characters, right? What could be wrong? thanks. | Raw string literals don't treat backslashes as initiating escape sequences **except** when the immediately-following character is the quote-character that is delimiting the literal, in which case the backslash **does** escape it.
The design motivation is that raw string literals really exist only for the convenience o... |
Python raw literal string | 3,517,802 | 6 | 2010-08-19T00:24:33Z | 3,517,887 | 7 | 2010-08-19T00:40:43Z | [
"python",
"string"
] | ```
str = r'c:\path\to\folder\' # my comment
```
IDE: Eclipse, Python2.6
When the last character in the string is backslash, it seems will escape the last single quote and treat my comment as part of the string. But the raw string suppose to ignore all escape characters, right? What could be wrong? thanks. | It's IMHO an inconsistency in Python, but it's described in the documentation. Go to the second last paragraph:
<http://docs.python.org/reference/lexical_analysis.html#string-literals>
> r"\" is not a valid string literal
> (even a raw string cannot end in an
> odd number of backslashes) |
Why Does Looping Beat Indexing Here? | 3,518,574 | 10 | 2010-08-19T03:44:00Z | 3,519,188 | 11 | 2010-08-19T06:15:15Z | [
"python",
"performance",
"memory-management",
"numpy"
] | A few years ago, someone [posted](http://code.activestate.com/recipes/498246/) on *Active State Recipes* for comparison purposes, three python/NumPy functions; each of these accepted the same arguments and returned the same result, a **distance matrix**.
Two of these were taken from published sources; they are both--o... | **TL; DR** The second code above is only looping over the number of dimensions of the points (3 times through the for loop for 3D points) so the looping isn't much there. The real speed-up in the second code above is that it better harnesses the power of Numpy to avoid creating some extra matrices when finding the diff... |
How to read csv into record array in numpy? | 3,518,778 | 160 | 2010-08-19T04:41:53Z | 3,519,314 | 236 | 2010-08-19T06:34:54Z | [
"python",
"numpy",
"scipy",
"genfromtxt"
] | I wonder if there is a direct way to import the contents of a csv file into a record array, much in the way that R's read.table(), read.delim(), and read.csv() family imports data to R's data frame? Or is the best way to use [csv.reader()](http://stackoverflow.com/questions/2859404/reading-csv-files-in-scipy-numpy-in-p... | You can use Numpy's `genfromtxt()` method to do so, by setting the `delimiter` kwarg to a comma.
```
from numpy import genfromtxt
my_data = genfromtxt('my_file.csv', delimiter=',')
```
More information on the function can be found at its respective [documentation](http://docs.scipy.org/doc/numpy/reference/generated/n... |
How to read csv into record array in numpy? | 3,518,778 | 160 | 2010-08-19T04:41:53Z | 4,724,179 | 51 | 2011-01-18T12:44:35Z | [
"python",
"numpy",
"scipy",
"genfromtxt"
] | I wonder if there is a direct way to import the contents of a csv file into a record array, much in the way that R's read.table(), read.delim(), and read.csv() family imports data to R's data frame? Or is the best way to use [csv.reader()](http://stackoverflow.com/questions/2859404/reading-csv-files-in-scipy-numpy-in-p... | You can also try `recfromcsv()` which can guess data types and return a properly formatted record array. |
How to read csv into record array in numpy? | 3,518,778 | 160 | 2010-08-19T04:41:53Z | 26,296,194 | 48 | 2014-10-10T09:30:25Z | [
"python",
"numpy",
"scipy",
"genfromtxt"
] | I wonder if there is a direct way to import the contents of a csv file into a record array, much in the way that R's read.table(), read.delim(), and read.csv() family imports data to R's data frame? Or is the best way to use [csv.reader()](http://stackoverflow.com/questions/2859404/reading-csv-files-in-scipy-numpy-in-p... | I would recommend the [`read_csv`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.parsers.read_csv.html) function from the `pandas` library:
```
import pandas as pd
df=pd.read_csv('myfile.csv', sep=',',header=None)
df.values
array([[ 1. , 2. , 3. ],
[ 4. , 5.5, 6. ]])
```
This gives a pand... |
How to read csv into record array in numpy? | 3,518,778 | 160 | 2010-08-19T04:41:53Z | 28,554,340 | 30 | 2015-02-17T03:52:37Z | [
"python",
"numpy",
"scipy",
"genfromtxt"
] | I wonder if there is a direct way to import the contents of a csv file into a record array, much in the way that R's read.table(), read.delim(), and read.csv() family imports data to R's data frame? Or is the best way to use [csv.reader()](http://stackoverflow.com/questions/2859404/reading-csv-files-in-scipy-numpy-in-p... | I timed the
```
from numpy import genfromtxt
genfromtxt(fname = dest_file, dtype = (<whatever options>))
```
versus
```
import csv
import numpy as np
with open(dest_file,'r') as dest_f:
data_iter = csv.reader(dest_f,
delimiter = delimiter,
quotechar = '"')
... |
How do I set the transaction isolation level in SQLAlchemy for PostgreSQL? | 3,518,863 | 7 | 2010-08-19T05:05:33Z | 3,570,283 | 7 | 2010-08-25T21:16:28Z | [
"python",
"postgresql",
"transactions",
"sqlalchemy",
"isolation-level"
] | We're using SQLAlchemy declarative base and I have a method that I want isolate the transaction level for. To explain, there are two processes concurrently writing to the database and I must have them execute their logic in a transaction. The default transaction isolation level is READ COMMITTED, but I need to be able ... | From Michael Bayer, the maintainer of SQLAlchemy:
> Please use the "isolation\_level"
> argument to [create\_engine()](http://www.sqlalchemy.org/docs/reference/dialects/postgresql.html?highlight=isolation_level#transaction-isolation-level)
> and use the [latest tip of SQLAlchemy](http://hg.sqlalchemy.org/sqlalchemy/ar... |
Python Regex, re.sub, replacing multiple parts of pattern? | 3,519,487 | 15 | 2010-08-19T07:02:46Z | 3,519,554 | 16 | 2010-08-19T07:13:44Z | [
"python",
"regex"
] | I can't seem to find a good resource on this.. I am trying to do a simple re.place
I want to replace the part where its (.\*?), but can't figure out the syntax on how to do this.. I know how to do it in PHP, so I've been messing around with what I think it could be based on that (which is why it has the $1 but I know ... | ```
>>> import re
>>> originalstring = 'fksf var:asfkj;'
>>> pattern = '.*?var:(.*?);'
>>> pattern_obj = re.compile(pattern, re.MULTILINE)
>>> replacement_string="\\1" + 'test'
>>> pattern_obj.sub(replacement_string, originalstring)
'asfkjtest'
```
Edit: The [Python Docs](http://docs.python.org/howto/regex.html#search... |
Python Regex, re.sub, replacing multiple parts of pattern? | 3,519,487 | 15 | 2010-08-19T07:02:46Z | 3,519,561 | 7 | 2010-08-19T07:14:41Z | [
"python",
"regex"
] | I can't seem to find a good resource on this.. I am trying to do a simple re.place
I want to replace the part where its (.\*?), but can't figure out the syntax on how to do this.. I know how to do it in PHP, so I've been messing around with what I think it could be based on that (which is why it has the $1 but I know ... | ```
>>> import re
>>> regex = re.compile(r".*?var:(.*?);")
>>> regex.sub(r"\1test", "fksf var:asfkj;")
'asfkjtest'
``` |
Find the indexes of all regex matches in Python? | 3,519,565 | 24 | 2010-08-19T07:14:56Z | 3,519,601 | 64 | 2010-08-19T07:22:33Z | [
"python",
"regex"
] | I'm parsing strings that could have any number of quoted strings inside them (I'm parsing code, and trying to avoid PLY). I want to find out if a substring is quoted, and I have the substrings index. My initial thought was to use re to find all the matches and then figure out the range of indexes they represent.
It se... | This is what you want: ([source](http://docs.python.org/2/library/re.html#re.finditer))
> ```
> re.finditer(pattern, string[, flags])
> ```
>
> Return an iterator yielding MatchObject instances over all
> non-overlapping matches for the RE pattern in string. The string is
> scanned left-to-right, and matches are retur... |
Python "show in finder" | 3,520,493 | 3 | 2010-08-19T09:42:30Z | 3,520,693 | 9 | 2010-08-19T10:10:16Z | [
"python"
] | How can I launch a new Finder window (or Explorer on Win) from python in a specific folder. The behaviour I'm looking for is the equivalent of "Show in finder" link in a tracks context menu in iTunes or most other programs come to think of it.
What I have currently is a UI built with PyQt and I'd like to add a menu op... | For OS X, you can use the Finder's Apple Events (AppleScript) interface via [py-appscript](http://pypi.python.org/pypi/appscript/):
```
>>> from appscript import *
>>> file_to_show = "/Applications/iTunes.app"
>>> app("Finder").reveal(mactypes.Alias(file_to_show).alias)
app(u'/System/Library/CoreServices/Finder.app').... |
installing libxml2 on python 2.7 windows | 3,520,826 | 9 | 2010-08-19T10:26:33Z | 4,246,354 | 9 | 2010-11-22T14:23:13Z | [
"python",
"libxml2"
] | I've searched but theres no libxml2 binaries for py2.7.
I have also tried running setup.py for version py2.6.9 but it gave me the error
```
failed to find headers for libxml2: update includes_dir
```
Does anyone have a solution? | Some time before I found a good page with prebuilt libraries for different versions of python and arch: <http://www.lfd.uci.edu/~gohlke/pythonlibs/>
I suspect it will be useful for you. |
Set Host-header when using Python and urllib2 | 3,520,966 | 7 | 2010-08-19T10:45:03Z | 3,520,986 | 10 | 2010-08-19T10:49:10Z | [
"python",
"http",
"urllib2"
] | I'm using my own resolver and would like to use urllib2 to just connect to the IP (no resolving in urllib2) and I would like set the HTTP Host-header myself. But urllib2 is just ignoring my Host-header:
```
txheaders = { 'User-Agent': UA, "Host: ": nohttp_url }
robots = urllib2.Request("http://" + ip + "/robots.txt",... | You have included `": "` in the `"Host"` string.
```
txheaders = { "User-Agent": UA, "Host": nohttp_url }
robots = urllib2.Request("http://" + ip + "/robots.txt", txdata, txheaders)
``` |
How can I access Oracle from Python? | 3,521,692 | 16 | 2010-08-19T12:24:17Z | 4,784,441 | 24 | 2011-01-24T16:33:17Z | [
"python",
"oracle",
"database-connection",
"cx-oracle"
] | How can I access Oracle from Python? I have downloaded a cx\_Oracle msi installer, but Python can't import the library.
I get the following error:
```
import cx_Oracle
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
import cx_Oracle
ImportError: DLL load failed: The specified module ... | Here's what worked for me. My Python and Oracle versions are slightly different from yours, but the same approach should apply. Just make sure the cx\_Oracle binary installer version matches your Oracle client and Python versions.
**My versions:**
* Python 2.7
* Oracle Instant Client 11G R2
* cx\_Oracle 5.0.4 (Unicod... |
Call a Python method by name | 3,521,715 | 35 | 2010-08-19T12:26:28Z | 3,521,742 | 49 | 2010-08-19T12:30:02Z | [
"python"
] | If I have an object and a method name in a string, how can I call the method?
```
class Foo:
def bar1(self):
print 1
def bar2(self):
print 2
def callMethod(o, name):
???
f = Foo()
callMethod(f, "bar1")
``` | Easy one:
```
class Foo:
def bar1(self):
print 1
def bar2(self):
print 2
def callMethod(o, name):
getattr(o, name)()
f = Foo()
callMethod(f, "bar1")
```
Take a look at [getattr](http://docs.python.org/library/functions.html#getattr)
You can also use [setattr](http://docs.python.org/lib... |
Quickly remove first n lines from many text files | 3,521,812 | 3 | 2010-08-19T12:38:44Z | 3,521,835 | 9 | 2010-08-19T12:40:46Z | [
"python",
"file-io",
"sed",
"performance"
] | I need to create an output text file by deleting the first two lines of the input file.
At the moment I'm using
sed "1,2d" input.txt > output.txt
I need to do this for thousands of files, so am using python:
```
import os
for filename in somelist:
os.system('sed "1,2d" %s-in.txt > %s-out.txt'%(filename,filename))
... | Use `tail`. Doubt anything could be significantly faster:
```
tail -n +3 input.txt > output.txt
```
Wrap it in your loop of choice. But I really doubt sed is a whole ton slower - as you say, disk i/o is usually the ultimate bottleneck. |
Changing the directory where .pyc files are created | 3,522,079 | 21 | 2010-08-19T13:09:13Z | 3,522,217 | 16 | 2010-08-19T13:24:21Z | [
"python",
"path",
"python-3.x",
"pyc"
] | Is there a way to change the directory where `.pyc` file are created by the Python interpreter? I saw two PEPs about that subject ([0304](http://www.python.org/dev/peps/pep-0304/) and [3147](http://www.python.org/dev/peps/pep-3147/)), but none seems to be implemented in the default interpreter (I'm working with Python ... | There's no way to change where the .pyc files go. Python 3.2 implements the `__pycache__` scheme whereby all the .pyc files go into a directory named `__pycache__`. Python 3.2 alpha 1 is available now if you really need to keep your directories clean.
Until 3.2 is released, configure as many tools as you can to ignore... |
Changing the directory where .pyc files are created | 3,522,079 | 21 | 2010-08-19T13:09:13Z | 7,229,655 | 13 | 2011-08-29T11:48:04Z | [
"python",
"path",
"python-3.x",
"pyc"
] | Is there a way to change the directory where `.pyc` file are created by the Python interpreter? I saw two PEPs about that subject ([0304](http://www.python.org/dev/peps/pep-0304/) and [3147](http://www.python.org/dev/peps/pep-3147/)), but none seems to be implemented in the default interpreter (I'm working with Python ... | This might be useful for some:
[Miscellaneous options](http://docs.python.org/using/cmdline.html#miscellaneous-options)
-B
If given, Python wonât try to write .pyc or .pyo files on the import of source modules. See also PYTHONDONTWRITEBYTECODE.
```
New in version 2.6.
``` |
How to config nltk data directory from code? | 3,522,372 | 32 | 2010-08-19T13:42:58Z | 3,903,787 | 35 | 2010-10-11T05:55:15Z | [
"python",
"path",
"directory",
"nlp",
"nltk"
] | How to config nltk data directory from code? | Just change items of `nltk.data.path`, it's a simple list. |
How to config nltk data directory from code? | 3,522,372 | 32 | 2010-08-19T13:42:58Z | 22,979,193 | 8 | 2014-04-10T05:17:41Z | [
"python",
"path",
"directory",
"nlp",
"nltk"
] | How to config nltk data directory from code? | I use append, example
```
nltk.data.path.append('/libs/nltk_data/')
``` |
How to config nltk data directory from code? | 3,522,372 | 32 | 2010-08-19T13:42:58Z | 22,987,374 | 19 | 2014-04-10T11:59:41Z | [
"python",
"path",
"directory",
"nlp",
"nltk"
] | How to config nltk data directory from code? | From the code, <http://www.nltk.org/_modules/nltk/data.html>:
> ```
> ``nltk:path``: Specifies the file stored in the NLTK data
> package at *path*. NLTK will search for these files in the
> directories specified by ``nltk.data.path``.
> ```
Then within the code:
```
##############################################... |
Python Pickling Slots Error | 3,522,765 | 8 | 2010-08-19T14:27:00Z | 3,523,501 | 11 | 2010-08-19T15:40:15Z | [
"python",
"pickle"
] | I have a large instance that I've been pickling just fine, but recently I started getting this error when I tried to dump it:
```
File "/usr/lib/python2.6/copy_reg.py", line 77, in _reduce_ex
raise TypeError("a class that defines __slots__ without "
TypeError: a class that defines __slots__ without defining __ge... | Use a binary protocol for your pickling (instead of the old ASCII one you seem to be defaulting to) and you'll be fine. Observe:
```
>>> class ws(object):
... __slots__ = 'a', 'b'
... def __init__(self, a=23, b=45): self.a, self.b = a, b
...
>>> x = ws()
>>> import pickle
>>> pickle.dumps(x, -1)
'\x80\x02c__main_... |
Handling race condition in model.save() | 3,522,827 | 14 | 2010-08-19T14:32:58Z | 3,523,439 | 12 | 2010-08-19T15:34:15Z | [
"python",
"database",
"django",
"django-models",
"race-condition"
] | How should one handle a possible race condition in a model's `save()` method?
For example, the following example implements a model with an ordered list of related items. When creating a new Item the current list size is used as its position.
From what I can tell, this can go wrong if multiple Items are created concu... | It may *feel* like a hack to you, but to me it looks like a legitimate, reasonable implementation of the "optimistic concurrency" approach -- try doing whatever, detect conflicts caused by race conditions, if one occurs, retry a bit later. Some databases systematically uses that instead of locking, and it can lead to m... |
Using Numpy arrays as lookup tables | 3,522,946 | 6 | 2010-08-19T14:47:18Z | 3,523,320 | 7 | 2010-08-19T15:22:26Z | [
"python",
"numpy"
] | I have a 2D array of Numpy data read from a .csv file. Each row represents a data point with the final column containing a a 'key' which corresponds uniquely to 'key' in another Numpy array - the 'lookup table' as it were.
What is the best (most Numpythonic) way to match up the lines in the first table with the values... | Some example data:
```
import numpy as np
lookup = np.array([[ 1. , 3.14 , 4.14 ],
[ 2. , 2.71818, 3.7 ],
[ 3. , 42. , 43. ]])
a = np.array([[ 1, 11],
[ 1, 12],
[ 2, 21],
[ 3, 31]])
```
Build a di... |
Add another tuple to a tuple of tuples | 3,523,048 | 23 | 2010-08-19T14:56:28Z | 3,523,128 | 26 | 2010-08-19T15:04:02Z | [
"python",
"tuples"
] | I have the following list of tuple:
```
my_choices=(
('1','first choice'),
('2','second choice'),
('3','third choice')
)
```
and I want to add another tuple to the start of it
```
another_choice = ('0', 'zero choice')
```
How can I do this?
the result would be:
```
final_choices=(
... | Build another tuple-of-tuples out of `another_choice`, then concatenate:
```
final_choices = (another_choice,) + my_choices
```
Alternately, consider making `my_choices` a list-of-tuples instead of a tuple-of-tuples by using square brackets instead of parenthesis:
```
my_choices=[
('1','first choice'),
('2... |
Python string.replace() not replacing characters | 3,523,054 | 9 | 2010-08-19T14:57:17Z | 3,523,101 | 21 | 2010-08-19T15:01:33Z | [
"python",
"string",
"str-replace"
] | Some background information: We have an ancient web-based document database system where I work, almost entirely consisting of MS Office documents with the "normal" extensions (.doc, .xls, .ppt). They are all named based on some sort of arbitrary ID number (i.e. 1245.doc). We're switching to SharePoint and I need to re... | That's because `filename` and `foldername` get thrown away with each iteration of the loop. The `.replace()` method returns a string, but you're not saving the result anywhere.
You should use:
```
filename = line[2]
foldername = line[5]
for letter in bad_characters:
filename = filename.replace(letter, "_")
f... |
raw_input in python without pressing enter | 3,523,174 | 8 | 2010-08-19T15:07:17Z | 3,523,340 | 8 | 2010-08-19T15:24:42Z | [
"python",
"user-input"
] | I'm using `raw_input` in Python to interact with user in shell.
```
c = raw_input('Press s or n to continue:')
if c.upper() == 'S':
print 'YES'
```
It works as intended, but the user has to press enter in the shell after pressing 's'. Is there a way to accomplish what I need from an user input without needing to ... | Under Windows, you need the `msvcrt` module, specifically, it seems from the way you describe your problem, the function [msvcrt.getch](http://docs.python.org/library/msvcrt.html#msvcrt.getch):
> Read a keypress and return the
> resulting character. Nothing is echoed
> to the console. This call will block
> if a keypr... |
raw_input in python without pressing enter | 3,523,174 | 8 | 2010-08-19T15:07:17Z | 3,523,389 | 7 | 2010-08-19T15:29:29Z | [
"python",
"user-input"
] | I'm using `raw_input` in Python to interact with user in shell.
```
c = raw_input('Press s or n to continue:')
if c.upper() == 'S':
print 'YES'
```
It works as intended, but the user has to press enter in the shell after pressing 's'. Is there a way to accomplish what I need from an user input without needing to ... | Python does not provide a multiplatform solution out of the box.
If you are on Windows you could try [msvcrt](http://docs.python.org/library/msvcrt.html) with:
```
import msvcrt
print 'Press s or n to continue:\n'
input_char = msvcrt.getch()
if input_char.upper() == 'S':
print 'YES'
``` |
How do I get a python module's version number through code? | 3,524,168 | 19 | 2010-08-19T16:55:32Z | 3,524,247 | 16 | 2010-08-19T17:03:27Z | [
"python"
] | I'm trying to get the version number of a specific few modules that I use. Something that I can store in a variable. | Generalized answer from Matt's, do a `dir(YOURMODULE)` and look for `__version__`, `VERSION`, or `version`. Most modules like `__version__` but I think `numpy` uses `version.version` |
How do I get a python module's version number through code? | 3,524,168 | 19 | 2010-08-19T16:55:32Z | 17,767,076 | 28 | 2013-07-20T21:54:19Z | [
"python"
] | I'm trying to get the version number of a specific few modules that I use. Something that I can store in a variable. | Use [pkg\_resources](http://packages.python.org/distribute/pkg_resources.html). Anything installed from PyPI at least have a version number.
```
>>> import pkg_resources
>>> pkg_resources.get_distribution("simplegist").version
'0.3.2'
``` |
How to handle a one line for loop without putting it in a List? | 3,524,339 | 2 | 2010-08-19T17:11:36Z | 3,525,133 | 9 | 2010-08-19T18:47:34Z | [
"python"
] | Maybe the question is a bit vague, but what I mean is this code:
```
'livestream' : [cow.legnames for cow in listofcows]
```
Now the problem is cow.legnames is also a list so I will get a list in a list when I try to return it with Json. How should I make it to return a single list.
This is the json that would be re... | In addition to shahjapan's reduce you can use this syntax to flatten list.
```
[legname for cow in listofcows for legname in cow.legnames]
``` |
Why the second time I run "readlines" in Python in the same file nothing is returned? | 3,524,528 | 2 | 2010-08-19T17:35:23Z | 3,524,543 | 9 | 2010-08-19T17:37:18Z | [
"python"
] | ```
>>> f = open('/tmp/version.txt', 'r')
>>> f
<open file '/tmp/version.txt', mode 'r' at 0xb788e2e0>
>>> f.readlines()
['2.3.4\n']
>>> f.readlines()
[]
>>>
```
I've tried this in Python's interpreter. Why does this happen? | You need to seek to the beginning of the file. Use `f.seek(0)` to return to the begining:
```
>>> f = open('/tmp/version.txt', 'r')
>>> f
<open file '/tmp/version.txt', mode 'r' at 0xb788e2e0>
>>> f.readlines()
['2.3.4\n']
>>> f.seek(0)
>>> f.readlines()
['2.3.4\n']
>>>
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.