content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
Django i18n find supported languages
I'm determining a user's language preference through some third party service he's also registered at. This service provides me with a locale code (e.g. en_US). If I do not have the corresponding language code in settings.LANGUAGES, does Django provide some integrated (simple) ... | Django i18n find supported languages | I'm determining a user's language preference through some third party service he's also registered at. This service provides me with a locale code (e.g. en_US). If I do not have the corresponding language code in settings.LANGUAGES, does Django provide some integrated (simple) way to determine the best fallback choise ... | [
"You can see the code Django uses to determine the language based on a request here. Unfortunately there doesn't seem to be a handy utility function for what you're doing. The logic used is trivial however -- just lop the end off if the sub-language isn't supported and search for the main language as a fallback. Th... | [
5
] | [] | [] | [
"django",
"internationalization",
"locale",
"python"
] | stackoverflow_0005538700_django_internationalization_locale_python.txt |
Q:
UTF-8 error with Python and gettext
I use UTF-8 in my editor, so all strings displayed here are UTF-8 in file.
I have a python script like this:
# -*- coding: utf-8 -*-
...
parser = optparse.OptionParser(
description=_('automates the dice rolling in the classic game "risk"'),
usage=_("usage: %prog attacking d... | UTF-8 error with Python and gettext | I use UTF-8 in my editor, so all strings displayed here are UTF-8 in file.
I have a python script like this:
# -*- coding: utf-8 -*-
...
parser = optparse.OptionParser(
description=_('automates the dice rolling in the classic game "risk"'),
usage=_("usage: %prog attacking defending"))
Then I used xgettext to get ... | [
"That error means you've called encode on a bytestring, so it tries to decode it to Unicode using the system default encoding (ascii on Python 2), then re-encode it with whatever you've specified.\nGenerally, the way to resolve it is to call s.decode('utf-8') (or whatever encoding the strings are in) before trying ... | [
7,
5,
3
] | [] | [] | [
"gettext",
"localization",
"python"
] | stackoverflow_0005545197_gettext_localization_python.txt |
Q:
Are annotations supported by Python 2.6.x
I am referring to JUnit annotations like @test, @before , @after.
e.g i can write a method:
@Ignore("Not Ready to Run")
@Test
multiplication():
self.assertEqual('15', simpleMath.multiply(3, 5))
A:
That syntax is called decorator in python 2.6. ... | Are annotations supported by Python 2.6.x | I am referring to JUnit annotations like @test, @before , @after.
e.g i can write a method:
@Ignore("Not Ready to Run")
@Test
multiplication():
self.assertEqual('15', simpleMath.multiply(3, 5))
| [
"That syntax is called decorator in python 2.6. I'm not sure whether it is the same thing as an innotation though.\n"
] | [
0
] | [] | [] | [
"junit4",
"python"
] | stackoverflow_0005545168_junit4_python.txt |
Q:
Django user groups with decorators vs permission
I understand the basic user authentication, login, creating accounts, extending user model...
I am trying to create a site where teachers and students can login. Teachers would have access to pages students cannot access with rights to post homeworks ect...
I think... | Django user groups with decorators vs permission | I understand the basic user authentication, login, creating accounts, extending user model...
I am trying to create a site where teachers and students can login. Teachers would have access to pages students cannot access with rights to post homeworks ect...
I think it is possible to do this with:
Assigning a user to ... | [
"It seems there are a hundred ways that people get to the same results in Django regarding authorization and permissions. Groups are one way, definitely.\nDjango permissions are usually based on your data, so \"table based\", or \"row based\". Row based permissions are not native to Django, you have to either rol... | [
4
] | [] | [] | [
"django",
"python"
] | stackoverflow_0005544654_django_python.txt |
Q:
Temporary Shelves?
I am designing a class that has undo/redo functionality and has to temporarily store a lot of data. I'm currently implementing a "temporary" file by overloading the del operator to delete the file when the class is garbage collected, but I have to believe there is a better way to do this. I ha... | Temporary Shelves? | I am designing a class that has undo/redo functionality and has to temporarily store a lot of data. I'm currently implementing a "temporary" file by overloading the del operator to delete the file when the class is garbage collected, but I have to believe there is a better way to do this. I have tried using the tempf... | [
"Depending on how your code is run you can still encounter a race condition where two different processes obtain the same timestamp and same filename, rare as that might be. Adding the current process id would help mitigate this, but I would recommend you stick with using the tempfile module.\nIf you just need the ... | [
4,
2
] | [] | [] | [
"python",
"shelve",
"temporary_files"
] | stackoverflow_0005545473_python_shelve_temporary_files.txt |
Q:
The Web 2.0 Ecosystem/Stack
Being new to front-end website development, I can understand some stuff, things like routes, ORM, etc. What I don't understand is how they all play together. My understanding is, there are a bunch of components for a website built with Pyramid/Django etc:
A templating engine: Something... | The Web 2.0 Ecosystem/Stack | Being new to front-end website development, I can understand some stuff, things like routes, ORM, etc. What I don't understand is how they all play together. My understanding is, there are a bunch of components for a website built with Pyramid/Django etc:
A templating engine: Something for you to abstract away your HT... | [
"\n1) A templating engine: Something for\n you to abstract away your HTML from\n your code. Makes sense.\n\nThere's several of these available. Mako tries to utilize many common Python idioms in the templates to avoid having to learn many new concepts. Jinja2 is similar to Django, but with more functionality. Gen... | [
8,
3
] | [] | [] | [
"ajax",
"django",
"javascript",
"pyramid",
"python"
] | stackoverflow_0004918575_ajax_django_javascript_pyramid_python.txt |
Q:
How do I change where Bash looks for Python in Linux?
I just updated my ReadyNas from python 2.3.5 to python 2.6.6. The upgrade placed the new version in the /usr/local/bin directory. So
/usr/local/bin/python is Python 2.6.6
/usr/bin/python is Python 2.3.5
When I type python at a bash prompt tries to run /... | How do I change where Bash looks for Python in Linux? | I just updated my ReadyNas from python 2.3.5 to python 2.6.6. The upgrade placed the new version in the /usr/local/bin directory. So
/usr/local/bin/python is Python 2.6.6
/usr/bin/python is Python 2.3.5
When I type python at a bash prompt tries to run /usr/bin/python or my old version. I relocated my old versio... | [
"Your PATH environment variable. It has a list of directories which bash searches (in the same order) when it's looking for an program to execute. Basically you want to put /usr/local/bin at the start of your PATH environment variable. Add the following to your ~/.bashrc file:\nexport PATH=/usr/local/bin:$PATH\n\nY... | [
16,
0
] | [] | [] | [
"bash",
"linux",
"python"
] | stackoverflow_0005546141_bash_linux_python.txt |
Q:
What is the performance of SPARK-based parsers?
SPARK-based parsers are more slow than PLY-based ones, AFAIK. But how much slower? Are they suitable for industrial-strength compilers?
If you have something else to say about pros and cons of SPARK, I'll be glad to hear.
A:
The speed of these parsers is mostly a p... | What is the performance of SPARK-based parsers? | SPARK-based parsers are more slow than PLY-based ones, AFAIK. But how much slower? Are they suitable for industrial-strength compilers?
If you have something else to say about pros and cons of SPARK, I'll be glad to hear.
| [
"The speed of these parsers is mostly a property of the grammar they support. SPARK supports Earley grammars and PLY supports LALR(1) grammars. There is a great deal of information available about the pros and cons of each style of grammar, so I will just provide a quick overview here.\nThe biggest difference betwe... | [
4
] | [] | [] | [
"parsing",
"performance",
"python"
] | stackoverflow_0005546062_parsing_performance_python.txt |
Q:
Including a template does not render the variable value
Possible Duplicate:
how to pass the variable from included template to the template where it is included?
main.html
{% extends "new-base.html" %}
{% block side-bar %}
<div id="foo1">
{% for foo in foo_list %}
{{ foo_id }} // ???
{% ifequa... | Including a template does not render the variable value |
Possible Duplicate:
how to pass the variable from included template to the template where it is included?
main.html
{% extends "new-base.html" %}
{% block side-bar %}
<div id="foo1">
{% for foo in foo_list %}
{{ foo_id }} // ???
{% ifequal foo.id foo_id %}
<li id="my-id_{{ foo.id }}" cla... | [
"I don't really understand your question. I assume you mean that you want foo_id to be accessible from the AJAX request response, but that's not possible, since the page is rendered (and the context set) before the AJAX request is made, so part.html is just a template to django, and it uses the context of the main ... | [
0
] | [] | [] | [
"ajax",
"django",
"jquery",
"python"
] | stackoverflow_0005545556_ajax_django_jquery_python.txt |
Q:
Creating a List from a Binary Search Tree
I'm trying to make a list of all items in a binary search tree. I understand the recursion but I don't know how to make it return each value and then append it into a list. I want to create a function called makeList() that will return a list of all the items in my tree. A... | Creating a List from a Binary Search Tree | I'm trying to make a list of all items in a binary search tree. I understand the recursion but I don't know how to make it return each value and then append it into a list. I want to create a function called makeList() that will return a list of all the items in my tree. All the functions in my programs work except the... | [
"You're so close! makeList can be pretty simple:\ndef makeList(self, aNode):\n if aNode is None:\n # Stop recursing here\n return []\n return self.makeList(aNode.lChild) + [aNode.data] + self.makeList(aNode.rChild)\n\nBasically, make sure you're not trying to recurse past empty nodes. Then retur... | [
6,
1,
1
] | [] | [] | [
"binary_search_tree",
"python"
] | stackoverflow_0005546072_binary_search_tree_python.txt |
Q:
What's with binary files on Windows?
I made a script to download a file, but it only works on Unix/Linux/OSX when I'm downloading binary executables, swf's, images, etc
\#Modfied section from PWB.py
import sys
if sys.version_info<(2,8):
import urllib as request
else:
import urllib.request as requ... | What's with binary files on Windows? | I made a script to download a file, but it only works on Unix/Linux/OSX when I'm downloading binary executables, swf's, images, etc
\#Modfied section from PWB.py
import sys
if sys.version_info<(2,8):
import urllib as request
else:
import urllib.request as request
x=request.urlopen("http://homestarru... | [
"Open binary files in binary mode.\nz = open(\"intro.swf\",\"wb\")\n\n",
"From the Python 2 documentation:\n\nOn Windows, 'b' appended to the mode\n opens the file in binary mode, so\n there are also modes like 'rb', 'wb',\n and 'r+b'. Python on Windows makes a\n distinction between text and binary\n files; ... | [
8,
6,
0,
0
] | [] | [] | [
"python",
"windows_xp"
] | stackoverflow_0005546500_python_windows_xp.txt |
Q:
how to pass the variable from included template to the template where it is included?
In Django Views:-
if request.is_ajax():
t = get_template('bar-templates.html')
html = t.render(Context({'edit': True, 'user':'some-user' }))
return HttpResponse(html)
There is two templates:
Main template (foo-templ... | how to pass the variable from included template to the template where it is included? | In Django Views:-
if request.is_ajax():
t = get_template('bar-templates.html')
html = t.render(Context({'edit': True, 'user':'some-user' }))
return HttpResponse(html)
There is two templates:
Main template (foo-templates.html) which includes the template (bar-templates.html). In context edit and user is p... | [
"Using details from your other post, which you should edit to include into this one:\nFrom what i can tell, you are trying to add a \"selected\" class to your sidebar menu. This won't work for you because as gcbirzan said, you aren't going to be able to get the context of your ajax response into your base template.... | [
1,
0
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0005541312_django_django_templates_python.txt |
Q:
Can't copy the value of a Tkinter Entry
So i have this code:
from Tkinter import *
Admin = Tk()
def searches():
gett = search.get()
lab = Label(frame, text='searching for ' + gett)
lab.pack(side='bottom')
frame = Frame(Admin)
frame.pack()
search = Entry(frame)
search.pack(side='left')
button = Button... | Can't copy the value of a Tkinter Entry | So i have this code:
from Tkinter import *
Admin = Tk()
def searches():
gett = search.get()
lab = Label(frame, text='searching for ' + gett)
lab.pack(side='bottom')
frame = Frame(Admin)
frame.pack()
search = Entry(frame)
search.pack(side='left')
button = Button(frame, text='Search', command=searches)
butt... | [
"You are calling search.get() and assigning the result to getts -- and then assigning that to other -- prior to the GUI ever being displayed on the screen. Because of this the result of search.get() will be the empty string since you don't pre-load the widget with any data. And because getts is empty, when it is as... | [
0,
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0005546470_python_tkinter.txt |
Q:
Problem with Twitter package by sixohsix
I am using a Twitter Python package which is installed by
easy_install twitter
The package can be found at : https://github.com/sixohsix/twitter
I am running into some weird errors.
import twitter
twitter_search = twitter.Twitter(domain="search.twitter.com")
results = tw... | Problem with Twitter package by sixohsix | I am using a Twitter Python package which is installed by
easy_install twitter
The package can be found at : https://github.com/sixohsix/twitter
I am running into some weird errors.
import twitter
twitter_search = twitter.Twitter(domain="search.twitter.com")
results = twitter_search.search(q="japan")
Than I receive... | [
"This was a library defect that the author just fixed.\nThe problem was that the library was versioning the path to the search resource, and thereby causing a 404 error.\nThis part of the error message you provided details the problem:\nTwitter sent status 404 for URL: 1/search.json using parameters: (q=japan)\n\nT... | [
1
] | [] | [] | [
"python",
"twitter",
"ubuntu"
] | stackoverflow_0005521848_python_twitter_ubuntu.txt |
Q:
C++ Objects That Carry Custom Python Data In SWIG
Is there a way for C++ objects, wrapped by SWIG, to carry custom Python data with them as they pass back and forth between C++ and Python? Example:
example.h
class MyClass
{
public:
int foo;
};
// Black box functions.
// Only thing guaranteed is that the last ... | C++ Objects That Carry Custom Python Data In SWIG | Is there a way for C++ objects, wrapped by SWIG, to carry custom Python data with them as they pass back and forth between C++ and Python? Example:
example.h
class MyClass
{
public:
int foo;
};
// Black box functions.
// Only thing guaranteed is that the last object handed to consume
// will be returned by eject.
... | [
"This is the only (partial) solution I've come up with so far:\nclass MyClass\n{\n...\nMyClass() : data(NULL) {}\n~MyClass() {if(data) Py_DECREF(data);}\nPyObject *data;\n};\n\n\n%typemap(in) PyObject* data {\n if(arg1 && arg1->data != NULL)\n Py_DECREF(arg1->data);\n $1 = $input;\n Py_XINCREF($1);\... | [
0
] | [] | [] | [
"attributes",
"c++",
"python",
"swig"
] | stackoverflow_0005546344_attributes_c++_python_swig.txt |
Q:
python keystroke classifier
I need to write a program that does the following:
User enters a character
The program outputs whether it is alphabetic, numeric, a space, or a newline.
A:
The documentation for python string methods should give you exactly what you are looking for.
| python keystroke classifier | I need to write a program that does the following:
User enters a character
The program outputs whether it is alphabetic, numeric, a space, or a newline.
| [
"The documentation for python string methods should give you exactly what you are looking for.\n"
] | [
0
] | [] | [] | [
"io",
"python"
] | stackoverflow_0004041581_io_python.txt |
Q:
matplotlib draw showing nothing
I'm using python's matplotlib to do some contours using contour and contourf functions. They all work fine when using show, but when I try to use draw() inside a method, I get the matplotlib window but not graph. The show() call will be done much later on the code and in a different... | matplotlib draw showing nothing | I'm using python's matplotlib to do some contours using contour and contourf functions. They all work fine when using show, but when I try to use draw() inside a method, I get the matplotlib window but not graph. The show() call will be done much later on the code and in a different method, and I would like to show one... | [
"Have you turned interactive mode on using ion()? The following works for me on OSX, using the Tk backend and running from the shell's command line:\nimport matplotlib.pyplot as plt\n\nplt.ion()\nplt.figure()\nfor i in range(10):\n plt.plot([i], [i], 'o')\n plt.draw()\nraw_input(\"done >>\") \n\nThat is, as... | [
7,
2
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0005541594_matplotlib_python.txt |
Q:
Non ascii characters in Python again
How can I successfully add non-ASCII character into Python source code?
For example:
a = "ű" - Hungarian letter
--------Sample------
#-*- coding: iso8859_2 -*-
a = "ű"
print "ű"
---------------------
output = √
Not ű, as desired.
A:
You have to use utf-8 instead of iso... | Non ascii characters in Python again | How can I successfully add non-ASCII character into Python source code?
For example:
a = "ű" - Hungarian letter
--------Sample------
#-*- coding: iso8859_2 -*-
a = "ű"
print "ű"
---------------------
output = √
Not ű, as desired.
| [
"You have to use utf-8 instead of iso8859-2 like :\n#-*- coding: utf-8 -*-\na = \"ű\"\nprint \"ű\"\n\nOuput:\nű\n\nIn addition, be sure that you have saved your source code file with the right encoding (utf-8 here).\n",
"The other answers mention specifying the coding and making sure the source file is encoded wi... | [
3,
3,
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0005539704_python.txt |
Q:
Can someone explain this program to me?
What does the following expression produce as a value:
[(x, x*y) for x in range(2) for y in range(2)]
[(0,0), (0,1), (1,0), (1,1)]
[0, 1, 2]
[(0,0), (1,0), (0,0), (1,1)]
[(0,0), (0,0), (1,0), (1,1)]
None of the above
The answer is 4, but I don't understand why.
A:
read ... | Can someone explain this program to me? | What does the following expression produce as a value:
[(x, x*y) for x in range(2) for y in range(2)]
[(0,0), (0,1), (1,0), (1,1)]
[0, 1, 2]
[(0,0), (1,0), (0,0), (1,1)]
[(0,0), (0,0), (1,0), (1,1)]
None of the above
The answer is 4, but I don't understand why.
| [
"read as:\nfor x in range(2): # 0,1\n for y in range(2): # 0,1\n (x, x*y)\n\n",
"Assuming python 2.\nrange(2) returns the list [0, 1]\n[(x, x*y) for x in [0, 1] for y in [0,1]]\n\nThus x and y will be all combinations of the lists [0, 1] and [0, 1]\n[(x, x*y) for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]]\n... | [
2,
2,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0005547155_python.txt |
Q:
Python Lxml: Adding and deleting tags
I am attempting to add and remove tags in an xml tree (snip below). I have a dict of boolean values that I use to determine whether to add or remove a tag. If the value is true, and the element does not exist, it creates the tag (and its parent if it doesn't exist). If false, ... | Python Lxml: Adding and deleting tags | I am attempting to add and remove tags in an xml tree (snip below). I have a dict of boolean values that I use to determine whether to add or remove a tag. If the value is true, and the element does not exist, it creates the tag (and its parent if it doesn't exist). If false, it deletes the value.
However, it doesn't s... | [
"There are several things could be improved in the code:\n\nnode.xpath returns the list of nodes - i.e. you can't do root.xpath(path).getparent(), check the list and take the node #0 if you're sure that it should exist (you node deletion code uses this);\nwhen working with attributes try using node.attrib dictionar... | [
2
] | [] | [] | [
"exception_handling",
"lxml",
"parsing",
"python"
] | stackoverflow_0005547257_exception_handling_lxml_parsing_python.txt |
Q:
Latitude,Longitude Coordinate Pairs from Matrix, Python Script
I have two text files: 1) single array of latitude values, 2) single array of longitude values. There are 94 latitude values in text file #1, and 192 longitude values in text file #2. I want to do a 1 to 1 mapping so that there are 94 latitude x 192 ... | Latitude,Longitude Coordinate Pairs from Matrix, Python Script | I have two text files: 1) single array of latitude values, 2) single array of longitude values. There are 94 latitude values in text file #1, and 192 longitude values in text file #2. I want to do a 1 to 1 mapping so that there are 94 latitude x 192 longitude = 18048 coordinate pairs. I need to keep the exact precisi... | [
"from itertools import product\n# This is just a scrap code to quickly read the values in the files, you can replace it with whatever suites you \nlat=open(\"lat.txt\",'r').read().replace(\"lat =\",\"\").replace(\";\",\"\").replace(\" \",\"\").replace(\"\\n\",\"\").split(',')\nlon=open(\"lon.txt\",'r').read().repla... | [
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0005547195_python.txt |
Q:
CSRF verification failing for post or preview using {% render_comment_form for ... %}
I have django.middleware.csrf.CsrfViewMiddleware in settings.MIDDLEWARE_CLASSES and CSRF verification is working just fine for all my other forms. render_comment_form is including {% csrf_token %} properly; I verified that the HT... | CSRF verification failing for post or preview using {% render_comment_form for ... %} | I have django.middleware.csrf.CsrfViewMiddleware in settings.MIDDLEWARE_CLASSES and CSRF verification is working just fine for all my other forms. render_comment_form is including {% csrf_token %} properly; I verified that the HTML is showing up. Any ideas?
| [
"I forgot to add\ncontext_instance=RequestContext(request)\n\nto my render_to_response call at the end of my view. Doh!\n"
] | [
1
] | [] | [] | [
"comments",
"csrf",
"django",
"python"
] | stackoverflow_0005545961_comments_csrf_django_python.txt |
Q:
How to handle adding elements and their parents using xpath
Ok, I have a case where I need to add a tag to a certain other tag given an xpath.
Example xml:
<?xml version="1.0" encoding="UTF-8"?>
<Assets>
<asset name="Adham">
<general>>
<services>
<land/>
<refuel/>
</services>
</general>
</asset... | How to handle adding elements and their parents using xpath | Ok, I have a case where I need to add a tag to a certain other tag given an xpath.
Example xml:
<?xml version="1.0" encoding="UTF-8"?>
<Assets>
<asset name="Adham">
<general>>
<services>
<land/>
<refuel/>
</services>
</general>
</asset>
<asset name="Test">
<general>
<Something/>
</general>
... | [
"def to_xml(parent, xpath, value):\n \"\"\"\n parent: lxml.etree.Element\n xpath: string like 'x/y/z', anything more complex is likely to break\n value: anything, if is False - means delete node\n \"\"\" \n # find the node to proceed further \n nodes = parent.xpath(xpath) \... | [
2
] | [] | [] | [
"add",
"lxml",
"python",
"xpath"
] | stackoverflow_0005547589_add_lxml_python_xpath.txt |
Q:
map data type for python google app engine
I would like to have a map data type for one of my entity types in my python google app engine application. I think what I need is essentially the python dict datatype where I can create a list of key-value mappings. I don't see any obvious way to do this with the provide... | map data type for python google app engine | I would like to have a map data type for one of my entity types in my python google app engine application. I think what I need is essentially the python dict datatype where I can create a list of key-value mappings. I don't see any obvious way to do this with the provided datatypes in app engine.
The reason I'd like t... | [
"You're probably better off using another kind, as you suggest. If you do want to store it all in the one entity, though, you have several options - parallel lists, as you suggest, are one option. You could also simply pickle a Python dictionary, assuming you don't want to query on it.\nYou may want to check out th... | [
1
] | [] | [] | [
"dictionary",
"google_app_engine",
"map",
"python"
] | stackoverflow_0005547364_dictionary_google_app_engine_map_python.txt |
Q:
python - using __init__.py for modules in multiple dirs
I'm having a hard time understanding this.
Lets assume I have a directory tree that looks like this:
~/speech
-- __init__.py
-- program.py
----------------
~/speech/parts
----__init__.py
----noun.py
----verb.py
----------------
~/speech/sentence
----__init... | python - using __init__.py for modules in multiple dirs | I'm having a hard time understanding this.
Lets assume I have a directory tree that looks like this:
~/speech
-- __init__.py
-- program.py
----------------
~/speech/parts
----__init__.py
----noun.py
----verb.py
----------------
~/speech/sentence
----__init__.py
----subject.py
----predicate.py
the __init__.py files... | [
"Unless ~ is your current directory or is in sys.path (which it shouldn't be) you won't be able to use any packages contained in it, including speech and its subpackages. Put the directory structure somewhere sane and add that path to $PYTHONPATH.\n",
"you can quickly add your current directory to the python sear... | [
1,
1,
1
] | [] | [] | [
"module",
"python"
] | stackoverflow_0005546937_module_python.txt |
Q:
minimum value of y axis is not being applied in matplotlib vlines plot
I am doing a vlines plot in matplotlib and I have all my y values in the dataset as >=0. I want my y axis bottom most tick to read 0, but instead, I get -500.
Here is the code:
#!/usr/bin/env python
import numpy as np
from matplotlib import py... | minimum value of y axis is not being applied in matplotlib vlines plot | I am doing a vlines plot in matplotlib and I have all my y values in the dataset as >=0. I want my y axis bottom most tick to read 0, but instead, I get -500.
Here is the code:
#!/usr/bin/env python
import numpy as np
from matplotlib import pyplot as plt, dates as mdates
import datetime as dt, time
# Read the data an... | [
"You can set the limit manually after plotting the data, like so:\npyplot.ylim(ymin=0)\n\nWhat happens is that Matplotlib adjusts the plot limits so that it looks \"best\". Sometimes, this implies going beyond the strict range of your data. You must then update the limits after the plot, since each plot updates t... | [
24
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0005548121_matplotlib_python.txt |
Q:
Python Structures
I am try to convert a C Structure to Python using Ctypes.
The Structure I am trying to convert is :
typedef struct LibraryInfo
{
uint32_t size; // Size of the structure
char libName[MAX_LIBRARY_NAME+1]; // Library... | Python Structures | I am try to convert a C Structure to Python using Ctypes.
The Structure I am trying to convert is :
typedef struct LibraryInfo
{
uint32_t size; // Size of the structure
char libName[MAX_LIBRARY_NAME+1]; // Library name
char ... | [
"From the function signature, it seems that you need to pass a pointer to the structure:\nlibraryInfo = LibraryInfo()\nresCode = QueryLibraryInfo(byref(libraryInfo))\n\nAnd you should really keep the + 1 in your structure definition.\n"
] | [
0
] | [] | [] | [
"ctypes",
"python"
] | stackoverflow_0005548387_ctypes_python.txt |
Q:
SA: can I have a 'year' column_property for a Date column?
I have a class with a Date column in sqlalchemy-0.7. Can I have a column_property or anything similar that gets me the year and lets me easily filter by it? How would I write it?
IE, I'd like to have (declarative syntax):
class Foo(Base):
id = Column... | SA: can I have a 'year' column_property for a Date column? | I have a class with a Date column in sqlalchemy-0.7. Can I have a column_property or anything similar that gets me the year and lets me easily filter by it? How would I write it?
IE, I'd like to have (declarative syntax):
class Foo(Base):
id = Column(Integer, primary_key=True)
date = Column(Date(), nullable=F... | [
"Sure you can define such property:\nyear = column_property(extract('year', date))\n\nBut do you realy need it? You can filter by year without such property defined by rewriting filter condition:\nquery(Foo).filter(extract('year', Foo.date)==2011)\n\nUpdate\nAlthough this solution looks simple it also have a drawba... | [
5
] | [] | [] | [
"declarative",
"properties",
"python",
"sqlalchemy"
] | stackoverflow_0005545245_declarative_properties_python_sqlalchemy.txt |
Q:
Password hash program
I need to create a program that will allow the user to enter a pin number without revealing what the pin number actually is. Here is some more detail:
I will need to store inside the program a PIN number which the user should know before hand. Then I will need to generate a string of ten rand... | Password hash program | I need to create a program that will allow the user to enter a pin number without revealing what the pin number actually is. Here is some more detail:
I will need to store inside the program a PIN number which the user should know before hand. Then I will need to generate a string of ten random numbers in the range 0 t... | [
"Maybe a dictionary would be a good way to do this. I'm trying to get you started, but please read both of these. \nhttp://docs.python.org/library/random.html\nhttp://docs.python.org/tutorial/datastructures.html#dictionaries\nAnd the python tutorial in general: http://docs.python.org/tutorial/index.html\nimport r... | [
1,
1
] | [] | [] | [
"hash",
"python"
] | stackoverflow_0005548907_hash_python.txt |
Q:
Syntax for using mr.ripley for benchmarking
I have a Plone 3.3.5 site that I'm migrating to plone.app.blob for BLOB storage. I'm looking to measure the difference in performance and resource usage by replaying requests to the site, pre-migration and post-migration.
I found that mr.ripley comes with it's own build... | Syntax for using mr.ripley for benchmarking | I have a Plone 3.3.5 site that I'm migrating to plone.app.blob for BLOB storage. I'm looking to measure the difference in performance and resource usage by replaying requests to the site, pre-migration and post-migration.
I found that mr.ripley comes with it's own buildout and I used that to install it. That buildout ... | [
"I've performed before and after load testing to test architecture changes. To do this we used JMeter. We took apache logs that represented the typical use we were after. JMeter allows these to be replayed. In addition it will simulate cookies/sessions and browser cache responses to make the request even more reali... | [
1
] | [] | [] | [
"benchmarking",
"plone",
"python",
"zope"
] | stackoverflow_0005547227_benchmarking_plone_python_zope.txt |
Q:
Syntax Error with lists in Python
python version: 2.71
I get a syntax error whenever I try to run it with IDLE....
horsemen = ["war", "famine", "pestilence", "death"]
i = 0
while i < 4:
print horsemen[i]
i = i + 1
The error occurs between horsemen and the equal sign
A:
Is there any reason you cannot us... | Syntax Error with lists in Python | python version: 2.71
I get a syntax error whenever I try to run it with IDLE....
horsemen = ["war", "famine", "pestilence", "death"]
i = 0
while i < 4:
print horsemen[i]
i = i + 1
The error occurs between horsemen and the equal sign
| [
"Is there any reason you cannot use a for loop?\nfor god in horsemen:\n print god\n\n",
"The code is fine (syntactically). You must have a problem with your python environment. Also make sure it is properly indented.\n"
] | [
8,
2
] | [] | [] | [
"list",
"python"
] | stackoverflow_0005549492_list_python.txt |
Q:
redirecting url after facebook logs in successfully with django app
I created a django application with a user login/registration page. I am trying to implement a facebook login also possible along with my django login. For doing so i was following this link : enter link description here. As the documentaion says,... | redirecting url after facebook logs in successfully with django app | I created a django application with a user login/registration page. I am trying to implement a facebook login also possible along with my django login. For doing so i was following this link : enter link description here. As the documentaion says, i have created a file called FaebookConnectMiddleware.py and put in sett... | [
"I think you just need to declare the variable at the top of your class as false\nclass FacebookConnectMiddleware(object):\n\n facebook_user_is_authenticated = False\n\n"
] | [
1
] | [] | [] | [
"django",
"django_models",
"facebook",
"python"
] | stackoverflow_0005549926_django_django_models_facebook_python.txt |
Q:
python to mssql encoding problem
Greetings
By using pymssql library, I want to write data to a MSSQL database however I encounter encoding issues. Here is my sample code to write to the DB:
# -*- coding: utf-8 -*-
import _mssql
....
Connection info data here
....
def mssql_connect():
return _mssql.connect(se... | python to mssql encoding problem | Greetings
By using pymssql library, I want to write data to a MSSQL database however I encounter encoding issues. Here is my sample code to write to the DB:
# -*- coding: utf-8 -*-
import _mssql
....
Connection info data here
....
def mssql_connect():
return _mssql.connect(server=HOST, user=USERNAME, password=PA... | [
"Here is a possible solution:\nThe key is INSERT_EX_SQ.encode('your language encoder').\nTry this instead:\ncon.execute_non_query(INSERT_EX_SQ.encode('your language encoder'))\n\n"
] | [
1
] | [] | [] | [
"character_encoding",
"pymssql",
"python",
"sql_server"
] | stackoverflow_0004791114_character_encoding_pymssql_python_sql_server.txt |
Q:
bash script checking if GPG signature is valid and belongs to a key
I am trying to write a bash script that checks if a given signature is valid or not. I have two possible outputs from:
$ gpg --no-default-keyring --keyring /etc/pubring.gpg --verify file.tgz.sig file.tgz
WRONG
gpg: Signature made Tue 05 Apr 20... | bash script checking if GPG signature is valid and belongs to a key | I am trying to write a bash script that checks if a given signature is valid or not. I have two possible outputs from:
$ gpg --no-default-keyring --keyring /etc/pubring.gpg --verify file.tgz.sig file.tgz
WRONG
gpg: Signature made Tue 05 Apr 2011 11:01:19 CEST using RSA key ID E32804F0
gpg: Can't check signature: pu... | [
"I don't know the gpg command but does it return a different exit value for the \"wrong\" and \"right\" results? The easiest way to check this after running the command would be:\necho $?\n\nI would expect it to return 0 if everything is OK and something else if not. So your bash script would look like:\ngpg --no... | [
7,
1
] | [] | [] | [
"bash",
"gnupg",
"python"
] | stackoverflow_0005550145_bash_gnupg_python.txt |
Q:
Django query: Another count question
Hello I seem to be having some problem involving counting in Django. I have a list of items which only displays its latest status. All of these items that has a status "Destroyed" have been removed. This prints nicely.
status_items = models.StorageItem.objects.filter(client=c... | Django query: Another count question | Hello I seem to be having some problem involving counting in Django. I have a list of items which only displays its latest status. All of these items that has a status "Destroyed" have been removed. This prints nicely.
status_items = models.StorageItem.objects.filter(client=client_id, itemstatushistory__isnull=False)... | [
"after\nstatus_items = models.StorageItem.objects\n .filter(client=client_id, itemstatushistory__isnull=False)\n .distinct().count()\n\nstatus_items will contain the count of items --> an intobject\nusing it in the template in {% for item in status_items %} will obviously gen... | [
2,
0,
0
] | [] | [] | [
"django",
"django_templates",
"python",
"templates"
] | stackoverflow_0005550286_django_django_templates_python_templates.txt |
Q:
error using pywinauto
I am new to python and have just installed pywinauto using easy_install.
I am trying to execute a simple code as follow:
from pywinauto import application
app = application.Application.start ('notepad.exe')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeEr... | error using pywinauto | I am new to python and have just installed pywinauto using easy_install.
I am trying to execute a simple code as follow:
from pywinauto import application
app = application.Application.start ('notepad.exe')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: type object 'Applicati... | [
"Pywinauto is very confused about the naming convention used (I know - I wrote it!).\nThere are two choices:\na) create an instance of the Application class first and then call start() on it.\n>>> from pywinauto import Application\n>>> app = Application()\n>>> app.start('notepad.exe')\n<pywinauto.application.Applic... | [
4,
0
] | [] | [] | [
"python",
"pywinauto"
] | stackoverflow_0005452830_python_pywinauto.txt |
Q:
Docx to pdf using openoffice headless way too slow
I've been using PHPWord for docx files generation. And it's been working great.
But now I have the need to also make available some of those files on a pdf version.
After a few research I found PyODConverter which use OOo. Seemed quite a good option since I don't ... | Docx to pdf using openoffice headless way too slow | I've been using PHPWord for docx files generation. And it's been working great.
But now I have the need to also make available some of those files on a pdf version.
After a few research I found PyODConverter which use OOo. Seemed quite a good option since I don't want to depend on third party web services. I tried it o... | [
"I manage to eliminate the delay by using pipes instead of sockets for the connection.\ncontext = resolver.resolve(\"uno:pipe,name=myuser_OOffice;urp;StarOffice.ComponentContext\")\n\nI still have one problem though... the user executing the python script must be the same that starts OOo for everything to work okay... | [
6,
2,
2
] | [] | [] | [
"docx",
"headless",
"pdf_generation",
"php",
"python"
] | stackoverflow_0005504308_docx_headless_pdf_generation_php_python.txt |
Q:
Pywinauto to control the media player
i am trying to control the windows media player using python with pywinauto framework. I am able to access the menu for example with app.WindowsMediaPlayer.MenuSelect("View->GoTo->Library")
but when i try to access the library items, using the dialog unable to do so.
similarly... | Pywinauto to control the media player | i am trying to control the windows media player using python with pywinauto framework. I am able to access the menu for example with app.WindowsMediaPlayer.MenuSelect("View->GoTo->Library")
but when i try to access the library items, using the dialog unable to do so.
similarly for the taskbar on the left want to access... | [
">>> wmp.WindowsMediaPlayer.MenuSelect(\"View->Library\")\n>>> wmp.WindowsMediaPlayer.print_control_identifiers()\nControl Identifiers:\nWMPAppHost - 'WMPAppHost' (L40, T152, R731, B648)\n 'WMPAppHost' 'WMPAppHostWMPAppHost'\nWMP Skin Host - '' (L40, T188, R731, B588)\n '' '0' '1' 'WMP Skin Host'\... | [
0
] | [] | [] | [
"automation",
"python",
"pywinauto",
"user_interface"
] | stackoverflow_0004957524_automation_python_pywinauto_user_interface.txt |
Q:
Using Pickle object like an API call
I trained a NaiveBayes classifier to do elementary sentiment analysis. The model is 208MB . I want to load it only once and then use Gearman workers to keep calling the model to get the results. It takes rather long time to load it only once. How do i load the model only once... | Using Pickle object like an API call | I trained a NaiveBayes classifier to do elementary sentiment analysis. The model is 208MB . I want to load it only once and then use Gearman workers to keep calling the model to get the results. It takes rather long time to load it only once. How do i load the model only once and then keep calling it ?
Some code , h... | [
"If the question is how to use pickle, than that's the answer\n import pickle\n class Model(object):\n #some crazy array of data\n def getClass(sentiment)\n #return class of sentiment\n\n def loadModel(filename):\n f = open(filename, 'rb')\n res = pickle.load(f)\n ... | [
0
] | [] | [] | [
"pickle",
"python"
] | stackoverflow_0005550527_pickle_python.txt |
Q:
Sorting a List based on dates
Below is a code which I wrote to sort the elements of a list based on certain parameters. One the parameters is a date. Now the date format is mm/dd/yy. Now if the year is the same, I dont face any problem. However, if I change the year from 2011 to 2012 of a particular element, the s... | Sorting a List based on dates | Below is a code which I wrote to sort the elements of a list based on certain parameters. One the parameters is a date. Now the date format is mm/dd/yy. Now if the year is the same, I dont face any problem. However, if I change the year from 2011 to 2012 of a particular element, the solution breaks down. For example it... | [
"Try this:\nsorted(List, key=lambda x: (x[2].split('/')[2], x[2].split('/')[0], x[2].split('/')[1]))\n\nFor an example:\nList=[['G1','E','03/12/2011',2],\n ['G2','E','03/10/2011',2],\n ['G3','2','03/19/2012',1],\n ['G4','2','03/15/2010',2],\n ['G6','2','03/15/2012',2]]\n\nit returns:\n[['G4', '2... | [
11,
0
] | [] | [] | [
"python"
] | stackoverflow_0005549000_python.txt |
Q:
Retrieve json value in templates
I have the following objects queried form a table after which the various objects are put In the following objarr.How to retrieve these values in UI in javascript
from django.core.serializers import serialize
json = serialize("json", objarr)
logging.debug(type(json))
response_d... | Retrieve json value in templates | I have the following objects queried form a table after which the various objects are put In the following objarr.How to retrieve these values in UI in javascript
from django.core.serializers import serialize
json = serialize("json", objarr)
logging.debug(type(json))
response_dict.update({'objarr' : (json) })
ret... | [
"You can also try below code to make that work:\nString.prototype.toArr = function() {\n eval(\"var obj = \" + this);\n return obj ? obj : [];\n};\nfunction retrieve_data(formid){\n var form = $(formid);\n form.ajaxSubmit({\n dataType: 'json',\n success: function (data) {\n if(data){\n data = data... | [
1,
0
] | [] | [] | [
"javascript",
"jquery",
"json",
"python"
] | stackoverflow_0005550374_javascript_jquery_json_python.txt |
Q:
Efficient way to read a specific line number of a file. (BONUS: Python Manual Misprint)
I have a 100 GB text file, which is a BCP dump from a database. When I try to import it with BULK INSERT, I get a cryptic error on line number 219506324. Before solving this issue I would like to see this line, but alas my favo... | Efficient way to read a specific line number of a file. (BONUS: Python Manual Misprint) | I have a 100 GB text file, which is a BCP dump from a database. When I try to import it with BULK INSERT, I get a cryptic error on line number 219506324. Before solving this issue I would like to see this line, but alas my favorite method of
import linecache
print linecache.getline(filename, linenumber)
is throwing a ... | [
"Here's my elegant version in C#:\nConsole.Write(File.ReadLines(@\"s:\\source\\transactions.dat\").ElementAt(219506323));\n\nor more general:\nConsole.Write(File.ReadLines(filename).ElementAt(linenumber - 1));\n\nOf course, you may want to show some context before and after the given line:\nConsole.Write(string.Joi... | [
8,
6,
1,
0,
0
] | [] | [] | [
".net",
"c#",
"file",
"python"
] | stackoverflow_0003589327_.net_c#_file_python.txt |
Q:
DRY approach to accessing instance value in custom Django ImageField form field?
I'm using django-storages to save images uploaded to S3, and I want to create a custom form field that will display the image when editing, along with an option to change it.
The problem I'm running into is the path's value that is ... | DRY approach to accessing instance value in custom Django ImageField form field? | I'm using django-storages to save images uploaded to S3, and I want to create a custom form field that will display the image when editing, along with an option to change it.
The problem I'm running into is the path's value that is stored in my database is not the full path to the image, as django-storages does the g... | [
"I think overriding the __init__ in your custom widget and passing in your url would do the trick.\nedit:\nclass ImageViewWidget(forms.Widget):\n def __init__(self, *args, **kwargs):\n self.path = kwargs.pop('path', '')\n super(ImageViewWidget, self).__init__(*args, **kwargs)\n\n markup = \"\"\"... | [
2,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0005399588_django_python.txt |
Q:
Python equivalents to Perl's URI::Find
In Python, are there any modules for extracting plain urls from a string like Perl's URI::Find does?
Thanks.
A:
Here is a regex which can help you find the urls in text. There is no famous package in python which does uri::find in plain text. The sphinx documentation proje... | Python equivalents to Perl's URI::Find | In Python, are there any modules for extracting plain urls from a string like Perl's URI::Find does?
Thanks.
| [
"Here is a regex which can help you find the urls in text. There is no famous package in python which does uri::find in plain text. The sphinx documentation project however, includes a builder called linkcheck which finds all the links and checks for validity. You can check it's source too, but the linked regex is... | [
3
] | [] | [] | [
"perl",
"python"
] | stackoverflow_0005552305_perl_python.txt |
Q:
Using python in part of a Cocoa application - How do I package the .py with the application?
I'm writing a Cocoa application that uses Python to perform some calculations and data manipulation. I've got an Objective-C class that I'm using to run the Python scripts via the Python API. I can currently call Python wi... | Using python in part of a Cocoa application - How do I package the .py with the application? | I'm writing a Cocoa application that uses Python to perform some calculations and data manipulation. I've got an Objective-C class that I'm using to run the Python scripts via the Python API. I can currently call Python with no problem using the API and linking to Python.framework.
I'm looking at how to package the cod... | [
"You can use py2app to compile an NSBundle which can be loaded at runtime (you could add this loadable bundle to your app bundle's PlugIns/ folder). However, while initially quite easy to get working, there appears to be a bug in PyObjC or py2app that leads to significant memory leaks depending on the API of your p... | [
2
] | [] | [] | [
"bundle",
"cocoa",
"python",
"xcode"
] | stackoverflow_0005546222_bundle_cocoa_python_xcode.txt |
Q:
wxPython frames shown in XP but not win2003 server
I have written an app that runs fine on my XP dev platform. When I compile it with py2exe and move it to other XP platforms without python etc installed it also works fine. When I move it to a 2003 server platform it fails to display the main frame, but will dis... | wxPython frames shown in XP but not win2003 server | I have written an app that runs fine on my XP dev platform. When I compile it with py2exe and move it to other XP platforms without python etc installed it also works fine. When I move it to a 2003 server platform it fails to display the main frame, but will display the wx.messagebox popups.
On the same 2003 platfo... | [
"I don't have time to read your lengthy code sample, but I wonder if it is the infamous msvcr90.dll issue. I got good feedback on this from the py2exe list here and here.\n",
"I rebuilt the code using wxGlade (original was done using boaConstructor) and for some reason, It works. I don't know why or how, but it... | [
0,
0
] | [] | [] | [
"python",
"windows_server_2003",
"windows_xp"
] | stackoverflow_0005543138_python_windows_server_2003_windows_xp.txt |
Q:
python unbound method must must be called with instance as first argument (got nothing instead)
When trying to compile I get the error
C:\Temp\pythonWork\superGui>superGui.py
Traceback (most recent call last):
File "C:\Temp\pythonWork\superGui\superGui.py", line 747, in <module>
MyFrame.disableAll()
Type... | python unbound method must must be called with instance as first argument (got nothing instead) | When trying to compile I get the error
C:\Temp\pythonWork\superGui>superGui.py
Traceback (most recent call last):
File "C:\Temp\pythonWork\superGui\superGui.py", line 747, in <module>
MyFrame.disableAll()
TypeError: unbound method disableAll() must be called with MyFrame instance as first argument (got nothing ... | [
"You probably need to use an instance of that class.\nmainFrame.disableAll()\n\nshould do the trick, as indicated in other answers.\n",
"mainFrame.disableAll()\n\ninstead of\nMyFrame.disableAll()\n\nThis should do the job.\n",
"You're calling it as if it was a class or static method. Where is self supposed to c... | [
4,
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0005552787_python.txt |
Q:
SQLAlchemy Misuse Causing Memory Leak?
My program is sucking up a meg every few seconds. I read that python doesn't see curors in garbage collection, so I have a feeling that I might be doing something wrong with my use of pydbc and sqlalchemy and maybe not closing something somwhere?
#Set up SQL Connection
def co... | SQLAlchemy Misuse Causing Memory Leak? | My program is sucking up a meg every few seconds. I read that python doesn't see curors in garbage collection, so I have a feeling that I might be doing something wrong with my use of pydbc and sqlalchemy and maybe not closing something somwhere?
#Set up SQL Connection
def connect():
conn_string = 'DRIVER={Free... | [
"I would not necessarily blame SQLAlchemy. It could also be a problem of the underlaying driver. In general memory leaks are hard to detect. In any case you should ask on the SQLALchemy mailing list where the core developer Michael Bayer is responding on almost\nevery question...perhaps a better chance to get real ... | [
1
] | [] | [] | [
"memory_leaks",
"pyodbc",
"python",
"sqlalchemy"
] | stackoverflow_0005552932_memory_leaks_pyodbc_python_sqlalchemy.txt |
Q:
Content-Length is being stripped
I'm using webpy 0.34, python 2.6.6. I'm also using mimerender. I am trying to include the content-length in my http response, but for some reason the header is being removed. I say removed because I can create custom headers just fine, and I can see those headers on the client. But... | Content-Length is being stripped | I'm using webpy 0.34, python 2.6.6. I'm also using mimerender. I am trying to include the content-length in my http response, but for some reason the header is being removed. I say removed because I can create custom headers just fine, and I can see those headers on the client. But when I try to set content-length, the... | [
"If the data is sent as chunked (Transfer-Encoding: chunked), then the Content-Length header must be omitted, as per RFC 2616:\n\n\n[snip]\n\n\n\n\nIf a Transfer-Encoding header field (section 14.41) is present and\nhas any value other than \"identity\", then the transfer-length is\ndefined by use of the \"chunked\... | [
3
] | [] | [] | [
"python",
"web.py",
"web_services"
] | stackoverflow_0005553151_python_web.py_web_services.txt |
Q:
How to print all possibilities of nested lists in python?
Here is my list:
pos = [['det'], ['noun', 'adj'], ['noun'], ['vb'], ['det'], ['vb', 'noun', 'adj']]
Or
pos = ['det', ['noun', 'adj'], 'noun', 'vb', 'det', ['vb', 'noun', 'adj']]
I'm trying to print all the combinations:
det noun noun vb det vb
det adj ... | How to print all possibilities of nested lists in python? | Here is my list:
pos = [['det'], ['noun', 'adj'], ['noun'], ['vb'], ['det'], ['vb', 'noun', 'adj']]
Or
pos = ['det', ['noun', 'adj'], 'noun', 'vb', 'det', ['vb', 'noun', 'adj']]
I'm trying to print all the combinations:
det noun noun vb det vb
det adj noun vb det vb
det noun noun vb det noun
det adj noun vb det no... | [
"I think itertools.product() actually is what you are looking for:\npos = [['det'], ['noun', 'adj'], ['noun'],\n ['vb'], ['det'], ['vb', 'noun', 'adj']]\nfor x in itertools.product(*pos):\n print \" \".join(x)\n\nprints\ndet noun noun vb det vb\ndet noun noun vb det noun\ndet noun noun vb det adj\ndet adj ... | [
10,
1
] | [] | [] | [
"list",
"python",
"recursion"
] | stackoverflow_0005553518_list_python_recursion.txt |
Q:
Adding a column containing screen-scraped values to a CSV file
I am working on building a map of building permits issued in El Paso, TX. This is my first foray into the wonderful world of python, and it's been fun, but I cannot figure out the csv module to save my life.
I have a .csv file containing the fields 'Da... | Adding a column containing screen-scraped values to a CSV file | I am working on building a map of building permits issued in El Paso, TX. This is my first foray into the wonderful world of python, and it's been fun, but I cannot figure out the csv module to save my life.
I have a .csv file containing the fields 'Date', 'Building Number', 'Building Type', 'Description', 'Project Nam... | [
"Not really sure i fully understand your question, but if it's about using the CSV module, then your code should look something like that:\nimport csv,os\n\nwith open('foo.csv', 'rb') as r, open('foo.tmp', 'wb') as w:\n reader = csv.reader(r)\n writer = csv.writer(w)\n\n for row in reader:\n newrow=... | [
0,
0
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0005551477_csv_python.txt |
Q:
processing stdout in python
I have a script that keeps on dumping some values to the screen. Lets call this script 1
I need the values that gets dumped to the screen to be processed by another python script.Lets call this script2. I Script1 cant be stopped
I currently use python 2.2 so it would be great if someone... | processing stdout in python | I have a script that keeps on dumping some values to the screen. Lets call this script 1
I need the values that gets dumped to the screen to be processed by another python script.Lets call this script2. I Script1 cant be stopped
I currently use python 2.2 so it would be great if someone could provide an example without... | [
"I'm not going to say anything about code design here, because I really don't know what you are working on. \nBut for script2.py:\nimport sys\nfor line in sys.stdin:\n print \"From stdin:\", line\n\nAnd then run (at least on unix/linux, if you are on windows, google \"piping in powershell\"):\npython script1.py ... | [
7,
2
] | [] | [] | [
"python"
] | stackoverflow_0005553658_python.txt |
Q:
getting etag from 'google reader bundle' feed using universal feed parser in python
I am using the universal feed parser library in python to get an atom feed. This atom feed has been generated using google reader after bundling several subscriptions.
I am able to receive the latest feeds, however the feedparser.... | getting etag from 'google reader bundle' feed using universal feed parser in python | I am using the universal feed parser library in python to get an atom feed. This atom feed has been generated using google reader after bundling several subscriptions.
I am able to receive the latest feeds, however the feedparser.parse(url) returns a FeedParserDict which doesnot have the etag or modified values. I una... | [
"The Google Reader API does not support ETags or If-Modified-Since. However, it does support an ot=<timestamp in seconds since the epoch> parameter which you can use to restrict fetched data to items since you last attempted a fetch.\n"
] | [
0
] | [] | [] | [
"atom_feed",
"google_reader",
"python"
] | stackoverflow_0005552049_atom_feed_google_reader_python.txt |
Q:
stuck with first steps with py2app on os x with ActivePython
I have a simple python program I want to turn into an app.
py2app is what I need, according to my research.
I'm using ActivePython 2.7 on OS X (snow leopard).
via the PyPM tool (package manager) I have installed a package called py2app.
The documentatio... | stuck with first steps with py2app on os x with ActivePython | I have a simple python program I want to turn into an app.
py2app is what I need, according to my research.
I'm using ActivePython 2.7 on OS X (snow leopard).
via the PyPM tool (package manager) I have installed a package called py2app.
The documentation for py2app has a tutorial page http://svn.pythonmac.org/py2app/p... | [
"Try running this command:\n$ pypm files py2app | grep py2applet\n~/Library/Python/2.7/bin/py2applet \n~/Library/Python/2.7/lib/python/site-packages/py2app/script_py2applet.py \n$\n\nSo, do you have ~/Library/Python/2.7/bin/py2applet?\nYou can also add ~/Library/Python/2.7/bin/ to your $PATH (in ~/.profile) - which... | [
1
] | [] | [] | [
"activepython",
"macos",
"py2app",
"pypm",
"python"
] | stackoverflow_0005546032_activepython_macos_py2app_pypm_python.txt |
Q:
How to do integration tests for a Python script?
I have a Python command line script that connects to a database, generates files from the data and sends e-mails. I already have some unit-tests for the important components. Now I'd like to do tests that use several or all components together, load the test databas... | How to do integration tests for a Python script? | I have a Python command line script that connects to a database, generates files from the data and sends e-mails. I already have some unit-tests for the important components. Now I'd like to do tests that use several or all components together, load the test database with sample data and check for the correct output.
... | [
"Yes. The unittest libraries can be used for this. \nDon't be fooled by the name. A \"unit\" is not always a single, standalone class (or function).\nA \"unit\" can be a composite \"unit\" of one or more classes or modules or packages.\n",
"I use nosetests\nhttp://somethingaboutorange.com/mrl/projects/nose/1.0... | [
1,
1
] | [] | [] | [
"integration_testing",
"python",
"shell"
] | stackoverflow_0005554429_integration_testing_python_shell.txt |
Q:
How do I get the manager object for a Model foreign key field?
I'm trying to retrieve the Manager (or Model) for a Django foreign key. This should be straightforward but I can't seem to find the right attribtues.
class ModelA(models.Model):
pass
class ModelB(models.Model):
thing = models.ForeignKey(ModelA... | How do I get the manager object for a Model foreign key field? | I'm trying to retrieve the Manager (or Model) for a Django foreign key. This should be straightforward but I can't seem to find the right attribtues.
class ModelA(models.Model):
pass
class ModelB(models.Model):
thing = models.ForeignKey(ModelA)
Let's say I have the variable modelBInstance and the string "thin... | [
"All the relevant information about fields is stored in the _meta class of the model. In there, you'll see a get_field_by_name method that will return the actual foreign key field. From there, you can get the model it points at via rel.to.\nthing = ModelB._meta.get_field_by_name('thing')[0]\nprint thing.rel.to\n\n"... | [
2,
1
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0005554860_django_django_models_python.txt |
Q:
plotting a 2D matrix in python, code and most useful visualization
I have a very large matrix(10x55678) in "numpy" matrix format. the rows of this matrix correspond to some "topics" and the columns correspond to words(unique words from a text corpus). Each entry i,j in this matrix is a probability, meaning that wo... | plotting a 2D matrix in python, code and most useful visualization | I have a very large matrix(10x55678) in "numpy" matrix format. the rows of this matrix correspond to some "topics" and the columns correspond to words(unique words from a text corpus). Each entry i,j in this matrix is a probability, meaning that word j belongs to topic i with probability x. since I am using ids rather ... | [
"You could certainly use matplotlib's imshowor pcolor method to display the data, but as comments have mentioned, it might be hard to interpret without zooming in on subsets of the data.\na = np.random.normal(0.0,0.5,size=(5000,10))**2\na = a/np.sum(a,axis=1)[:,None] # Normalize\n\npcolor(a)\n\n\nYou could then so... | [
17,
2
] | [] | [] | [
"matplotlib",
"numpy",
"plot",
"python",
"visualization"
] | stackoverflow_0005552641_matplotlib_numpy_plot_python_visualization.txt |
Q:
Rounding the duration of two date values
I have two date values in Python which Im trying to get a rounded duration from.
For example: 01-01-2000 to 12-31-2099 is really "100 years", not "99 years".
I have an example, in Java, but Im not sure how to port this to Python speak:
round(endDateEpochInMilliseconds -sta... | Rounding the duration of two date values | I have two date values in Python which Im trying to get a rounded duration from.
For example: 01-01-2000 to 12-31-2099 is really "100 years", not "99 years".
I have an example, in Java, but Im not sure how to port this to Python speak:
round(endDateEpochInMilliseconds -startDateEpochInMilliseconds /(365.25 * 24 * 3600... | [
"import datetime\n\ndate1 = datetime.date(2000,1,1)\ndate2 = datetime.date(2099, 12, 31)\n\ndelta = date2-date1\n\nprint round(delta.days/365.25,0)\n\n",
"You defently must put endDateEpochInMilliseconds -startDateEpochInMilliseconds into brackets!\nround( (endDateEpochInMilliseconds -startDateEpochInMilliseconds... | [
4,
0
] | [] | [] | [
"date",
"python",
"rounding"
] | stackoverflow_0005554991_date_python_rounding.txt |
Q:
Casting in python
I have problem with casting in python.
I have a method in file module_A.py:
import Common.Models.Pax as Pax
def verify_passangers_data(self,paxes):
for i in range(len(paxes)):
pax=paxes[i]
Here is my Pax.py
class Pax:
""""""
#----------------------------------------------... | Casting in python | I have problem with casting in python.
I have a method in file module_A.py:
import Common.Models.Pax as Pax
def verify_passangers_data(self,paxes):
for i in range(len(paxes)):
pax=paxes[i]
Here is my Pax.py
class Pax:
""""""
#---------------------------------------------------------------------... | [
"\nHow can I check is pax is instance of Adult?\n\nUse the isinstance function:\nisinstance(pax, Common.Models.Pax.Adult)\n\nMake you have imported the class, though (e.g., import Common.Models.Pax).\n(Although purists would argue that there's rarely a need to check the type of a Python object. Python is dynamicall... | [
3,
0,
0,
0
] | [] | [] | [
"casting",
"python"
] | stackoverflow_0005555500_casting_python.txt |
Q:
How do I find a coordinate using cartesian coordinate system with just an index?
How do I find a coordinate using cartesian coordinate system with just an index?
For instance, 4 points to 1,2 and 9 points to 1,3.
Assume that the blocks will always wrap around 1,1.
I'm not married to the order of the grid, but ... | How do I find a coordinate using cartesian coordinate system with just an index? | How do I find a coordinate using cartesian coordinate system with just an index?
For instance, 4 points to 1,2 and 9 points to 1,3.
Assume that the blocks will always wrap around 1,1.
I'm not married to the order of the grid, but I want to call the location by an index rather then a coronate if at all possible.
I'm... | [
"Assuming the coordinates are:\n\nPurely integer\nFinite, say in a square of dimension 'N'.\n\nThen\n (x,y) -> x + N*y\n n -> (x,y) = (n%N, n/N)\n\nSee also: this wikipedia picture for a way of handling non-finite ranges.\nHere is an Excel image . Excel is quite a nice tool for prototyping a calculation. you can... | [
3,
1,
0
] | [
"Making some assumptions here, but you could solve these as linear equations:\n9 = 1x + 3y\n4 = 1x + 2y\n-----------\n5 = 0x + 1y\n\n-> 5 = y\n-> -6 = x, by plugging y back into one of the two linear equations\n\nNow you that you have (x, y), you can translate any coordinate pair (x', y') into an index:\nnewIndex ... | [
-1
] | [
"math",
"python"
] | stackoverflow_0005546751_math_python.txt |
Q:
Storing app constants in database
I am creating little blog app. Here is a snippet from my views:
views.py
from django.shortcuts import render_to_response
from blog.post.models import Post, Comment
from django.contrib.auth.models import User
from django.http import Http404
PAGE_SIZE = 5
ABSTRACT_CONTENT_SIZE = 30... | Storing app constants in database | I am creating little blog app. Here is a snippet from my views:
views.py
from django.shortcuts import render_to_response
from blog.post.models import Post, Comment
from django.contrib.auth.models import User
from django.http import Http404
PAGE_SIZE = 5
ABSTRACT_CONTENT_SIZE = 300
def main(request, page = 0):
pos... | [
"class SiteSettings(models.Model):\n value = models.IntegerField() # Assuming you are only using integer value \n type = models.CharField(unique=True) # could also make this the primary key\n\n\nPAGE_SIZE = SiteSettings.Objects.filter(type=\"page_size\").get() \n# you should be able to do this as well s... | [
4,
1
] | [] | [] | [
"django",
"django_views",
"python"
] | stackoverflow_0005555443_django_django_views_python.txt |
Q:
How do I force a download of xml in python?
I know there are several threads on this, but I can't find what I'm doing wrong.
This is the code that is erroring:
print 'Content-Type: text/xml \n'
print 'Content-Disposition:attachment;filename="test.qwc" \n'
print 'Content-Length:' + len(xml)
print xml
t... | How do I force a download of xml in python? | I know there are several threads on this, but I can't find what I'm doing wrong.
This is the code that is erroring:
print 'Content-Type: text/xml \n'
print 'Content-Disposition:attachment;filename="test.qwc" \n'
print 'Content-Length:' + len(xml)
print xml
the xml variable is simply a string of xml. The xm... | [
"\nThis can't be the code you used to serve the XML because \"string\" + len(whatever) is guaranteed to be an exception.\nYou are adding two newlines instead of one to each header line, so your header will contain only the first line. The header and the body are separated by two newlines, you're putting two right a... | [
4,
2
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0005555545_python_xml.txt |
Q:
iPython clear cache from within function call?
I am having memory issues with iPython, and I find that calling %clear out occasionally clears this out. It seems to be caching output somewhere within some of the functions that I'm calling.
I would like to build this into my function. clear out calls:
self.outputc... | iPython clear cache from within function call? | I am having memory issues with iPython, and I find that calling %clear out occasionally clears this out. It seems to be caching output somewhere within some of the functions that I'm calling.
I would like to build this into my function. clear out calls:
self.outputcache.flush()
How can I get a reference to the iPyth... | [
"The output cache is Out or _oh in your user namespace, so you can call Out.clear(). Edit: This might be a different output cache to self.outputcache. I'm not so familiar with 0.10.\nIf you need a reference to your IPython shell, in IPython 0.10, use __IP or __IPYTHON__. In 0.11 (the development version), use get_i... | [
3
] | [] | [] | [
"caching",
"ipython",
"python"
] | stackoverflow_0005555957_caching_ipython_python.txt |
Q:
Django - Removing extraneous unicode symbols from geraldo reports
I am using geraldo/reportlab to generate part reports on my database. Reportlab only lets me perform one queryset at a time (as I understand it.) As a result, certain aspects of my report are pulled out of ManyToMany fields and ForeignKeys.
For exam... | Django - Removing extraneous unicode symbols from geraldo reports | I am using geraldo/reportlab to generate part reports on my database. Reportlab only lets me perform one queryset at a time (as I understand it.) As a result, certain aspects of my report are pulled out of ManyToMany fields and ForeignKeys.
For example, class band_detail in reports.py:
ObjectValue(attribute_name='numbe... | [
"Try:\n[s.encode() for s in\n ObjectValue(attribute_name='number',\n left = 9*cm, \n get_value=lambda instance:\n Drawing.objects.filter(number=DrawingRevision.objects\n .filter(part__id=instance.id)\n ... | [
1
] | [] | [] | [
"django",
"python",
"reportlab",
"unicode"
] | stackoverflow_0005556282_django_python_reportlab_unicode.txt |
Q:
How can I edit a JSON element in-place, without rewriting the rest of the JSON object?
I am receiving several objects, currently in JSON, and need to be able to modify parts of them, while leaving the later parts EXACTLY, space for space, bit for bit, identical.
For instance, Imagine I was receiving following obje... | How can I edit a JSON element in-place, without rewriting the rest of the JSON object? | I am receiving several objects, currently in JSON, and need to be able to modify parts of them, while leaving the later parts EXACTLY, space for space, bit for bit, identical.
For instance, Imagine I was receiving following object
{
"example": [
{
"Name": "Thing One",
"Line2... | [
"The object_pairs_hook argument of the json load functions will allow you to use a OrderedDictionary such that you can retain the same order of the elements of JSON objects.\n",
"The best answer to this question may be \"Don't Do that.\"\nIf I need the bits to remain identical, I can replace \"Thing Three\" with ... | [
1,
1,
0
] | [] | [] | [
"json",
"python",
"xml"
] | stackoverflow_0005520594_json_python_xml.txt |
Q:
Django Haystack Indexing More than one models
I am trying to implement Haystack search for my website with Whoosh back-end. I have been able to successfully setup the haystack app and I can search the model that I have registered, but when I create the search_indexes.py file for another app, I am having the follow... | Django Haystack Indexing More than one models | I am trying to implement Haystack search for my website with Whoosh back-end. I have been able to successfully setup the haystack app and I can search the model that I have registered, but when I create the search_indexes.py file for another app, I am having the following issue:
I have two models: Member and Events. I ... | [
"I've had the same problem the past couple of days (nice timing). I decided to start where you left off and see if I couldn't isolate the cause a bit better.\nThe narrowed results are (at least partially) generated by a query of the models which are registered to the site (L298 and on). For my code, the query it ge... | [
2,
1
] | [] | [] | [
"django",
"django_haystack",
"python",
"whoosh"
] | stackoverflow_0005529760_django_django_haystack_python_whoosh.txt |
Q:
python mail no subject coming through
i am sending gmail via python but I do not get any subject. I realize the code I am showing you does not have any subject but i have tried many variations without success. can someone tell me how to implement a subject. The subject will be the same every time.
fromadd... | python mail no subject coming through | i am sending gmail via python but I do not get any subject. I realize the code I am showing you does not have any subject but i have tried many variations without success. can someone tell me how to implement a subject. The subject will be the same every time.
fromaddr = 'XXXX@gmail.com'
toaddrs = 'jas... | [
"There are 2 important step in sending out a Internet email - create a RFC-2822 message and then sent it using SMTP. You were looking at the SMTP part but has not created the right message in the first place. It is easier to demonstrate by doing it.\n>>> from email.mime.text import MIMEText\n>>>\n>>> fromaddr = 'XX... | [
4,
3,
2
] | [] | [] | [
"python",
"sendmail"
] | stackoverflow_0005555004_python_sendmail.txt |
Q:
Google Appengine URLFetch Timeouts - Any Best Practices?
New to python and appengine. Have got a little toy i've been playing with and ran into some script timeouts last night. I know you're capped at 10 seconds. Whats best practice for dealing with this?
edit
Sorry, should have been more clear. the URLFetch Time... | Google Appengine URLFetch Timeouts - Any Best Practices? | New to python and appengine. Have got a little toy i've been playing with and ran into some script timeouts last night. I know you're capped at 10 seconds. Whats best practice for dealing with this?
edit
Sorry, should have been more clear. the URLFetch Timeout is the issue I am having. By Default it is set to 5 second... | [
"You have not told us what your application does, so here are some generic suggestions:\n\nYou can trap the timeout exception with this exception class google.appengine.api.urlfetch.DownloadError and gently alert the users to retry.\nWeb request run time is 30 seconds max; if what you are trying to download is rela... | [
4
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0005554100_google_app_engine_python.txt |
Q:
Fixing the singularity of a function
Assume you have a function like
F = lambda x: sin(x)/x
Evaluating F(0.0) would result in a divide by zero warning, and would not give the expected result of 1.0. Is it possible to write another function fix_singularity that would give the desired result when applied to the ab... | Fixing the singularity of a function | Assume you have a function like
F = lambda x: sin(x)/x
Evaluating F(0.0) would result in a divide by zero warning, and would not give the expected result of 1.0. Is it possible to write another function fix_singularity that would give the desired result when applied to the above function, so that
fix_singularity(F)(0... | [
"numpy has a sinc() function, which is the normalised form of your function, i.e.\nF = lambda x: sin(pi*x) / (pi*x)\n\nIt handles the case for x == 0.0 correctly,\nIn [16]: x = numpy.linspace(-1,1,11)\n\nIn [17]: print x\n[-1. -0.8 -0.6 -0.4 -0.2 0. 0.2 0.4 0.6 0.8 1. ]\n\nTo \"unnormalize\" do,\nIn [22]: s... | [
7,
3,
2,
1,
0,
0
] | [] | [] | [
"nan",
"numpy",
"python",
"singular"
] | stackoverflow_0005556919_nan_numpy_python_singular.txt |
Q:
python code organisation
As a beginning programmer (I'm rather doing scripting), I'm struggling with my growing collection of scripts and modules.
Currently, small scripts are in a general folder that is added to my pythonpath. Specific projects get their own subfolder, but more and more I try to write the gene... | python code organisation | As a beginning programmer (I'm rather doing scripting), I'm struggling with my growing collection of scripts and modules.
Currently, small scripts are in a general folder that is added to my pythonpath. Specific projects get their own subfolder, but more and more I try to write the general parts of those projects as... | [
"General-purpose custom modules should go to ~/.local/lib/pythonX.Y/site-packages, or to /usr/local/lib/pythonX.Y/site-packages if they should be available to everyone. Both paths are automatically available in your $PYTHONPATH. (The former is available since Python 2.6 – see PEP 370 – Per user site-packages dire... | [
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0005557089_python.txt |
Q:
How can I find which interface a connection to a given host will be routed through?
My script needs configure SNMP trap destinations for a number of hosts which exist different networks. It is therefor important that the trap destination address is of the interface that is accessible to the remote node.
I don't re... | How can I find which interface a connection to a given host will be routed through? | My script needs configure SNMP trap destinations for a number of hosts which exist different networks. It is therefor important that the trap destination address is of the interface that is accessible to the remote node.
I don't really want to parse the linux kernel routing table as it's likely to be fragile and break ... | [
"The best answer for this in all scenarios is given by the Linux command ip route get $DEST. This takes into account policy routing (multiple routing tables selected by different selectors).\nSyntax (from ip route help):\n ip route get ADDRESS [ from ADDRESS iif STRING ]\n [ oif STRING ... | [
3,
1
] | [] | [] | [
"linux",
"python",
"routing"
] | stackoverflow_0005556373_linux_python_routing.txt |
Q:
CRC32 checksum in Python with hex input
I'm wanting to calculate the CRC32 checksum of a string of hex values in python. I found zlib.crc32(data) and binascii.crc32(data), but all the examples I found using these functions have 'data' as a string ('hello' for example). I want to pass hex values in as data and find... | CRC32 checksum in Python with hex input | I'm wanting to calculate the CRC32 checksum of a string of hex values in python. I found zlib.crc32(data) and binascii.crc32(data), but all the examples I found using these functions have 'data' as a string ('hello' for example). I want to pass hex values in as data and find the checksum. I've tried setting data as a h... | [
"I think you are looking for binascii.a2b_hex():\n>>> binascii.crc32(binascii.a2b_hex('18329a7e'))\n-1357533383\n\n",
">>> import struct,binascii\n>>> ncrc = lambda numVal: binascii.crc32(struct.pack('!I', numVal))\n>>> ncrc(0x18329a7e)\n-1357533383\n\n",
"Try converting the list of hex values to a string:\nt =... | [
12,
1,
0
] | [] | [] | [
"checksum",
"crc32",
"hex",
"python",
"string"
] | stackoverflow_0005557214_checksum_crc32_hex_python_string.txt |
Q:
py.magic in py.test 2.0.2
In py.test 2.0.2, What do we use in place of
py.magic.autopath().dirpath()
since 'py.magic' has been removed after py-1.0.2
A:
os.path.abspath(os.path.dirname(file))
// gives the parent directory of the current file.
| py.magic in py.test 2.0.2 | In py.test 2.0.2, What do we use in place of
py.magic.autopath().dirpath()
since 'py.magic' has been removed after py-1.0.2
| [
"os.path.abspath(os.path.dirname(file)) \n// gives the parent directory of the current file. \n"
] | [
0
] | [] | [] | [
"python",
"testing"
] | stackoverflow_0005459864_python_testing.txt |
Q:
python startswith method
I'm a bit new to python and can't figure out why this is not working.
I have a variable that is something like this:
[u'\n Data I want ']
but I also have variables that are simply:
[u' more Data I want ']
I am running the variables ... | python startswith method | I'm a bit new to python and can't figure out why this is not working.
I have a variable that is something like this:
[u'\n Data I want ']
but I also have variables that are simply:
[u' more Data I want ']
I am running the variables through a loop but I need to s... | [
"How about:\ndef stripName(name):\n return name[0].strip()\n\n?\n",
"I think you are passing in a list instance and then converting that into a string using str (in name=str(name)). Try name=name[0] instead.\nAlso, the code looks improperly formatted. The lines following def should be indented by one level.\nA... | [
5,
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0005557922_python.txt |
Q:
Django: how can I apply a middleware action only to certain filetypes?
I'm working in Django, and I want to apply some middleware ONLY to HTML pages - not to images, js, css etc. This is to reduce the number of requests on the server.
This is my middleware code:
class checkLdapUser:
def process_request(self, r... | Django: how can I apply a middleware action only to certain filetypes? | I'm working in Django, and I want to apply some middleware ONLY to HTML pages - not to images, js, css etc. This is to reduce the number of requests on the server.
This is my middleware code:
class checkLdapUser:
def process_request(self, request):
if response.META['CONTENT_TYPE'] is 'text/html':
... | [
"You're on the right track, but you need to put that code in process_response rather than process_request. The latter runs before the request is handled by your view code, so it doesn't have access to the response and its content type.\n"
] | [
2
] | [] | [] | [
"django",
"http",
"python"
] | stackoverflow_0005558008_django_http_python.txt |
Q:
Pylint not working with Emacs GUI on OS X; works from command-line
When run from the command-line (emacs filename.py) flymake and pylint work perfectly together. Errors are highlighted properly. (Although I can't tooltip hover to get error details because it's text-mode.)
When run from the GUI (Carbon Emacs) Flyma... | Pylint not working with Emacs GUI on OS X; works from command-line | When run from the command-line (emacs filename.py) flymake and pylint work perfectly together. Errors are highlighted properly. (Although I can't tooltip hover to get error details because it's text-mode.)
When run from the GUI (Carbon Emacs) Flymake returns immediately, and the first line in the file is highlighted wi... | [
"To more clearly see what's going wrong, increase flymake's log level, then look in *messages*:\n(setq flymake-log-level 3)\n\nWithout that info, I wouldn't speculate on the likely problem.\nThere's a trick for avoiding the environment.plist approach, BTW; you can get Emacs to ask your regular shell for your prefer... | [
2
] | [] | [] | [
"emacs",
"flymake",
"macos",
"pylint",
"python"
] | stackoverflow_0005543989_emacs_flymake_macos_pylint_python.txt |
Q:
Python base64 data decode and byte order convert
I am now using python base64 module to decode a base64 coded XML file, what I did was to find each of the data (there are thousands of them as for exmaple in "ABC....", the "ABC..." was the base64 encoded data) and add it to a string, lets say s, then I use base64.b... | Python base64 data decode and byte order convert | I am now using python base64 module to decode a base64 coded XML file, what I did was to find each of the data (there are thousands of them as for exmaple in "ABC....", the "ABC..." was the base64 encoded data) and add it to a string, lets say s, then I use base64.b64decode(s) to get the result, I am not sure of the re... | [
"Each base64 encoded string should be decoded separately - you can't concatenate encoded strings (and get a correct decoding).\nThe result of the decode is a string, of byte-buffer - in Python, they're equivalent.\nRegarding the network/host order - sequences of bytes, have no such 'order' (or endianity) - it only ... | [
2,
2,
1
] | [] | [] | [
"base64",
"byte",
"python"
] | stackoverflow_0003422457_base64_byte_python.txt |
Q:
finding divisors of N using a list comprehension
I have started to write some Python code. What I have is:
from math import *
def ex(N):
l = []
sum = 0
N = abs(int(N));
for n in range(1,N):
if N % n == 0:
l.append(n)
sum += n
l.append(N)
print ' of ... | finding divisors of N using a list comprehension | I have started to write some Python code. What I have is:
from math import *
def ex(N):
l = []
sum = 0
N = abs(int(N));
for n in range(1,N):
if N % n == 0:
l.append(n)
sum += n
l.append(N)
print ' of '+str(N),l
print 'SUM', (sum+N)
I don't know if t... | [
"l = [n for n in range(1,N+1) if N % n == 0]\ntotal = sum(l)\n\n",
"Very simply (this actually uses a generator expression rather than a list comprehension, if you don't need to keep the results).\ndef ex(N):\n N = abs(int(N))\n print 'SUM', sum(n for n in xrange(1, N + 1) if N % n == 0)\n\nIf you care abou... | [
6,
5,
4,
0
] | [] | [] | [
"python"
] | stackoverflow_0005558488_python.txt |
Q:
Python routes non-parameter wildcards
I am using pylons and have a trouble with the terminating '/' character, simply, I want to ignore it.
My route file looks like this:
with map.submapper(path_prefix='/app', controller='app') as m:
m.connect('{_:/?}', action='index')
and I would like much to wri... | Python routes non-parameter wildcards | I am using pylons and have a trouble with the terminating '/' character, simply, I want to ignore it.
My route file looks like this:
with map.submapper(path_prefix='/app', controller='app') as m:
m.connect('{_:/?}', action='index')
and I would like much to write /? instead of {_:/?}, as it sets the req... | [
"Instead of \"{_:/?}\" or \"/?\", use \"\":\nwith map.submapper(path_prefix='/app', controller='app') as m:\n m.connect('', action='index')\n\n"
] | [
1
] | [] | [] | [
"pylons",
"python",
"routes"
] | stackoverflow_0005463945_pylons_python_routes.txt |
Q:
Python cx_Oracle ImportError: DLL load failed
Im attempting to import cx_Oracle and it outputs the error
ImportError: DLL load failed: The specified module could not be found
Im doing this on a win 2003 server with python 2.7 and cx_Oracle 5.1, installed from the .msi. Oracle 10g (3 instances) exist on the same ... | Python cx_Oracle ImportError: DLL load failed | Im attempting to import cx_Oracle and it outputs the error
ImportError: DLL load failed: The specified module could not be found
Im doing this on a win 2003 server with python 2.7 and cx_Oracle 5.1, installed from the .msi. Oracle 10g (3 instances) exist on the same server. Looking at other questions, I have validat... | [
"Using (Dependency Walker) on the cx_oracle lib should make it clear very fast what is missing.\nIf you cannot use that, a typical guess would be the oracle client libs oraclntsh not being accessible.\n"
] | [
0
] | [] | [] | [
"cx_oracle",
"python"
] | stackoverflow_0005557607_cx_oracle_python.txt |
Q:
Using Python's Subprocess to Display Output in New Xterm Window
I am trying to output different information in two terminals from the same Python script (much like this fellow). The way that my research has seemed to point to is to open a new xterm window using subprocess.Popen and running cat to display the stdin... | Using Python's Subprocess to Display Output in New Xterm Window | I am trying to output different information in two terminals from the same Python script (much like this fellow). The way that my research has seemed to point to is to open a new xterm window using subprocess.Popen and running cat to display the stdin of the terminal in the window. I would then write the necessary info... | [
"This doesn't work because you pipe stuff to xterm itself not the program running inside xterm. Consider using named pipes:\nimport os\nfrom subprocess import Popen, PIPE\nimport time\n\nPIPE_PATH = \"/tmp/my_pipe\"\n\nif not os.path.exists(PIPE_PATH):\n os.mkfifo(PIPE_PATH)\n\nPopen(['xterm', '-e', 'tail -f %s'... | [
4
] | [] | [] | [
"pipe",
"python",
"subprocess"
] | stackoverflow_0005558720_pipe_python_subprocess.txt |
Q:
python regular expression appengine
i have an application that uses appengine with python. Its a social network that maps places. I want to have each place in this kind or url: www.mysite.com/place/nameoftheplace
for that i did this regular expression as a parameter of mine WSGIApplication:
r'/place/(.*)'
and on... | python regular expression appengine | i have an application that uses appengine with python. Its a social network that maps places. I want to have each place in this kind or url: www.mysite.com/place/nameoftheplace
for that i did this regular expression as a parameter of mine WSGIApplication:
r'/place/(.*)'
and on the get requisition i have:
def get(self... | [
"It sounds like you're using relative URLs in your <link rel-'stylesheet' href='css/something'> tags in your HTML, so the browser is trying to fetch /place/css/something.\n\nIn your HTML, use, e.g., <link rel='stylesheet' href='/static/something.css'>, and in app.yaml use:\n- url: /static/\n static_dir: static\n\n... | [
2
] | [] | [] | [
"google_app_engine",
"python",
"regex",
"seo"
] | stackoverflow_0005558837_google_app_engine_python_regex_seo.txt |
Q:
Python convert dictionary into tuple
How do I convert a dictionary into a tuple? Below is my dynamic dictionary.
genreOptions = GenreGuideServiceProxy.get_all_genres();
genreDictionary = {};
for genre in genreOptions:
genreDictionary[genre.name] = genre.name;
A:
tuples = genreDictionary.items()
See ... | Python convert dictionary into tuple | How do I convert a dictionary into a tuple? Below is my dynamic dictionary.
genreOptions = GenreGuideServiceProxy.get_all_genres();
genreDictionary = {};
for genre in genreOptions:
genreDictionary[genre.name] = genre.name;
| [
"tuples = genreDictionary.items()\n\nSee http://docs.python.org/library/stdtypes.html#dict.items\n",
"Do you want to make (key, value) pairs? Here is code to generate a list of (key, value) tuples...\nthelist = [(key, genreOptions[key]) for key in genreOptions]\n\nAhh I see there is a more efficient answer above.... | [
7,
3,
1
] | [] | [] | [
"django_forms",
"python"
] | stackoverflow_0005559056_django_forms_python.txt |
Q:
Help with specific Python re application
folks,
I am working on using Python re to parse a configuration file that contains lines like this:
[VAR: abc123]
...
...
.CSIIND~~~LOCAL~~~I4~~~0~~~
[VAR: def234]
...
<bunch of stuff>
...
.CSIIND~~~LOCAL~~~I4~~~1~~~
...
I'm trying to build up to extract... | Help with specific Python re application | folks,
I am working on using Python re to parse a configuration file that contains lines like this:
[VAR: abc123]
...
...
.CSIIND~~~LOCAL~~~I4~~~0~~~
[VAR: def234]
...
<bunch of stuff>
...
.CSIIND~~~LOCAL~~~I4~~~1~~~
...
I'm trying to build up to extracting something like this:
varname / CSIIND
abc1... | [
"Need more detail. Is the variable the \"var\" the thing enclosed in square brackets? With the name before the \":\" and the value everything after?\n[foo:\"Mr Bar's Foo shop\"]\nIf so, you might just be able to split on the \":\" rather than bothering with a complex regex.\nOk look at this:\nimport re\nstuff0='[... | [
0,
0
] | [] | [] | [
"parsing",
"python",
"regex"
] | stackoverflow_0005555224_parsing_python_regex.txt |
Q:
Grabbing output FILE from Python Popen process?
I have written a python program to interface with a compiled program (call it ProgramX) that has some idiosyncrasies that are proving difficult to deal with. I need to feed many thousands of input files to ProgramX via my python program. What I would like to do is to... | Grabbing output FILE from Python Popen process? | I have written a python program to interface with a compiled program (call it ProgramX) that has some idiosyncrasies that are proving difficult to deal with. I need to feed many thousands of input files to ProgramX via my python program. What I would like to do is to grab the output file that ProgramX creates with each... | [
"To do what your shell script above does, assuming you've only got one ProgramX* in the current directory:\nimport glob, os\n\nprogramxoutput = glob.glob('ProgramX*')[0]\nos.rename(programxoutput, 'input.output')\n\nIf you need to sort by time, etc., there are ways to do that too (look at os.stat), but using the mo... | [
2,
2,
0
] | [] | [] | [
"bash",
"popen",
"python"
] | stackoverflow_0005559114_bash_popen_python.txt |
Q:
what is meant by parallel lists in Python
i have just started using python and i can't figure out what is meant by parallel list
any info would be great . i think it is just using two list to store info
A:
"Parallel lists" is a variation on the term "parallel array". The idea is that instead of having a singl... | what is meant by parallel lists in Python | i have just started using python and i can't figure out what is meant by parallel list
any info would be great . i think it is just using two list to store info
| [
"\"Parallel lists\" is a variation on the term \"parallel array\". The idea is that instead of having a single array/list/collection of records (objects with attributes, in Python terminology) you have a separate array/list/collection for each field of a conceptual record.\nFor example, you could have Person record... | [
4,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0005559159_python.txt |
Q:
What profiling do I need to do to optimize a multi-step producer-consumer model?
I have a 3-step producer/consumer setup.
Client creates JSON-encoded dictionaries and sends them to PipeServer via a named pipe
Here are my threading.Thread subclasses:
PipeServer creates a named pipe and places messages into a queue ... | What profiling do I need to do to optimize a multi-step producer-consumer model? | I have a 3-step producer/consumer setup.
Client creates JSON-encoded dictionaries and sends them to PipeServer via a named pipe
Here are my threading.Thread subclasses:
PipeServer creates a named pipe and places messages into a queue unprocessed messages
Processor gets items from unprocessed messages, processes them (v... | [
"Generally speaking, you want to optimize for the maximum throughput of your slowest component. In this case, it sounds like either Client or Printer. If it's the Client, you want just enough Printers and Processors to be able to keep up with new messages (maybe that's just one!). Otherwise you'll be wasting resour... | [
2
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0005558864_multithreading_python.txt |
Q:
Private functions / Variables enforcement in python
I see a lot of python code that does "loose" private variables / functions. They'll declare functions / variables with one underscore (eg. _foo) and then use it just in the class / file. It really annoys me that they don't use the double underscore because eventu... | Private functions / Variables enforcement in python | I see a lot of python code that does "loose" private variables / functions. They'll declare functions / variables with one underscore (eg. _foo) and then use it just in the class / file. It really annoys me that they don't use the double underscore because eventually, someone will call this "private" member from outsid... | [
"No. And that's the philosophy of python: Do not make the compiler/parser enforce privacy since developers who want to access private members have ways to do so anyway (reflection etc.).\nThe idea is telling people Hey, this is not part of the public API. If you use it improperly, it could breaks things or kill you... | [
9,
6
] | [] | [] | [
"python"
] | stackoverflow_0005559256_python.txt |
Q:
python regular expression
whats the regular expression in python for any string without the char '/'. Thanks
A:
No need for regular expressions
>>> s = 'asdf'
>>> '/' in s
False
>>> s = 'asd/asdf'
>>> '/' in s
True
A:
I don't know python's flavor of regex, but I can only imagine it would look something like th... | python regular expression | whats the regular expression in python for any string without the char '/'. Thanks
| [
"No need for regular expressions\n>>> s = 'asdf'\n>>> '/' in s\nFalse\n>>> s = 'asd/asdf'\n>>> '/' in s\nTrue\n\n",
"I don't know python's flavor of regex, but I can only imagine it would look something like this:\n^[^/]*$\n\n"
] | [
8,
3
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0005559349_python_regex.txt |
Q:
QtScript Introspection/Reflection?
Does QtScript support introspection/reflection (i.e. like python's dir() for example) that would enble me to 'map out' an api from the inside by exploring the object model at runtime?
A:
You really should look more at QObject and QMetaObject.
QScriptValue supports the types def... | QtScript Introspection/Reflection? | Does QtScript support introspection/reflection (i.e. like python's dir() for example) that would enble me to 'map out' an api from the inside by exploring the object model at runtime?
| [
"You really should look more at QObject and QMetaObject.\nQScriptValue supports the types defined in the ECMA-262 standard: The primitive types, which are Undefined, Null, Boolean, Number, and String; and the Object type. Additionally, Qt Script has built-in support for QVariant, QObject and QMetaObject.\nFrom Qt's... | [
1,
1
] | [] | [] | [
"introspection",
"python",
"qt",
"qtscript"
] | stackoverflow_0005547692_introspection_python_qt_qtscript.txt |
Q:
Framework for acceptance testing involving text files with regexes
I have created a software package that produces a directory full of results. I would like to test the results from some standard input files. The directories should be somewhat similar on each run except for a limited number of things that change: ... | Framework for acceptance testing involving text files with regexes | I have created a software package that produces a directory full of results. I would like to test the results from some standard input files. The directories should be somewhat similar on each run except for a limited number of things that change: traces of the current date/time, a run-specific UUID, current Subversion... | [
"I sounds like you should take a look at TextTest. I haven't used it personally but based on what I know it ought to fit into your needs pretty well.\n",
"Cram is derived from Mercurial's test format, which basically works on shell transcripts but lets you use regular expressions. It sounds ideal for your use ca... | [
0,
0
] | [] | [] | [
"acceptance_testing",
"python",
"regex",
"testing"
] | stackoverflow_0005544158_acceptance_testing_python_regex_testing.txt |
Q:
Set up coverage configuration on pydev
I reinstalled Eclipse with pydev (2.0.0.2011040403) but the run configuration with "coverage" is missing from the debug and run menus. I am sure that option used to be there, how can I get it show up again?
A:
This changed on PyDev 2.0, now, instead of a run as coverage, yo... | Set up coverage configuration on pydev | I reinstalled Eclipse with pydev (2.0.0.2011040403) but the run configuration with "coverage" is missing from the debug and run menus. I am sure that option used to be there, how can I get it show up again?
| [
"This changed on PyDev 2.0, now, instead of a run as coverage, you have to open the code-coverage view (under the window > views menu) and select the 'enable code coverage for new launches' options -- after that, any launch (regular or unit-test) will be automatically traced by the code-coverage.\nThere's a small v... | [
5
] | [] | [] | [
"code_coverage",
"eclipse",
"pydev",
"python"
] | stackoverflow_0005554784_code_coverage_eclipse_pydev_python.txt |
Q:
Calling a method of a class, the classname is a variable
I came up with this solution. But this looks too complicated. There must be a better and easier way. And second : is there a way to dynamically import the class ?
class_name = "my_class_name" # located in the module : my_class_name.py
impo... | Calling a method of a class, the classname is a variable | I came up with this solution. But this looks too complicated. There must be a better and easier way. And second : is there a way to dynamically import the class ?
class_name = "my_class_name" # located in the module : my_class_name.py
import my_class_name from my_class_name
my_class = glob... | [
"Take a look at the __import__ built-in function. It does exactly what you expect it to do.\nEdit: as promised, here's an example. Not a very good one, I just kinda got bad news and my head is elsewhere, so you'd probably write a smarter one with more practical application for your context. At least, it illustrates... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0005559531_python.txt |
Q:
Finding an object within an image containing many objects (Python)
I have to create a python image processing program which reads in two images, one containing a single object and the other containing several objects. However, the first images object is present in the second image but is surrounded by other object... | Finding an object within an image containing many objects (Python) | I have to create a python image processing program which reads in two images, one containing a single object and the other containing several objects. However, the first images object is present in the second image but is surrounded by other objects (some similar).
The images are both the same size but I am having pro... | [
"The following is not Python, but a proof of concept for Image Correlation.\nThe following example is Mathematic code:\n\nThe same for Combos: \n\n",
"I guess the most straightforward way to achieve this is to compute the correlation map of the two images. Just convolve the two images using a scientific library ... | [
2,
1
] | [] | [] | [
"algorithm",
"image_processing",
"python"
] | stackoverflow_0005555975_algorithm_image_processing_python.txt |
Q:
Prevent a file from being created in python
I'm working on a python server which concurrently handles transactions on a number of databases, each storing performance data about a different application. Concurrency is accomplished via the Multiprocessing module, so each transaction thread starts in a new process, a... | Prevent a file from being created in python | I'm working on a python server which concurrently handles transactions on a number of databases, each storing performance data about a different application. Concurrency is accomplished via the Multiprocessing module, so each transaction thread starts in a new process, and shared-memory data protection schemes are not ... | [
"The usual Unix-style way of handling this for regular files is to just try to create the file and see if it fails. In Python's case, that would be:\ntry:\n os.open(filename, os.O_WRONLY | os.O_CREAT | os.O_EXCL)\nexcept IOError: # or OSError?\n # Someone else created it already.\n\nAt the very least, you ca... | [
1,
0,
0,
0,
0
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0005559660_python_sqlite.txt |
Q:
pythonic way of finding a value in a list which hasn't been supplied
Here is an example of what I mean:
a = 0
b = 1
c = range(3)
so I would like to find the missing number in the list which in this case would be 2.
The way I have programmed it at the moment is cumbersome and ugly.
If there was a function opposit... | pythonic way of finding a value in a list which hasn't been supplied | Here is an example of what I mean:
a = 0
b = 1
c = range(3)
so I would like to find the missing number in the list which in this case would be 2.
The way I have programmed it at the moment is cumbersome and ugly.
If there was a function opposite to list.append() so that I could remove values from the list instead tha... | [
"Use sets:\n>>> a = 0\n>>> b = 1\n>>> c = range(3)\n>>> set(c) - set([a, b])\nset([2])\n\n",
"Use set difference by converting the list to a set, then preforming the set difference operation.\n>>> supplied_list = [0, 1]\n>>> list(set(range(3)) - set(supplied_list))\n[2]\n\n",
"list.remove will remove the first ... | [
4,
2,
1
] | [] | [] | [
"list",
"python"
] | stackoverflow_0005559707_list_python.txt |
Q:
Python: regex on big file. Easy way?
I need to run a regex match over a file, but I'm faced with an unexpected problem: the file is too big to read() or mmap() in one call, File objects don't support the buffer() interface, and the regex module takes only strings or buffers.
Is there an easy way to do this?
A:
T... | Python: regex on big file. Easy way? | I need to run a regex match over a file, but I'm faced with an unexpected problem: the file is too big to read() or mmap() in one call, File objects don't support the buffer() interface, and the regex module takes only strings or buffers.
Is there an easy way to do this?
| [
"The Python mmap module provides a nice Python-friendly way of memory mapping a file. On a 32-bit operating system, the maximum size of the file is will be limited to no more than a GB or maybe two, but on a 64-bit OS you will be able to memory map a file of arbitrary size (until storage sizes exceed 264, of course... | [
6
] | [] | [] | [
"file",
"io",
"python",
"regex"
] | stackoverflow_0005559536_file_io_python_regex.txt |
Q:
How can I convert a list type to a numeric type in Python
I have a external file that is a single column of floating point numbers ( want to be able to expand it to have multiple columns in the future). I want to import it into an array. The file is a cvs file but it just as well could be a txt file.
I am using:
r... | How can I convert a list type to a numeric type in Python | I have a external file that is a single column of floating point numbers ( want to be able to expand it to have multiple columns in the future). I want to import it into an array. The file is a cvs file but it just as well could be a txt file.
I am using:
reader = csv.reader(open("e=0.6.csv"))
table = []
for row in rea... | [
"reader = csv.reader(open(\"e=0.6.csv\"))\ntable = tuple(float(col) for row in reader for col in row)\n\n",
"Why do you make a new list called values? Why not append to table instead? i.e.\nreader = csv.reader(open(\"e=0.6.csv\"))\ntable = []\nfor row in reader: \n for col in row: \n table.append(float(... | [
2,
1,
1,
0,
0,
0,
0
] | [] | [] | [
"list",
"numeric",
"python",
"types"
] | stackoverflow_0005559284_list_numeric_python_types.txt |
Q:
On mod_wsgi daemon process' restarting
I have a wsgi application running as a mod_wsgi daemon process (in daemon mode). My setup is such that each daemon restarts after 1000 requests, as shown in the mod_wsgi configuration guidelines:
http://code.google.com/p/modwsgi/wiki/ConfigurationGuidelines
WSGIDaemonProcess ... | On mod_wsgi daemon process' restarting | I have a wsgi application running as a mod_wsgi daemon process (in daemon mode). My setup is such that each daemon restarts after 1000 requests, as shown in the mod_wsgi configuration guidelines:
http://code.google.com/p/modwsgi/wiki/ConfigurationGuidelines
WSGIDaemonProcess www.site.com threads=1 processes=4 maximum-r... | [
"The use of 'maximum-requests' in production settings is not recommended unless your application is so broken that it leaks memory badly and you can't/don't want to fix it.\nThat said, the flag triggered by maximum requests is currently set at the start of the request which caused the count to reach that value. Thi... | [
3
] | [] | [] | [
"mod_wsgi",
"python",
"wsgi"
] | stackoverflow_0005556569_mod_wsgi_python_wsgi.txt |
Q:
SQLAlchemy 3.2 and MS SQL Connectivity
I'm currently working on a proof of concept application using Python 3.2 via SQLAlchemy with a MS SQL Server back end. Thus far, I'm hitting a brick wall looking for ways to actually do the connection. Most discussions point to using pyODBC, however it does not support Pyth... | SQLAlchemy 3.2 and MS SQL Connectivity | I'm currently working on a proof of concept application using Python 3.2 via SQLAlchemy with a MS SQL Server back end. Thus far, I'm hitting a brick wall looking for ways to actually do the connection. Most discussions point to using pyODBC, however it does not support Python 3.x yet.
Does anyone have any connection ... | [
"At this moment none of the known Python drivers to connect to Sql Server had a compatible python 3000 version.\n\nPyODBC\nmxODBC\npymssql\nzxjdbc \nAdoDBAPI\n\n"
] | [
0
] | [] | [] | [
"python",
"sql_server",
"sqlalchemy"
] | stackoverflow_0005559645_python_sql_server_sqlalchemy.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.