title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
How to get week number in Python?
2,600,775
139
2010-04-08T14:35:52Z
5,245,186
11
2011-03-09T11:33:56Z
[ "python", "datetime", "week-number" ]
How to find out what week number is this year on June 16th (wk24) with Python?
Generally to get the current week number (starts from Sunday): ``` from datetime import * today = datetime.today() print today.strftime("%U") ```
How to get week number in Python?
2,600,775
139
2010-04-08T14:35:52Z
28,069,361
14
2015-01-21T14:15:32Z
[ "python", "datetime", "week-number" ]
How to find out what week number is this year on June 16th (wk24) with Python?
You can get the week number directly from datetime as string. ``` >>> import datetime >>> datetime.date(2010, 6, 16).strftime("%V") '24' ``` Also you can get diferent "types" of the week number of the year changing the strftime parameter for: > %U - week number of the current year, starting with the first Sunday > a...
How to get week number in Python?
2,600,775
139
2010-04-08T14:35:52Z
28,341,213
7
2015-02-05T10:10:56Z
[ "python", "datetime", "week-number" ]
How to find out what week number is this year on June 16th (wk24) with Python?
For the integer value of the instantaneous week of the year try: ``` import datetime datetime.datetime.utcnow().isocalendar()[1] ```
Multiple levels of 'collection.defaultdict' in Python
2,600,790
85
2010-04-08T14:37:36Z
2,600,813
182
2010-04-08T14:40:29Z
[ "python", "dictionary", "nested" ]
Thanks to some great folks on SO, I discovered the possibilities offered by `collections.defaultdict`, notably in readability and speed. I have put them to use with success. Now I would like to implement three levels of dictionaries, the two top ones being `defaultdict` and the lowest one being `int`. I don't find the...
Use: ``` d = defaultdict(lambda: defaultdict(int)) ``` This will create a new `defaultdict(int)` whenever a new key is accessed in `d`.
Multiple levels of 'collection.defaultdict' in Python
2,600,790
85
2010-04-08T14:37:36Z
2,600,847
7
2010-04-08T14:44:52Z
[ "python", "dictionary", "nested" ]
Thanks to some great folks on SO, I discovered the possibilities offered by `collections.defaultdict`, notably in readability and speed. I have put them to use with success. Now I would like to implement three levels of dictionaries, the two top ones being `defaultdict` and the lowest one being `int`. I don't find the...
Look at nosklo's answer [here](http://stackoverflow.com/questions/651794/whats-the-best-way-to-initialize-a-dict-of-dicts-in-python) for a more general solution. > ``` > class AutoVivification(dict): > """Implementation of perl's autovivification feature.""" > def __getitem__(self, item): > try: > ...
Multiple levels of 'collection.defaultdict' in Python
2,600,790
85
2010-04-08T14:37:36Z
26,390,172
7
2014-10-15T19:06:59Z
[ "python", "dictionary", "nested" ]
Thanks to some great folks on SO, I discovered the possibilities offered by `collections.defaultdict`, notably in readability and speed. I have put them to use with success. Now I would like to implement three levels of dictionaries, the two top ones being `defaultdict` and the lowest one being `int`. I don't find the...
Another way to make a pickleable, nested defaultdict is to use a partial object instead of a lambda: ``` from functools import partial ... d = defaultdict(partial(defaultdict, int)) ``` This will work because the defaultdict class is globally accessible at the module level: > "You can't pickle a partial object unles...
Import a python module without the .py extension
2,601,047
30
2010-04-08T15:11:21Z
2,601,083
23
2010-04-08T15:15:57Z
[ "python", "import" ]
I have a file called foobar (without .py extension). In the same directory I have another python file that tries to import it: ``` import foobar ``` But this only works if I rename the file to foobar.py. Is it possible to import a python module that doesn't have the .py extension? Update: the file has no extension b...
You can use the `imp.load_source` function (from the `imp` module), to load a module dynamically from a given file-system path. ``` foobar = imp.load_source('foobar', '/path/to/foobar') ``` This [SO discussion](http://stackoverflow.com/questions/301134/dynamic-module-import-in-python) also shows some interesting opti...
Import a python module without the .py extension
2,601,047
30
2010-04-08T15:11:21Z
2,601,102
12
2010-04-08T15:18:18Z
[ "python", "import" ]
I have a file called foobar (without .py extension). In the same directory I have another python file that tries to import it: ``` import foobar ``` But this only works if I rename the file to foobar.py. Is it possible to import a python module that doesn't have the .py extension? Update: the file has no extension b...
`imp.load_source(module_name, path)` should do or you can do the more verbose `imp.load_module(module_name, file_handle, ...)` route if you have a file handle instead
Import a python module without the .py extension
2,601,047
30
2010-04-08T15:11:21Z
2,601,767
12
2010-04-08T16:40:45Z
[ "python", "import" ]
I have a file called foobar (without .py extension). In the same directory I have another python file that tries to import it: ``` import foobar ``` But this only works if I rename the file to foobar.py. Is it possible to import a python module that doesn't have the .py extension? Update: the file has no extension b...
Like others have mentioned, you could use imp.load\_source, but it will make your code more difficult to read. I would really only recommend it if you need to import modules whose names or paths aren't known until run-time. What is your reason for not wanting to use the .py extension? The most common case for not want...
Displaying a webcam feed using OpenCV and Python
2,601,194
47
2010-04-08T15:30:14Z
2,602,410
41
2010-04-08T18:22:33Z
[ "python", "opencv", "webcam" ]
I have been trying to create a simple program with [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29) which uses OpenCV to get a video feed from my webcam and display it on the screen. I know I am partly there because the window is created and the light on my webcam flicks on, but it just doesn't...
Try adding the line `c = cv.WaitKey(10)` at the bottom of your `repeat()` method. This waits for 10 ms for the user to enter a key. Even if you're not using the key at all, put this in. I think there just needed to be some delay, so `time.sleep(10)` may also work. In regards to the camera index, you could do somethin...
Displaying a webcam feed using OpenCV and Python
2,601,194
47
2010-04-08T15:30:14Z
9,816,454
7
2012-03-22T04:29:28Z
[ "python", "opencv", "webcam" ]
I have been trying to create a simple program with [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29) which uses OpenCV to get a video feed from my webcam and display it on the screen. I know I am partly there because the window is created and the light on my webcam flicks on, but it just doesn't...
If you only have one camera, or you don't care which camera is the correct one, then use "-1" as the index. Ie for your example `capture = cv.CaptureFromCAM(-1)`.
Displaying a webcam feed using OpenCV and Python
2,601,194
47
2010-04-08T15:30:14Z
11,449,901
57
2012-07-12T10:28:07Z
[ "python", "opencv", "webcam" ]
I have been trying to create a simple program with [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29) which uses OpenCV to get a video feed from my webcam and display it on the screen. I know I am partly there because the window is created and the light on my webcam flicks on, but it just doesn't...
An update to show how to do it in the recent versions of OpenCV: ``` import cv2 cv2.namedWindow("preview") vc = cv2.VideoCapture(0) if vc.isOpened(): # try to get the first frame rval, frame = vc.read() else: rval = False while rval: cv2.imshow("preview", frame) rval, frame = vc.read() key = cv2...
Django-Registration & Django-Profile, using your own custom form
2,601,487
29
2010-04-08T16:05:30Z
2,687,377
28
2010-04-22T00:03:59Z
[ "python", "django", "django-forms", "registration", "profile" ]
I am making use of django-registration and django-profile to handle registration and profiles. I would like to create a profile for the user at the time of registration. I have created a custom registration form, and added that to the urls.py using the tutorial on: <http://dewful.com/?p=70> The basic idea in the tuto...
You're halfway there - you've successfully built a custom form that replaces the default form. But you're attempting to do your custom processing with a save() method on your model form. That was possible in older versions of django-registration, but I can see from the fact that you specified a backend in your URL conf...
Django-Registration & Django-Profile, using your own custom form
2,601,487
29
2010-04-08T16:05:30Z
2,947,546
8
2010-06-01T05:59:03Z
[ "python", "django", "django-forms", "registration", "profile" ]
I am making use of django-registration and django-profile to handle registration and profiles. I would like to create a profile for the user at the time of registration. I have created a custom registration form, and added that to the urls.py using the tutorial on: <http://dewful.com/?p=70> The basic idea in the tuto...
[Solution with signals](http://dmitko.ru/?p=546) - here I wrote how to use signals to save additional data
Django-Registration & Django-Profile, using your own custom form
2,601,487
29
2010-04-08T16:05:30Z
3,298,481
10
2010-07-21T11:01:22Z
[ "python", "django", "django-forms", "registration", "profile" ]
I am making use of django-registration and django-profile to handle registration and profiles. I would like to create a profile for the user at the time of registration. I have created a custom registration form, and added that to the urls.py using the tutorial on: <http://dewful.com/?p=70> The basic idea in the tuto...
As described in [my comment on Django Trac ticket](http://code.djangoproject.com/ticket/7018#comment:9) I made a metaclass and mixin to allow multiple inheritance for `ModelForm` Django forms. With this you can simply make a form which allows registration with fields from user and profile models at the same time withou...
Is it possible for BeautifulSoup to work in a case-insensitive manner?
2,602,390
12
2010-04-08T18:18:24Z
2,602,432
11
2010-04-08T18:26:22Z
[ "python", "beautifulsoup" ]
I am trying to extract Meta Description for fetched webpages. But here I am facing the problem of case sensitivity of BeautifulSoup. As some of the pages have `<meta name="Description` and some have `<meta name="description`. My problem is very much similar to that of [Question on Stackoverflow](http://stackoverflow....
You can give BeautifulSoup a regular expression to match attributes against. Something like ``` soup.findAll('meta', name=re.compile("^description$", re.I)) ``` might do the trick. Cribbed from [the BeautifulSoup docs](http://www.crummy.com/software/BeautifulSoup/documentation.html#Searching%20the%20Parse%20Tree).
Is it possible for BeautifulSoup to work in a case-insensitive manner?
2,602,390
12
2010-04-08T18:18:24Z
2,605,635
7
2010-04-09T07:03:55Z
[ "python", "beautifulsoup" ]
I am trying to extract Meta Description for fetched webpages. But here I am facing the problem of case sensitivity of BeautifulSoup. As some of the pages have `<meta name="Description` and some have `<meta name="description`. My problem is very much similar to that of [Question on Stackoverflow](http://stackoverflow....
With minor changes it works. ``` soup.findAll('meta', attrs={'name':re.compile("^description$", re.I)}) ```
Update Tkinter Label from variable
2,603,169
7
2010-04-08T20:22:12Z
2,603,371
13
2010-04-08T20:50:56Z
[ "python", "label", "tkinter" ]
I wrote a Python script that does some task to generate, and then keep changing some text stored as a string variable. This works, and I can print the string each time it gets changed. I can get the Label to display the string for the first time, but it never updates. Here's my code: ``` from tkinter import * outpu...
The window is only displayed once the mainloop is entered. So you won't see any changes you make in your `while True` block preceding the line `root.mainloop()`. --- GUI interfaces work by reacting to events while in the mainloop. Here's an example where the StringVar is also connected to an Entry widget. When you ch...
IPython tab completion not working
2,603,798
53
2010-04-08T22:10:14Z
2,603,811
69
2010-04-08T22:14:41Z
[ "python", "ipython", "tab-completion" ]
Tab completion on IPython seems not to be working. For example, ``` import numpy numpy.<tab> ``` simply adds a tab. ``` import numpy num<tab> ``` just adds a tab, too. Could you please suggest some possible causes for this problem? I am running Windows 7 and Python 2.6.5.
Be sure you have installed the pyreadline library It is needed for Tab completion and other ipython functions. In windows it doesnt come with the ipython package and you have to install it separately. you can get it from <https://launchpad.net/pyreadline> Edit 2015: Just to update this answer, this is to confirm what ...
IPython tab completion not working
2,603,798
53
2010-04-08T22:10:14Z
8,057,327
10
2011-11-08T21:31:27Z
[ "python", "ipython", "tab-completion" ]
Tab completion on IPython seems not to be working. For example, ``` import numpy numpy.<tab> ``` simply adds a tab. ``` import numpy num<tab> ``` just adds a tab, too. Could you please suggest some possible causes for this problem? I am running Windows 7 and Python 2.6.5.
Your ipythonrc file may be out of date. Try running ``` ipython -upgrade ```
Can we have assignment in a condition?
2,603,956
19
2010-04-08T22:45:49Z
2,603,966
42
2010-04-08T22:47:47Z
[ "python" ]
Is it possible to have assignment in a condition? For ex. ``` if (a=some_func()): # Use a ```
Why not try it out? ``` >>> def some_func(): ... return 2 ... >>> a = 2 >>> if (a = some_func()): File "<stdin>", line 1 if (a = some_func()): ^ SyntaxError: invalid syntax >>> ``` So, no.
Can we have assignment in a condition?
2,603,956
19
2010-04-08T22:45:49Z
2,604,036
7
2010-04-08T23:02:58Z
[ "python" ]
Is it possible to have assignment in a condition? For ex. ``` if (a=some_func()): # Use a ```
<http://docs.python.org/tutorial/datastructures.html> > Note that in Python, unlike C, > assignment cannot occur inside > expressions. C programmers may grumble > about this, but it avoids a common > class of problems encountered in C > programs: typing = in an expression > when == was intended. also see: <http://ef...
Can we have assignment in a condition?
2,603,956
19
2010-04-08T22:45:49Z
2,604,121
23
2010-04-08T23:26:14Z
[ "python" ]
Is it possible to have assignment in a condition? For ex. ``` if (a=some_func()): # Use a ```
Nope, the BDFL didn't like that feature. From where I sit, Guido van Rossum, "Benevolent Dictator For Life”, has fought hard to keep Python as simple as it can be. We can quibble with some of the decisions he's made -- I'd have preferred he said 'No' more often. But the fact that there hasn't been a committee design...
Why does easy_install extract some python eggs and not others?
2,604,600
13
2010-04-09T01:45:33Z
2,604,694
24
2010-04-09T02:09:08Z
[ "python", "egg" ]
Looking in my /usr/local/lib/python.../dist-package directory, I have `.egg` directories and `.egg` files. Why does the installer choose to extra packages to the `.egg` directory, yet leave other files with `.egg` extensions?
If the package contains only pure-Python code, it can stay as just an egg file. The Python interpreter can load the Python modules directly from the egg. If the package contains modules written in C or other data, then egg needs to be extracted so the C modules and/or data can be accessed. That's the default behavior o...
Website stress test in Python - Django
2,604,747
10
2010-04-09T02:26:27Z
2,604,755
8
2010-04-09T02:30:20Z
[ "python", "django", "http", "testing", "load" ]
I'm trying to build a small stress test script to test how quickly a set of requests gets done. Need to measure speed for 100 requests. Problem is that I wouldn't know how to implement it, as it would require parallel url requests to be called. Any ideas?
Why build it? There are several available. 1. For a single url and many requests try [ab](http://httpd.apache.org/docs/2.0/programs/ab.html) 2. For multiple urls and random tests try [siege](http://freshmeat.net/projects/siege/)
Website stress test in Python - Django
2,604,747
10
2010-04-09T02:26:27Z
2,606,022
11
2010-04-09T08:39:52Z
[ "python", "django", "http", "testing", "load" ]
I'm trying to build a small stress test script to test how quickly a set of requests gets done. Need to measure speed for 100 requests. Problem is that I wouldn't know how to implement it, as it would require parallel url requests to be called. Any ideas?
If you want to stay within the Python framework you might try Corey Goldberg's [Pylot](http://www.pylot.org/) or its successor [multi-mechanize](http://testutils.org/multi-mechanize/).
Website stress test in Python - Django
2,604,747
10
2010-04-09T02:26:27Z
16,429,317
14
2013-05-07T22:04:24Z
[ "python", "django", "http", "testing", "load" ]
I'm trying to build a small stress test script to test how quickly a set of requests gets done. Need to measure speed for 100 requests. Problem is that I wouldn't know how to implement it, as it would require parallel url requests to be called. Any ideas?
Also, there is an awesome open-source pure-python distributed and scaleable [locust](http://locust.io/) framework that uses [greenlets](http://greenlet.readthedocs.org/en/latest/). It's great at simulating enormous amount of simultaneous users.
ImportError: No Module named simplejson
2,604,841
31
2010-04-09T02:53:52Z
2,604,855
75
2010-04-09T02:58:20Z
[ "python", "unix" ]
I'm trying to run a command to install bespinclient on my Windows laptop but every time I execute the command `python bootstrap.py --no-site-packages`, I get an error saying: > ImportError: No module named > simplejson I'm using Mozilla build tools to run these Linux commands.
That means you must install [`simplejson`](http://pypi.python.org/pypi/simplejson/). On newer versions of python, it was included by default into python's distribution, and renamed to `json`. So if you are on python 2.6+ you should change all instances of `simplejson` to `json`. For a quick fix you could also edit the...
ImportError: No Module named simplejson
2,604,841
31
2010-04-09T02:53:52Z
2,605,098
8
2010-04-09T04:34:21Z
[ "python", "unix" ]
I'm trying to run a command to install bespinclient on my Windows laptop but every time I execute the command `python bootstrap.py --no-site-packages`, I get an error saying: > ImportError: No module named > simplejson I'm using Mozilla build tools to run these Linux commands.
@noskio is correct... it just means that `simplejson` isn't found on your system and you need to install it for Python older than 2.6. one way is to use the [setuptools](http://pypi.python.org/pypi/setuptools) `easy_install` tool. with it, you can install it as easily as: `easy_install simplejson` UPDATE (Feb 2014): t...
Accessing a dictionary value by custom object value in Python?
2,604,897
6
2010-04-09T03:12:12Z
2,604,908
11
2010-04-09T03:15:46Z
[ "python", "dictionary", "object" ]
So I have a square that's made up of a series of points. At every point there is a corresponding value. What I want to do is build a dictionary like this: ``` class Point: def __init__(self, x, y): self._x = x self._y = y square = {} for x in range(0, 5): for y in range(0, 5): ...
Define [`Point.__hash__()`](http://docs.python.org/reference/datamodel.html#object.__hash__) and [`Point.__eq__()`](http://docs.python.org/reference/datamodel.html#object.__eq__) so that they can be compared properly within dicts. And while you're at it, consider defining [`Point.__repr__()`](http://docs.python.org/re...
Issue with making python program executable
2,604,917
2
2010-04-09T03:19:11Z
2,604,921
14
2010-04-09T03:20:38Z
[ "python" ]
I'm trying to make a program so that I can run it through the command line with the following format: ``` ./myProgram ``` I made it executable and put `#!/usr/bin/env python` in the header, but it's giving me the following error. ``` env: python\r: No such file or directory ``` However, when I run "python myProgram...
Your line endings are wrong. Use `dos2unix` to fix them.
Issue with making python program executable
2,604,917
2
2010-04-09T03:19:11Z
2,605,038
11
2010-04-09T04:13:02Z
[ "python" ]
I'm trying to make a program so that I can run it through the command line with the following format: ``` ./myProgram ``` I made it executable and put `#!/usr/bin/env python` in the header, but it's giving me the following error. ``` env: python\r: No such file or directory ``` However, when I run "python myProgram...
+1 on ignacio's suggestion. however, to answer the 1st part of your question more directly, each OS/system uses a different line termination character: POSIX (any Unix-flavor like Linux, \*BSD, Mac OS X, etc.) uses **`\n`** (NEWLINE) while DOS/Win uses the combo **`\r\n`** (CR/carriage return + NEWLINE) and old Mac O...
How do I do this loop in Django template?
2,604,979
2
2010-04-09T03:45:22Z
2,604,991
8
2010-04-09T03:48:39Z
[ "python", "django", "templates", "loops" ]
``` {% for d in mydata %} {{ d.title }} {% endfor %} ``` However, I would like the **first one** to be bolded. How can I use the loop to say...if the d is the first one, then bold it?
Check out <http://docs.djangoproject.com/en/dev/ref/templates/builtins/#for>. Looks like: ``` {% for d in mydata %} {% if forloop.first %} <strong>{{ d.title }}</strong> {% else %} {{ d.title }} {% endif %} {% endfor %} ```
Silence loggers and printing to screen - Python
2,605,117
4
2010-04-09T04:39:57Z
2,605,125
8
2010-04-09T04:42:20Z
[ "python", "logging", "printing", "mechanize" ]
I'm having a problem with my python script. It's printing massive amounts of data on the screen, and I would like to prevent all sorts of printing to screen. --- **Edit:** The library I'm using is **mechanize**, and it's printing a LOT of data on screen. I have set these to false with no luck! ``` br.set_debug_re...
(Based on your 2nd edit) If you don't want to disable all output, you can try to be specific to `mechanize` itself. <http://wwwsearch.sourceforge.net/mechanize/> provides a snippet, which I've modified (though I'm not sure if it will work): ``` import logging logger = logging.getLogger("mechanize") # only log really ...
How do you use scripting language (PHP, Python, etc) to improve your productivity?
2,605,274
13
2010-04-09T05:31:31Z
2,605,302
17
2010-04-09T05:39:31Z
[ "php", "python", "ruby", "perl", "scripting" ]
I'm a Delphi developer on the Windows platform, recently read the PHP tutorial at W3CSchools, it looks interesting. We all know scripting languages are very good at web site development, but I also want to utilize it to improve my productivity or get some tedious tasks done quickly, maybe some quick-and-dirty string/f...
I'll tell you how I've improved my productivity with Python on Windows. I just try to write everything in Python - every application I need, unless I know it won't scale and I'll need more efficient tools (in which case I personally use C++, but you could also use C#/Delphi). It turns out that for most (> 95%) of the ...
How do you use scripting language (PHP, Python, etc) to improve your productivity?
2,605,274
13
2010-04-09T05:31:31Z
2,605,403
10
2010-04-09T06:10:44Z
[ "php", "python", "ruby", "perl", "scripting" ]
I'm a Delphi developer on the Windows platform, recently read the PHP tutorial at W3CSchools, it looks interesting. We all know scripting languages are very good at web site development, but I also want to utilize it to improve my productivity or get some tedious tasks done quickly, maybe some quick-and-dirty string/f...
1. You can DEFINITELY help yourself by automating a lot of tasks with scripting languages. Please note: some of those "scripting" languages - like Perl - **are actually very powerful general purpose software development languages which just happen to be labeled "scripting"** because their initial niche and/or paren...
Path between two nodes
2,606,018
8
2010-04-09T08:39:18Z
2,606,671
12
2010-04-09T10:34:06Z
[ "python", "networkx", "igraph" ]
I'm using networkx to work with graphs. I have pretty large graph (it's near 200 nodes in it) and I try to find all possible paths between two nodes. But, as I understand, networkx can find only shortest path. How can I get not just shortest path, but all possible paths? UPD: path can contain each node only once. UPD...
[igraph](http://packages.python.org/pypi/python-igraph), another graph module for Python can calculate all the *shortest* paths between a given pair of nodes. Calculating all the paths does not make sense as you have infinitely many such paths. An example for calculating all the shortest paths from vertex 0: ``` >>> ...
Path between two nodes
2,606,018
8
2010-04-09T08:39:18Z
5,683,508
10
2011-04-16T00:05:14Z
[ "python", "networkx", "igraph" ]
I'm using networkx to work with graphs. I have pretty large graph (it's near 200 nodes in it) and I try to find all possible paths between two nodes. But, as I understand, networkx can find only shortest path. How can I get not just shortest path, but all possible paths? UPD: path can contain each node only once. UPD...
This one actually works with networkx, and it's non-recursive, which may be nice for large graphs. ``` def find_all_paths(graph, start, end): path = [] paths = [] queue = [(start, end, path)] while queue: start, end, path = queue.pop() print 'PATH', path path = path + [start] ...
How to replace empty string with zero in comma-separated string?
2,606,976
4
2010-04-09T11:29:06Z
2,607,026
8
2010-04-09T11:37:40Z
[ "python", "string" ]
"8,5,,1,4,7,,,,7,,1,9,3,6,,,8,6,3,9,,2,5,4,,,,,3,2,,,7,4,1,1,,4,,6,9,,5,,,,5,,,1,,6,3,,,6,5,,,,7,4,,1,7,6,,,,8,,5,,,7,1,,3,9," I'm doing a programming challenge where i need to parse this sequence into my sudoku script. Need to get the above sequence into 8,5,0,1,4,7,0,0,0,7,0,1,9,3,6,0,0,8......... I tried re but wit...
You could use ``` [(int(x) if x else 0) for x in data.split(',')] ``` `data.split(',')` splits the string into a list. It splits on the comma character: ``` ['8', '5', '', '1', '4', '7', '', '', '', ...] ``` The expression ``` (int(x) if x else 0) ``` returns `int(x)` if `x` is True, 0 if `x` is False. Note that ...
How do I find out if the variable is declared in Python?
2,607,037
3
2010-04-09T11:40:15Z
2,607,060
7
2010-04-09T11:44:02Z
[ "python", "variables", "singleton", "declaration" ]
I want to use a module as a singleton referenced in other modules. It looks something like this (that's not actually a code I'm working on, but I simplified it to throw away all unrelated stuff): main.py ``` import singleton import printer def main(): singleton.Init(1,2) printer.Print() if __name__ == '__main...
The assignment inside `Init` is forcing the variables to be treated as locals. Use the `global` keyword to fix this: ``` variable1 = '' variable2 = '' def Init(var1, var2) global variable1, variable2 variable1 = var1 variable2 = var2 ```
tmpfile and gzip combination problem
2,607,206
7
2010-04-09T12:08:01Z
2,607,239
8
2010-04-09T12:14:02Z
[ "python", "gzip", "base64" ]
I have problem with this code: ``` file = tempfile.TemporaryFile(mode='wrb') file.write(base64.b64decode(data)) file.flush() os.fsync(file) # file.seek(0) f = gzip.GzipFile(mode='rb', fileobj=file) print f.read() ``` I dont know why it doesn't print out anything. If I uncomment file.seek then error occurs: ``` Fil...
`'wrb'` is not a valid mode. This works fine: ``` import tempfile import gzip with tempfile.TemporaryFile(mode='w+b') as f: f.write(data.decode('base64')) f.flush() f.seek(0) gzf = gzip.GzipFile(mode='rb', fileobj=f) print gzf.read() ```
Django syncdb error: One or more models did not validate
2,608,017
6
2010-04-09T13:55:54Z
2,608,064
8
2010-04-09T14:00:58Z
[ "python", "django", "django-models", "django-views" ]
/mysite/project4 ``` class notes(models.Model): created_by = models.ForeignKey(User) detail = models.ForeignKey(Details) ``` Details and User are in the same module i.e,/mysite/project1 In project1 models i have defined ``` class User(): ...... class Details(): ...... ``` When DB i synced ...
Gee we just had this one; and I answered... You have a number of foreign keys which django is unable to generate unique names for. You can help out by adding "related\_name" arguments to the foreignkey field definitions in your models. Eg: ``` class notes(models.Model): created_by = models.ForeignKey(User, rela...
How to find out whether a model's column is a foreign key?
2,608,067
7
2010-04-09T14:01:03Z
2,608,180
10
2010-04-09T14:16:49Z
[ "python", "django", "foreign-keys" ]
I'm dynamically storing information in the database depending on the request: ``` // table, id and column are provided by the request table_obj = getattr(models, table) record = table_obj.objects.get(pk=id) setattr(record, column, request.POST['value']) ``` The problem is that request.POST['value'] sometimes contain...
You can use get\_field\_by\_name on the models \_meta object: ``` from django.db.models import ForeignKey def get_fk_model(model, fieldname): '''returns None if not foreignkey, otherswise the relevant model''' field_object, model, direct, m2m = model._meta.get_field_by_name(fieldname) if not m2m and direc...
Problems with umlauts in python appdata environvent variable
2,608,200
7
2010-04-09T14:19:24Z
2,608,368
8
2010-04-09T14:45:50Z
[ "python", "encoding", "variables", "environment", "appdata" ]
I can't find a correct way to get the environment variable for the appdata path in python. The problem is that my user name includes special characters (the german ae and ue). I made a workaround wit PyQt for Vista and Windows 7 but it doesn't work for XP Systems. Does anybody know the correct encoding of these envir...
As Mike says, you can get the system codepage from `getfilesystemencoding`. This encoding is used to convert Windows's native Unicode strings into bytes for all C stdio functions used by Python, including the filesystem calls that use byte string filepaths, and `os.environ`. What this means is that you will be able to...
Is there a way to make python become interactive in the middle of a script?
2,608,751
13
2010-04-09T15:38:28Z
2,608,800
8
2010-04-09T15:44:04Z
[ "python", "scripting", "interactive" ]
I'd like to do something like: ``` do lots of stuff to prepare a good environement become_interactive #wait for Ctrl-D automatically clean up ``` Is it possible with python?If not, do you see another way of doing the same thing?
The [`code`](http://docs.python.org/library/code.html) module will allow you to start a Python REPL.
Is there a way to make python become interactive in the middle of a script?
2,608,751
13
2010-04-09T15:38:28Z
2,609,485
10
2010-04-09T17:19:50Z
[ "python", "scripting", "interactive" ]
I'd like to do something like: ``` do lots of stuff to prepare a good environement become_interactive #wait for Ctrl-D automatically clean up ``` Is it possible with python?If not, do you see another way of doing the same thing?
Use the -i flag when you start Python and set an atexit handler to run when cleaning up. File script.py: ``` import atexit def cleanup(): print "Goodbye" atexit.register(cleanup) print "Hello" ``` and then you just start Python with the -i flag: ``` C:\temp>\python26\python -i script.py Hello >>> print "interac...
Python nested function scopes
2,609,518
9
2010-04-09T17:25:11Z
2,609,593
15
2010-04-09T17:38:47Z
[ "python", "function" ]
I have code like this: ``` def write_postcodes(self): """Write postcodes database. Write data to file pointer. Data is ordered. Initially index pages are written, grouping postcodes by the first three characters, allowing for faster searching.""" status("POSTCODE", "Preparing to sort...", 0, 1) # ...
Since the nested function can't rebind a nonlocal name (in Python 2; in Python 3, you'd use the `nonlocal` statement to enable that), you need to perform your incrementing without barename rebinding (by keeping the counter as an item or attribute of some barename, **not** as a barename itself). For example: ``` ... ct...
A better python property decorator
2,610,621
3
2010-04-09T20:17:49Z
2,610,714
8
2010-04-09T20:33:19Z
[ "python", "debugging", "properties", "decorator" ]
I've inherited some python code that contains a rather cryptic decorator. This decorator sets properties in classes all over the project. The problem is that this I have traced my debugging problems to this decorator. Seems it "fubars" all debuggers I've tried and trying to speed up the code with psyco breaks everthing...
The same thing? No. You can't do what that decorator does without magic like sys.settrace. (It technically doesn't have to be sys.settrace, but using something else -- like bytecode rewriting -- wouldn't be an improvement.) You can make it a lot simpler by doing, for example: ``` def Property(f): fget, fset, fde...
Django project models.py versus app models.py
2,610,727
10
2010-04-09T20:35:41Z
2,610,797
17
2010-04-09T20:46:12Z
[ "python", "django", "django-models" ]
I am learning Django and I am trying to understand the use of models.py in the project versus the application. It seems from the tutorial examples that I include a model definition in the app, but when I went to apply that knowledge to my own existing database I got stuck. I took a database that I use (a copy of cours...
There shouldn't be any reason to have "project level models" (or "project level views" for that matter). You just need to split the functionality into separate apps. Let's say you are designing an intranet website for a school. You would have one app that deals with students' accounts, and another app generating timet...
Making all variables accessible to namespace
2,610,931
3
2010-04-09T21:08:00Z
2,611,071
9
2010-04-09T21:31:30Z
[ "python" ]
Say I have a simple function: ``` def myfunc(): a = 4.2 b = 5.5 ... many similar variables ... ``` I use this function one time only and I am wondering what is the easiest way to make all the variables inside the function accessible to my main name-space. Do I have to declare global for each item? or any...
Best way, in my biased opinion, is to wrap the dictionary into a nice object where the "variables" are accessed as attributes -- the pattern I named [Bunch](http://code.activestate.com/recipes/52308-the-simple-but-handy-collector-of-a-bunch-of-named/?in=user-97991) when I introduced it many years ago, and a great examp...
How do I write raw binary data in Python?
2,611,205
10
2010-04-09T21:58:06Z
2,617,930
18
2010-04-11T17:23:27Z
[ "python", "codec", "string" ]
I've got a Python program that stores and writes data to a file. The data is raw binary data, stored internally as `str`. I'm writing it out through a utf-8 codec. However, I get `UnicodeDecodeError: 'charmap' codec can't decode byte 0x8d in position 25: character maps to <undefined>` in the `cp1252.py` file. This loo...
*NOTE: this was written for Python 2.x. Not sure if applicable to 3.x.* Your use of `str` for raw binary data in memory is correct. [If you're using Python 2.6+, it's even better to use `bytes` which in 2.6+ is just an alias to `str` but expresses your intention better, and will help if one day you port the code to ...
Quickest way to dump Python dictionary (dict) object to a MySQL table?
2,611,239
6
2010-04-09T22:03:22Z
2,611,547
9
2010-04-09T23:17:29Z
[ "python", "mysql", "dictionary" ]
I have a dict object. I dumped the data using this: ``` for alldata in data: # print all data to screen print data[alldata] ``` Each field had brackets [] and 'None' values for NULLS and date.datetime for date values. How do I dump this dict to MySQL table? Thank you! print data displays something like this : ...
Assuming you have [MySQLdb](http://pypi.python.org/pypi/MySQL-python) (mysql-python) installed: ``` sql = "INSERT INTO mytable (a,b,c) VALUES (%(qwe)s, %(asd)s, %(zxc)s);" data = {'qwe':1, 'asd':2, 'zxc':None} conn = MySQLdb.connect(**params) cursor = conn.cursor() cursor.execute(sql, data) cursor.close() conn.clos...
working on lists in python
2,611,307
2
2010-04-09T22:16:12Z
2,611,351
8
2010-04-09T22:24:52Z
[ "python", "django", "django-models" ]
'm trying to make a small modification to django lfs project, that will allow me to deactivate products with no stocks. Unfortunatelly I'm just beginning to learn python, so I have big trouble with its syntax. That's what I'm trying to do. I'm using method 'is\_variant' returning tru if my product is a sub type. If it ...
First, I wouldn't call the list `set`, because this is a Python built-in method (see [`set`](http://docs.python.org/tutorial/datastructures.html#sets)). Use `append` on the list (your syntax is just incorrect and the error you get explicitly tells you so ;) ) and you have to initialize the list before: ``` def deactiv...
struct.error: unpack requires a string argument of length 4
2,611,858
12
2010-04-10T01:12:20Z
2,612,851
14
2010-04-10T09:14:07Z
[ "python", "struct" ]
Python says I need 4 bytes for a format code of "BH": ``` struct.error: unpack requires a string argument of length 4 ``` Here is the code, I am putting in 3 bytes as I think is needed: ``` major, minor = struct.unpack("BH", self.fp.read(3)) ``` "B" Unsigned char (1 byte) + "H" Unsigned short (2 bytes) = 3 bytes (!...
The struct module mimics C structures. It takes more CPU cycles for a processor to read a 16-bit word on an odd address or a 32-bit dword on an address not divisible by 4, so structures add "pad bytes" to make structure members fall on natural boundaries. Consider: ``` struct { 11 char a; 01...
Rationale behind Python's preferred for syntax
2,611,867
11
2010-04-10T01:16:17Z
2,611,876
11
2010-04-10T01:21:06Z
[ "python", "performance" ]
What is the rationale behind the advocated use of the `for i in xrange(...)`-style looping constructs in Python? For simple integer looping, the difference in overheads is substantial. I conducted a simple test using two pieces of code: File `idiomatic.py`: ``` #!/usr/bin/env python M = 10000 N = 10000 if __name__ ...
You forgot to reset y to 0 after the inner loop. ``` #!/usr/bin/env python M = 10000 N = 10000 if __name__ == "__main__": x, y = 0, 0 while x < N: while y < M: y += 1 x += 1 y = 0 ``` ed: 20.63s after fix vs. 6.97s using xrange
Rationale behind Python's preferred for syntax
2,611,867
11
2010-04-10T01:16:17Z
2,611,917
22
2010-04-10T01:47:05Z
[ "python", "performance" ]
What is the rationale behind the advocated use of the `for i in xrange(...)`-style looping constructs in Python? For simple integer looping, the difference in overheads is substantial. I conducted a simple test using two pieces of code: File `idiomatic.py`: ``` #!/usr/bin/env python M = 10000 N = 10000 if __name__ ...
Here's the proper comparison, e.g. in loop.py: ``` M = 10000 N = 10000 def thegoodone(): for x in xrange(N): for y in xrange(M): pass def thebadone(): x = 0 while x < N: y = 0 while y < M: y += 1 x += 1 ``` All substantial code should **always** be in...
get python class parent(s)
2,611,892
97
2010-04-10T01:32:20Z
2,611,897
113
2010-04-10T01:35:02Z
[ "python", "oop" ]
How can I get the parent(s) object of python class?
Use the following attribute: ``` cls.__bases__ ``` From the [docs](http://docs.python.org/library/stdtypes.html#class.__bases__): > The tuple of base classes of a class > object. Example: ``` >>> str.__bases__ (<type 'basestring'>,) ``` Another example: ``` >>> class A(object): ... pass ... >>> class B(object...
get python class parent(s)
2,611,892
97
2010-04-10T01:32:20Z
2,611,939
55
2010-04-10T02:00:17Z
[ "python", "oop" ]
How can I get the parent(s) object of python class?
If you want all the *ancestors* rather than just the immediate ones, use [inspect.getmro](http://docs.python.org/library/inspect.html?highlight=getmro#inspect.getmro): ``` import inspect print inspect.getmro(cls) ``` Usefully, this gives you all ancestor classes in the "method resolution order" -- i.e. the order in w...
get python class parent(s)
2,611,892
97
2010-04-10T01:32:20Z
2,612,192
8
2010-04-10T03:56:04Z
[ "python", "oop" ]
How can I get the parent(s) object of python class?
New-style classes have an mro method you can call which returns a list of parent classes in method resolution order.
Python: Is there a way to reflectivly list all attributes of a class
2,612,257
4
2010-04-10T04:36:30Z
2,612,264
7
2010-04-10T04:39:11Z
[ "python", "reflection", "swig" ]
Given a class such as ``` class MyClass: text = "hello" number = 123 ``` Is there a way in python to inspect MyClass an determine that it has the two attributes `text` and `number`. I can not use something like `inspect.getSource(object)` because the class I am to get it's attributes for are generate using SW...
I usually just use `dir(MyClass)`. Works on instantiated objects too. **edit:** I should mention this is a shorthand function I use for figuring out if my objects are getting created correctly. You might want to look more carefully into the reflection API's if you're doing this programmatically. Also it may not work ...
convert RGB values to equivalent HSV values using python
2,612,361
3
2010-04-10T05:24:04Z
2,612,377
13
2010-04-10T05:30:56Z
[ "python", "image-processing" ]
I want to convert RGB values to HSV using python. I got some code samples, which gave the result with the S and V values greater than 100. (example : <http://code.activestate.com/recipes/576554-covert-color-space-from-hsv-to-rgb-and-rgb-to-hsv/> ) . anybody got a better code which convert RGB to HSV and vice versa tha...
Did you try using the [colorsys](http://docs.python.org/library/colorsys.html) library? > The colorsys module defines > bidirectional conversions of color > values between colors expressed in the > RGB (Red Green Blue) color space used > in computer monitors and three other > coordinate systems: YIQ, HLS (Hue > Lightn...
Create thumbnail images for jpegs with python
2,612,436
5
2010-04-10T06:06:58Z
2,612,451
15
2010-04-10T06:12:31Z
[ "python", "image-processing" ]
As the title says i am looking for a way convert a huge number of images into thumbnails of different sizes , How do i go about doing this in python
See: <http://www.pythonware.com/products/pil/index.htm> ``` import os, sys import Image size = 128, 128 for infile in sys.argv[1:]: outfile = os.path.splitext(infile)[0] + ".thumbnail" if infile != outfile: try: im = Image.open(infile) im.thumbnail(size) im.save(ou...
Extracting an attribute value with beautifulsoup
2,612,548
33
2010-04-10T06:53:01Z
2,612,577
52
2010-04-10T07:06:28Z
[ "python", "parsing", "attributes", "beautifulsoup" ]
I am trying to extract the content of a single "value" attribute in a specific "input" tag on a webpage. I use the following code: ``` import urllib f = urllib.urlopen("http://58.68.130.147") s = f.read() f.close() from BeautifulSoup import BeautifulStoneSoup soup = BeautifulStoneSoup(s) inputTag = soup.findAll(attr...
`.findAll()` returns list of all found elements, so: ``` inputTag = soup.findAll(attrs={"name" : "stainfo"}) ``` `inputTag` is a list (probably containing only one element). Depending on what you want exactly you either should do: ``` output = inputTag[0]['value'] ``` or use `.find()` method which returns only one...
How to access object attribute given string corresponding to name of that attribute
2,612,610
35
2010-04-10T07:22:52Z
2,612,615
89
2010-04-10T07:25:08Z
[ "python", "object", "attributes" ]
How do you set/get the values of attributes of `t` given by `x`. ``` class test(): attr1 = int attr2 = int t = test() x = "attr1" ```
There is built-in functions called [`getattr`](https://docs.python.org/2/library/functions.html#getattr) and [`setattr`](https://docs.python.org/2/library/functions.html#setattr) ``` getattr(object, attrname) setattr(object, attrname, value) ``` In this case ``` x = getattr(t, "attr1") setattr(t, 'attr1', 21) ```
how to do bitwise exclusive or of two strings in python?
2,612,720
27
2010-04-10T08:15:14Z
2,612,730
38
2010-04-10T08:18:55Z
[ "python", "string", "bitwise-operators" ]
I would like to perform a bitwise exclusive or of two strings in python, but xor of strings are not allowed in python. How can I do it ?
You can convert the characters to integers and xor those instead: ``` l = [ord(a) ^ ord(b) for a,b in zip(s1,s2)] ``` Here's an updated function in case you need a string as a result of the XOR: ``` def sxor(s1,s2): # convert strings to a list of character pair tuples # go through each tuple, converting ...
how to do bitwise exclusive or of two strings in python?
2,612,720
27
2010-04-10T08:15:14Z
2,612,877
7
2010-04-10T09:26:32Z
[ "python", "string", "bitwise-operators" ]
I would like to perform a bitwise exclusive or of two strings in python, but xor of strings are not allowed in python. How can I do it ?
Here is your string XOR'er, presumably for some mild form of encryption: ``` >>> src = "Hello, World!" >>> code = "secret" >>> xorWord = lambda ss,cc: ''.join(chr(ord(s)^ord(c)) for s,c in zip(ss,cc*100)) >>> encrypt = xorWord(src, code) >>> encrypt ';\x00\x0f\x1e\nXS2\x0c\x00\t\x10R' >>> decrypt = xorWord(encrypt,cod...
how to do bitwise exclusive or of two strings in python?
2,612,720
27
2010-04-10T08:15:14Z
2,613,148
22
2010-04-10T11:11:03Z
[ "python", "string", "bitwise-operators" ]
I would like to perform a bitwise exclusive or of two strings in python, but xor of strings are not allowed in python. How can I do it ?
If you want to operate on bytes or words then you'll be better to use Python's array type instead of a string. If you are working with fixed length blocks then you may be able to use H or L format to operate on words rather than bytes, but I just used 'B' for this example: ``` >>> import array >>> a1 = array.array('B'...
how to do bitwise exclusive or of two strings in python?
2,612,720
27
2010-04-10T08:15:14Z
15,106,386
8
2013-02-27T07:27:38Z
[ "python", "string", "bitwise-operators" ]
I would like to perform a bitwise exclusive or of two strings in python, but xor of strings are not allowed in python. How can I do it ?
For bytearrays you can directly use XOR: ``` >>> b1 = bytearray("test123") >>> b2 = bytearray("321test") >>> b = bytearray(len(b1)) >>> for i in range(len(b1)): ... b[i] = b1[i] ^ b2[i] >>> b bytearray(b'GWB\x00TAG') ```
How to clone or copy a list?
2,612,802
933
2010-04-10T08:49:46Z
2,612,808
11
2010-04-10T08:53:06Z
[ "python", "list", "copy", "clone" ]
What are the options to clone or copy a list in Python? Using `new_list = my_list` then modifies `new_list` every time `my_list` changes. Why is this?
Use `thing[:]` ``` >>> a = [1,2] >>> b = a[:] >>> a += [3] >>> a [1, 2, 3] >>> b [1, 2] >>> ```
How to clone or copy a list?
2,612,802
933
2010-04-10T08:49:46Z
2,612,810
10
2010-04-10T08:53:19Z
[ "python", "list", "copy", "clone" ]
What are the options to clone or copy a list in Python? Using `new_list = my_list` then modifies `new_list` every time `my_list` changes. Why is this?
Python's idiom for doing this is `newList = oldList[:]`
How to clone or copy a list?
2,612,802
933
2010-04-10T08:49:46Z
2,612,815
1,324
2010-04-10T08:55:21Z
[ "python", "list", "copy", "clone" ]
What are the options to clone or copy a list in Python? Using `new_list = my_list` then modifies `new_list` every time `my_list` changes. Why is this?
You have various possibilities: * You can slice it: ``` new_list = old_list[:] ``` [Alex Martelli's](https://en.wikipedia.org/wiki/Alex_Martelli) opinion (at least [back in 2007](https://www.youtube.com/watch?v=g7V89K8QfgQ)) about this is, that *it is a weird syntax and it does not make sense to use it ever*...
How to clone or copy a list?
2,612,802
933
2010-04-10T08:49:46Z
2,612,833
16
2010-04-10T09:03:03Z
[ "python", "list", "copy", "clone" ]
What are the options to clone or copy a list in Python? Using `new_list = my_list` then modifies `new_list` every time `my_list` changes. Why is this?
`new_list = list(old_list)`
How to clone or copy a list?
2,612,802
933
2010-04-10T08:49:46Z
2,612,990
273
2010-04-10T10:16:24Z
[ "python", "list", "copy", "clone" ]
What are the options to clone or copy a list in Python? Using `new_list = my_list` then modifies `new_list` every time `my_list` changes. Why is this?
Felix already provided an excellent answer, but I thought I'd do a speed comparison of the various methods: 1. 10.59 sec (105.9us/itn) - [`copy.deepcopy(old_list)`](http://docs.python.org/library/copy.html#copy.deepcopy) 2. 10.16 sec (101.6us/itn) - pure python `Copy()` method copying classes with deepcopy 3. 1.488 se...
How to clone or copy a list?
2,612,802
933
2010-04-10T08:49:46Z
17,810,305
49
2013-07-23T12:32:56Z
[ "python", "list", "copy", "clone" ]
What are the options to clone or copy a list in Python? Using `new_list = my_list` then modifies `new_list` every time `my_list` changes. Why is this?
I've [been told](http://mail.python.org/pipermail/python-ideas/2013-July/022368.html) that Python 3.3+ [adds list.copy()](http://bugs.python.org/issue10516) method, which should be as fast as slicing: `newlist = old_list.copy()`
How to clone or copy a list?
2,612,802
933
2010-04-10T08:49:46Z
26,562,235
42
2014-10-25T12:13:47Z
[ "python", "list", "copy", "clone" ]
What are the options to clone or copy a list in Python? Using `new_list = my_list` then modifies `new_list` every time `my_list` changes. Why is this?
> # What are the options to clone or copy a list in Python? There are two semantic ways to copy a list. A shallow copy creates a new list of the same objects, a deep copy creates a new list containing equivalent objects. ## Shallow list copy A shallow copy only copies the list itself, which is a container of referen...
How to clone or copy a list?
2,612,802
933
2010-04-10T08:49:46Z
27,091,494
21
2014-11-23T16:45:30Z
[ "python", "list", "copy", "clone" ]
What are the options to clone or copy a list in Python? Using `new_list = my_list` then modifies `new_list` every time `my_list` changes. Why is this?
There are many answers already that tell you how to make a proper copy, but none of them say why your original 'copy' failed. Python doesn't store values in variables; it binds names to objects. Your original assignment took the object referred to by `my_list` and bound it to `new_list` as well. No matter which name y...
How to clone or copy a list?
2,612,802
933
2010-04-10T08:49:46Z
31,332,158
9
2015-07-10T03:51:13Z
[ "python", "list", "copy", "clone" ]
What are the options to clone or copy a list in Python? Using `new_list = my_list` then modifies `new_list` every time `my_list` changes. Why is this?
All of the other contributors gave **great** answers, which work when you have a single dimension (leveled) list, however of the methods mentioned so far, only `copy.deepcopy()` works to clone/copy a list and not have it point to the nested `list` objects when you are working with multidimensional, nested lists (list o...
Python regex look-behind requires fixed-width pattern
2,613,237
8
2010-04-10T11:43:12Z
2,613,246
9
2010-04-10T11:47:16Z
[ "python", "html", "regex" ]
When trying to extract the title of a html-page I have always used the following regex: ``` (?<=<title.*>)([\s\S]*)(?=</title>) ``` Which will extract everything between the tags in a document and ignore the tags themselves. However, when trying to use this regex in Python it raises the following Exception: ``` Trac...
Toss out the idea of parsing HTML with regular expressions and use an actual HTML parsing library instead. After a quick search I found [this one](http://docs.python.org/library/htmlparser.html). It's a much safer way to extract information from an HTML file. Remember, HTML is not a regular language so regular express...
beautifulsoup: find the n-th element's sibling
2,613,527
8
2010-04-10T13:25:29Z
2,613,587
8
2010-04-10T13:44:50Z
[ "python", "find", "beautifulsoup", "siblings" ]
I have a complex html DOM tree of the following nature: ``` <table> ... <tr> <td> ... </td> <td> <table> <tr> <td> <!-- inner most table --> <table> .....
If `tag` is the innermost table, then ``` tag.findNextSibling('h2') ``` will be ``` <h2>This is hell!</h2> ``` To literally get the next sibling, you could use `tag.nextSibling`, which in this case, is `u'\n'`. If you want the next sibling that is not a NavigableString (such as `u'\n'`), then you could use ``` ta...
Sqlite / SQLAlchemy: how to enforce Foreign Keys?
2,614,984
22
2010-04-10T21:07:15Z
2,615,603
11
2010-04-11T00:36:05Z
[ "python", "sqlite", "foreign-keys", "sqlalchemy" ]
The new version of SQLite has the ability to enforce Foreign Key constraints, but for the sake of backwards-compatibility, you have to turn it on for each database connection separately! ``` sqlite> PRAGMA foreign_keys = ON; ``` I am using SQLAlchemy -- how can I make sure this always gets turned on? What I have trie...
I now have this working: Download the latest sqlite and pysqlite2 builds as described above: make sure correct versions are being used at runtime by python. ``` import sqlite3 import pysqlite2 print sqlite3.sqlite_version # should be 3.6.23.1 print pysqlite2.__path__ # eg C:\\Python26\\lib\\site-packages\...
Sqlite / SQLAlchemy: how to enforce Foreign Keys?
2,614,984
22
2010-04-10T21:07:15Z
7,831,210
31
2011-10-20T04:36:06Z
[ "python", "sqlite", "foreign-keys", "sqlalchemy" ]
The new version of SQLite has the ability to enforce Foreign Key constraints, but for the sake of backwards-compatibility, you have to turn it on for each database connection separately! ``` sqlite> PRAGMA foreign_keys = ON; ``` I am using SQLAlchemy -- how can I make sure this always gets turned on? What I have trie...
For recent versions (SQLAlchemy ~0.7) the [SQLAlchemy homepage](http://www.sqlalchemy.org/docs/core/interfaces.html?highlight=poollistener#sqlalchemy.interfaces.PoolListener) says: > PoolListener is deprecated. Please refer to [PoolEvents](http://www.sqlalchemy.org/docs/core/events.html#sqlalchemy.events.PoolEvents). ...
Sqlite / SQLAlchemy: how to enforce Foreign Keys?
2,614,984
22
2010-04-10T21:07:15Z
15,542,046
16
2013-03-21T07:51:48Z
[ "python", "sqlite", "foreign-keys", "sqlalchemy" ]
The new version of SQLite has the ability to enforce Foreign Key constraints, but for the sake of backwards-compatibility, you have to turn it on for each database connection separately! ``` sqlite> PRAGMA foreign_keys = ON; ``` I am using SQLAlchemy -- how can I make sure this always gets turned on? What I have trie...
Building on the answers from conny and shadowmatter, here's code that will check if you are using SQLite3 before emitting the PRAGMA statement: ``` from sqlalchemy import event from sqlalchemy.engine import Engine from sqlite3 import Connection as SQLite3Connection @event.listens_for(Engine, "connect") def _set_sqlit...
How do I use Logging in the Django Debug Toolbar?
2,615,042
36
2010-04-10T21:24:29Z
2,615,120
43
2010-04-10T21:44:17Z
[ "python", "django", "debugging", "django-views" ]
I would like to output debug messages in my django app at different points in a view function. The docs for the [django-debug-toolbar](http://github.com/robhudson/django-debug-toolbar) say it uses the build in python logging but I can't find any more information then that. I don't really want to log to a file but to th...
You just use the [logging module](http://docs.python.org/library/logging.html) methods and DjDT will intercept and display them in the Logging Panel. ``` import logging logging.debug('Debug Message') if some_error: logging.error('Error Message') ```
Profiling python C extensions
2,615,153
28
2010-04-10T21:54:21Z
2,625,366
14
2010-04-12T20:53:26Z
[ "python", "c", "profiling" ]
I have developed a python C-extension that receives data from python and compute some cpu intensive calculations. It's possible to profile the C-extension? The problem here is that writing a sample test in C to be profiled would be challenging because the code rely on particular inputs and data structures (generated b...
I've found my way using [google-perftools](http://code.google.com/p/google-perftools/). The trick was to wrap the functions StartProfiler and StopProfiler in python (throught cython in my case). To profile the C extension is sufficient to wrap the python code inside the StartProfiler and StopProfiler calls. ``` from ...
Profiling python C extensions
2,615,153
28
2010-04-10T21:54:21Z
5,197,099
18
2011-03-04T17:24:09Z
[ "python", "c", "profiling" ]
I have developed a python C-extension that receives data from python and compute some cpu intensive calculations. It's possible to profile the C-extension? The problem here is that writing a sample test in C to be profiled would be challenging because the code rely on particular inputs and data structures (generated b...
After the comment by pygabriel I decided to upload a package to pypi that implements a profiler for python extensions using the cpu-profiler from google-perftools: <http://pypi.python.org/pypi/yep>
Python: eliminating stack traces into library code?
2,615,414
7
2010-04-10T23:28:44Z
2,615,442
10
2010-04-10T23:37:50Z
[ "python" ]
When I get a runtime exception from the standard library, it's almost always a problem in my code and not in the library code. Is there a way to truncate the exception stack trace so that it doesn't show the guts of the library package? For example, I would like to get this: ``` Traceback (most recent call last): F...
The [traceback](http://docs.python.org/library/traceback.html?highlight=traceback#module-traceback) module in Python's standard library lets you emit error tracebacks in a way that accords to your liking, while an exception is propagating. You can use this power either in the `except` leg of a `try`/`except` statement,...
Why can't I download a whole image file with urllib2.urlopen()
2,615,593
5
2010-04-11T00:33:13Z
2,615,609
10
2010-04-11T00:39:34Z
[ "python", "image", "download" ]
When I run the following code, it only seems to be downloading the first little bit of the file and then exiting. Occassionally, I will get a 10054 error, but usually it just exits without getting the whole file. My internet connection is crappy wireless, and I often get broken downloads on larger files in firefox, but...
To write a binary file on Windows you need to explicitly *open* it as binary, i.e.: ``` xkcdpicfile=open("C:\\Documents and Settings\\John Gann\\Desktop\\xkcd.png", "wb") ``` note the extra `b` in the options: `"wb"`, **not** just `"w"`! I would also recommend losing the `print chunk` which may send...
Storing URLs while Spidering
2,615,830
7
2010-04-11T02:19:52Z
2,615,836
7
2010-04-11T02:21:46Z
[ "python", "database", "url", "storage", "web-crawler" ]
I created a little web spider in Python which I'm using to collect URLs. I'm not interested in the content. Right now I'm keeping all the visited URLs in a set in memory, because I don't want my spider to visit URLs twice. Of course that's a very limited way of accomplishing this. So what's the best way to keep track ...
These seem to be the important aspects to me: 1. You can't keep the URLs in memory as RAM will get too high 2. You need fast existence lookups at least O(logn) 3. You need fast insertions There are many ways to do this and it depends on how big your database will get. I think an SQL database can provide a good model ...
Storing URLs while Spidering
2,615,830
7
2010-04-11T02:19:52Z
2,615,904
9
2010-04-11T03:04:29Z
[ "python", "database", "url", "storage", "web-crawler" ]
I created a little web spider in Python which I'm using to collect URLs. I'm not interested in the content. Right now I'm keeping all the visited URLs in a set in memory, because I don't want my spider to visit URLs twice. Of course that's a very limited way of accomplishing this. So what's the best way to keep track ...
I've written a lot of spiders. To me, a bigger problem than running out of memory is the potential of losing all the URLs you've spidered already if the code or machine crashes or you decide you need to tweak the code. If you run out of RAM most machines and OSes these days will page so you'll slow down but still funct...
Installing virtualenvwrapper on Windows
2,615,968
32
2010-04-11T03:42:56Z
2,616,482
10
2010-04-11T08:42:20Z
[ "python", "windows", "virtualenv", "virtualenvwrapper" ]
I've installed virtualenv and virtualenvwrapper on Windows using easy\_install. But `mkvirtualenv` is missing. I tried to search on my machine but I couldn't find it. I don't know how to solve it. Do you have any idea?
mkvirtualenv is a bash script so you need to run bash shell to make use of it. mkvirtualenv is a bash function in the mkvirtualenv\_bashrc script You will need to run this from cygwin under Windows. (You can call a native python from this and not need a cygwin python)
Installing virtualenvwrapper on Windows
2,615,968
32
2010-04-11T03:42:56Z
2,798,618
13
2010-05-09T18:13:30Z
[ "python", "windows", "virtualenv", "virtualenvwrapper" ]
I've installed virtualenv and virtualenvwrapper on Windows using easy\_install. But `mkvirtualenv` is missing. I tried to search on my machine but I couldn't find it. I don't know how to solve it. Do you have any idea?
I've ported virtualenvwrapper to Powershell. [Grab it from the BitBucket repo!](https://bitbucket.org/guillermooo/virtualenvwrapper-powershell)
Installing virtualenvwrapper on Windows
2,615,968
32
2010-04-11T03:42:56Z
5,844,759
56
2011-04-30T21:36:32Z
[ "python", "windows", "virtualenv", "virtualenvwrapper" ]
I've installed virtualenv and virtualenvwrapper on Windows using easy\_install. But `mkvirtualenv` is missing. I tried to search on my machine but I couldn't find it. I don't know how to solve it. Do you have any idea?
Virtualenv helpers for Windows: * [virtualenvwrapper-win](https://github.com/davidmarble/virtualenvwrapper-win) written as DOS-style batch files (not work with Powershell). Installation cheatsheet: ``` pip install virtualenvwrapper-win pyassoc ``` * [Env.py](https://bitbucket.org/jdriscoll/envdotpy/wiki/Home) is an...
How to simulate tuples and sets in C#?
2,616,255
15
2010-04-11T06:47:50Z
2,616,269
13
2010-04-11T06:59:11Z
[ "c#", "python", "data-structures", "set", "tuples" ]
I want to use some features of python like as Tuples and Sets in c#. should I implement them? or there are already implemented? could anybody knows a library of dynamic data structures for .net languages?
.NET 3.5 has [HashSet](http://msdn.microsoft.com/en-us/library/bb495294.aspx). .NET 4.0 will have a [Tuple](http://msdn.microsoft.com/en-us/magazine/dd942829.aspx) class. As noted in the article, earlier version of .NET do contain KeyValuePair< TKey, TValue > which is similar to a Tuple< T1, T2 >, with the main differ...
Unknown reason for code executing the way it does in python
2,616,468
3
2010-04-11T08:37:58Z
2,616,486
8
2010-04-11T08:43:31Z
[ "python", "osx" ]
I am a beginner programmer, using python on Mac. I created a function as a part of a game which receives the player's input for the main character's name. The code is: ``` import time def newGameStep2(): print ' ****************************************** ' print '\nStep2\t\t\t\tCharacter Name' ...
Your recursive call to `newGameStep2()` isn't returning, so when the second call finishes, control flow continues in the first call after the if/else block, and `return newStep2Choice` returns the first read value. You need to change the recursive call to: ``` return newGameStep2() ```
fade out in Image module Python
2,616,645
2
2010-04-11T10:00:13Z
2,616,677
7
2010-04-11T10:14:28Z
[ "python", "image", "fadeout" ]
Hi I want to take a BMP or JPG and duplicate it so the new image will darker (or brighrt) what function can I use? Ariel
You can use [ImageEnhance module](http://www.pythonware.com/library/pil/handbook/imageenhance.htm) of PIL: ``` import Image import ImageEnhance image = Image.open(r'c:\temp\20090809210.jpg') enhancer = ImageEnhance.Brightness(image) brighter_image = enhancer.enhance(2) darker_image = enhancer.enhance(0.5) ``` Look a...
Parsing srt subtitles
2,616,766
5
2010-04-11T10:54:32Z
2,616,817
11
2010-04-11T11:15:52Z
[ "python", "regex" ]
I want to parse srt subtitles: ``` 1 00:00:12,815 --> 00:00:14,509 Chlapi, jak to jde s těma pracovníma světlama?. 2 00:00:14,815 --> 00:00:16,498 Trochu je zesilujeme. 3 00:00:16,934 --> 00:00:17,814 Jo, sleduj. ``` Every item into structure. With this regexs: A: ``` RE...
Why not use [pysrt](http://pypi.python.org/pypi/pysrt)?
Can I treat IronPython as a Pythonic replacement to C#?
2,617,007
12
2010-04-11T12:38:26Z
2,617,019
10
2010-04-11T12:42:46Z
[ "python", ".net", "ironpython", "cpython", "python.net" ]
I do understand that this topic has been covered in some way at StackOverflow but I'm still not able to figure out the exact answer: **can I treat IronPython as a Pythonic replacement to C#**? I use CPython every day, I love the Zen :) but my current task is a Windows-only application with a complex GUI and some other...
That depends on what it is about C# that you need, and which needs replacing. If the reason you use C# is that you need a reasonably high performance statically typed language then no, IronPython is likely not going to be a replacement. If the reason you use it is simply "I need something that runs on .NET and can ac...
Can I treat IronPython as a Pythonic replacement to C#?
2,617,007
12
2010-04-11T12:38:26Z
2,617,936
13
2010-04-11T17:24:06Z
[ "python", ".net", "ironpython", "cpython", "python.net" ]
I do understand that this topic has been covered in some way at StackOverflow but I'm still not able to figure out the exact answer: **can I treat IronPython as a Pythonic replacement to C#**? I use CPython every day, I love the Zen :) but my current task is a Windows-only application with a complex GUI and some other...
IronPython is NOT equivalent to "other languages that run on .NET", as the language has support for substantially fewer CLR runtime features. IronPython classes are not "real" .NET classes, and [DLR](http://en.wikipedia.org/wiki/Dynamic_Language_Runtime) APIs need to be used when calling IronPython code from tradition...
How to supply stdin, files and environment variable inputs to Python unit tests?
2,617,057
23
2010-04-11T12:57:34Z
2,617,114
25
2010-04-11T13:18:54Z
[ "python", "unit-testing", "user-input" ]
How to write tests where conditions like the following arise: 1. Test user Input. 2. Test input read from a file. 3. Test input read from an environment variable. It'd be great if someone could show me how to approach the above mentioned scenarios; it'd still be awesome if you could point me to a few docs/articles/bl...
All three situations you've described are where you need to specifically go out of your way to ensure you are using loose coupling in your design. Do you *really* need to unit test Python's `raw_input` method? The `open` method? `os.environ.get`? No. You need to set up your design so that you can substitute other way...
How to supply stdin, files and environment variable inputs to Python unit tests?
2,617,057
23
2010-04-11T12:57:34Z
17,353,967
23
2013-06-27T22:01:00Z
[ "python", "unit-testing", "user-input" ]
How to write tests where conditions like the following arise: 1. Test user Input. 2. Test input read from a file. 3. Test input read from an environment variable. It'd be great if someone could show me how to approach the above mentioned scenarios; it'd still be awesome if you could point me to a few docs/articles/bl...
If you are tied to using raw\_input (or any other specific input source), I'm a big proponent of the [mock library](http://www.voidspace.org.uk/python/mock/patch.html). Given the code that Mark Rushakoff used in his example: ``` def say_hello(): name = raw_input("What is your name? ") return "Hello " + name ``...