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:
how to create a "byte stream" from different data type in python
Here is a little problem: I want to create a byte stream (a table of byte integer) from different data type, integer of variable length, string.
val1 = 0x2
val2 = 0x0001020304050607
val3 = "blablabla"
And I want to obtain a stream like:
byteStream =... | how to create a "byte stream" from different data type in python | Here is a little problem: I want to create a byte stream (a table of byte integer) from different data type, integer of variable length, string.
val1 = 0x2
val2 = 0x0001020304050607
val3 = "blablabla"
And I want to obtain a stream like:
byteStream = val1 + val2 + val3
byteStream = [0x02, 0x00, 0x01, 0x02, 0x03, 0x04, ... | [
"import struct\n\nval1 = 0x2\nval2 = 0x0001020304050607\nval3 = \"blablabla\"\n\ndata=struct.pack('>BQ9s',val1,val2,val3)\nprint repr(data)\n\nyields\n'\\x02\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07blablabla'\n\nBQ9s tells struct.pack to pack one unsigned int (1 byte) , followed by one unsigned long long (8 bytes) f... | [
3
] | [] | [] | [
"byte",
"python"
] | stackoverflow_0007246001_byte_python.txt |
Q:
Python - String to list
I need cast a list to a string and get back the string to a list. There's a python way to make this behavior?
l1 = ['aa','bb','cc']
s = str(l1)
l2 = cast_string_to_list(s)
print l2
"['aa','bb','cc']"
A:
Use a serialization library like json:
import json
l1 = ['aa','bb','cc']
s = json.dum... | Python - String to list | I need cast a list to a string and get back the string to a list. There's a python way to make this behavior?
l1 = ['aa','bb','cc']
s = str(l1)
l2 = cast_string_to_list(s)
print l2
"['aa','bb','cc']"
| [
"Use a serialization library like json:\nimport json\n\nl1 = ['aa','bb','cc']\ns = json.dumps(l1)\nl2 = json.loads(s)\n\nprint s\nprint l1 == l2\n\n",
"In somewhat recent Python versions, you can use ast.literal_eval, which is essentially eval without the security problems. You could also try to do the parsing yo... | [
9,
4,
3,
1
] | [
"If you are always working with a list, then the following kind of thing should work just fine. Beware, it will not cast ints to ints and such; they will always be string items in the list.\nl1 = ['aa','bb','cc']\ns = str(l1)\n\nl2 = s[1:-1].split(',')\n\nprint l2\n['aa', 'bb', 'cc']\n\nYou probably want to check t... | [
-4
] | [
"list",
"python",
"serialization",
"string"
] | stackoverflow_0007245827_list_python_serialization_string.txt |
Q:
GQL/Alternatives to retrieve data from Many to Many relationship
I haven't been able to find a good simple tutorial on how to query many to many relationship model using GQL or any alternative. Can anyone give me an example with Python using GQL or any alternative?
EDIT:
results = RestaurantReview.all().filter("Re... | GQL/Alternatives to retrieve data from Many to Many relationship | I haven't been able to find a good simple tutorial on how to query many to many relationship model using GQL or any alternative. Can anyone give me an example with Python using GQL or any alternative?
EDIT:
results = RestaurantReview.all().filter("Restaurant = %s", restaurant_key).filter("User = %s", user[0].key().__st... | [
"ManyToManyModel.all().filter(\"model1 =\", model1_key).filter(\"model2 =\", model2_key).fetch()\nManyToManyModel is a model with two properties, both reference properties, model1 and model2. model1_key and model2_key are each a single key for their respective fields. For more in-depth information, see this helpful... | [
2
] | [] | [] | [
"datastore",
"google_app_engine",
"python"
] | stackoverflow_0007246042_datastore_google_app_engine_python.txt |
Q:
Python AJAX response string literal
I have an AJAX response that returns a JSON object. One of the dictionary values is supposed to read:
"image\/jpeg"
But instead in reads:
"images\\/jpeg"
I've gone through the documentation on string literals and how to ignore escape sequences, and I've tried to prefix the strin... | Python AJAX response string literal | I have an AJAX response that returns a JSON object. One of the dictionary values is supposed to read:
"image\/jpeg"
But instead in reads:
"images\\/jpeg"
I've gone through the documentation on string literals and how to ignore escape sequences, and I've tried to prefix the string with 'r', but so far no luck.
My JSON e... | [
"According to the JSON spec, the \\ character should be escaped as \\\\ in JSON.\nSo the Python json library is correct:\n>>> import json\n>>> json.dumps({\"type\": r\"image\\/jpeg\", \"size\": False})\n'{\"type\": \"image\\\\\\\\/jpeg\", \"size\": false}'\n\nWhen the JSON is parsed/evaluated in the browser, the ty... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0007229465_python.txt |
Q:
coarse-grain parallelization with python using multicore processors
I have a python program, at a point it calls an external program (foo). This external program needs to be run several times. The exact number of times (num_pros) is variable and depends on the input.
Because this external program is by far the mos... | coarse-grain parallelization with python using multicore processors | I have a python program, at a point it calls an external program (foo). This external program needs to be run several times. The exact number of times (num_pros) is variable and depends on the input.
Because this external program is by far the most time consuming part of my Python program I would like to take advantage... | [
"I think multiprocessing is more intended for the case where the work you want to farm out is in python, not a totally different process. It's all about using fork and passing stuff from python process to python process, so I don't think it will work for you.\nIn your current implementation, once the max number of... | [
0,
0
] | [] | [] | [
"multicore",
"multithreading",
"parallel_processing",
"python"
] | stackoverflow_0007206608_multicore_multithreading_parallel_processing_python.txt |
Q:
nested for loops in Python involving 2 files
I have 2 files: one (ranges.txt) with rows that contain 2 tab-delimited integers, and a second (values.txt) with tab-delimited values, the first of which is an integer. The integers in ranges.txt represent the start and end points for a range, and for each of these rang... | nested for loops in Python involving 2 files | I have 2 files: one (ranges.txt) with rows that contain 2 tab-delimited integers, and a second (values.txt) with tab-delimited values, the first of which is an integer. The integers in ranges.txt represent the start and end points for a range, and for each of these ranges I want to ask how many of the integers in value... | [
"the second for loop reads the whole ValuesFile. after its execution, the file pointer is at the end of the file, and there is no more values to be read from it. \nyou should reset the ValuesFile file pointer before starting the second for loop to start reading ValuesFile from the beginning again.\n"
] | [
4
] | [] | [] | [
"for_loop",
"python"
] | stackoverflow_0007247031_for_loop_python.txt |
Q:
python doctest exception test handling
I have the following contents in a file called test2.txt.
>>> def faulty():
... yield 5
... return 7
Traceback(most recent call last):
SyntaxError: 'return' with argument inside generator(<doctest test.txt[0]>,line 3)
I invoke the test run with python -m test2.txt.... | python doctest exception test handling | I have the following contents in a file called test2.txt.
>>> def faulty():
... yield 5
... return 7
Traceback(most recent call last):
SyntaxError: 'return' with argument inside generator(<doctest test.txt[0]>,line 3)
I invoke the test run with python -m test2.txt. The results below are quite out of my expec... | [
"doctest is extremely careful with the format of expected exceptions. You missed a space:\nTraceback(most recent call last): should be Traceback (most recent call last):\nMoreover, this would still fail, as your traceback message is overly specific (and also has incorrect whitespace)! Use the ELLIPSIS or IGNORE_EXC... | [
10
] | [] | [] | [
"doctest",
"python"
] | stackoverflow_0007245698_doctest_python.txt |
Q:
How to remove lines from stdout in Python - in SciTe, Idle, Eclipse or other editor with console
For a standard Python Console window, you can remove the last line with for example sys.stdout.write('\r'+' '*len(line)) as I explained here.
But for editors like SciTe, Idle or Eclipse (with PyDev), the stdout is a fi... | How to remove lines from stdout in Python - in SciTe, Idle, Eclipse or other editor with console | For a standard Python Console window, you can remove the last line with for example sys.stdout.write('\r'+' '*len(line)) as I explained here.
But for editors like SciTe, Idle or Eclipse (with PyDev), the stdout is a file-type object, probably flushing its content to the console window leaving its buffer empty and thus ... | [
"I am comming to the conclusion that it is not possible, please correct me if I am wrong.\nPython Console Window (terminal) does not 'flush' the written line until the next line is passed, as if it keeps a carriage returns like '\\n' in memory that can be ignored when writing('\\r). The other, more GUI based consol... | [
1
] | [] | [] | [
"pydev",
"python",
"python_idle",
"stdout",
"wxpython"
] | stackoverflow_0006804521_pydev_python_python_idle_stdout_wxpython.txt |
Q:
Exception raised with unittest assertions
When I run a unit-test where I am testing for equality of two integers, I get an assertion error exception instead of unittest reporting a failure, then proceding to the next test. Here is the test code (greatly simplified to prove the point).
import unittest
class TestC... | Exception raised with unittest assertions | When I run a unit-test where I am testing for equality of two integers, I get an assertion error exception instead of unittest reporting a failure, then proceding to the next test. Here is the test code (greatly simplified to prove the point).
import unittest
class TestClass(unittest.TestCase):
def test_method(s... | [
"Right - thanks to @agf I have reached an acceptable compromise. I have removed AssertionError from the 'Always Report' section of the 'Debugger:Exceptions' and now the debugger no longer stops on the assertion. The downside is that while this is fine while running a test script (because I will see the results in... | [
0,
0
] | [] | [] | [
"assertions",
"python",
"python_unittest",
"unit_testing"
] | stackoverflow_0007116526_assertions_python_python_unittest_unit_testing.txt |
Q:
Python re.sub with a flag does not replace all occurrences
The Python docs say:
re.MULTILINE: When specified, the pattern character '^' matches at the beginning of the string and at the beginning of each line (immediately following each newline)... By default, '^' matches only at the beginning of the string...
S... | Python re.sub with a flag does not replace all occurrences | The Python docs say:
re.MULTILINE: When specified, the pattern character '^' matches at the beginning of the string and at the beginning of each line (immediately following each newline)... By default, '^' matches only at the beginning of the string...
So what's going on when I get the following unexpected result?
>>... | [
"Look at the definition of re.sub:\nre.sub(pattern, repl, string[, count, flags])\n\nThe 4th argument is the count, you are using re.MULTILINE (which is 8) as the count, not as a flag.\nEither use a named argument:\nre.sub('^//', '', s, flags=re.MULTILINE)\n\nOr compile the regex first:\nre.sub(re.compile('^//', re... | [
144,
12,
8
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0000042581_python_regex.txt |
Q:
BeautifulSoup removes trailing whitespace?
Apparently using Soup.text removes trailing whitespace for some reason. For example:
In [1]: from BeautifulSoup import BeautifulSoup as Soup
In [2]: print Soup('<a href=''>a </a>').text+ 'a'
aa
Is this intended behaviour and is there any way to stop it happening?
Edit... | BeautifulSoup removes trailing whitespace? | Apparently using Soup.text removes trailing whitespace for some reason. For example:
In [1]: from BeautifulSoup import BeautifulSoup as Soup
In [2]: print Soup('<a href=''>a </a>').text+ 'a'
aa
Is this intended behaviour and is there any way to stop it happening?
Edit: the desired output is
a a
| [
"Maybe it comes from the fact that trailing whitespaces are eliminated in HTML\n"
] | [
1
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0007247776_beautifulsoup_python.txt |
Q:
How to Model a Foreign Key in a Reusable Django App?
In my django site I have two apps, blog and links. blog has a model blogpost, and links has a model link. There should be a one to many relationship between these two things. There are many links per blogpost, but each link has one and only one blog post. The si... | How to Model a Foreign Key in a Reusable Django App? | In my django site I have two apps, blog and links. blog has a model blogpost, and links has a model link. There should be a one to many relationship between these two things. There are many links per blogpost, but each link has one and only one blog post. The simple answer is to put a ForeignKey to blogpost in the link... | [
"If you think the link app will always point to a single app then one approach would be to pass the name of the foreign model as a string containing the application label instead of a class reference (Django docs explanation).\nIn other words, instead of:\nclass Link(models.Model):\n blog_post = models.ForeignKe... | [
24,
2,
1,
0,
0,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0001419442_django_django_models_python.txt |
Q:
regex result filter in python
I am working on a program with regexes, I have to filter them but I can't find out how. I want to match every red,xxxx or xxxx,red expression in my string and put the colors xxxx into a group. Here is my code:
string = "blue,red red,yellow blue,yellow red,green purple red, ...... | regex result filter in python | I am working on a program with regexes, I have to filter them but I can't find out how. I want to match every red,xxxx or xxxx,red expression in my string and put the colors xxxx into a group. Here is my code:
string = "blue,red red,yellow blue,yellow red,green purple red, ..."
regex = re.compile('(?:red,(?P<re... | [
">>> import re\n>>> regex = re.compile('(?:red,(?P<redfirst>\\w+)|(?P<othercolorfirst>\\w+),red)')\n\n>>> string = \"blue,red red,yellow blue,yellow red,green purple red, ...\"\n\n>>> for matches in regex.finditer(string):\n... if matches.group('redfirst'):\n... print matches.group('redfirst')\n... | [
3,
2,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0007248640_python_regex.txt |
Q:
Using __getattribute__ or __getattr__ to call methods in Python
I am trying to create a subclass which acts as a list of custom classes. However, I want the list to inherit the methods and attributes of the parent class and return a sum of the quantities of each item. I am attempting to do this using the __getattr... | Using __getattribute__ or __getattr__ to call methods in Python | I am trying to create a subclass which acts as a list of custom classes. However, I want the list to inherit the methods and attributes of the parent class and return a sum of the quantities of each item. I am attempting to do this using the __getattribute__ method, but I cannot figure out how to pass arguments to call... | [
"You have a few points of confusion here:\n1) __getattribute__ intercepts all attribute access, which isn't what you want. You only want your code to step in if a real attribute doesn't exist, so you want __getattr__.\n2) Your __getattribute__ is calling the method on the list elements, but it shouldn't be doing r... | [
10,
10,
4,
2
] | [] | [] | [
"getattr",
"getattribute",
"python"
] | stackoverflow_0007247868_getattr_getattribute_python.txt |
Q:
Saving select updating data points from an external webpage to a text file
I am trying to take updating weather data from a website that isn't mine and put a chunk of it into a generic text file every 30 minutes. The text file should not have any html tags or anything but could be delimited by commas or periods or... | Saving select updating data points from an external webpage to a text file | I am trying to take updating weather data from a website that isn't mine and put a chunk of it into a generic text file every 30 minutes. The text file should not have any html tags or anything but could be delimited by commas or periods or tabs. The website generating the data puts the data in a table with no class or... | [
"Maybe you can use it in a cronjob:\n$file = file_get_contents ($url);\n$onlyText = strip_tags ($file);\n$fp = fopen('data.txt', 'w');\nfwrite($fp, $onlyText);\nfclose($fp);\n\n",
"For Python\n\nFor timed tasks for N minutes create an UNIX cron job or Windows equivalent which runs your .py script regularly\nDown... | [
0,
0,
0
] | [] | [] | [
"html",
"php",
"python"
] | stackoverflow_0007249412_html_php_python.txt |
Q:
Why would a model instance not be found when committing count using write-behind or sharded counters in App Engine?
I'm working on a counter for an App Engine application and am following the example outlined here http://blog.notdot.net/2010/04/High-concurrency-counters-without-sharding
I'm having trouble understa... | Why would a model instance not be found when committing count using write-behind or sharded counters in App Engine? | I'm working on a counter for an App Engine application and am following the example outlined here http://blog.notdot.net/2010/04/High-concurrency-counters-without-sharding
I'm having trouble understanding the need for the following lines:
counter = cls.get_by_key_name(name)
if not counter:
counter = cls()
It seems a... | [
"The first one should be\ncounter = cls(key_name=name)\n\n"
] | [
0
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0007248433_google_app_engine_google_cloud_datastore_python.txt |
Q:
Django image uploading
I have a problem with image uploading. For now, chosen image file is not copied to destination directory and path to this file is not added to database.
I'm giving my code below:
models.py:
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Mod... | Django image uploading | I have a problem with image uploading. For now, chosen image file is not copied to destination directory and path to this file is not added to database.
I'm giving my code below:
models.py:
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.OneTo... | [
"https://docs.djangoproject.com/en/dev/topics/http/file-uploads/\nyour form should have the enctype=\"multipart/form-data\" or request.FILES won't have any data stream associated\n",
"your ModelForm is bound to UserProfile model, but your are instantiating it with instance=user. \nPS: request.user is User.objects... | [
2,
1
] | [] | [] | [
"django",
"image",
"python",
"upload"
] | stackoverflow_0007241743_django_image_python_upload.txt |
Q:
Is the concept of a Point3 class, separate from a Vec3 class, unpythonic?
I'm writing some 3D math classes for Python. I'd like to make a Point3 class that is separate from Vec3 in the following respects:
Point3 - Point3 = Vec3
Point3 + Vec3 = Point3
Otherwise, all operations on Vec3 you can perform on Point3.... | Is the concept of a Point3 class, separate from a Vec3 class, unpythonic? | I'm writing some 3D math classes for Python. I'd like to make a Point3 class that is separate from Vec3 in the following respects:
Point3 - Point3 = Vec3
Point3 + Vec3 = Point3
Otherwise, all operations on Vec3 you can perform on Point3. The motivation for this is to separate the mathematical concept of a point fro... | [
"I don't think this is particularly unpythonic. It's not too unusual to distinguish types when they have the same domain, but when one has a particular frame of reference, such as a time zone, Since a point is the sum of a vector and the origin, it's reasonable to encode that in some way. \n",
"It seems superf... | [
3,
3,
1,
1
] | [] | [] | [
"math",
"python"
] | stackoverflow_0007247648_math_python.txt |
Q:
How to set filename property in BlobStore?
I'm programatically uploading image files and want to set the filename. When I upload a file via POST, the filename property is set automatically. However when using the method below, the filename is not getting set.
image = urllib2.urlopen(url)
file_nam... | How to set filename property in BlobStore? | I'm programatically uploading image files and want to set the filename. When I upload a file via POST, the filename property is set automatically. However when using the method below, the filename is not getting set.
image = urllib2.urlopen(url)
file_name = files.blobstore.create(mime_type='image/png'... | [
"Parse the filename from the url (see related question here). Then you can set it by adding an additional parameter to your files.blobstore.create call:\nfile_name = files.blobstore.create(mime_type='image/png',_blobinfo_uploaded_filename=file_name_from_url)\n\n",
"I know this is an old question but ...\nself.se... | [
8,
4
] | [] | [] | [
"blobstore",
"google_app_engine",
"python"
] | stackoverflow_0005697844_blobstore_google_app_engine_python.txt |
Q:
Defining ways to visualise admin fields - Django
I'm trying to add graphs to the admin interface, problem is that I have not found any documentation regarding this.
I'm sure there are generally accepted ways of customizing the way fields are displayed, and I do not wish to follow any problematic route.
Any ideas... | Defining ways to visualise admin fields - Django | I'm trying to add graphs to the admin interface, problem is that I have not found any documentation regarding this.
I'm sure there are generally accepted ways of customizing the way fields are displayed, and I do not wish to follow any problematic route.
Any ideas?
Edit:
this is a model I'm trying to reproduce!
Uni... | [
"Here's an example of using Highcharts via the Django admin:\nhttp://blogs.law.harvard.edu/rprasad/2011/08/30/highcharts-django-admin/\n",
"Django does not have built in report/graph libraries as far as i know so you should use 3rd party library for generating graphs and customize your admin interface.\nSee this ... | [
2,
0
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0002743814_django_django_admin_python.txt |
Q:
xpath - following-sibling question
basic question that i'm missing something.
have the text html
<tr ><td class="CourseTitle" >foo </td></tr>
<tr "> <th >Code</th><th >Type</th> </tr>
<tr valign="top" bgcolor="#FFFFCC"><td ">40000</td><td ">40000</td></tr>
<tr valign="top" bgcolor="#FFFFCC"><td ">40001... | xpath - following-sibling question | basic question that i'm missing something.
have the text html
<tr ><td class="CourseTitle" >foo </td></tr>
<tr "> <th >Code</th><th >Type</th> </tr>
<tr valign="top" bgcolor="#FFFFCC"><td ">40000</td><td ">40000</td></tr>
<tr valign="top" bgcolor="#FFFFCC"><td ">40001</td><td ">40000</td></tr>
<tr valign="t... | [
"import lxml.html as lh\nimport urllib2\n\nurl='http://websoc.reg.uci.edu/?YearTerm=2011-92&Breadth=ANY&Dept=CHEM&CourseNum=&Division=ANY&CourseCodes=&InstrName=&CourseTitle=&ClassType=ALL&Units=&Days=&StartTime=&EndTime=&MaxCap=&FullCourses=ANY&FontSize=100&CancelledCourses=Exclude&Bldg=&Room=&Submit=Display+Web+R... | [
0,
0
] | [] | [] | [
"python",
"xpath"
] | stackoverflow_0007249555_python_xpath.txt |
Q:
Efficient multiple, arbitrary index access in Python tuple?
I have a long Python tuple t. I would like to grab the elements at indices i1, i2, ..., iN from t as efficiently as possible. What's the best way?
One approach is:
(1) result = [t[j] for j in (i1, i2, ..., iN)]
but this would seem to cause N separat... | Efficient multiple, arbitrary index access in Python tuple? | I have a long Python tuple t. I would like to grab the elements at indices i1, i2, ..., iN from t as efficiently as possible. What's the best way?
One approach is:
(1) result = [t[j] for j in (i1, i2, ..., iN)]
but this would seem to cause N separate lookups into the tuple. Is there a faster way? When Python do... | [
"If you are doing a bunch of identical lookups, it may be worth using an itemgetter\nfrom operator import itemgetter\nmygetter = itemgetter(i1, i2, ..., iN)\nfor tup in lots_of_tuples:\n result = mygetter(tup)\n\nFor one off, the overhead of creating the itemgetter is not worthwhile\nQuick test in iPython shows:... | [
7,
2,
0,
0,
0
] | [] | [] | [
"python",
"slice",
"tuples"
] | stackoverflow_0007248737_python_slice_tuples.txt |
Q:
Import package from upper level of application
So I have an application with a structure of:
main.py
core/__init__.py
core/user_interface.py
core/util/__init__.py
core/util/widgets/__init__.py
core/util/widgets/tab.py
The main.py file makes an import of:
from core import user_interface
This runs successfully, ... | Import package from upper level of application | So I have an application with a structure of:
main.py
core/__init__.py
core/user_interface.py
core/util/__init__.py
core/util/widgets/__init__.py
core/util/widgets/tab.py
The main.py file makes an import of:
from core import user_interface
This runs successfully, then user_interface makes an import call:
import cor... | [
"I've just experienced the exact same problem - but it only appears if the module is called core. (I proved this by renaming the module and it worked fine. Renaming back to core and the ImportError exception is thrown again).\nI'm fairly new to python but have concluded it's due to another module called core alread... | [
1,
0
] | [] | [] | [
"import",
"importerror",
"python"
] | stackoverflow_0005954344_import_importerror_python.txt |
Q:
django debugging help
I am new to python, django and wing ide. I come from .net. I need to debug a django web app and I am not sure where the entry point is so I can start debugging right from the beginning. Please advise.
Does the app have to be in the mysites folder i configured during the configuring django? O... | django debugging help | I am new to python, django and wing ide. I come from .net. I need to debug a django web app and I am not sure where the entry point is so I can start debugging right from the beginning. Please advise.
Does the app have to be in the mysites folder i configured during the configuring django? Or it can be anywhere?
I hav... | [
"Read the Tutorial. The second part covers the basics of debugging.\n"
] | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007250376_django_python.txt |
Q:
django testing response.context TypeError: 'NoneType' object is not subscriptable
I want to test this view:
def register(request):
"""
handle user registration
code variable is for testing purposes
"""
if request.method== 'GET':
form = RegisterForm(auto_id=False)
code = 1
... | django testing response.context TypeError: 'NoneType' object is not subscriptable | I want to test this view:
def register(request):
"""
handle user registration
code variable is for testing purposes
"""
if request.method== 'GET':
form = RegisterForm(auto_id=False)
code = 1
return render_to_response('register_home.html',locals(),context_instance=RequestConte... | [
"What is the response status? Redirects doesn't have context. Anyway, printing the response should help.\n",
"My guess is\nkey = register_user(login,email,password,newsletter)\n\nthrows an exception on duplicate register attempts and thus the handler does not generate a response.\n"
] | [
2,
0
] | [] | [] | [
"django",
"python",
"testing",
"unit_testing"
] | stackoverflow_0007245433_django_python_testing_unit_testing.txt |
Q:
Appengine: put_async doesn't work (at least in the development server)?
NOTE:
IT DOES WORK IN PRODUCTION. I MEAN, WHEN I UPLOAD THE APPLICATION IT JUST WORKS FINE. THE PROBLEM IS IN THE DEVELOPMENT SERVER.
Here is some code that can show you what i'm trying to do:
e = Employee(key_name = 'some_key_name',name='John... | Appengine: put_async doesn't work (at least in the development server)? | NOTE:
IT DOES WORK IN PRODUCTION. I MEAN, WHEN I UPLOAD THE APPLICATION IT JUST WORKS FINE. THE PROBLEM IS IN THE DEVELOPMENT SERVER.
Here is some code that can show you what i'm trying to do:
e = Employee(key_name = 'some_key_name',name='John Bonham')
db.put_async(e)
If i do it, and after some time i try to get it
e ... | [
"If you don't call .wait() or .get_result() on an RPC, there is no way to guarantee it's completed. In the case of the dev_appserver, which is not multi-threaded, the actual work is done when you call those methods - it's not actually asynchronous in development, only in production.\n"
] | [
14
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0007244081_google_app_engine_google_cloud_datastore_python.txt |
Q:
String Manipulation of All Elements of an Array in Python
I'm trying to isolate a substring of each string element of an array such that it is the string until the last period. For example I would want to have:
input = 'A.01.0'
output = 'A.01'
or
input = 'A.0'
output = 'A'
And I want to do this for all element... | String Manipulation of All Elements of an Array in Python | I'm trying to isolate a substring of each string element of an array such that it is the string until the last period. For example I would want to have:
input = 'A.01.0'
output = 'A.01'
or
input = 'A.0'
output = 'A'
And I want to do this for all elements of an array.
| [
"Use some rsplit magic:\nx=[\"123\",\"456.678\",\"abc.def.ghi\"]\n[y.rsplit(\".\",1)[0] for y in x]\n\n",
"This is one way to produce the wanted output format. You need to alter this to suit your needs.\noutput = input[:input.rindex('.')]\n\nFor the entire array:\narr = ['A.01.0', 'A.0']\narr = [x[:x.rindex('.')]... | [
3,
0
] | [
"Something like this?\n>>> i = ['A.01.0', 'A.0']\n>>> [x[:x.rfind('.')] for x in i]\n['A.01', 'A']\n\n"
] | [
-1
] | [
"arrays",
"python",
"string"
] | stackoverflow_0007250626_arrays_python_string.txt |
Q:
Python TarFile with bz2 data
Im trying to download a bz2 compressed tarfile and create a tarfile.TarFile object from it.
import MyModule
import StringIO
import tarfile
tardata = StringIO.StringIO()
tardata.write(MyModule.getBz2TarFileData())
tardata.seek(0)
tar = tarfile.open(fileobj = tardata, mode="r:bz2")
Tr... | Python TarFile with bz2 data | Im trying to download a bz2 compressed tarfile and create a tarfile.TarFile object from it.
import MyModule
import StringIO
import tarfile
tardata = StringIO.StringIO()
tardata.write(MyModule.getBz2TarFileData())
tardata.seek(0)
tar = tarfile.open(fileobj = tardata, mode="r:bz2")
Traceback (most recent call last):
... | [
"I just have thrown a look into tarfile.py on my systems. The line numbers were quite different (I have 2.6), so that I would suppose there was heavy work since 2.4.\nMaybe the module had a bug in 2.4 times which has been corrected, or the said interface has changed thus the docs don't match your module version any... | [
0
] | [] | [] | [
"python",
"tarfile"
] | stackoverflow_0007249341_python_tarfile.txt |
Q:
Having trouble trying to add a line to a text file if that line doesn't exist already using Python fileinput.FileInput(...)
I'm trying to edit text files using the Python FileInput class. First I store the lines that i need to write in a Dictionary. Then I iterate through that dictionary, and if the dictionary[k... | Having trouble trying to add a line to a text file if that line doesn't exist already using Python fileinput.FileInput(...) | I'm trying to edit text files using the Python FileInput class. First I store the lines that i need to write in a Dictionary. Then I iterate through that dictionary, and if the dictionary[key] matches any line in that line, I replace the line with the dictionary key-value pair. If the dictionary[key] does not exist i... | [
"re.findall() will never return None, if there are no matches it will return an empty list. Because of this your first elif will always be true. You should be using re.search() instead (since you aren't using the result of findall() anyway):\n>>> re.findall(r'[a-zA-Z0-9=:]+', \"(>'_')>\")\n[]\n>>> re.findall(r'[a... | [
1
] | [] | [] | [
"file_io",
"python",
"writetofile"
] | stackoverflow_0007250941_file_io_python_writetofile.txt |
Q:
PYTHON-2.x Syntax error on line 1 but i don't see any?
the following file is located in this directory: /Users/whiteglider/Documents
name of file: server.py
this is my practice code which i just copied from http://www.tutorialspoint.com/python/python_networking.htm
import socket
s=socket.socket()
host... | PYTHON-2.x Syntax error on line 1 but i don't see any? | the following file is located in this directory: /Users/whiteglider/Documents
name of file: server.py
this is my practice code which i just copied from http://www.tutorialspoint.com/python/python_networking.htm
import socket
s=socket.socket()
host=socket.gethostname()
port=12345
s.bind((host,port))... | [
"You've saved the file as a Rich Text Format file rather than a plain text file.\nI don't know what editor you're using, but make sure to save the file as plain text / ASCII text, something like that, not RTF.\n",
"The 'line continuation character' is typically a backslash at the end of a line.\nHowever, I don't ... | [
8,
0
] | [] | [] | [
"python",
"python_2.x",
"syntax_error"
] | stackoverflow_0007250921_python_python_2.x_syntax_error.txt |
Q:
Efficient processing of email list in Python
I have a very long list of emails that I would like to process to:
separate good emails from bad emails, and
remove duplicates but keep all the non-duplicates in the same order.
This is what I have so far:
email_list = ["joe@example.com", "invalid_email", ...]
email_... | Efficient processing of email list in Python | I have a very long list of emails that I would like to process to:
separate good emails from bad emails, and
remove duplicates but keep all the non-duplicates in the same order.
This is what I have so far:
email_list = ["joe@example.com", "invalid_email", ...]
email_set = set()
bad_emails = []
good_emails = []
dups ... | [
"Look at: Does Python have an ordered set? , and select an implementation you like.\nSo just:\nemail_list = OrderedSet([\"joe@example.com\", \"invalid_email\", ...])\n\nbad_emails = [] \ngood_emails = []\n\nfor email in email_list:\n if email_re.match(email):\n good_emails.append(email)\n else:\n ... | [
2,
2
] | [] | [] | [
"iterator",
"list",
"performance",
"python"
] | stackoverflow_0007250527_iterator_list_performance_python.txt |
Q:
Problem with C library linked to Python interpreter, on Mac OS X
I'm trying to use a C library that is supposed to be available from Python. The library compiles fine on Mac OS X (10.6.0, i386) with GCC (version: i686-apple-darwin10-gcc-4.2.1 (GCC) 4.2.1 (Apple Inc. build 5659).
When I try to import the python mo... | Problem with C library linked to Python interpreter, on Mac OS X | I'm trying to use a C library that is supposed to be available from Python. The library compiles fine on Mac OS X (10.6.0, i386) with GCC (version: i686-apple-darwin10-gcc-4.2.1 (GCC) 4.2.1 (Apple Inc. build 5659).
When I try to import the python module from python, I get the error:
$ python
Enthought Python Distribut... | [
"It is hard to know exactly what the problem is without more information but it appears you are using a 64-bit version of Python (from EPD). Is the library that you built also built as a 64-bit library? You should be able to tell by doing something like this:\nfile $(python -c 'import sys;print(sys.executable)') ... | [
1
] | [] | [] | [
"gcc",
"macos",
"python",
"unix"
] | stackoverflow_0007251240_gcc_macos_python_unix.txt |
Q:
View code within Python egg files in PyDev
One of the nice features of working in Eclipse with PyDev is that clicking F3 you can browse into almost anything. However, if the package you're using is contained in a Python egg, that doesn't work.
Is it possible to make it work?
If not, would it work to extract the eg... | View code within Python egg files in PyDev | One of the nice features of working in Eclipse with PyDev is that clicking F3 you can browse into almost anything. However, if the package you're using is contained in a Python egg, that doesn't work.
Is it possible to make it work?
If not, would it work to extract the egg's contents into site-packages and delete the e... | [
"Actually, what you're saying should work (i.e.: doing F3 on a reference to a file within a zip should open the file properly).\nSo, this was actually a rather critical bug when dealing with zip files in PyDev (which I've just fixed and is already available in the current nightly build -- it'll be released for PyDe... | [
4,
3
] | [] | [] | [
"egg",
"pydev",
"python"
] | stackoverflow_0007241368_egg_pydev_python.txt |
Q:
python stdout flush and tee
The following code ends with broken pipe when piped into tee, but behave correctly when not piped :
#!/usr/bin/python
import sys
def testfun():
while 1:
try :
s = sys.stdin.readline()
except(KeyboardInterrupt) :
print('Ctrl-C pressed')
... | python stdout flush and tee | The following code ends with broken pipe when piped into tee, but behave correctly when not piped :
#!/usr/bin/python
import sys
def testfun():
while 1:
try :
s = sys.stdin.readline()
except(KeyboardInterrupt) :
print('Ctrl-C pressed')
sys.stdout.flush()
... | [
"Nope, hitting Ctrl-C does NOT terminate both processes. It terminates the tee process only,\nthe end of the tee process close the pipe between your script and tee, and hence your script dies with the broken pipe message.\nTo fix that, tee has an option to pass the Ctrl-C to its previous process in the pipe: -i\ntr... | [
9,
5,
4
] | [] | [] | [
"python",
"tee"
] | stackoverflow_0001192870_python_tee.txt |
Q:
python unable to detach process when teed. How to span background process and exit with no wait?
I started with a simple testcase:
cat foo2.py
#!/usr/bin/python
import subprocess, sys, os
def alert():
subprocess.Popen ("xterm &", shell=True, stdin=None, stdout=None, stderr=None, close_fds=True)
if __name__ =... | python unable to detach process when teed. How to span background process and exit with no wait? | I started with a simple testcase:
cat foo2.py
#!/usr/bin/python
import subprocess, sys, os
def alert():
subprocess.Popen ("xterm &", shell=True, stdin=None, stdout=None, stderr=None, close_fds=True)
if __name__ == "__main__":
print "hello"
alert ()
os._exit (0)
When I run that code on the command line ... | [
"Run nohup xterm & (so that the process is decoupled)\n"
] | [
0
] | [] | [] | [
"background",
"daemon",
"python",
"tee"
] | stackoverflow_0007251414_background_daemon_python_tee.txt |
Q:
Filtering app engine data from datastore dynamically
My app-engine data model is defined as:
class Event(db.Model):
title = db.LinkProperty();
refresh_interval = db.IntegerProperty();
class EventSchedule(db.Model):
event = db.ReferenceProperty(Event) # referencing the event
refresh_date = db.... | Filtering app engine data from datastore dynamically | My app-engine data model is defined as:
class Event(db.Model):
title = db.LinkProperty();
refresh_interval = db.IntegerProperty();
class EventSchedule(db.Model):
event = db.ReferenceProperty(Event) # referencing the event
refresh_date = db.DateTimeProperty(); # date & time of last successful ref... | [
"This join operation is not possible with the GAE data store, and is highly inefficient on normal SQL databases as well (since it requires a scan of the entire event_schedule table).\nYou should instead store a next_refresh DateTimeProperty in your EventSchedule entities, initialized to be refresh_date + refresh_in... | [
4
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0007251188_google_app_engine_python.txt |
Q:
What does 'while' with an integer mean in Python and how does this GCD code work?
I found this greatest common denominator code:
def gcd(x,y):
while y:
x, y = y, x % y
return x
I cannot understand what we mean by while y as y is an integer. How does it work? Furthermore, what does the line x, y = ... | What does 'while' with an integer mean in Python and how does this GCD code work? | I found this greatest common denominator code:
def gcd(x,y):
while y:
x, y = y, x % y
return x
I cannot understand what we mean by while y as y is an integer. How does it work? Furthermore, what does the line x, y = y, x % y add to the code?
| [
"For while, read this: http://docs.python.org/reference/compound_stmts.html#the-while-statement\nIt says \"This repeatedly tests the expression and, if it is true, executes the first suite;\"\nNow the question is: What's True?\nRead this: http://docs.python.org/library/functions.html#bool\nThen read this: http://do... | [
10,
4,
1,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0007251492_python_python_3.x.txt |
Q:
Running maximum of numpy array values
I need a fast way to keep a running maximum of a numpy array. For example, if my array was:
x = numpy.array([11,12,13,20,19,18,17,18,23,21])
I'd want:
numpy.array([11,12,13,20,20,20,20,20,23,23])
Obviously I could do this with a little loop:
def running_max(x):
result = ... | Running maximum of numpy array values | I need a fast way to keep a running maximum of a numpy array. For example, if my array was:
x = numpy.array([11,12,13,20,19,18,17,18,23,21])
I'd want:
numpy.array([11,12,13,20,20,20,20,20,23,23])
Obviously I could do this with a little loop:
def running_max(x):
result = [x[0]]
for val in x:
if val > r... | [
"numpy.maximum.accumulate works for me.\n>>> import numpy\n>>> numpy.maximum.accumulate(numpy.array([11,12,13,20,19,18,17,18,23,21]))\narray([11, 12, 13, 20, 20, 20, 20, 20, 23, 23])\n\n",
"As suggested, there is scipy.maximum.accumulate:\nIn [9]: x\nOut[9]: [1, 3, 2, 5, 4]\n\nIn [10]: scipy.maximum.accumulate(x)... | [
70,
3
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0007251421_numpy_python.txt |
Q:
How to work with ModelForm and ModelFormSet
I just want some clarification. I'm working through the Django Form Wizard documentation
In the documentation it talks about the Form Wizard being able to 'work' with ModelForm and ModelFormSet. I want clarification on what this means. Does it mean that the Form Wizard c... | How to work with ModelForm and ModelFormSet | I just want some clarification. I'm working through the Django Form Wizard documentation
In the documentation it talks about the Form Wizard being able to 'work' with ModelForm and ModelFormSet. I want clarification on what this means. Does it mean that the Form Wizard can save the post data of a form straight to the d... | [
"No, it is not saving the form information automatically!\nUsually you need to process the form in your view. A ModelForm is basically just a helper to make model instance edting/creating easier and of course more native for your frontend. So here something you usually would do in your view (in short):\nform = MyFo... | [
1
] | [] | [] | [
"django",
"django_formwizard",
"python"
] | stackoverflow_0007251547_django_django_formwizard_python.txt |
Q:
Automatically remove generator object from memory at StopIteration (Python)
I noticed once a generator is exhausted, the object remains in memory. How can I make the generator object automatically remove itself from memory once it is exhausted?
A:
This is not an operation supported by Python.
A:
You could try ... | Automatically remove generator object from memory at StopIteration (Python) | I noticed once a generator is exhausted, the object remains in memory. How can I make the generator object automatically remove itself from memory once it is exhausted?
| [
"This is not an operation supported by Python.\n",
"You could try making a wrapper generator that makes sure it doesn't have a reference to the inner generator once it finishes. The following might even do it (completely untested):\ndef strange(gen):\n for thing in gen:\n yield thing\n\nOnce gen raises ... | [
1,
1
] | [] | [] | [
"generator",
"memory_management",
"python"
] | stackoverflow_0007251648_generator_memory_management_python.txt |
Q:
python-crypto for OS X?
I am trying to install a django project on OS X. The instructions are written for Ubuntu and there is a list of dependencies. Some I have found on PIP, others I have not.
apt get install python-crypto
How can I find this same package(s) on PIP? If not on PIP, will I have to find their s... | python-crypto for OS X? | I am trying to install a django project on OS X. The instructions are written for Ubuntu and there is a list of dependencies. Some I have found on PIP, others I have not.
apt get install python-crypto
How can I find this same package(s) on PIP? If not on PIP, will I have to find their source and compile them on OS ... | [
"pip install pycrypto\n\nDepending on your Xcode version you may need to disable the ppc version by changing your ARCHFLAGS.\n",
"To search the pypi index, use pip search and try some different keywords. For example:\npip search crypto\n\nand you'll find pycrypto in the list.\nThen install it:\npip install pycryp... | [
6,
3
] | [] | [] | [
"django",
"macos",
"python"
] | stackoverflow_0007251676_django_macos_python.txt |
Q:
Process entire files in Hadoop using Python code (preferably in Dumbo)
It seems a very common use case but so hard to do in Hadoop (it is possible with WholeFileRecordReader class).
Is it at all possible in Dumbo or Pig?
Does anyone knows a way to process whole files as map tasks using Dumbo or Pig?
A:
WholeFile... | Process entire files in Hadoop using Python code (preferably in Dumbo) | It seems a very common use case but so hard to do in Hadoop (it is possible with WholeFileRecordReader class).
Is it at all possible in Dumbo or Pig?
Does anyone knows a way to process whole files as map tasks using Dumbo or Pig?
| [
"WholeFileRecordReader means not split the input file? If so, define mapred.min.split.size to a very large value, both mapreduce and Pig will take it.\n",
"I am assuming you want to have one file as on record in Pig. If not, please be more specific in your question.\nI don't know of a Pig storage loader that load... | [
0,
0
] | [] | [] | [
"apache_pig",
"hadoop",
"python"
] | stackoverflow_0007247179_apache_pig_hadoop_python.txt |
Q:
Coroutine vs Continuation vs Generator
What is the difference between a coroutine and a continuation and a generator ?
A:
I'll start with generators, seeing as they're the simplest case. As @zvolkov mentioned, they're functions/objects that can be repeatedly called without returning, but when called will return ... | Coroutine vs Continuation vs Generator | What is the difference between a coroutine and a continuation and a generator ?
| [
"I'll start with generators, seeing as they're the simplest case. As @zvolkov mentioned, they're functions/objects that can be repeatedly called without returning, but when called will return (yield) a value and then suspend their execution. When they're called again, they will start up from where they last suspend... | [
135,
33,
13
] | [] | [] | [
"continuations",
"coroutine",
"generator",
"python"
] | stackoverflow_0000715758_continuations_coroutine_generator_python.txt |
Q:
Making a menu in Python
Possible Duplicate:
Calling a function from a string with the function's name in Python
I think I could write some terrible code that would do this, but I'd much rather see the 'clean version'.
What seems the good approach to me, is to make a dict that holds the various functions that a g... | Making a menu in Python |
Possible Duplicate:
Calling a function from a string with the function's name in Python
I think I could write some terrible code that would do this, but I'd much rather see the 'clean version'.
What seems the good approach to me, is to make a dict that holds the various functions that a given object can use. Then w... | [
"In your example Man.cmds is a list not a dictionary. So they TypeError is raised when the string in the self.cmds list is called as a function.\nCreate a dictionary with the function name as a string paired with the function itself.\n def __init__(self):\n self.cmds = {'foo':self.foo, 'bar':self.bar}\n\n... | [
3
] | [] | [] | [
"dictionary",
"menu",
"python"
] | stackoverflow_0007251819_dictionary_menu_python.txt |
Q:
Python: Usage of PyDateTime_FromTimestamp
I'm working on a python c-extension and want to create an instance of python datetime object with a unix timestamp.
On the documentation site ( http://docs.python.org/c-api/datetime.html ) I found the function PyDateTime_FromTimestamp() which returns a new reference based ... | Python: Usage of PyDateTime_FromTimestamp | I'm working on a python c-extension and want to create an instance of python datetime object with a unix timestamp.
On the documentation site ( http://docs.python.org/c-api/datetime.html ) I found the function PyDateTime_FromTimestamp() which returns a new reference based on an input parameter.
The description is as f... | [
"Thank you Ignacio! Sometimes small hints make the solution - here the full working example:\n\nstatic double doubleValue = 1314761451; \nPyObject *floatObj = NULL; \nPyObject *timeTuple = NULL; \nPyObject *dateTime = NULL; \nfloatObj = PyFloat_FromDouble(doubleValue); \ntimeTuple = Py_BuildValue(\"(O)\", floa... | [
4
] | [] | [] | [
"c",
"datetime",
"python",
"python_c_api",
"python_c_extension"
] | stackoverflow_0007236364_c_datetime_python_python_c_api_python_c_extension.txt |
Q:
Paramiko Error: Error reading SSH protocol banner
I'm using Fabric for my build script. I just cloned one of my VMs and created a new server. The Fabric script (which uses paramiko underneath) works fine one server but not the other. Since it's a clone I don't know what could be different but everytime I run my Fa... | Paramiko Error: Error reading SSH protocol banner | I'm using Fabric for my build script. I just cloned one of my VMs and created a new server. The Fabric script (which uses paramiko underneath) works fine one server but not the other. Since it's a clone I don't know what could be different but everytime I run my Fabric script I get the error Error reading SSH protocol ... | [
"This issue didn't lie with Paramiko, Fabric or the SSH daemon. It was simply a firewall configuration in ISPs internal network. For some reason, they don't allow communication between different subnets of theirs.\nWe couldn't really fix the firewall configuration so instead we switched all our IPs to be on the sam... | [
8,
3
] | [] | [] | [
"fabric",
"linux",
"paramiko",
"python",
"ssh"
] | stackoverflow_0007206272_fabric_linux_paramiko_python_ssh.txt |
Q:
Instantiate all functions in Python
Is there a way to do something like this:
util.py contains:
def add
def subtract
instantiate.py contains:
def instantiate
where instantiate does:
import util
def instantiate():
add = util.add
subtract = util.subtract
So I can skip typing util everytime I use a functi... | Instantiate all functions in Python | Is there a way to do something like this:
util.py contains:
def add
def subtract
instantiate.py contains:
def instantiate
where instantiate does:
import util
def instantiate():
add = util.add
subtract = util.subtract
So I can skip typing util everytime I use a function and I can instantiate them all using o... | [
"You can import specific functions from a module :\nfrom util import add, substract\n\n",
"if you just want to import those functions into the same namespace, you could do something like this:\nfrom util import *\n\nthen you can write add and so on without prefixing it with that module\n",
"If you want a method... | [
7,
4,
0
] | [] | [] | [
"python"
] | stackoverflow_0007252640_python.txt |
Q:
How to gracefully deal with failed future feature (__future__) imports due to old interpreter version?
How do you gracefully handle failed future feature imports? If a user is running using Python 2.5 and the first statement in my module is:
from __future__ import print_function
Compiling this module for Python 2... | How to gracefully deal with failed future feature (__future__) imports due to old interpreter version? | How do you gracefully handle failed future feature imports? If a user is running using Python 2.5 and the first statement in my module is:
from __future__ import print_function
Compiling this module for Python 2.5 will fail with a:
File "__init__.py", line 1
from __future__ import print_function
SyntaxError: fut... | [
"\"I'd like to inform the user that they need to rerun the program with Python >= 2.6 and maybe provide some instructions on how to do so.\"\nIsn't that what a README file is for?\nHere's your alternative. A \"wrapper\": a little blob of Python that checks the environment before running your target aop.\nFile: app... | [
60,
48,
41
] | [] | [] | [
"python",
"python_import"
] | stackoverflow_0000388069_python_python_import.txt |
Q:
Twitter Python API in Terminal - Errors installing
I've installed the following libraries and gotten through all the steps in the twitter python setup:
httplib2-0.7.1 simplegeo-python-oauth2-1fcc1a6
python-twitter-0.8.2 simplejson-2.1.6
I'm using the setup instructions here: http://code.google.co... | Twitter Python API in Terminal - Errors installing | I've installed the following libraries and gotten through all the steps in the twitter python setup:
httplib2-0.7.1 simplegeo-python-oauth2-1fcc1a6
python-twitter-0.8.2 simplejson-2.1.6
I'm using the setup instructions here: http://code.google.com/p/python-twitter/
When I run python setup.py test, I g... | [
"I think the error messages that you omitted contains important information for troubleshooting. Let me guess - you downloaded the tar.gz file from the Downloads section of the project but it for some reason didn't package the test data in. So the reason of failure must be that it couldn't find the required testing... | [
0
] | [] | [] | [
"python",
"python_twitter",
"twitter"
] | stackoverflow_0007251624_python_python_twitter_twitter.txt |
Q:
python: __doc__ doc trings is displayed as none
I coded a relatively simple script using python and also wrote doc strings for all the methods as follow:
def processData(rawData):
"""Proccessing raw data from weather station using Regex to get final sensor readings.
Args:
rawData: A string contain... | python: __doc__ doc trings is displayed as none | I coded a relatively simple script using python and also wrote doc strings for all the methods as follow:
def processData(rawData):
"""Proccessing raw data from weather station using Regex to get final sensor readings.
Args:
rawData: A string contains all the sensor readings. This string will be proces... | [
"There are different doc strings for different objects. The docstring for your function would be processData.__doc__, for the module it is weather.__doc__, which you didn't define. Define that as a bare string (unassigned) in the global scope at the top of the file.\n",
"You are showing us the doc string of one m... | [
4,
1
] | [] | [] | [
"docstring",
"python"
] | stackoverflow_0007253018_docstring_python.txt |
Q:
How to determine the sum of a group of integers without using recursion
This is my first post on Stack Overflow, and I'm hoping that it'll be a good one.
This is a problem that I thought up myself, and now I'm a bit embarrassed to say, but it's beating the living daylights out of me. Please note that this is not a... | How to determine the sum of a group of integers without using recursion | This is my first post on Stack Overflow, and I'm hoping that it'll be a good one.
This is a problem that I thought up myself, and now I'm a bit embarrassed to say, but it's beating the living daylights out of me. Please note that this is not a homework exercise, scout's honor.
Basically, the program takes (as input) a ... | [
"A program that finds all solutions can be expressed elegantly in functional style.\nPartitions\nFirst, write a function that partitions your string in every possible way. (The following implementation is based on http://code.activestate.com/recipes/576795/.) Example:\ndef partitions(iterable):\n 'Returns a list... | [
3,
3,
1
] | [] | [] | [
"nested_loops",
"python"
] | stackoverflow_0007251358_nested_loops_python.txt |
Q:
Customized views with django-registration
I need to make a very simple modification -- require that certain views only show up when a user is not authenticated -- to django-registration default views. For example, if I am logged in, I don't want users to be able to visit the /register page again.
So, I think the ... | Customized views with django-registration | I need to make a very simple modification -- require that certain views only show up when a user is not authenticated -- to django-registration default views. For example, if I am logged in, I don't want users to be able to visit the /register page again.
So, I think the idea here is that I want to subclass the regist... | [
"As far as I remember django-registration is using function-based views, so you can not really subclass them. The approach I usually follow is \"overwriting\" the original views (without modifying the django-registration app of course). This works like this:\n\nCreate another app (you could call it custom_registrat... | [
5
] | [] | [] | [
"django",
"django_registration",
"inheritance",
"python"
] | stackoverflow_0007253132_django_django_registration_inheritance_python.txt |
Q:
Unicode characters are boxes in Geraldo/ReportLab generated PDF
I'm running into some Unicode related issues when generating PDF reports using Geraldo and ReportLab.
When Unicode strings containing Asian characters are passed into the report, they appear in the output PDF as black boxes. This example (http://dl.dr... | Unicode characters are boxes in Geraldo/ReportLab generated PDF | I'm running into some Unicode related issues when generating PDF reports using Geraldo and ReportLab.
When Unicode strings containing Asian characters are passed into the report, they appear in the output PDF as black boxes. This example (http://dl.dropbox.com/u/2627296/report.pdf) was generated using the following cod... | [
"You should specify the font name as in the official example \"Additional Fonts\". Use additional_fonts and default_style:\n#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom geraldo import Report, ReportBand, ObjectValue\nfrom geraldo.generators import PDFGenerator\n\nclass UnicodeReport(Report): \n titl... | [
1
] | [] | [] | [
"geraldo",
"pdf",
"python",
"reportlab",
"unicode"
] | stackoverflow_0007251211_geraldo_pdf_python_reportlab_unicode.txt |
Q:
Delete a specific string (not line) from a text file python
I have a text file with two lines in a text file:
<BLAHBLAH>483920349<FOOFOO>
<BLAHBLAH>4493<FOOFOO>
Thats the only thing in the text file. Using python, I want to write to the text file so that i can take away BLAHBLAH and FOOFOO from each line. It see... | Delete a specific string (not line) from a text file python | I have a text file with two lines in a text file:
<BLAHBLAH>483920349<FOOFOO>
<BLAHBLAH>4493<FOOFOO>
Thats the only thing in the text file. Using python, I want to write to the text file so that i can take away BLAHBLAH and FOOFOO from each line. It seems like a simple task but after refreshing my file manipulation i... | [
"If it's a text file as you say, and not HTML/XML/something else, just use replace:\nfor line in infile.readlines():\n cleaned_line = line.replace(\"BLAHBLAH\",\"\")\n cleaned_line = cleaned_line.replace(\"FOOFOO\",\"\")\n\nand write cleaned_line to an output file.\n",
"f = open(path_to_file, \"w+\")\n\nf.w... | [
5,
5,
1
] | [] | [] | [
"python"
] | stackoverflow_0007250471_python.txt |
Q:
Composite a numpy array/matrix based on column values and variables?
I'm playing with NumPy and Scipy and I'm having trouble finding a feature in the documentation. I was thus wondering if anyone could help.
Suppose I have an array in NumPy with two columns and k rows. One column serves as an numerical indicator (... | Composite a numpy array/matrix based on column values and variables? | I'm playing with NumPy and Scipy and I'm having trouble finding a feature in the documentation. I was thus wondering if anyone could help.
Suppose I have an array in NumPy with two columns and k rows. One column serves as an numerical indicator (e.g. 2 = male, 1 = female, 0 = unknown) while the second column is perhaps... | [
"If I understand your description, you have a dataset something like this:\nIn [79]: x=np.random.randint(0,3,size=100)\n\nIn [80]: y=np.random.randint(0,100,size=100)\n\nIn [81]: d=np.vstack([x,y]).T\n\nIn [88]: print d[:5,:]\n[[ 0 43]\n [ 1 60]\n [ 2 60]\n [ 1 4]\n [ 0 30]]\n\nIn this situation numpy.unique can b... | [
4,
2
] | [] | [] | [
"numpy",
"python",
"scipy"
] | stackoverflow_0007252851_numpy_python_scipy.txt |
Q:
Parsing text in python
I've got a text file that is structured like so
1\t 13249\n
2\t 3249\n
3\t 43254\n
etc...
It's a very simple list. I've got the file opened and I can read the lines. I have the following code:
count = 0
for x in open(filename):
count += 1
return count
What I wan... | Parsing text in python | I've got a text file that is structured like so
1\t 13249\n
2\t 3249\n
3\t 43254\n
etc...
It's a very simple list. I've got the file opened and I can read the lines. I have the following code:
count = 0
for x in open(filename):
count += 1
return count
What I want to do is to assign the fir... | [
"No need to reinvent the wheel..\nimport numpy as np\n\nfor xi, yi in np.loadtxt('blah.txt'):\n print(xi)\n print(yi)\n\n",
"count = 0\nfor x in open(filename):\n # strip removes all whitespace on the right (so the newline in this case)\n # split will break a string in two based on the passed parameter\... | [
4,
3,
2
] | [
"with regular expression:\nimport re\ndef FUNC(path):\nxi=[]\nyi=[]\nf=open(path).read().split(\"\\n\") # spliting file's content into a list\npatt=re.compile(\"^\\s*(\\d)\\t\\s(\\d).*\") # first some whitespaces then first number\n#then a tab or space second number and other characters \nfor iter in f:\n try:\n... | [
-1
] | [
"parsing",
"python"
] | stackoverflow_0007252831_parsing_python.txt |
Q:
MySQL statement in Python: Variables don't work
I have a problem with MySQL and Python's MySQLdb when I try to INSERT more than one variable.
I have a table wordurl with three fields. The first one is an auto_increment ID, second and third should hold the values. Second and third fields are named word_id and url_i... | MySQL statement in Python: Variables don't work | I have a problem with MySQL and Python's MySQLdb when I try to INSERT more than one variable.
I have a table wordurl with three fields. The first one is an auto_increment ID, second and third should hold the values. Second and third fields are named word_id and url_id.
This is the code.
cursor.execute("INSERT INTO wor... | [
"Regarding your update:\nAFAIK:\nfetchall() returns a tuple with tuples inside. Those tuples inside are what you would get from fetchone(). You can image it like\nfetchall() = (fetchone(), fetchtwo(), ...)\n\nAnd fetchone also returns a tuple which has the actual variable values. This is why you can't simply insert... | [
0,
0
] | [] | [] | [
"mysql",
"mysql_python",
"python"
] | stackoverflow_0007253276_mysql_mysql_python_python.txt |
Q:
Minimal domain for sphinx
I would like to use Sphinx for my own project and for that I want to create a new sphinx domain. But I have serious trouble getting started. My minimal sphinx domain would allow only a single instruction called 'command':
.. xx:command:: Somecommand
I can't find any introduction to writi... | Minimal domain for sphinx | I would like to use Sphinx for my own project and for that I want to create a new sphinx domain. But I have serious trouble getting started. My minimal sphinx domain would allow only a single instruction called 'command':
.. xx:command:: Somecommand
I can't find any introduction to writing sphinx domains "on the inter... | [
"Checkout the reStructuredText domain in the Sphinx source code, it's fairly simple and should get you started. You may also find some good examples in the sphinx-contrib source.\n"
] | [
7
] | [] | [] | [
"python",
"python_sphinx"
] | stackoverflow_0007202999_python_python_sphinx.txt |
Q:
Prune similar strings by length
How would one remove elements containing strings from a Python list by their similarity and length (if a string X is found in another, longer string Y, X must be removed)?
IN: [('this is string that stays', 0), ('this is string', 1), ('string that stays', 2), ('i am safe', 3)]
O... | Prune similar strings by length | How would one remove elements containing strings from a Python list by their similarity and length (if a string X is found in another, longer string Y, X must be removed)?
IN: [('this is string that stays', 0), ('this is string', 1), ('string that stays', 2), ('i am safe', 3)]
OUT: [('this is string that stays',... | [
"Here you go:\nl = [('this is string that stays', 0), ('this is string', 1), ('string that stays', 2), ('i am safe', 3)]\nsurvivors = set(s for s, _ in l)\nfor s1, _ in l:\nif any(s1 != s2 and s1 in s2 for s2 in survivors):\n survivors.discard(s1)\n\nsurvivors is what you want, except that it does not contain th... | [
0,
0,
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0007253412_list_python.txt |
Q:
python/django - assigning to global variable in decorator
I use thread-locals in order to implement user-based theming. First I wrote a middleware and have had no issues. Now I am converting it to a decorator and having an embarrassing issue. Here's the simplified code:
# views.py
_thread_locals = threading.local... | python/django - assigning to global variable in decorator | I use thread-locals in order to implement user-based theming. First I wrote a middleware and have had no issues. Now I am converting it to a decorator and having an embarrassing issue. Here's the simplified code:
# views.py
_thread_locals = threading.local()
def foo_decorator(f):
def _wrapper(*args, **kwargs):
... | [
"Your code is working for me, but only if some_view is called before get_theme.\nThe devserver kills your process and restarts a new one every time you modify a file in your project directory. Your thread data is of course lost when this is done. If you see the \"Validating models...\" message, your thread data i... | [
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006149089_django_python.txt |
Q:
python : working with german umlaut
months = ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"]
print months[2].decode("utf-8")
Printing month[2] fails with
UnicodeDecodeError: 'utf8' codec can't decode bytes in position 1-2: invalid data
hel... | python : working with german umlaut | months = ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"]
print months[2].decode("utf-8")
Printing month[2] fails with
UnicodeDecodeError: 'utf8' codec can't decode bytes in position 1-2: invalid data
help to get rid of this!
| [
"Did you add an encoding in the begining of your source file ?\n# -*- coding: utf-8 -*-\n\n",
"Are you sure you are working in UTF8?\nNevertheless, I would recommend to define\nmonths = [u\"Januar\", u\"Februar\", u\"März\", u\"April\", u\"Mai\", u\"Juni\",\n u\"Juli\", u\"August\", u\"September\", u\"Ok... | [
38,
5
] | [] | [] | [
"diacritics",
"python",
"unicode"
] | stackoverflow_0007254047_diacritics_python_unicode.txt |
Q:
how to create year/month/day structure when uploading files with django
am using a basic imagefield and upload_to function to point to my destination folder. I was wondering if there is something i can use to create folder structure with year/month/day on upload date or something..
regards,
A:
https://docs.djan... | how to create year/month/day structure when uploading files with django | am using a basic imagefield and upload_to function to point to my destination folder. I was wondering if there is something i can use to create folder structure with year/month/day on upload date or something..
regards,
| [
"https://docs.djangoproject.com/en/dev/ref/models/fields/#imagefield\nFor example, say your MEDIA_ROOT is set to '/home/media', and upload_to is set to 'photos/%Y/%m/%d'.\nThe '%Y/%m/%d' part of upload_to is strftime formatting.\n\n%Y is the four-digit year.\n%m is the two-digit month.\n%d is the two-digit day. \n\... | [
16,
8
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007254143_django_python.txt |
Q:
Python optparse and spaces in an argument
When using optparse i want to get the whole string after an option, but I only get part of it up to the first space.
e.g.:
python myprog.py --executable python someOtherProg.py
What I get in 'executable' is just 'python'.
Is it possible to parse such lines using optparse... | Python optparse and spaces in an argument | When using optparse i want to get the whole string after an option, but I only get part of it up to the first space.
e.g.:
python myprog.py --executable python someOtherProg.py
What I get in 'executable' is just 'python'.
Is it possible to parse such lines using optparse or do you have to use argparse to do it?
€: I ... | [
"You can enclose them in quotes to make them work with the existing code.\npython myprog.py --executable \"python someOtherProg.py\"\n\n\nIs it possible to parse such lines using optparse or do you have to use argparse to do it?\n\nI don't know if/how you can do it with optparse as I haven't really worked with optp... | [
12,
6,
4,
4,
1
] | [] | [] | [
"optparse",
"python"
] | stackoverflow_0003839791_optparse_python.txt |
Q:
Python assigning wrong dictionary values
In my code:
line_x = 10
c = 'A'
d = 'B'
a = {}
a['one']='| | | | | |'
a['two']='| | | | | |'
#untill thirteen
vak = a.keys()
b = a #copy the dictionary
spot = a[vak[0]]
spot2 = b[vak[0]]
a[vak[0]] = spot[:(line_x)]+ d+ spot[(line_x+1):]
b[vak[0]] = spot... | Python assigning wrong dictionary values | In my code:
line_x = 10
c = 'A'
d = 'B'
a = {}
a['one']='| | | | | |'
a['two']='| | | | | |'
#untill thirteen
vak = a.keys()
b = a #copy the dictionary
spot = a[vak[0]]
spot2 = b[vak[0]]
a[vak[0]] = spot[:(line_x)]+ d+ spot[(line_x+1):]
b[vak[0]] = spot2[:(line_x)]+ c+ spot2[(line_x+1):]
print a[v... | [
"b = a doesn't copy the dictionary, it rebinds b to point at the same object as a (so when you change a, you can observe the effect on b as well). Use b = copy.copy(a) (copy module) instead.\n",
"The\nb = a #copy the dictionary\n\ndoes not copy the dictionary, just its reference. You have to copy it explicitly:\n... | [
5,
3
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0007255029_dictionary_python.txt |
Q:
Django filter against Multiple Item QuerySets
I have two Model's which are related with a ForeignKey field.
Let's call these objects Event and EventRegistration.
I can easily, for example, do this:
EventRegistration.objects.filter(event=Event.objects.get(name="Some Event"))
But, I cannot do something like this:
E... | Django filter against Multiple Item QuerySets | I have two Model's which are related with a ForeignKey field.
Let's call these objects Event and EventRegistration.
I can easily, for example, do this:
EventRegistration.objects.filter(event=Event.objects.get(name="Some Event"))
But, I cannot do something like this:
EventRegistration.objects.filter(event=Event.objects... | [
"EventRegistration.objects.filter(event__in=Event.objects.all())\n\n"
] | [
0
] | [] | [] | [
"django",
"django_models",
"django_queryset",
"python"
] | stackoverflow_0007255107_django_django_models_django_queryset_python.txt |
Q:
Unit-testing extensions for an 'external' program with pyunit
I'm struggling to know where to start with unittest, having read the dive-into-python tutorial and looked at http://pyunit.sourceforge.net/.
I've got a piece of analysis software (call it 'prog.exe') which uses python for its input decks. I've started ... | Unit-testing extensions for an 'external' program with pyunit | I'm struggling to know where to start with unittest, having read the dive-into-python tutorial and looked at http://pyunit.sourceforge.net/.
I've got a piece of analysis software (call it 'prog.exe') which uses python for its input decks. I've started writing a python module which I'm going to import from that input d... | [
"Pyunit is a little bit outdated (2001), it is now completely included in python core distribution (http://docs.python.org/library/unittest.html). You should start read this documentation, especially the basic example part. \nTo test your module you'll have to create a file, let's call it mymodule_test.py and put i... | [
0
] | [] | [] | [
"python",
"python_unittest",
"unit_testing"
] | stackoverflow_0007255198_python_python_unittest_unit_testing.txt |
Q:
Python - Extract important string information
I have the following string
http://example.com/variable/controller/id32434242423423234?param1=321¶m2=4324342
How in best way to extract id value, in this case - 32434242423423234
Regardz,
Mladjo
A:
You could just use a regular expression, e.g.:
import re
s = "ht... | Python - Extract important string information | I have the following string
http://example.com/variable/controller/id32434242423423234?param1=321¶m2=4324342
How in best way to extract id value, in this case - 32434242423423234
Regardz,
Mladjo
| [
"You could just use a regular expression, e.g.:\nimport re\n\ns = \"http://example.com/variable/controller/id32434242423423234?param1=321¶m2=4324342\"\n\nm = re.search(r'controller/id(\\d+)\\?',s)\nif m: \n print \"Found the id:\", m.group(1)\n\nIf you need the value as an number rather than a string, you... | [
8,
3,
2,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0005210662_python_string.txt |
Q:
Python logic error?
Basically, I'm trying to flatten a list in my function but ignore that (you can also ignore the print functions I put in).
take x = [[1,2,3],4,5] to be my variable.
I call prob7(x) but the issue is that when type([1,2,3]) gets checked == list, it returns false. Why is that? I explicitly check... | Python logic error? | Basically, I'm trying to flatten a list in my function but ignore that (you can also ignore the print functions I put in).
take x = [[1,2,3],4,5] to be my variable.
I call prob7(x) but the issue is that when type([1,2,3]) gets checked == list, it returns false. Why is that? I explicitly check this on the interpreter ... | [
"Just not use 'list' as a variable name and use isinstance(var, list) instead of type(var) == list. \nPlease find corrected sample below.\ndef prob7(mylist): # flatten a list\n tempList = []\n if mylist: # meaning if there are elements in the list and it is not empty\n for i in mylist:\n if ... | [
3,
3,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0007253485_python.txt |
Q:
Opening a pop with custom UI in python gtk
I am new to Python GTK programming. In my UI i have a button. On click of that i have to open a popup which has a three button and some label. I have to pass some variables from main window to popup window. on click of buttons on the popup window I have to update this var... | Opening a pop with custom UI in python gtk | I am new to Python GTK programming. In my UI i have a button. On click of that i have to open a popup which has a three button and some label. I have to pass some variables from main window to popup window. on click of buttons on the popup window I have to update this variable. Then once i close this popup window I nee... | [
"You probably need dialog boxes.\nFrom pygtk :\n import gtk\n\n label = gtk.Label(\"Nice label\")\n dialog = gtk.Dialog(\"My dialog\",\n None,\n gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,\n (gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT,\n ... | [
6
] | [] | [] | [
"glade",
"popup",
"pygtk",
"python"
] | stackoverflow_0007254793_glade_popup_pygtk_python.txt |
Q:
QtDesigner & PySide: QTableWidget don't get accessible
I made a form in QtDesigner. This form gets loaded from PySide with help of the function
widget = loader.load(file, parent)
However, the QTableWidget (with objectNname buffer_table) don't get accessible with
widget.buffer_table
If I use a QPushButton instead... | QtDesigner & PySide: QTableWidget don't get accessible | I made a form in QtDesigner. This form gets loaded from PySide with help of the function
widget = loader.load(file, parent)
However, the QTableWidget (with objectNname buffer_table) don't get accessible with
widget.buffer_table
If I use a QPushButton instead it works. How can I get this working.
I'd like to fill up t... | [
"You could try to see if the table is there with: widget.findChild(QWidget, \"buffer_table\") (even from the parent, since it is a recursive search). \n"
] | [
2
] | [] | [] | [
"pyside",
"python",
"qt_designer",
"qtablewidget"
] | stackoverflow_0007250727_pyside_python_qt_designer_qtablewidget.txt |
Q:
Command Line app arguments style guide
Is there a style guide to writing command line applications' arguments on unix platforms? Coming from the iOS world I'm thinking of something akin to the Human Interface Guidelines (HIG). I'm writing a script in Python that can take parameters.
Example: How to name arguments,... | Command Line app arguments style guide | Is there a style guide to writing command line applications' arguments on unix platforms? Coming from the iOS world I'm thinking of something akin to the Human Interface Guidelines (HIG). I'm writing a script in Python that can take parameters.
Example: How to name arguments, when to use -dash or --doubleDash.
| [
"Look at this standard library module: http://docs.python.org/library/argparse.html\nIt will make your life much easier implementing a command line interface, and you end up using its style guide.\nNote that argparse only became available in Python 2.7 (or 3.2, in the 3.x series). Before that there was http://docs.... | [
6,
5,
4
] | [] | [] | [
"command_line",
"command_line_arguments",
"python",
"shell",
"unix"
] | stackoverflow_0007251734_command_line_command_line_arguments_python_shell_unix.txt |
Q:
"TypeError: Can't convert 'int' object to str implicitly" Trying to rename files in python3
I wrote the following function to rename a series of JPGs. They come off the scanner as a sequential number, however I need to know what the front and back of each document is (in JPG form). How I chose to do this is make... | "TypeError: Can't convert 'int' object to str implicitly" Trying to rename files in python3 | I wrote the following function to rename a series of JPGs. They come off the scanner as a sequential number, however I need to know what the front and back of each document is (in JPG form). How I chose to do this is make one end in A, and one end in B. For example:
00001.jpg becomes 00001B.jpg
00002.jpg becomes 00... | [
"0) Don't compare to boolean literals. Just use the condition directly.\n1) Don't write \"if <something>\" and then \"if <not something>\". That's what else is for.\n2) % 2 is a clearer parity test than & 1.\n3) Your logic is wrong: you're subtracting 1 from the even numbers and leaving the odd numbers untouched, s... | [
3,
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0007252144_python.txt |
Q:
How to add .xml extension to all files in a folder in Unix/Linux
I want to rename all files in a folder and add a .xml extension. I am using Unix. How can I do that?
A:
On the shell, you can do this:
for file in *; do
if [ -f ${file} ]; then
mv ${file} ${file}.xml
fi
done
Edit
To do this recurs... | How to add .xml extension to all files in a folder in Unix/Linux | I want to rename all files in a folder and add a .xml extension. I am using Unix. How can I do that?
| [
"On the shell, you can do this:\nfor file in *; do\n if [ -f ${file} ]; then\n mv ${file} ${file}.xml\n fi\ndone\n\nEdit\nTo do this recursively on all subdirectories, you should use find:\nfor file in $(find -type f); do\n mv ${file} ${file}.xml\ndone\n\nOn the other hand, if you're going to do any... | [
22,
4,
3,
2
] | [] | [] | [
"linux",
"php",
"python",
"shell",
"unix"
] | stackoverflow_0007253198_linux_php_python_shell_unix.txt |
Q:
python numpy - efficient dense matrix creation
I am currently writing function to generate matrices based on a input file for a transportation package. It's an 1850x1850 matrix representing the zones in a network. These 1850 zones are also partitioned into 10 different zone groups. Basically I am required to as... | python numpy - efficient dense matrix creation | I am currently writing function to generate matrices based on a input file for a transportation package. It's an 1850x1850 matrix representing the zones in a network. These 1850 zones are also partitioned into 10 different zone groups. Basically I am required to assign a Time Factor (number) to each combination orig... | [
"It should be possible to do it in one loop as this :\n #Generated the matrix\n for i in xrange(10):\n #Assign the time factor for each O-D pair\n I = PythonMatrixGroups[i]\n data[I] = lines[i]\n\nBut I did not test this.\n"
] | [
0
] | [] | [] | [
"indexing",
"matrix",
"numpy",
"python"
] | stackoverflow_0007251983_indexing_matrix_numpy_python.txt |
Q:
How to get User information of the Oauth authenticated user from Google & Twitter?
I have authenticated the user with oauth on both twitter & Google and have access_tokens.
(Using Python)
But,
How to get the information about this authenticated user ?
Eg:
Name, Age, Email, gender, etc.
A:
For Twitter, I'd sugge... | How to get User information of the Oauth authenticated user from Google & Twitter? | I have authenticated the user with oauth on both twitter & Google and have access_tokens.
(Using Python)
But,
How to get the information about this authenticated user ?
Eg:
Name, Age, Email, gender, etc.
| [
"For Twitter, I'd suggest using the tweepy library. It provides a nice Python API for accessing all the data you can get back from Twitter, such as user data.\nIf you want to do it yourself, you'd want to look at the docs for Twitter's REST API, specifically the User resource. I don't think you can get such persona... | [
2
] | [
"Google is more complicated since it has many APIs for different things. This Python library supports a bunch of them: http://code.google.com/p/google-api-python-client/\n"
] | [
-2
] | [
"oauth",
"python",
"twitter"
] | stackoverflow_0007241587_oauth_python_twitter.txt |
Q:
python : re how to replace everything beside some pattern
re_filter = re.compile(r'(?s)<div style="border.*?</div>')
s = re_filter.sub('', s)
this substitutes lines with constructed pattern.
But how can I substitute everything beside the constructed pattern ?
A:
s = ''.join(re_filter.findall(s))
| python : re how to replace everything beside some pattern | re_filter = re.compile(r'(?s)<div style="border.*?</div>')
s = re_filter.sub('', s)
this substitutes lines with constructed pattern.
But how can I substitute everything beside the constructed pattern ?
| [
"s = ''.join(re_filter.findall(s))\n\n"
] | [
2
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0007255899_python_regex.txt |
Q:
Allow range function to evaluate non numerical expression
I am using a makearange function to input a start, stop, and increment range for an array i.e.
User = raw_input('Enter start,[stop],[increment]: ').split(',')
makearange = lambda a: numpy.arange(int(a[0]),int(a[1]),int(a[2]))
x = makearange(User)
However I... | Allow range function to evaluate non numerical expression | I am using a makearange function to input a start, stop, and increment range for an array i.e.
User = raw_input('Enter start,[stop],[increment]: ').split(',')
makearange = lambda a: numpy.arange(int(a[0]),int(a[1]),int(a[2]))
x = makearange(User)
However I am also using these numbers to run a program to create arrays ... | [
"Instead of immediately trying to split User on commas, test if it is the empty string first:\nimport numpy as np\nimport sys\n\nuser_input = raw_input('Enter [start,] stop[, increment]: ')\nif user_input = '':\n sys.exit()\nelse:\n x=np.arange(*map(int,user_input.split(',')))\n\nPS. Enter start,[stop],[incre... | [
1,
0
] | [] | [] | [
"arrays",
"numpy",
"python",
"while_loop"
] | stackoverflow_0007256198_arrays_numpy_python_while_loop.txt |
Q:
Making a python script only be able to run once at a time
Possible Duplicate:
Python: single instance of program
I am looking to make a python script be unique in the sense that it can only run once at a time. For example if I run the script and open another session of the same script a second time and the first... | Making a python script only be able to run once at a time |
Possible Duplicate:
Python: single instance of program
I am looking to make a python script be unique in the sense that it can only run once at a time. For example if I run the script and open another session of the same script a second time and the first session is still running, then the second session will just e... | [
"Never written python before, but this is what I've just implemented in mycheckpoint, to prevent it being started twice or more by crond:\nimport os\nimport sys\nimport fcntl\nfh=0\ndef run_once():\n global fh\n fh=open(os.path.realpath(__file__),'r')\n try:\n fcntl.flock(fh,fcntl.LOCK_EX|fcntl.LOCK... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0002959474_python.txt |
Q:
python bsddb doesnt flush when removing entries
I got a python BSDDB database. Obviously, it's stored on the hard drive. When I remove some entries, the file on the drive does not get any smaller (consequently - it grows quite fast...)
utDelList = []
urlsDelList = []
for ut in iter(self.urls2task):
tmp = st... | python bsddb doesnt flush when removing entries | I got a python BSDDB database. Obviously, it's stored on the hard drive. When I remove some entries, the file on the drive does not get any smaller (consequently - it grows quite fast...)
utDelList = []
urlsDelList = []
for ut in iter(self.urls2task):
tmp = string.split(ut, ":")
uid = tmp[1]
url = cPickl... | [
"Did you try to use the db.compact() method ?\nAccording to the documentation : \n\ncompact(start=None, stop=None, flags=0, compact_fillpercent=0, compact_pages=0, compact_timeout=0)\nCompacts Btree and Recno access\n method databases, and optionally returns unused Btree, Hash or Recno\n database pages to the und... | [
1,
0,
0
] | [] | [] | [
"bsddb",
"flush",
"python",
"sync"
] | stackoverflow_0007255873_bsddb_flush_python_sync.txt |
Q:
How can I use bulkuploader to populate class with a db.SelfReferenceProperty?
I've got a class that is using db.SelfReferenceProperty to create a tree-like structure.
When trying to populate the database using appcfg.py upload_data -- config_file=bulkloader.yaml --kind=Group --filename=group.csv (...)
, I'm getti... | How can I use bulkuploader to populate class with a db.SelfReferenceProperty? | I've got a class that is using db.SelfReferenceProperty to create a tree-like structure.
When trying to populate the database using appcfg.py upload_data -- config_file=bulkloader.yaml --kind=Group --filename=group.csv (...)
, I'm getting an exception saying BadValueError: name must not be empty. (Full stack below)
I ... | [
"Using an answer given to a similar problem as a base, I could successfully solve this by creating a small helpers.py file to do act as a wrapper around transform.create_foreign_key:\nfrom google.appengine.api import datastore\n\ndef create_foreign_key(kind, key_is_id=False):\n def generate_foreign_key_lambda(valu... | [
4,
2
] | [] | [] | [
"bulkloader",
"google_app_engine",
"python"
] | stackoverflow_0003704717_bulkloader_google_app_engine_python.txt |
Q:
Programmatically animate a blender model — where to start?
I have to create a simplistic 3D demo.
Having a model in Blender, I will write a python program that will:
build a scene, set camera, draw an infinite plane, fill it with texture
load a model (exported from Blender) and position the object
handle key pres... | Programmatically animate a blender model — where to start? | I have to create a simplistic 3D demo.
Having a model in Blender, I will write a python program that will:
build a scene, set camera, draw an infinite plane, fill it with texture
load a model (exported from Blender) and position the object
handle key presses to produce the object moves
I need a link to descriptive tu... | [
"Not much to say: OpenGL / Glut\nAlso, take a look at the OpenGL red book. You can read it online.\n Samples are written in C, but can be easily ported to python, since function calls are the same.\n\nAs for loading the blender model, take a look at this:\nLoading wavefront obj files with python\nIn a nutshell look... | [
0,
0
] | [] | [] | [
"3d",
"blender",
"python"
] | stackoverflow_0007098760_3d_blender_python.txt |
Q:
Comparing multiple strings
Hey I am new I need some help with comparing strings
My Assignment is to make a chatbot, one that reads from a text file, that has possible things to input, and what the resulting output will be.
My problem is that it asks to choose the most suited one from the text file, easy yeh? but y... | Comparing multiple strings | Hey I am new I need some help with comparing strings
My Assignment is to make a chatbot, one that reads from a text file, that has possible things to input, and what the resulting output will be.
My problem is that it asks to choose the most suited one from the text file, easy yeh? but you also must save variables at t... | [
"I would prefer pyparsing over any regex-based approach to tackle this task. It's easier to construct a readable parser even for more involved and complex grammars.\n",
"As a quick-and-stupid solution, parse input file and store entries in list. Each entry should contain dynamically-compiled \"matching regex\" (e... | [
2,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0007256186_python_string.txt |
Q:
Python script to run an exe-file on all files in a directory
I have a small .exe file that I'd like to run on all files in a given directory. It is launched as follows "./myprogram.exe file" and converts my files into a different data type.
Now I want to build a python script, that runs this exe on all files in a ... | Python script to run an exe-file on all files in a directory | I have a small .exe file that I'd like to run on all files in a given directory. It is launched as follows "./myprogram.exe file" and converts my files into a different data type.
Now I want to build a python script, that runs this exe on all files in a given directory, including all subdirectories. I am totally new to... | [
"On a linux box, I would have told you to use a find call, but the .exe seems to tell you are on windows.\nIn python, you should use something like this \nfor root, dir, files in os.walk(path):\n for name in files:\n subprocess.call([\"path_to_your_programm/myprogram.exe\", os.path.join(root, name)]\n\n",
... | [
2,
1,
0
] | [] | [] | [
"exe",
"loops",
"python",
"subdirectory"
] | stackoverflow_0007257066_exe_loops_python_subdirectory.txt |
Q:
Python Fast Webserver
Have a simple webserver in python:
try:
server = HTTPServer(('', 80), MyHandler)
print 'started httpserver...'
server.serve_forever()
except KeyboardInterrupt:
print '^C received, shutting down server'
server.socket.close()
Is there any way I can make it faster? I believ... | Python Fast Webserver | Have a simple webserver in python:
try:
server = HTTPServer(('', 80), MyHandler)
print 'started httpserver...'
server.serve_forever()
except KeyboardInterrupt:
print '^C received, shutting down server'
server.socket.close()
Is there any way I can make it faster? I believe the above is blocking so ... | [
"To make web server scaleble use non-blocking IO sockets. A good framework/server for Python is Spawning:\nhttp://pypi.python.org/pypi/Spawning/\nNote that this makes your service scalable only in horizontally (you can easily add more concurrent requests). The delay of processing a single request depends on your co... | [
1
] | [] | [] | [
"python",
"webserver"
] | stackoverflow_0007257010_python_webserver.txt |
Q:
Test Apache config file from Python
How would I go about testing the apache config file from python? I've trying using the "os.popen" with "text = stdout_handle.read() to get the result, but nothing happens.
Any help would be great :)
A:
I'm guessing you're trying to automate apachectl configtest? Have you tri... | Test Apache config file from Python | How would I go about testing the apache config file from python? I've trying using the "os.popen" with "text = stdout_handle.read() to get the result, but nothing happens.
Any help would be great :)
| [
"I'm guessing you're trying to automate apachectl configtest? Have you tried subprocess.Popen? Something like the following should get you in started:\nfrom subprocess import Popen, PIPE\n\nargs = ['/usr/bin/apachectl','configtest']\n\nresult = Popen(args,stdout=PIPE,stderr=PIPE).communicate()\n# result[0] will b... | [
1
] | [] | [] | [
"apache",
"config",
"python",
"testing"
] | stackoverflow_0007257442_apache_config_python_testing.txt |
Q:
Cython install problem
I got Cython 0.15 and tried to install it like this
python setup.py install
I get this:
running install
running build
running build_py
running build_ext
building 'Cython.Plex.Scanners' extension
error: Unable to find vcvarsall.bat
What does this mean? I have Micorsoft Visual Studio 2008 an... | Cython install problem | I got Cython 0.15 and tried to install it like this
python setup.py install
I get this:
running install
running build
running build_py
running build_ext
building 'Cython.Plex.Scanners' extension
error: Unable to find vcvarsall.bat
What does this mean? I have Micorsoft Visual Studio 2008 and Windows SDK. Using Windows... | [
"I have no direct answer to your question, but I would strongly recommend to give this pre-built Cython package a try.\n"
] | [
5
] | [] | [] | [
"cython",
"installation",
"python",
"windows"
] | stackoverflow_0007255390_cython_installation_python_windows.txt |
Q:
Create a dictionary in python which is indexed by lists
I would like to create a dictionary which is indexed by lists. For instance, my dictionary should look like:
D = {[1,2,3]:1, [2,3]:3}
Anyone know how to do this? If I just type D([1,2,3]) = 1 it returns an error.
A:
dict keys must be hashable, which lists ... | Create a dictionary in python which is indexed by lists | I would like to create a dictionary which is indexed by lists. For instance, my dictionary should look like:
D = {[1,2,3]:1, [2,3]:3}
Anyone know how to do this? If I just type D([1,2,3]) = 1 it returns an error.
| [
"dict keys must be hashable, which lists are not becase they are mutable. You can change a list after you make it. Think of how tricky it would be to try to keep a dict when the data used as keys changes; it doesn't make any sense. Imagine this scenario\n>>> foo = [1, 2]\n>>> bar = {foo: 3}\n>>> foo.append(4)\n\nan... | [
20,
2,
1
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0002671211_dictionary_python.txt |
Q:
Tkinter - Setting the Current Selection in TextWidget
I am looking for a way to set the current selection inside a Tkinter text widget.
I already tried to set it with mark_set(), but it doesn't work...
text_widget.mark_set("sel.first", 1.0)
text_widget.mark_set("sel.last", END)
Would anyone know how to work this... | Tkinter - Setting the Current Selection in TextWidget | I am looking for a way to set the current selection inside a Tkinter text widget.
I already tried to set it with mark_set(), but it doesn't work...
text_widget.mark_set("sel.first", 1.0)
text_widget.mark_set("sel.last", END)
Would anyone know how to work this one out?
| [
"sel is a tag, not a mark, so you need to use the tag commands, such as tag_add\nimport Tkinter as tk\n\nclass SampleApp(tk.Tk):\n def __init__(self, *args, **kwargs):\n tk.Tk.__init__(self, *args, **kwargs)\n self.text = tk.Text(self)\n self.text.pack()\n self.text.insert(\"1.0\", \"... | [
7
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0007256558_python_tkinter.txt |
Q:
handling None values in conversion to numpy recarray
Is there a graceful way of handling None values in a conversion of a list of tuples to a numpy recarray using the single call to np.rec.fromrecords? Assuming I know what I want the missing value to be (e.g. -1 for integers), how do I catch and handle the below ... | handling None values in conversion to numpy recarray | Is there a graceful way of handling None values in a conversion of a list of tuples to a numpy recarray using the single call to np.rec.fromrecords? Assuming I know what I want the missing value to be (e.g. -1 for integers), how do I catch and handle the below contrived example:
import numpy as np
a = [('Bob', 40, 3.1... | [
"Return -1 for the NULL column values using the database query, something like this:\nSELECT COALESCE(ColumnName, -1) FROM Schema.Table;\n\nThis will return -1 for ColumnName values that are NULL, otherwise the actual value is returned. Documentation for COALESCE here if needed. This allows you to provide a NULL re... | [
1
] | [] | [] | [
"numpy",
"pyodbc",
"python",
"recarray"
] | stackoverflow_0007069198_numpy_pyodbc_python_recarray.txt |
Q:
geodjango - search by city, state or zip code
How can I use geodjango to search by city and state or zip code in my django application? I am very new to geodjango and just trying to wrap my head around what would be involved in this.
Also, does anyone know of an app that already implements this functionality?
A:... | geodjango - search by city, state or zip code | How can I use geodjango to search by city and state or zip code in my django application? I am very new to geodjango and just trying to wrap my head around what would be involved in this.
Also, does anyone know of an app that already implements this functionality?
| [
"First thing you need to do is create a ZipCode model which will be table of geometry objects that represent each zipcode. You'll also need to have another model that you'll be searching, which needs to have a geographic location field. Then you'd do something like:\nzip = 10010\nzipcode = ZipCode.objects.get(numbe... | [
1,
0
] | [] | [] | [
"django",
"geodjango",
"python"
] | stackoverflow_0002046887_django_geodjango_python.txt |
Q:
Maybe I need to export paths but not sure
I'm trying to use the check-html flag with linkchecker. It gives an error that the tidy module is not installed. If I say tidy at a command line I can use it. I have MacPorts installed and have installed just about every option for libtidy or tidy that has to do with pytho... | Maybe I need to export paths but not sure | I'm trying to use the check-html flag with linkchecker. It gives an error that the tidy module is not installed. If I say tidy at a command line I can use it. I have MacPorts installed and have installed just about every option for libtidy or tidy that has to do with python. I'm thinking it has to do with a $PATH issue... | [
"if you have 2 python compilers running, be sure you use the right one with the \"python\"-command.\nyou can see the used interpreter-version if you access the interactive-console with \"python\".\nand you're right, the py26-...-library is for the python2.6 version. if there is no precompiled version you can always... | [
0
] | [] | [] | [
"link_checking",
"linux",
"python"
] | stackoverflow_0007258488_link_checking_linux_python.txt |
Q:
Tuples Vs List Vs Numpy Arrays for Plotting a Boxplot in Python
I am trying to plot a boxplot for a column in several csv files (without the header row of course), but running into some confusion around tuples, lists and arrays. Here is what I have so far
#!/usr/bin/env python
import csv
from numpy im... | Tuples Vs List Vs Numpy Arrays for Plotting a Boxplot in Python | I am trying to plot a boxplot for a column in several csv files (without the header row of course), but running into some confusion around tuples, lists and arrays. Here is what I have so far
#!/usr/bin/env python
import csv
from numpy import *
import pylab as p
import matplotlib
#open one fil... | [
"elapsed contains strings. Matplotlib needs integers or floats to plot something. Try converting each value of elapsed to integer. You can do this like so \nelapsed = tuple([int(i) for i in elapsed])\n\nor as FredL commented below:\nelapsed_list = array(elapsed_list, dtype=float)\n\n",
"I'm not familiar with nump... | [
4,
1
] | [] | [] | [
"arrays",
"list",
"matplotlib",
"numpy",
"python"
] | stackoverflow_0007258144_arrays_list_matplotlib_numpy_python.txt |
Q:
How to pass template variable to django wizard form
I have done a simple wizard form as following
forms.py
class Posting_Wizard(FormWizard):
def done(self, request, form_list):
return HttpResponseRedirect(reverse('accounts-registration-wizard-done'))
def get_template(self, step):
return '... | How to pass template variable to django wizard form | I have done a simple wizard form as following
forms.py
class Posting_Wizard(FormWizard):
def done(self, request, form_list):
return HttpResponseRedirect(reverse('accounts-registration-wizard-done'))
def get_template(self, step):
return 'listing/post/wizard/wizard_%s.html' % step
and then crea... | [
"You can provide the attribute extra_context as a dictionary in your Posting_Wizard class or pass it in your url configuration.\nSee here for details: https://docs.djangoproject.com/en/1.3/ref/contrib/formtools/form-wizard/#creating-templates-for-the-forms\nYou could also override the render_template method on your... | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007257276_django_python.txt |
Q:
Python Regular expression
I want to seach within a string for heading tags,I'm looking for a regular expression to find the index within the document wherever a heading tag occurs, So something like:
str.index('<h*>')
Where the * would represent only 1 character ie. 1 , 2 , 3 etc. eliminating any head tags or ht... | Python Regular expression | I want to seach within a string for heading tags,I'm looking for a regular expression to find the index within the document wherever a heading tag occurs, So something like:
str.index('<h*>')
Where the * would represent only 1 character ie. 1 , 2 , 3 etc. eliminating any head tags or html tags
Any help would be much ... | [
"import re\n\nmatches = re.finditer('<h[1-6]>', your_text)\nfor match in matches:\n print match.start()\n\n",
"The regex you need is this:\n<h.>\n\nThis will match <h1>, <h2>, <hr>, etc... If you only want to match heading tags, use:\n<h\\d>\n\n"
] | [
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0007258768_python_regex.txt |
Q:
Test whether tuples have the same content
I have to implement a function cmpT which should return the following results:
>>> cmpT((1, 2), (1, 2))
True
>>> cmpT((1, 2), (2, 1))
True
>>> cmpT((1, 2), (1, 2, 1))
False
>>> cmpT((1, 2), ())
False
My Code:
def cmpT(t1, t2):
if t1 == t2:
return True
el... | Test whether tuples have the same content | I have to implement a function cmpT which should return the following results:
>>> cmpT((1, 2), (1, 2))
True
>>> cmpT((1, 2), (2, 1))
True
>>> cmpT((1, 2), (1, 2, 1))
False
>>> cmpT((1, 2), ())
False
My Code:
def cmpT(t1, t2):
if t1 == t2:
return True
else:
return False
It does not give the ... | [
"You should check for each element if it is in both lists and the same number of times. The best solution is just sorting.\ndef cmpT(t1, t2): \n return sorted(t1) == sorted(t2)\n\nHave a look: http://codepad.org/PH6LrAvU\n"
] | [
15
] | [
"First, your code could be replaced by:\ndef cmpT(t1, t2):\n return t1 == t2\n\nSecond, I have no idea why it isn't working. It works fine for me too.\n",
"If you want to compare the content of two sets you have to convert the tuples to sets. \n>>> a = set((1,2))\n>>> b = set((2,1))\n>>> a\nset([1, 2])\n>>> b\... | [
-3,
-3,
-3
] | [
"python"
] | stackoverflow_0007258476_python.txt |
Q:
Python's os.listdir behaviour on Windows
>>> import os
>>> os.chdir('c:/python27')
>>> os.listdir('c:')
['Tools', 'include', 'python.exe', 'libs', 'DLLs', 'Lib', 'NEWS.txt',
'w9xpopen.exe', 'Doc', 'pythonw.exe', 'LICENSE.txt', 'README.txt', 'tcl']
>>> os.listdir('c:/')
['users', 'Program Files', 'Python27', 'windo... | Python's os.listdir behaviour on Windows | >>> import os
>>> os.chdir('c:/python27')
>>> os.listdir('c:')
['Tools', 'include', 'python.exe', 'libs', 'DLLs', 'Lib', 'NEWS.txt',
'w9xpopen.exe', 'Doc', 'pythonw.exe', 'LICENSE.txt', 'README.txt', 'tcl']
>>> os.listdir('c:/')
['users', 'Program Files', 'Python27', 'windows']
Why is the "/" after "c:" affecting the ... | [
"This is not specific to Python, it's a Windows question at heart.\nIn Windows C: and C:\\ (or, alternatively C:/) have quite different meanings:\n\nC: refers to the current directory on the drive C:\nC:\\ (and C:/) refers to the root directory of the drive C:\n\nWhile UNIX-like operating systems simply have a \"cu... | [
26,
4
] | [] | [] | [
"filepath",
"operating_system",
"python",
"windows"
] | stackoverflow_0007258993_filepath_operating_system_python_windows.txt |
Q:
.python-eggs permission denied
I'm getting the following error when trying to create a simple db with Django. I'm the only user on this computer, so I should be an admin. How do I make it so that I have permissions so that Django can just do its thing?
here is some more of the error:
[Errno 13] Permission denied: ... | .python-eggs permission denied | I'm getting the following error when trying to create a simple db with Django. I'm the only user on this computer, so I should be an admin. How do I make it so that I have permissions so that Django can just do its thing?
here is some more of the error:
[Errno 13] Permission denied: '/Users/tyre77/.python-eggs/simplejs... | [
"Files seem to be owned by root, and members of group staff do not have the rights to write into those files/directories and you're not root. \nTry to change the owner of those files : sudo chown -R tyre77 /Users/tyre77/.python-eggs/\nMaybe you've installed the module with a sudo command, so the files were created ... | [
1
] | [] | [] | [
"database",
"django",
"python",
"terminal"
] | stackoverflow_0007258776_database_django_python_terminal.txt |
Q:
Python urlopen windows authentication
I am not experienced with python and using the below code to open a url and read the response. I am getting an unauthorized error because the site uses Windows Authentication. Can someone provide a code sample on how to send in the user name and password?
response = urllib.re... | Python urlopen windows authentication | I am not experienced with python and using the below code to open a url and read the response. I am getting an unauthorized error because the site uses Windows Authentication. Can someone provide a code sample on how to send in the user name and password?
response = urllib.request.urlopen(url, params.encode("ASCII"))
... | [
"Try using urllib2 and python-ntlm Some example code:\nimport urllib2\nfrom ntlm import HTTPNtlmAuthHandler\n\nuser = 'DOMAIN\\User'\npassword = \"Password\"\nurl = \"http://ntlmprotectedserver/securedfile.html\"\n\npassman = urllib2.HTTPPasswordMgrWithDefaultRealm()\npassman.add_password(None, url, user, password)... | [
2
] | [] | [] | [
"python",
"windows_authentication"
] | stackoverflow_0007258951_python_windows_authentication.txt |
Q:
Checking list values
I have a list that must only contain ints, how would i proceed to control every element of the list and return a message if it is not an int?
Could i for instance somehow use isdigit()?
Thanks
A:
You can use all and the abstract base class Number:
>>> all(isinstance(x, Number) for x in mylis... | Checking list values | I have a list that must only contain ints, how would i proceed to control every element of the list and return a message if it is not an int?
Could i for instance somehow use isdigit()?
Thanks
| [
"You can use all and the abstract base class Number:\n>>> all(isinstance(x, Number) for x in mylist)\n\n",
"You can use abstract base class numbers and a simple loop:\nfrom numbers import Number\n\nfor item in my_list:\n if not isinstance(item, Number):\n print '{} is not a number'.format(item)\n\n",
... | [
6,
0,
0
] | [
"You can check if all elements of a list are of a particular type:\nall(map(lambda x: type(x) == type(0), list))\n\nThis will return False iif there is at least one element of list which is not of the same type as 0. You can change the condition to fit your needs, depending on whether you need integers or reals or ... | [
-1
] | [
"python"
] | stackoverflow_0007259188_python.txt |
Q:
get GPS coordinates via bluetooth with python on OSX
I just bought a GPS bluetooth receiver, which has been correctly paired with my OSX machine. Now I would like to query the device for my position with python. How do I do it?
A:
I assume your GPS receiver works over a virtual COM port, so it's independent of b... | get GPS coordinates via bluetooth with python on OSX | I just bought a GPS bluetooth receiver, which has been correctly paired with my OSX machine. Now I would like to query the device for my position with python. How do I do it?
| [
"I assume your GPS receiver works over a virtual COM port, so it's independent of bluetooth.\nProbably these libraries will help you:\n\nPython bindings for gpsd (which is available for Mac too)\nPyGPS, untested\n\n",
"with a virtual COM port you can use this script with the NMEA 0183 protocol http://miguellopes.... | [
1,
1
] | [] | [] | [
"bluetooth",
"geolocation",
"gps",
"python"
] | stackoverflow_0003702158_bluetooth_geolocation_gps_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.