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: unique sorting in python I am quite new in python.I want to get unique string from a file.txt I have some data like so... Tempranillo Rioja_%28wine%29%23Wine_regions Gr%C3%BCner_Veltliner Czech_Republic_%28wine%29 Marsanne California_%28wine%29 Carm%C3%A9n%C3%A8re Wines_of_Chile Carm%C3%A9n%C3...
unique sorting in python
I am quite new in python.I want to get unique string from a file.txt I have some data like so... Tempranillo Rioja_%28wine%29%23Wine_regions Gr%C3%BCner_Veltliner Czech_Republic_%28wine%29 Marsanne California_%28wine%29 Carm%C3%A9n%C3%A8re Wines_of_Chile Carm%C3%A9n%C3%A8re Washington_%28U.S._s...
[ "To filter out duplicates lines from the file, do this:\nwith open(\"file.txt\") as f:\n unique_lines = set(f)\n\n", "Well, if I understand you correctly:\nPut this before you open the file:\n wines = {}\n\nPut this at the last lines inside the loop:\n# if the wine location does not exist in the wines dictiona...
[ 5, 1, 1, 0, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0006557936_python_string.txt
Q: Python, inter-class relationships and object dependents Edit Apologies for previous generality! I hereby try to be clearer. I am testing an image, so I am to write a number of methods which will run to analyse the image. Not all images tested will be the same, and so I want an object for each image. Many of the m...
Python, inter-class relationships and object dependents
Edit Apologies for previous generality! I hereby try to be clearer. I am testing an image, so I am to write a number of methods which will run to analyse the image. Not all images tested will be the same, and so I want an object for each image. Many of the methods I am to write don't run on all of the image. For exam...
[ "You could do it like this:\nclass Point(object):\n def __init__(self, image):\n self._image = image\n\nclass Image(object):\n def __init__(self, width, height):\n self._points = [Point(self) for unused in range(width * height)]\n\nThis way, each point requires an image on initialization, and ea...
[ 1, 1 ]
[]
[]
[ "class", "python", "relationship" ]
stackoverflow_0006556744_class_python_relationship.txt
Q: Calling a Python script with Arguments using IronPython - "Need more than x values to unpack" I'm using the following C# code to call a Python script using IronPython: ScriptEngine scriptEngine; var opts = new Dictionary<string, object>(); opts["Arguments"] = new[] { Server.MapPath(@"~\Processing\input.7z"),...
Calling a Python script with Arguments using IronPython - "Need more than x values to unpack"
I'm using the following C# code to call a Python script using IronPython: ScriptEngine scriptEngine; var opts = new Dictionary<string, object>(); opts["Arguments"] = new[] { Server.MapPath(@"~\Processing\input.7z"), // Input Server.MapPath(@"~\Processing\key.pem"), // Key Server.MapPath(@"~\Processing\")...
[ "The line\narg0,input,key,output = sys.argv\n\nunpacks the list of arguments in sys.argv into the four variables on the left. Since there are only three arguments in sys.argv, this fails with the error message you posted (apparently you need to manually pass in the script path for it to appear as the first element ...
[ 5, 2 ]
[]
[]
[ "asp.net", "ironpython", "python" ]
stackoverflow_0006558126_asp.net_ironpython_python.txt
Q: I need to convert to a wave file Here is my work as yet. import matplotlib.pyplot as plot import numpy as num def xr(start, stop, step): while start < stop: yield start start = start + step wavef = lambda x: num.sin(x)/x t0 = [wavef(x) for x in xr(5.0,200.0,0.1) if x is not 0] plot.plot(t0)...
I need to convert to a wave file
Here is my work as yet. import matplotlib.pyplot as plot import numpy as num def xr(start, stop, step): while start < stop: yield start start = start + step wavef = lambda x: num.sin(x)/x t0 = [wavef(x) for x in xr(5.0,200.0,0.1) if x is not 0] plot.plot(t0) plot.show()
[ "Python has a wave module wave — Read and write WAV files .\nAn example of how to use it to write function data to a wav file is given here,\nCreate a synthetic 'sine wave' wave file and How to make a simple .wav file with Python.\nYou could also use Audiolab .\nAs you are already using numpy, you could use numpy.l...
[ 0 ]
[]
[]
[ "audio", "python" ]
stackoverflow_0006556192_audio_python.txt
Q: Best way to get future event from a date and a time attribute In one of my Django application I have an object with both a date and a time attribute, and i don't wish to use a datetime single attribute. For the sake of example let's call this object "Meeting": class Meeting(models.Model): publication_date = mo...
Best way to get future event from a date and a time attribute
In one of my Django application I have an object with both a date and a time attribute, and i don't wish to use a datetime single attribute. For the sake of example let's call this object "Meeting": class Meeting(models.Model): publication_date = models.DateField() publication_time = models.TimeField() Now I w...
[ "Nope that would be the correct way to do it given the constraint of not using a datetime field. Why you don't want to use a datetime field I don't know.\n" ]
[ 0 ]
[]
[]
[ "date", "datetime", "django", "python" ]
stackoverflow_0006558559_date_datetime_django_python.txt
Q: Using Python to Automatically Login to a Website with a JavaScript Form I'm attempting to write a particular script that logs into a website. This specific website contains a Javascript form so I had little to no luck by making use of "mechanize". I'm curious if there exist other solutions that I may be unaware o...
Using Python to Automatically Login to a Website with a JavaScript Form
I'm attempting to write a particular script that logs into a website. This specific website contains a Javascript form so I had little to no luck by making use of "mechanize". I'm curious if there exist other solutions that I may be unaware of that would help me in my situation. If this particular question or some rel...
[ "I've recently been using PhantomJS for this kind of work - it's a command-line tool that allows you to run Javascript in a browser environment (based on Webkit). This allows you to do scraping and online interactions that require Javascript-enabled interfaces. There's a Python-based implementation here that's full...
[ 1 ]
[]
[]
[ "javascript", "mechanize", "python" ]
stackoverflow_0006558704_javascript_mechanize_python.txt
Q: Differing behavior with Python script on RHEL and Debian, nearly identical python versions I rarely post questions to a forum, but this one has me stumped. I'm very curious as to what's causing this (a solution would also be nice, but mostly, I'd like to know why I'm having this issue): I recently wrote a python s...
Differing behavior with Python script on RHEL and Debian, nearly identical python versions
I rarely post questions to a forum, but this one has me stumped. I'm very curious as to what's causing this (a solution would also be nice, but mostly, I'd like to know why I'm having this issue): I recently wrote a python script for wrapping the invocation of remote commands which are started by a PBS job: #! /usr/bin...
[ "I would guess that a difference in the packages available is causing a different branch of your \"subprocess instantiation wrapper\" to be used on either machine. In one branch, you'd be using SIGTERM (the terminate() call) and in the other, SIGKILL.\nHaving said that, sleep seems to end prematurely given either s...
[ 1, 0 ]
[]
[]
[ "debian", "python", "rhel" ]
stackoverflow_0006529598_debian_python_rhel.txt
Q: Recursive thread creation in python I'm trying to implement a recursive Fibonacci series which returns the value at an index. It's a homework and needs to be done using multi-threading. This is what I've done so far. My question is how do I add the results from live_thread1 and live_thread2. The threads have to be...
Recursive thread creation in python
I'm trying to implement a recursive Fibonacci series which returns the value at an index. It's a homework and needs to be done using multi-threading. This is what I've done so far. My question is how do I add the results from live_thread1 and live_thread2. The threads have to be created at every level in the recursion....
[ "This is not possible, because you cannot retrieve the return-value of a function executed in another thread. \nTo implement the behavior you want, you have to make FibonacciThreads a callable object that stores the result as a member variable:\nclass FibonacciThreads(object):\n def __init__(self):\n self...
[ 4, 1 ]
[]
[]
[ "fibonacci", "multithreading", "python", "recursion" ]
stackoverflow_0006558716_fibonacci_multithreading_python_recursion.txt
Q: How to call a python function by name from the C-API? From the c-api, I would like to call a python function by name. I would then be calling the function with a list of python objects as arguments. It is not clear to me in the Python documentation how I would get a "Callable" object from the main python interpre...
How to call a python function by name from the C-API?
From the c-api, I would like to call a python function by name. I would then be calling the function with a list of python objects as arguments. It is not clear to me in the Python documentation how I would get a "Callable" object from the main python interpreter. Any help appreciated in: Getting the address from the...
[ "Basically, you use the Python C API to get the module the function is contained in, then query the module dictionary for the function. That's more or less the same what the Python runtime does internally when your Python code invokes a function from somewhere.\nRelevant functions from the API to look at are PyImpo...
[ 3 ]
[]
[]
[ "python", "python_c_api" ]
stackoverflow_0006558957_python_python_c_api.txt
Q: Celery error: "str object is not callable", getstate() function is a string I'm getting this error when I try to pass a task to a Celery worker. Here is the traceback Traceback: File "/home/vivek/xpython/lib/python2.6/site-packages/Django-1.3-py2.6.egg/django/core/handlers/base.py" in get_response 111. ...
Celery error: "str object is not callable", getstate() function is a string
I'm getting this error when I try to pass a task to a Celery worker. Here is the traceback Traceback: File "/home/vivek/xpython/lib/python2.6/site-packages/Django-1.3-py2.6.egg/django/core/handlers/base.py" in get_response 111. response = callback(request, *callback_args, **callback_kwargs) Fil...
[ "You are trying to pass an object to a task that cannot be serialized. Try to pass simpler data (information that let's you recreate the complex objects when the task is run).\nNot sure if that's the actual cause of your error, but you should not pass Django models to tasks anyway. You will run into race conditions...
[ 2 ]
[]
[]
[ "celery", "python" ]
stackoverflow_0006558143_celery_python.txt
Q: Importing modules with variable paths? I have dev and production systems. My production system is different from my dev system in that that it adds one directory to the beginning path. for eg. on dev system: main->module1->module2 becomes on production: project_name->main->module1->module2. Because of that I have ...
Importing modules with variable paths?
I have dev and production systems. My production system is different from my dev system in that that it adds one directory to the beginning path. for eg. on dev system: main->module1->module2 becomes on production: project_name->main->module1->module2. Because of that I have to change all my imports to accommodate for ...
[ "Why not just modify sys.path to include the directory one level down? Then the same imports will work in both places.\n" ]
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0006559656_python.txt
Q: more descriptive error message than "SyntaxError: invalid syntax" learning python, coming from a php background. Keeping it short. Is there a way to get more descriptive error messages about the syntax error? like in php. Example: print var should give something like "expecting ( " , instead of the standard "Syn...
more descriptive error message than "SyntaxError: invalid syntax"
learning python, coming from a php background. Keeping it short. Is there a way to get more descriptive error messages about the syntax error? like in php. Example: print var should give something like "expecting ( " , instead of the standard "SyntaxError: invalid syntax" Thanks
[ "My advice would be to use a solid IDE. I only tried a few before settling down for Aptana studio which is free (as in freedom) and cross-platform, but I am sure that many other offer similar functionality.\nIDE with syntax highlighting will try to parse your code even before runtime, and will signal you any mistak...
[ 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0006559838_python_python_3.x.txt
Q: python fabric prompted for password everytime i execute a sudo command Below is a small code I've been working on to install packages on the remote server. The code is working fine and the packages are being installed, but once the installation is complete I get prompted for entering the password. Any idea what is...
python fabric prompted for password everytime i execute a sudo command
Below is a small code I've been working on to install packages on the remote server. The code is working fine and the packages are being installed, but once the installation is complete I get prompted for entering the password. Any idea what is causing this? import re import os import sys from datetime import datetime ...
[ "I'm speaking from limited experience, but I believe that since you're \"sudo\" installing py2.6 you need be \"sudo\" to run it, or at least in the right group (is it \"wheel\" or something like that on Ubuntu?).\nI suppose an easy test would be, change this:\n _sudo('apt-get install python2.6')\n version = run(\"p...
[ 1 ]
[]
[]
[ "fabric", "python" ]
stackoverflow_0006556920_fabric_python.txt
Q: pygtk WINDOW_TYPE_HINT_DOCK not working on windows I've been developing a dock-like program for linux, but the problem is that when I wanna run it on windows (xp/vista/7) these properties don't work: self.window.set_type_hint(gtk.gdk.WINDOW_TYPE_HINT_DOCK) and self.window.get_toplevel().show() # must call show() ...
pygtk WINDOW_TYPE_HINT_DOCK not working on windows
I've been developing a dock-like program for linux, but the problem is that when I wanna run it on windows (xp/vista/7) these properties don't work: self.window.set_type_hint(gtk.gdk.WINDOW_TYPE_HINT_DOCK) and self.window.get_toplevel().show() # must call show() before property_change() self.window.get_toplevel().wind...
[ "WINDOW_TYPE_HINT_DOCK is simply not implemented in the Windows port (or rather, implemented to do nothing); you can confirm this in the GDK source. Theoretically—even in X—window managers are not required to do anything with the type hint (see EWMH spec). If you don't want the window decoration, simply remove it u...
[ 1 ]
[]
[]
[ "gdk", "gtk", "pygtk", "python", "windows" ]
stackoverflow_0006557481_gdk_gtk_pygtk_python_windows.txt
Q: looping through list of lists How can I do this: coord + float(y) - float(x) out = [[ coord - float(y) for v in V ] for y in y_coord ] out = [[ coord + float(x) for v in V ] for x in x_coord ] A: out = [[coord + float(y) - float(x) for v in V] for x,y in zip(x_coord, y_coord)]
looping through list of lists
How can I do this: coord + float(y) - float(x) out = [[ coord - float(y) for v in V ] for y in y_coord ] out = [[ coord + float(x) for v in V ] for x in x_coord ]
[ "out = [[coord + float(y) - float(x) for v in V] for x,y in zip(x_coord, y_coord)]\n\n" ]
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0006560053_python.txt
Q: Unable to retrieve multiple tags from feed using feedparser I have the following XML document <?xml version='1.0' encoding='UTF-8'?><entry xmlns='http://www.w3.org/2005/Atom' xmlns:gd='http://schemas.google.com/g/2005' xmlns:issues='http://schemas.google.com/projecthosting/issues/2009' gd:etag='W/"DEAERH47eCl7ImA...
Unable to retrieve multiple tags from feed using feedparser
I have the following XML document <?xml version='1.0' encoding='UTF-8'?><entry xmlns='http://www.w3.org/2005/Atom' xmlns:gd='http://schemas.google.com/g/2005' xmlns:issues='http://schemas.google.com/projecthosting/issues/2009' gd:etag='W/"DEAERH47eCl7ImA9WhZTFEQ."'><id>http://code.google.com/feeds/issues/p/chromium/is...
[ "You could parse the XML with lxml instead:\n>>> import lxml.etree\n>>> doc = lxml.etree.parse(xml)\n>>> ns = {'issues':'http://schemas.google.com/projecthosting/issues/2009'}\n>>> [x.text for x in doc.xpath('//issues:label', namespaces=ns)]\n<<< \n['Type-Bug',\n 'Pri-2',\n 'OS-All',\n 'Area-Compat',\n 'Webkit-spec...
[ 1 ]
[]
[]
[ "atom_feed", "feedparser", "python", "xml" ]
stackoverflow_0006559612_atom_feed_feedparser_python_xml.txt
Q: Can't create a form to upade part of a model field This is really frustrating, I can't and can't find how to create a form (I'm guessing a forms.Form form) to update just one field of a more complex model. The model has 5 fields, and a form to create, update all of them. But in a different case i need to let the u...
Can't create a form to upade part of a model field
This is really frustrating, I can't and can't find how to create a form (I'm guessing a forms.Form form) to update just one field of a more complex model. The model has 5 fields, and a form to create, update all of them. But in a different case i need to let the user update only the title (a field in the model), so i n...
[ "If you're using ModelForms, you just have to define a fields attribute in Meta as a tuple containing just the names of the fields you want. See the documentation.\n" ]
[ 1 ]
[]
[]
[ "django", "django_forms", "django_models", "python" ]
stackoverflow_0006560070_django_django_forms_django_models_python.txt
Q: Can twisted be implemented in Java? I remember reading that the following features lead to the development of interesting frameworks/libraries in Python:- (I read the article from http://www.python.org/workshops/2002-02/papers/09/index.htm) A simple class model, which facilitates inheritance. Dynamic typing, whic...
Can twisted be implemented in Java?
I remember reading that the following features lead to the development of interesting frameworks/libraries in Python:- (I read the article from http://www.python.org/workshops/2002-02/papers/09/index.htm) A simple class model, which facilitates inheritance. Dynamic typing, which means that the code needs to assume les...
[ "Netty is an event-driven networking framework written in Java, so it would most likely be Twisted's equivalent. The features are relatively similar to Twisted, and it seems powerful (I don't have any firsthand experience). It seems like it is still actively maintained. You'd have to look into it yourself to really...
[ 6, 3, 2 ]
[]
[]
[ "asynchronous", "java", "python", "twisted" ]
stackoverflow_0004033271_asynchronous_java_python_twisted.txt
Q: Installing MySQLdb for Python on OSX 10.6 - Error Creating .egg Running Python 2.7 X86 on Snow Leopard. Installed 64 bit MySQL to avoid conflicts between bit versions. However, still have issues installing MySQLdb. After following this and various other online guides I'm still no closer. The output I receive durin...
Installing MySQLdb for Python on OSX 10.6 - Error Creating .egg
Running Python 2.7 X86 on Snow Leopard. Installed 64 bit MySQL to avoid conflicts between bit versions. However, still have issues installing MySQLdb. After following this and various other online guides I'm still no closer. The output I receive during install is: $ ARCHFLAGS='-arch x86_64' python setup.py install runn...
[ "Chances are that at one point you tried running python setup.py under sudo and now have a dist directory belonging to root. Clear out the existing dist subdirectory in your build directory and rerun:\nsudo rm -rf ./dist\nARCHFLAGS='-arch x86_64' python setup.py install\n\nIf you then get permission errors in the ...
[ 0 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0006560167_mysql_python.txt
Q: Python string range (parsing html) In python I have copied a webpage and want to get all occurrences of <a href= I am using urllib2 and my setup is as follows: import urllib2 response = urllib2.urlopen("http://python.org") html = response.read() What would be the best way to approach this task? How would I select...
Python string range (parsing html)
In python I have copied a webpage and want to get all occurrences of <a href= I am using urllib2 and my setup is as follows: import urllib2 response = urllib2.urlopen("http://python.org") html = response.read() What would be the best way to approach this task? How would I select a range of string text from a variable ...
[ "For parsing HTML in Python, I prefer BeautifulSoup. This is assuming you want to find links, and not just the literal <a href=, which you can easily do searching through the string.\n", "This is a job for Beautiful Soup for sure:\n>>> from BeautifulSoup import BeautifulSoup\n>>> import urllib2\n>>> page = urllib...
[ 4, 3, 1, 0, 0 ]
[]
[]
[ "html", "parsing", "python" ]
stackoverflow_0006560299_html_parsing_python.txt
Q: Generate "fuzzy" difference of two files in Python, with approximate comparison of floats I have an issue for comparing two files. Basically, what I want to do is a UNIX-like diff between two files, for example: $ diff -u left-file right-file However my two files contain floats; and because these files were genera...
Generate "fuzzy" difference of two files in Python, with approximate comparison of floats
I have an issue for comparing two files. Basically, what I want to do is a UNIX-like diff between two files, for example: $ diff -u left-file right-file However my two files contain floats; and because these files were generated on distinct architectures (but computing the same things), the floating values are not exac...
[ "In your case we specialize the general case: before we pass things into difflib, we need to detect and separately handle lines containing floats. Here is a basic approach, if you want to generate the deltas, lines of context etc you can build on this. Note it is easier to fuzzy-compare floats as actual floats rath...
[ 4 ]
[]
[]
[ "floating_point", "fuzzy_comparison", "inexact_arithmetic", "python" ]
stackoverflow_0003108274_floating_point_fuzzy_comparison_inexact_arithmetic_python.txt
Q: How to make string matching case insensitiv [text()="sTrInG"] in python (lxml)? I have this xpath pattern: tags = doc.xpath('/html/body//a[text() = "' + name.encode('utf8') + '"]/@href' This returns the url of every -tag with name name as text in it. Is it possible to get a case insensitiv matching of name? Edit ...
How to make string matching case insensitiv [text()="sTrInG"] in python (lxml)?
I have this xpath pattern: tags = doc.xpath('/html/body//a[text() = "' + name.encode('utf8') + '"]/@href' This returns the url of every -tag with name name as text in it. Is it possible to get a case insensitiv matching of name? Edit When trying @Shelhamer solution I get: >>> a_tag_list = html_string.xpath('/html/body...
[ "This can be done by using the lower-case function:\ntags = doc.xpath('/html/body//a[lower-case(text()) = \"' + name.encode('utf8') + '\"]/@href'\n\nA helpful list of functions is here:\nhttp://www.w3schools.com/xpath/xpath_functions.asp\n", "No. XPath is case sensitive. You could try normalising the text, by con...
[ 3, 0 ]
[]
[]
[ "case_insensitive", "python", "string", "xpath" ]
stackoverflow_0006560562_case_insensitive_python_string_xpath.txt
Q: Getting a 'AttributeError at /login/authenticated', 'User' object has no attribute 'backend' I'm using the Python-Oauth2 library found here, Django 1.3. I'll end up using the Twitter library located here. I've searched everything I could on this, but I can't see why I'm getting this error. When someone else asked ...
Getting a 'AttributeError at /login/authenticated', 'User' object has no attribute 'backend'
I'm using the Python-Oauth2 library found here, Django 1.3. I'll end up using the Twitter library located here. I've searched everything I could on this, but I can't see why I'm getting this error. When someone else asked this question, they were told it was because they didn't call for an authenticate(), but I have th...
[ "Actually, the issue was the authenticate call in my authenticate view function was failing due to the password (which is actually the access_token['oauth_token_secret']).\nSo that we're on the same page, I'm talking about the def twitter_authenticated(request): function, that is included in the python-oauth2 githu...
[ 1, 0 ]
[]
[]
[ "django", "python", "twitter_oauth" ]
stackoverflow_0006192747_django_python_twitter_oauth.txt
Q: Dynamically Alter HTML Source I am curious if there might be a way to dynamically alter source from a web page automatically. For instance, I know the firebug plugin for Firefox allows the capability to modify the source and see the reaction in real-time. So, say I want to login to a particular form. Could I alter...
Dynamically Alter HTML Source
I am curious if there might be a way to dynamically alter source from a web page automatically. For instance, I know the firebug plugin for Firefox allows the capability to modify the source and see the reaction in real-time. So, say I want to login to a particular form. Could I alter this dynamic source with a login n...
[ "If you want to login to a website automatically you don't need to edit the source, you need to interact with the webserver. Try curl and use it to submit login details and fetch the resulting web page.\n", "for firefox automation, I recommend chickenfoot to you. It can meet your needs: \n\nalter this dynamic sou...
[ 1, 1, 1, 0 ]
[]
[]
[ "firebug", "html", "python", "web_scraping" ]
stackoverflow_0006560678_firebug_html_python_web_scraping.txt
Q: redirecting shell output using subprocess I have a python script which calls a lot of shell functions. The script can be run interactively from a terminal, in which case I'd like to display output right away, or called by crontab, in which case I'd like to email error output. I wrote a helper function for calling...
redirecting shell output using subprocess
I have a python script which calls a lot of shell functions. The script can be run interactively from a terminal, in which case I'd like to display output right away, or called by crontab, in which case I'd like to email error output. I wrote a helper function for calling shell functions: import subprocess import shle...
[ "1) When you use communicate, you capture the output of the subprocess so nothing is sent to your standard output. The only reason why you see the output when the subprocess is finished is because you print it yourself.\nSince you want to either see it as it runs and not capture it or capture everything and do some...
[ 2 ]
[]
[]
[ "linux", "python", "subprocess" ]
stackoverflow_0006560782_linux_python_subprocess.txt
Q: Install Packages in Python 2.7 in Mac and use that instead of Python 2.6 packages So I just installed Python 2.7 in my Macbook Pro. The problem is I installed virtualenvwrapper, pip, virtualenv and many other packages in Python 2.6 and the binaries are in /usr/local/bin. What I want to do then is install the afore...
Install Packages in Python 2.7 in Mac and use that instead of Python 2.6 packages
So I just installed Python 2.7 in my Macbook Pro. The problem is I installed virtualenvwrapper, pip, virtualenv and many other packages in Python 2.6 and the binaries are in /usr/local/bin. What I want to do then is install the aforementioned packages for Python 2.7 and use them instead of the packages from Python 2.6....
[ "Install them in 2.7.\npython2.7 setup.py install\n\n" ]
[ 3 ]
[]
[]
[ "macos", "python" ]
stackoverflow_0006560823_macos_python.txt
Q: string as array in python I am new learner in python.I need to make the following string as array. ['Soyuz_TMA-16', '2009-09-30'] ['Soyuz_TMA-17', '2009-12-20'] ['Soyuz_TMA-01M', '2010-10-07'] ....... ....... ........ so that I can search in a text file for the string eg.['Soyuz_TMA-16', 2009-09-30'].If match to...
string as array in python
I am new learner in python.I need to make the following string as array. ['Soyuz_TMA-16', '2009-09-30'] ['Soyuz_TMA-17', '2009-12-20'] ['Soyuz_TMA-01M', '2010-10-07'] ....... ....... ........ so that I can search in a text file for the string eg.['Soyuz_TMA-16', 2009-09-30'].If match together in some line eg: abc...
[ "Parse the list of missions and dates into a dict missions, whose keys are the string value of dates: '2009-12-20'.\nThen, you can lookup the dict ('if date in missions: ...').\nYou'll also need to be able to parse the text-form of dates (using regex) into '2009-12-20' form, I wrote a function 'dtuple_to_date()'.\n...
[ 3 ]
[]
[]
[ "arrays", "python", "query_string" ]
stackoverflow_0006525204_arrays_python_query_string.txt
Q: Caching get_serving_url() URL Can I cache the url returned from get_serving_url()? How long until the url expire? I plan to add caching support to my application to reduce load. Thank you very much for your response :) A: Yes, you can cache it, as long as you keep a separate cache for each different size and cro...
Caching get_serving_url() URL
Can I cache the url returned from get_serving_url()? How long until the url expire? I plan to add caching support to my application to reduce load. Thank you very much for your response :)
[ "Yes, you can cache it, as long as you keep a separate cache for each different size and crop value. The URL will only expire if you delete the Blob (although it may take up to 24 hours to effectively be deleted).\nSource: here (see response by Ikai L)\n" ]
[ 5 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0006560125_google_app_engine_python.txt
Q: How to use introspection in Python 2.7 to find instances of certain class in a module? I have a Python module that defines a classes and instantiates a number of instances of that classes. I would like to write a test that the correct number have been instantiated. bar = Foo('abc') baz = Foo('def') ... quz = Foo(...
How to use introspection in Python 2.7 to find instances of certain class in a module?
I have a Python module that defines a classes and instantiates a number of instances of that classes. I would like to write a test that the correct number have been instantiated. bar = Foo('abc') baz = Foo('def') ... quz = Foo('xyz') Then in testing I have tried things like: assert num = len([ x for x in dir(foo) if ...
[ "You're really close. Use a double equals sign for comparison, and you need to use getattr() to retrieve the module member by name:\nassert num == len([getattr(foo, x) \n for x in dir(foo) \n if isinstance(getattr(foo, x), foo.Foo)])\n\nMight also be helpful to read the documenta...
[ 2 ]
[]
[]
[ "introspection", "python" ]
stackoverflow_0006561190_introspection_python.txt
Q: Nested list to string I have a list of instances of class Test. This class have method like name and parent [Test('a', ''), Test('b', ''), Test('c', 'a'), Test('d', 'a'), Test('e', 'c')] First argument is name, second parent. Parent arg is simply a arg name of parent class. I want convert this list to string like...
Nested list to string
I have a list of instances of class Test. This class have method like name and parent [Test('a', ''), Test('b', ''), Test('c', 'a'), Test('d', 'a'), Test('e', 'c')] First argument is name, second parent. Parent arg is simply a arg name of parent class. I want convert this list to string like: Test('a', '') |-- Test(...
[ "Here is code that works as is. Basically convert the array into a tree and then use recursive DFS to print it (you can use iterative DFS if you want):\nclass Test:\n def __init__(self, name, parent):\n self.name = name\n self.parent = parent\n def __repr__(self):\n return \"Test('\"+self...
[ 2, 0, 0 ]
[]
[]
[ "arrays", "nested", "python" ]
stackoverflow_0006561081_arrays_nested_python.txt
Q: Python CGI: Translate from stdout to html (e.g. replace \n with ) I have a great command line program that prints to stdout. I want to let people run this through CGI. In the CGI version, I want to have the same output (with "<BR>" instead of "\n"). My cgi_main works by calling my real_main; there are a lot of opt...
Python CGI: Translate from stdout to html (e.g. replace \n with )
I have a great command line program that prints to stdout. I want to let people run this through CGI. In the CGI version, I want to have the same output (with "<BR>" instead of "\n"). My cgi_main works by calling my real_main; there are a lot of options to process and it was bad design to do that multiple times. But si...
[ "At the start of your CGI script, put print \"Content-type: text/plain\\r\\n\\r\\n\". The result will show up on a webpage the same as on a console.\nIn general, if I want to have two variations on a program, one that formats output in HTML and the other that outputs plain text, I abstract as much of the logic as I...
[ 2 ]
[]
[]
[ "cgi", "python" ]
stackoverflow_0006561228_cgi_python.txt
Q: URL parsing error [BeautifulSoup] I'm trying to get a list of href links from website pages; however my code is not working properly. The code is appending when it shouldn't be to the urlList. It is also duplicating href links. import urllib2 from BeautifulSoup import BeautifulSoup response = urllib2.urlopen("htt...
URL parsing error [BeautifulSoup]
I'm trying to get a list of href links from website pages; however my code is not working properly. The code is appending when it shouldn't be to the urlList. It is also duplicating href links. import urllib2 from BeautifulSoup import BeautifulSoup response = urllib2.urlopen("http://www.gamefaqs.com") html = response....
[ "list comprehension FTW:\n[link['href'] for link in soup.findAll('a') \n if not any(bad in link['href'] for bad in doNotProcessList)]\n\nAnd, for readability...\ndef condition(x):\n return not any((bad in x) for bad in doNotProcessList)\n\n[link['href'] for link in soup.findAll('a') if condition(link['href'])]\n...
[ 2 ]
[]
[]
[ "beautifulsoup", "duplicates", "python" ]
stackoverflow_0006561252_beautifulsoup_duplicates_python.txt
Q: parse and answer questions Lets say I have a question named Q1 with 4 radio answers: Q1: a) b) c) d) In python, how would you go about finding the question and then selecting one of four of the answers, then submitting the webpage? A: You might want to automate the browser, refer to this A: Twill would work w...
parse and answer questions
Lets say I have a question named Q1 with 4 radio answers: Q1: a) b) c) d) In python, how would you go about finding the question and then selecting one of four of the answers, then submitting the webpage?
[ "You might want to automate the browser, refer to this\n", "Twill would work well in this situation. Here are some examples to get you started :\nhttp://twill.idyll.org/examples.html\nYou may or may not want to use twill in tandem with Beautiful Soup\n" ]
[ 0, 0 ]
[]
[]
[ "automation", "html", "parsing", "python" ]
stackoverflow_0006561170_automation_html_parsing_python.txt
Q: html to text conversion using python language import urllib2 from BeautifulSoup import * resp = urllib2.urlopen("file:///D:/sample.html") rawhtml = resp.read() resp.close() print rawhtml I am using this code to get text from a html document, but it also gives me html code. What should i do to fetch only text ...
html to text conversion using python language
import urllib2 from BeautifulSoup import * resp = urllib2.urlopen("file:///D:/sample.html") rawhtml = resp.read() resp.close() print rawhtml I am using this code to get text from a html document, but it also gives me html code. What should i do to fetch only text from the html document?
[ "Note that your example makes no use of Beautifulsoup.\nSee the doc, and follow examples.\nThe following example, taken from the link above, searches the soup for <td> elements.\nimport urllib2\nfrom BeautifulSoup import BeautifulSoup\n\npage = urllib2.urlopen(\"http://www.icc-ccs.org/prc/piracyreport.php\")\nsoup ...
[ 4, 3, 1, 1, 0 ]
[]
[]
[ "html", "python", "text" ]
stackoverflow_0003593784_html_python_text.txt
Q: How to get the dictionary with the highest value in a list of dicts I have a list of dictionaries. Is it possible to get the dictionary or its index that has the highest score key value? Here is the list: lst = [{'name': 'tom', 'score': 5}, {'name': 'jerry', 'score': 10}, {'name': 'jason', 'score...
How to get the dictionary with the highest value in a list of dicts
I have a list of dictionaries. Is it possible to get the dictionary or its index that has the highest score key value? Here is the list: lst = [{'name': 'tom', 'score': 5}, {'name': 'jerry', 'score': 10}, {'name': 'jason', 'score': 8}] It should return: {'name': 'jerry', 'score': 10}
[ "An alternative to using a lambda for the key argument to max, is operator.itemgetter:\nfrom operator import itemgetter\nmax(lst, key=itemgetter('score'))\n\n", "The built-in function, max() takes an optional key function, which can be supplied in the form of a lambda:\n>>> max(lst, key=lambda x:x['score'])\n{'sc...
[ 9, 8, 3, 2 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0006561653_dictionary_list_python.txt
Q: Skipping data in a binary file in Python I'm writing a file reader for my (binary) format and I sometimes need to skip some portion of the file. I could do fileobject.read(howmuchtoskip) for that, but I guess that will load the unneeded part to memory and will be slow. Can I just set the "index" of the "pointer"...
Skipping data in a binary file in Python
I'm writing a file reader for my (binary) format and I sometimes need to skip some portion of the file. I could do fileobject.read(howmuchtoskip) for that, but I guess that will load the unneeded part to memory and will be slow. Can I just set the "index" of the "pointer" or whatever that's called?
[ "Use fileobject.seek(offset).\n" ]
[ 7 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0006561896_file_io_python.txt
Q: how to 'clean' all the entries in a feedparser feed I backed up my blog in Google's XML format. It's quite long. So far, I have done this: >>> import feedparser >>> blogxml = feedparser.parse('blog.xml') >>> type(blogxml) <class 'feedparser.FeedParserDict'> In the book I'm reading, the author does this: >>> impor...
how to 'clean' all the entries in a feedparser feed
I backed up my blog in Google's XML format. It's quite long. So far, I have done this: >>> import feedparser >>> blogxml = feedparser.parse('blog.xml') >>> type(blogxml) <class 'feedparser.FeedParserDict'> In the book I'm reading, the author does this: >>> import feedparser >>> llog = feedparser.parse("http://language...
[ "import feedparser\nllog = feedparser.parse(\"http://languagelog.ldc.upenn.edu/nll/?feed=atom\")\n\nwith open('myblog.txt', 'w') as outfile:\n for entry in llog.entries:\n ## Do your processing here\n content = entry.content[0].value\n clean_content = nltk.word_tokenize(nltk.html_clean(conte...
[ 1 ]
[]
[]
[ "feedparser", "python" ]
stackoverflow_0006525783_feedparser_python.txt
Q: Linux libnetfilter_queue delayed packet problem I have to filter and modify network traffic using Linux kernel libnetfilter_queue (precisely the python binding) and dpkt, and i'm trying to implement delayed packet forward. Normal filtering works really well, but if i try to delay packets with function like this de...
Linux libnetfilter_queue delayed packet problem
I have to filter and modify network traffic using Linux kernel libnetfilter_queue (precisely the python binding) and dpkt, and i'm trying to implement delayed packet forward. Normal filtering works really well, but if i try to delay packets with function like this def setVerdict(pkt, nf_payload): nf_payload.set_ver...
[ "Sorry for the late reply, but I needed to do something like this, although slightly more complicated. I used the C-version of the library and I copied packets to a buffer inside my program, and then issued a DROP verdict. After a timeout relating to your delay, I reinject the packet using a raw socket. This works ...
[ 3, 0 ]
[]
[]
[ "linux", "netfilter", "networking", "python" ]
stackoverflow_0006237536_linux_netfilter_networking_python.txt
Q: list with xyz values to dictionary I have a list: list = [ '1', '1,'1', '-1','1','-1' ] and need to convert it to a dictionary of dictionaries. The first three values in are x y z and the second set three values are x y z. The result should be: d = { 0:{x:1,y:1,z:1}, 1:{x:-1,y:1,z:-1}} My attempt: mylist=[1,1,1...
list with xyz values to dictionary
I have a list: list = [ '1', '1,'1', '-1','1','-1' ] and need to convert it to a dictionary of dictionaries. The first three values in are x y z and the second set three values are x y z. The result should be: d = { 0:{x:1,y:1,z:1}, 1:{x:-1,y:1,z:-1}} My attempt: mylist=[1,1,1,-1,1,-1] count = 1 keycount = 0 l = {'x...
[ "A bit complicated one:\nl = [ '1', '1', '1', '-1', '1', '-1' ]\n\ndicts = [dict(zip(['x', 'y', 'z'], l[i:i+3])) for i in range(0, len(l), 3)]\nresult = dict(enumerate(dicts))\n\nprint result #prints {0: {'y': '1', 'x': '1', 'z': '1'}, 1: {'y': '1', 'x': '-1', 'z': '-1'}}\n\n", "Dictionary items are unordered.\nH...
[ 3, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006556260_python.txt
Q: Are accessors in Python ever justified? I realize that in most cases, it's preferred in Python to just access attributes directly, since there's no real concept of encapsulation like there is in Java and the like. However, I'm wondering if there aren't any exceptions, particularly with abstract classes that have d...
Are accessors in Python ever justified?
I realize that in most cases, it's preferred in Python to just access attributes directly, since there's no real concept of encapsulation like there is in Java and the like. However, I'm wondering if there aren't any exceptions, particularly with abstract classes that have disparate implementations. Let's say I'm writi...
[ "\nNote: I've considered properties, but I don't think they're a cleaner solution.\n\nBut they are. By using properties, you'll have the class signature you want, while being able to use the property as an attribute itself.\ndef _get_id(self):\n return self._id\n\ndef _set_id(self, newid):\n self._id = newid\n\...
[ 8, 4, 1, 1, 0 ]
[]
[]
[ "abstract_class", "attributes", "inheritance", "interface", "python" ]
stackoverflow_0003292631_abstract_class_attributes_inheritance_interface_python.txt
Q: Variable with name `None` I need to have a variable with name None: class QAbstractPrintDialog(QDialog): None = int() # QAbstractPrintDialog.PrintDialogOption enum PrintToFile = int() # QAbstractPrintDialog.PrintDialogOption enum PrintSelection = int() # QAbstractPrintDialog.PrintDialogOption enum ...
Variable with name `None`
I need to have a variable with name None: class QAbstractPrintDialog(QDialog): None = int() # QAbstractPrintDialog.PrintDialogOption enum PrintToFile = int() # QAbstractPrintDialog.PrintDialogOption enum PrintSelection = int() # QAbstractPrintDialog.PrintDialogOption enum ... But: syntax error: cannot...
[ "In python None is a reserved word and cannot be used as a variable name.\nQuoting python documentation:\n\nChanged in version 2.4: Assignments to None are illegal and raise a SyntaxError.\n\n", "You cannot. None is a Python built-in constant. \nTo do what you are makes no more sense than:\nclass = struct\n\n\n\"...
[ 9, 4, 3, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006561507_python.txt
Q: Python: Exceeding max recursion depth while calling superclass method from subclass I've got an inheritance chain of three classes: Baz inherits from Bar inherits from Foo. I'd like to define a method in the Foo class that, when called in a subclass, returns the output of its parent class appended with stuff of it...
Python: Exceeding max recursion depth while calling superclass method from subclass
I've got an inheritance chain of three classes: Baz inherits from Bar inherits from Foo. I'd like to define a method in the Foo class that, when called in a subclass, returns the output of its parent class appended with stuff of its own. This is the desired output: >>> foo = Foo() >>> bar = Bar() >>> baz = Baz() >>> pr...
[ "The problem is here:\n return super(self.__class__, self)...\n\nself.__class__ always refers to the current concrete class. So in Bar, it refers to Bar, and in Baz, it refers to Baz. So, Bar calls the superclass's method, but the self.__class__ still refers to Bar, not Foo. So you will get an endless recursion.\nT...
[ 8 ]
[]
[]
[ "exception", "inheritance", "python", "recursion" ]
stackoverflow_0006562507_exception_inheritance_python_recursion.txt
Q: Metaclasses in Python: a couple of questions to clarify After crashing with metaclasses i delved into the topic of metaprogramming in Python and I have a couple of questions that are, imho, not clearly anwered in available docs. When using both __new__ and __init__ in a metaclass, their arguments must be defined ...
Metaclasses in Python: a couple of questions to clarify
After crashing with metaclasses i delved into the topic of metaprogramming in Python and I have a couple of questions that are, imho, not clearly anwered in available docs. When using both __new__ and __init__ in a metaclass, their arguments must be defined the same? What's most efficient way to define class __init__ ...
[ "\nWhen using both __new__ and __init__\nin a metaclass, their arguments must\nbe defined the same?\nI think Alex Martelli explains\nit most succinctly:\nclass Name(Base1,Base2): <<body>>\n __metaclass__==suitable_metaclass\n\nmeans\nName = suitable_metaclass('Name', (Base1,Base2), <<dict-built-by-body>>)\n\nSo ...
[ 2, 1 ]
[]
[]
[ "metaclass", "metaprogramming", "python" ]
stackoverflow_0006562538_metaclass_metaprogramming_python.txt
Q: Python paths/import in standalone programs I'm writing a package that is a small application. It is distributed with portable Python, so code has no access to Windows settings. The program has this structure: mypr __init__.py gui __init.__.py prlib __init__.py I am trying to do this fr...
Python paths/import in standalone programs
I'm writing a package that is a small application. It is distributed with portable Python, so code has no access to Windows settings. The program has this structure: mypr __init__.py gui __init.__.py prlib __init__.py I am trying to do this from mypr.gui import Gui in prlib but, of course, ...
[ "If you just want to be able to access the 'gui' module in the directory above 'prlib' you can achieve that by:\nimport os\nimport sys\nsys.path.append(os.path.join(os.dirname(__file__), '../'))\n\nThen you should be able to import 'gui' via:\nfrom gui import Gui\n\n" ]
[ 2 ]
[]
[]
[ "import", "path", "python" ]
stackoverflow_0006562483_import_path_python.txt
Q: Threading HTTP requests (with proxies) I've looked at similar questions, but there always seems to be a whole lot of disagreement over the best way to handle threading with HTTP. What I specifically want to do: I'm using Python 2.7, and I want to try and thread HTTP requests (specifically, POSTing something), with...
Threading HTTP requests (with proxies)
I've looked at similar questions, but there always seems to be a whole lot of disagreement over the best way to handle threading with HTTP. What I specifically want to do: I'm using Python 2.7, and I want to try and thread HTTP requests (specifically, POSTing something), with a SOCKS5 proxy for each. The code I have al...
[ "Perhaps an easier way would be to just rely on gevent (or eventlet) to let you open lots of connections to the server. These libs monkeypatch urllib to make then async, whilst still letting you write code that is sync-ish. Their smaller overhead vs threads also means you can spawn lots more (1000s would not be unu...
[ 3 ]
[]
[]
[ "python", "twisted", "urllib2" ]
stackoverflow_0006545849_python_twisted_urllib2.txt
Q: Google API for Python I want to exploit Google services like Gmail, maps, search, buzz from Python on the client side. Anyone who has any experience working with any Library / Toolkit, please suggest me some A: What about Google's very own libary? This is the list of supported API's. As for e-mail, I would stick...
Google API for Python
I want to exploit Google services like Gmail, maps, search, buzz from Python on the client side. Anyone who has any experience working with any Library / Toolkit, please suggest me some
[ "What about Google's very own libary?\nThis is the list of supported API's. As for e-mail, I would stick with POP3 / IMAP / SMTP...\n" ]
[ 8 ]
[]
[]
[ "gmail", "google_api", "python" ]
stackoverflow_0006563311_gmail_google_api_python.txt
Q: reading binary data from a socket in python When I run the following python example code, tick = 0 while True: tick += 1 print tick data = s.recv(1024) if (tick == 1) and data: print 'from client: %s' %(data) elif (tick == 2) and data: print 'from client: %s' %(data) I see, 1 f...
reading binary data from a socket in python
When I run the following python example code, tick = 0 while True: tick += 1 print tick data = s.recv(1024) if (tick == 1) and data: print 'from client: %s' %(data) elif (tick == 2) and data: print 'from client: %s' %(data) I see, 1 from client: client msg 2 from client: ? 3 My int...
[ "elif (tick == 2) and data:\n print 'from client: %r' % data # (note 1)\n print struct.unpack(\"!B\", data[0]) # (note 2)\n\n\nPrint the representation like Ignacio suggested.\nYou want to unpak one byte, so give struct.unpack one byte.\n\n", "You can view a raw representation of an object by callin...
[ 5, 2, 0 ]
[]
[]
[ "binary", "parsing", "python", "sockets" ]
stackoverflow_0006560302_binary_parsing_python_sockets.txt
Q: Python - How do I make a dictionary inside of a text file? I'm writing a program that allows the user to create a username and password. How do I write this as a dictionary into a text file, and then retrieve it when I need it? Also, if there is an easier way to do this I'm welcome to any new ideas. A: Use Pytho...
Python - How do I make a dictionary inside of a text file?
I'm writing a program that allows the user to create a username and password. How do I write this as a dictionary into a text file, and then retrieve it when I need it? Also, if there is an easier way to do this I'm welcome to any new ideas.
[ "Use Python serialization mechanism - pickle.\nSmall example:\n>>> import pickle\n>>> s = pickle.dumps({'username': 'admin', 'password': '123'})\n>>> s\n\"(dp0\\nS'username'\\np1\\nS'admin'\\np2\\nsS'password'\\np3\\nS'123'\\np4\\ns.\"\n\nNow you can easily save content of s to some file. After that you can read i...
[ 7, 6, 2, 1 ]
[]
[]
[ "dictionary", "file", "python" ]
stackoverflow_0006563352_dictionary_file_python.txt
Q: Create multidimensional list in python through two other lists I have two lists and I want to create a new one. For instance a = ["Street zero", "Street one", "Street two"] b = [0,1,2] newlist [0][0] = "Street zero" newlist [1][1] = "Street one" newlist [2][2] = "Street two" How can I achieve this ? Thanks A: ...
Create multidimensional list in python through two other lists
I have two lists and I want to create a new one. For instance a = ["Street zero", "Street one", "Street two"] b = [0,1,2] newlist [0][0] = "Street zero" newlist [1][1] = "Street one" newlist [2][2] = "Street two" How can I achieve this ? Thanks
[ "Do you mean enumerate?\n>>> list(enumerate(a))\n[(0, 'Street zero'), (1, 'Street one'), (2, 'Street two')]\n\nOr zip:\n>>> zip(b, a)\n[(0, 'Street zero'), (1, 'Street one'), (2, 'Street two')]\n\n(that uses items from b as indexes)\n" ]
[ 4 ]
[]
[]
[ "list", "python" ]
stackoverflow_0006563432_list_python.txt
Q: 'classobj' object is not subscriptable I get the following error while calling a class-method using self.methodname() from inside another class method. TypeError: 'classobj' object is not subscriptable What could the problem be? Other methods are running fine except this one. code details are class loadbalancer:...
'classobj' object is not subscriptable
I get the following error while calling a class-method using self.methodname() from inside another class method. TypeError: 'classobj' object is not subscriptable What could the problem be? Other methods are running fine except this one. code details are class loadbalancer: def __init__(self): #somecode ...
[ "You probably have something like:\nbalancer = loadbalancer\nbalancer.create_loadbalancer(...)\n\nUnlike C++, you need the parentheses when creating an object even if __init__ takes no arguments:\nbalancer = loadbalancer()\nbalancer.create_loadbalancer(...)\n\nIn the former case, balancer is the class object, not a...
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0006563448_python.txt
Q: problem scraping with BeautifulSoup I am trying to scrape the url http://www.kat.ph/search/beatles/?categories[]=music using BeautifulSoup torrents = bs.findAll('tr',id = re.compile('torrent_*')) torrents gets all the torrents on that page ,now every element of torrents contains a tr element. My problem is that ...
problem scraping with BeautifulSoup
I am trying to scrape the url http://www.kat.ph/search/beatles/?categories[]=music using BeautifulSoup torrents = bs.findAll('tr',id = re.compile('torrent_*')) torrents gets all the torrents on that page ,now every element of torrents contains a tr element. My problem is that len(torrents[0].td) is 5 but i am not abl...
[ "I'd recommend using lxml or instead of BeautifulSoup, among other great features you can use xpath to grab your links:\nimport lxml.html\ndoc = lxml.html.parse('http://www.kat.ph/search/beatles/?categories[]=music')\nlinks = doc.xpath('//a[contains(@class,\"idownload\")]/@href')\n\n" ]
[ 2 ]
[]
[]
[ "beautifulsoup", "python", "web_scripting" ]
stackoverflow_0006563235_beautifulsoup_python_web_scripting.txt
Q: Python: how do I merge lists to create a nested list Possible Duplicate: Python - merge items of two lists into a list of tuples How do I merge two lists in a nested way? Eg: list1 = a,b,c list2 = d,e,f I want the output to be: [[a,d][b,e][c,f]] A: Just zip them: >>> l1 = ['a', 'b', 'c'] >>> l2 = ['d', 'e',...
Python: how do I merge lists to create a nested list
Possible Duplicate: Python - merge items of two lists into a list of tuples How do I merge two lists in a nested way? Eg: list1 = a,b,c list2 = d,e,f I want the output to be: [[a,d][b,e][c,f]]
[ "Just zip them:\n>>> l1 = ['a', 'b', 'c']\n>>> l2 = ['d', 'e', 'f']\n>>> zip(l1, l2)\n[('a', 'd'), ('b', 'e'), ('c', 'f')]\n\nIf you need lists, not tuples, in the result:\n>>> [list(l) for l in zip(l1, l2)]\n[['a', 'd'], ['b', 'e'], ['c', 'f']]\n\n", "Direct copy and paste from book:\nThe zip function\nSometimes...
[ 16, 5 ]
[]
[]
[ "list", "python" ]
stackoverflow_0006563711_list_python.txt
Q: What are the parameters create_constraint and name for, in Boolean type in sqlalchemy (python)? In the documentation of sqlalchemy I read: class sqlalchemy.types.Boolean(create_constraint=True, name=None) A bool datatype. Boolean typically uses BOOLEAN or SMALLINT on the DDL side, and on the Python side deals...
What are the parameters create_constraint and name for, in Boolean type in sqlalchemy (python)?
In the documentation of sqlalchemy I read: class sqlalchemy.types.Boolean(create_constraint=True, name=None) A bool datatype. Boolean typically uses BOOLEAN or SMALLINT on the DDL side, and on the Python side deals in True or False. Parameters: create_constraint – defaults to True. If the boolean is genera...
[ "\nquery_status = Column(Boolean, default = False) # Hope the syntax for default value is correct.\n\nyep\n\ncreate_constraint = If the boolean is generated as an int/smallint, also create a CHECK constraint on the table that ensures 1 or 0 as a value\n\nit deals on the database level (DDL). It creates a check cons...
[ 5 ]
[]
[]
[ "boolean", "parameters", "python", "sqlalchemy" ]
stackoverflow_0006563649_boolean_parameters_python_sqlalchemy.txt
Q: desperately simple python decimal Hi I need some help please. I want to calculate float numbers with a format like xxxxx.yyyyyyyyyyyyyyy. I have learned that I should use Decimal instead of float I tried a lot, and I searched a lot but I still have the following simple problem: getcontext().prec = 14 a = D...
desperately simple python decimal
Hi I need some help please. I want to calculate float numbers with a format like xxxxx.yyyyyyyyyyyyyyy. I have learned that I should use Decimal instead of float I tried a lot, and I searched a lot but I still have the following simple problem: getcontext().prec = 14 a = Decimal(str('12.737791301')) b = Dec...
[ "The real solution is format(), available in python 2.6 and 3.1.\nformat(c,\"f\") will convert the decimal to float repr-style output. This is part of the new style formatting in python.\nOther worse ideas for solutions are below: \nThis can be accomplished with a format string, as if your Decimal values were float...
[ 5, 0 ]
[]
[]
[ "decimal", "python" ]
stackoverflow_0006563620_decimal_python.txt
Q: Python 3.2 script to connect to local MySQL database I am running an Ubuntu Server. I would like for it to have a Python (v3.2) CGI script that would connect, and run a query, to the local MySQL database I have set up. Currently, the only things I found don't support Python 3.2. Please do not suggest switching to ...
Python 3.2 script to connect to local MySQL database
I am running an Ubuntu Server. I would like for it to have a Python (v3.2) CGI script that would connect, and run a query, to the local MySQL database I have set up. Currently, the only things I found don't support Python 3.2. Please do not suggest switching to an earlier version of Python, because that is not an optio...
[ "Take a look at this previous question: MySQL-db lib for Python 3.x?\nSeems that a python 3 option is available.\n" ]
[ 0 ]
[]
[]
[ "mysql", "python", "ubuntu" ]
stackoverflow_0006563441_mysql_python_ubuntu.txt
Q: using wsgiref.simple_server in unittests I have some functions like this one: URL = 'http://localhost:8080' def func(): response = urlopen(URL) return process(response) And i want to test it with unittest. I did something like this: from wsgiref.simple_server import make_server def app_200_hello(environ...
using wsgiref.simple_server in unittests
I have some functions like this one: URL = 'http://localhost:8080' def func(): response = urlopen(URL) return process(response) And i want to test it with unittest. I did something like this: from wsgiref.simple_server import make_server def app_200_hello(environ,start_response): stdout = StringIO('Hel...
[ "If you are testing a WSGI application, I can strongly recommend werkzeug.test which gets around these issues by testing the application itself without a server:\nfrom werkzeug.test import Client\n\n# then in your test case\ndef test1(self):\n client = Client(app_200_hello)\n appiter, status, headers = client...
[ 7, 5, 4, 2, 0 ]
[]
[]
[ "python", "unit_testing", "wsgiref" ]
stackoverflow_0000634485_python_unit_testing_wsgiref.txt
Q: Bcc Field in SMTP [ showing/not showing ] problem I'm trying to use python's smtplib to send, via gmail, an email with bcc addresses. I use this code: #imports etc... fromAddr = sender@origin.com to = [ recpt1@destinationTo.com ] cc = [ recpt2@destinationCc.com ] bcc = [ recpt3@destinationBcc.com, recpt4@destinati...
Bcc Field in SMTP [ showing/not showing ] problem
I'm trying to use python's smtplib to send, via gmail, an email with bcc addresses. I use this code: #imports etc... fromAddr = sender@origin.com to = [ recpt1@destinationTo.com ] cc = [ recpt2@destinationCc.com ] bcc = [ recpt3@destinationBcc.com, recpt4@destinationBcc.com ] server = SMTP( "smtp.gmail.com", 587) #star...
[ "My guess would be that gmail does a separate SMTP session for each BCC recipient. If everything between your two comments were a function dosend(fromAddr, toAddr, content, to, cc, bcc=None) you might do something like this:\ndosend(fromAddr, to+cc, content, to, cc)\nfor t in bcc:\n dosend(fromAddr, t, content,...
[ 1 ]
[]
[]
[ "bcc", "gmail", "python", "smtp" ]
stackoverflow_0006564450_bcc_gmail_python_smtp.txt
Q: How to express a context free design grammar as an internal DSL in Python? [Note: Rereading this before submitting, I realized this Q has become a bit of an epic. Thank you for indulging my long explanation of the reasoning behind this pursuit. I feel that, were I in a position to help another undertaking a simila...
How to express a context free design grammar as an internal DSL in Python?
[Note: Rereading this before submitting, I realized this Q has become a bit of an epic. Thank you for indulging my long explanation of the reasoning behind this pursuit. I feel that, were I in a position to help another undertaking a similar project, I would be more likely to get on board if I knew the motivation behin...
[ "Writing a parser for a context free grammar is hard. You're probably better off using some sort of library to make things easier on yourself.\nI would check out the PyParsing module. The download comes with a number of examples, one of which is a simple SQL parser, which might be enlightening to look at, at least ...
[ 4, 3 ]
[]
[]
[ "blender", "context_free_grammar", "dsl", "python" ]
stackoverflow_0006552380_blender_context_free_grammar_dsl_python.txt
Q: Python readlines not separating lines I have a xml file from a page which shows correctly on the text editor but once I use readlines(), I only get one line. I assume this means the line separator being used isn't recognized by python but it is by gedit. I want to do a split() on it to get the data correctly but h...
Python readlines not separating lines
I have a xml file from a page which shows correctly on the text editor but once I use readlines(), I only get one line. I assume this means the line separator being used isn't recognized by python but it is by gedit. I want to do a split() on it to get the data correctly but how can I see what line separator is being u...
[ "As is pointed out in the comments, if it's xml, just hand it to an XML parser like ElementTree or lxml. Newlines shouldn't matter in XML.\nFor information, using open(\"thefile.xml\", \"rU\") will open it with universal newline support, so Python will recognise \\n, \\r or \\r\\n as newline markers.\n" ]
[ 0 ]
[]
[]
[ "io", "python" ]
stackoverflow_0006564660_io_python.txt
Q: JSON string decoding error I am calling the URL : http://code.google.com/feeds/issues/p/chromium/issues/full/291?alt=json using urllib2 and decoding using the json module url = "http://code.google.com/feeds/issues/p/chromium/issues/full/291?alt=json" request = urllib2.Request(query) response = urllib2.urlopen(re...
JSON string decoding error
I am calling the URL : http://code.google.com/feeds/issues/p/chromium/issues/full/291?alt=json using urllib2 and decoding using the json module url = "http://code.google.com/feeds/issues/p/chromium/issues/full/291?alt=json" request = urllib2.Request(query) response = urllib2.urlopen(request) issue_report = json.loads...
[ "The feed has raw data from a JPEG in it at that point; the JSON is malformed, so it's not your fault. Report a bug to Google.\n", "You could consider using lxml instead, since the JSON is malformed. It's XPath support makes working with XML pretty straight-forward:\nimport lxml.etree\nurl = 'http://code.google.c...
[ 4, 2 ]
[]
[]
[ "json", "python", "urllib2" ]
stackoverflow_0006564474_json_python_urllib2.txt
Q: Python: Creating a Single Integer From Two Integers? I'm searching for a simple algorithm that 'combines' two 2bytes integers into one unique 4bytes integer. The two 2bytes integers are both whole positive numbers in the range 0..65535. I want to create one 4bytes integer that is the exact combination of both, in ...
Python: Creating a Single Integer From Two Integers?
I'm searching for a simple algorithm that 'combines' two 2bytes integers into one unique 4bytes integer. The two 2bytes integers are both whole positive numbers in the range 0..65535. I want to create one 4bytes integer that is the exact combination of both, in a way that will make it easy to: (1) given the two 2bytes ...
[ "How about:\ndef combine(n, m):\n return (n << 16) | m\n\ndef extract(c):\n return (c >> 16), c & 0xffff\n\nThis solution places one of the 2-byte integers in the upper half of a 32-bit word, and the other into the lower half. In order to extract the values, simply take the upper half of the word (c >> 16), a...
[ 16, 8 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0006564723_algorithm_python.txt
Q: How to solve No operation available for request in SUDS? first I imported SUDS client and logging from suds.client import Client as SudsClient import logger logging.basicConfig(level=logging.INFO) logging.getLogger('suds.client').setLevel(logging.DEBUG) I was provided with two wsdl files, an enterprise.wsdl and ...
How to solve No operation available for request in SUDS?
first I imported SUDS client and logging from suds.client import Client as SudsClient import logger logging.basicConfig(level=logging.INFO) logging.getLogger('suds.client').setLevel(logging.DEBUG) I was provided with two wsdl files, an enterprise.wsdl and ProgrammerClientHandler.wsdl.xml. i used enterprise.wsdl to lo...
[ "The serverUrl returned by login is for the enterprise API, but you're not using that, you shouldn't change the endpoint URL of your programmerclienthandler_client stub, its already correct.\n" ]
[ 1 ]
[]
[]
[ "python", "salesforce", "suds" ]
stackoverflow_0006562750_python_salesforce_suds.txt
Q: Date conversion in python I have some data in a text file in the following format: 50 Cent 1975-07-06 75 Cents 1933-01-29 9th Wonder 1975-01-15 A Fine Frenzy 1984-12-23 I want to convert it as like: 50 Cent July 6, 1975 75 Cents January 29, 1933 9th Wonder January 15, 1975 A Fine Frenzy Decem...
Date conversion in python
I have some data in a text file in the following format: 50 Cent 1975-07-06 75 Cents 1933-01-29 9th Wonder 1975-01-15 A Fine Frenzy 1984-12-23 I want to convert it as like: 50 Cent July 6, 1975 75 Cents January 29, 1933 9th Wonder January 15, 1975 A Fine Frenzy December 23, 1984 Could any of you ...
[ "import time\n\ntext = \"\"\"50 Cent 1975-07-06\n75 Cents 1933-01-29\n9th Wonder 1975-01-15\nA Fine Frenzy 1984-12-23\"\"\"\n\nfor line in text.splitlines():\n dob = line.rsplit(None, 1)[-1]\n dob_new = time.strftime('%B %d, %Y', time.strptime(dob, '%Y-%m-%d'))\n\n print line.replace(dob, dob_new...
[ 3, 3, 1 ]
[]
[]
[ "date", "python" ]
stackoverflow_0006565005_date_python.txt
Q: Implement Api to storing credential of facebook/twitter or something else I'm writing an internal API for mobile device like iPhone or Android. I want with these device, that the users can connect with the app only via Facebook Connect or Twitter Connect. I don't know iOS but i want to prepare the code in the back...
Implement Api to storing credential of facebook/twitter or something else
I'm writing an internal API for mobile device like iPhone or Android. I want with these device, that the users can connect with the app only via Facebook Connect or Twitter Connect. I don't know iOS but i want to prepare the code in the backend. How Must i prepare the code? I'm using Python/Django and Tastypie for the ...
[ "The best way is, After the user authenticates using any of the social networks on the device, Get the name,email,deviceid and any other relevant details, and store those details on the server like a normal registration.[i.e maintain your own user id rather than fb_id or twitter_id]\nIf there is a requirement to ...
[ 1 ]
[]
[]
[ "api", "django", "iphone", "python" ]
stackoverflow_0006565008_api_django_iphone_python.txt
Q: elif statement returning the "lost" result each time incorrectly. (homework) I have updated my code with the changes made. I am still getting incorrect results... # Import statements import random # Define main function that will ask for input, generate computer choice, # determine winner and show output when ...
elif statement returning the "lost" result each time incorrectly. (homework)
I have updated my code with the changes made. I am still getting incorrect results... # Import statements import random # Define main function that will ask for input, generate computer choice, # determine winner and show output when finished. def main(): # Initialize Accumulators tie = 0 win = 0 l...
[ "In Python:\n>>> print(\"3\" == 3)\nFalse\n\nStrings and integers are values of different data types, and will not compare equal. Try changing your input to:\nuserInput = int(input('Please enter your selection here: '))\n\nThis will convert the string typed by the user to a number for later comparison. (Note that I...
[ 4, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006565222_python.txt
Q: Filtering xml file to remove lines with certain text in them? For example, suppose I have: <div class="info"><p><b>Orange</b>, <b>One</b>, ... <div class="info"><p><b>Blue</b>, <b>Two</b>, ... <div class="info"><p><b>Red</b>, <b>Three</b>, ... <div class="info"><p><b>Yellow</b>, <b>Four</b>, ... And I'd like to r...
Filtering xml file to remove lines with certain text in them?
For example, suppose I have: <div class="info"><p><b>Orange</b>, <b>One</b>, ... <div class="info"><p><b>Blue</b>, <b>Two</b>, ... <div class="info"><p><b>Red</b>, <b>Three</b>, ... <div class="info"><p><b>Yellow</b>, <b>Four</b>, ... And I'd like to remove all lines that have words from a list so I'll only use xpath ...
[ "Use:\n//div\n [not(p/b[contains('|Orange|Red|', \n concat('|', ., '|')\n )\n ]\n )\n ]\n\nThis selects any div elements in the XML document, such that it has no p child whose b child's string valu is one of the strings in the pipe-separated list of strings to u...
[ 1, 0 ]
[]
[]
[ "html", "lxml", "python", "xml", "xpath" ]
stackoverflow_0006565344_html_lxml_python_xml_xpath.txt
Q: efficient function to retrieve a queryset of ancestors of an mptt queryset Does anybody have an efficient algorithm to retrieve all ancestors of an mptt queryset? The best I could think of so far is something like this: def qs_ancestors(queryset): if isinstance(queryset, EmptyQuerySet): return queryset...
efficient function to retrieve a queryset of ancestors of an mptt queryset
Does anybody have an efficient algorithm to retrieve all ancestors of an mptt queryset? The best I could think of so far is something like this: def qs_ancestors(queryset): if isinstance(queryset, EmptyQuerySet): return queryset queryset_aggs = queryset.values_list('tree_id', 'level').annotate(max_lft=M...
[ "I had to write a similar algorithm once. I had a view displaying a MPTT tree, it's was a very large tree so I couldn't load all of it's data in the HTML template. So I displayed only the root nodes in the initial load and used Ajax to load the other nodes.\nIt was working good until my boss asked me to implement a...
[ 6, 4 ]
[]
[]
[ "django", "django_mptt", "hierarchical_data", "mptt", "python" ]
stackoverflow_0006471354_django_django_mptt_hierarchical_data_mptt_python.txt
Q: Adding new command to module through C-API? How would I dynamically add methods to my module through the C-API? I have many functions I need to register, and they are not in the same array. I assume I can initialize the module with a NULL method table, as the documentation says that's possible. PyObject *mymod = ...
Adding new command to module through C-API?
How would I dynamically add methods to my module through the C-API? I have many functions I need to register, and they are not in the same array. I assume I can initialize the module with a NULL method table, as the documentation says that's possible. PyObject *mymod = Py_InitModule("my", NULL); What is the name of a...
[ "Basically, you'll have to get ahold of the module dict first:\nd = PyModule_GetDict(m);\n\nStore the module name in a PyString object:\nn = PyString_FromString(\"modname\");\n\nThen properly populate a PyMethodDef struct ml and create a new callable:\nv = PyCFunction_NewEx(&ml, (PyObject*)NULL, n);\n\nand add this...
[ 2 ]
[]
[]
[ "python", "python_c_api" ]
stackoverflow_0006565175_python_python_c_api.txt
Q: Is it possible to check whether a context variable is already set in a view within a custom context processor definition? The issue is that in some views, I am manually getting a context variable (let's say "G") of interest since I use it to find other information in that particular view (i.e.views A,B,C), but in ...
Is it possible to check whether a context variable is already set in a view within a custom context processor definition?
The issue is that in some views, I am manually getting a context variable (let's say "G") of interest since I use it to find other information in that particular view (i.e.views A,B,C), but in other views (i.e. X,Y,Z), I need to get that particular context variable since this context is to be available in every single ...
[ "def always_G(request):\n if not hasattr(request, 'G'):\n {'G':G.objects.get(user=request.user)}\n\n", "I just made middleware that sets the variabel G to request.G since I need it on virtually every request anyway. i.e.:\nclass GuildMiddleware(object):\n def process_request(self, request):\n ...
[ 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005996680_django_python.txt
Q: longest match in python I am new in python.I have data in a 2d- array in the following format. array[0] array[1] Arkan Adrian Edmondson Efgan All Rik 'Til Death Do Us Part (Star...
longest match in python
I am new in python.I have data in a 2d- array in the following format. array[0] array[1] Arkan Adrian Edmondson Efgan All Rik 'Til Death Do Us Part (Star Trek: Deep Space Nine) Br...
[ "I'm having a bit of trouble working out what you're asking, but maybe this will help:\nYou can remove a bracketed section of a string with:\nthetext = re.sub(r\"\\(.*?\\)\", \"\", thetext)\n\n(N.B. This won't work properly if you have \"((nested) brackets)\")\nYou can get substrings by slicing:\nthetext[4:10]\nthe...
[ 1 ]
[]
[]
[ "python", "string" ]
stackoverflow_0006565592_python_string.txt
Q: Code interpreter in a web service I'd like to build a website with a sandboxed interpreter (or compiler) either on the client side of on the server side that can take short blocks of code (python/java/c/c++ any common language would do) as input and execute it. What I want to build is a place where given a progra...
Code interpreter in a web service
I'd like to build a website with a sandboxed interpreter (or compiler) either on the client side of on the server side that can take short blocks of code (python/java/c/c++ any common language would do) as input and execute it. What I want to build is a place where given a programming question, the user can type in th...
[ "There are many contest websites that do something like this-- TopCoder and Timus Online Judge are two examples. They don't have much information on the technology, however.\ncodepad.org is the closest to what you want to do. They run programs on heavily sandboxed and firewalled EC2 servers that are periodically wi...
[ 2, 2, 1 ]
[]
[]
[ "interpreter", "python", "web_applications" ]
stackoverflow_0005739214_interpreter_python_web_applications.txt
Q: Suppyling a hessian to fmin_ncg in python For the SciPy function fmin_ncg, is there a way of suppling the hessian and gradient as a variable rather than a function? I'm trying to rewrite some Matlab code in python. The code involves using an optimisation routine to fit some parameters to a set of data. To do this,...
Suppyling a hessian to fmin_ncg in python
For the SciPy function fmin_ncg, is there a way of suppling the hessian and gradient as a variable rather than a function? I'm trying to rewrite some Matlab code in python. The code involves using an optimisation routine to fit some parameters to a set of data. To do this, I've supplied the gradient and hessian. E.g in...
[ "You can create a class that includes all of your functions. Each iteration, the common variables are calculated during the first function call, then are reused for the other calls. The callback feature of fmin_ncg can be used to reset the common variables at the end of each iteration.\nclass function(object):\n\...
[ 4 ]
[]
[]
[ "mathematical_optimization", "matlab", "numpy", "python", "scipy" ]
stackoverflow_0006565430_mathematical_optimization_matlab_numpy_python_scipy.txt
Q: urllib freeze if url is too big ! ok im trying to open a url using urllib but the problem is that the file is too big, so when i open the url python freezes, im also using wxpython which also freezes when i open the url my cpu goes to almost 100% when the url is opened any solutions ? is there a way i can open ...
urllib freeze if url is too big !
ok im trying to open a url using urllib but the problem is that the file is too big, so when i open the url python freezes, im also using wxpython which also freezes when i open the url my cpu goes to almost 100% when the url is opened any solutions ? is there a way i can open the url in chunks and maybe have a time...
[ "You want to split the download into a separate thread, so your UI thread continues to work while the download thread does the work separately. That way you don't get the \"freeze\" while the download happens.\nRead more about threading here:\nhttp://docs.python.org/library/threading.html\nAlternatively, you could ...
[ 1 ]
[]
[]
[ "python", "urllib", "urllib2" ]
stackoverflow_0006565910_python_urllib_urllib2.txt
Q: Parse HTML using Python and Beautiful Soup <div class="profile-row clearfix"><div class="profile-row-header">Member Since</div><div class="profile-information">January 2010</div></div> <div class="profile-row clearfix"><div class="profile-row-header">AIGA Chapter</div><div class="profile-information">Alaska</div><...
Parse HTML using Python and Beautiful Soup
<div class="profile-row clearfix"><div class="profile-row-header">Member Since</div><div class="profile-information">January 2010</div></div> <div class="profile-row clearfix"><div class="profile-row-header">AIGA Chapter</div><div class="profile-information">Alaska</div></div> <div class="profile-row clearfix"><div cla...
[ ">>> from BeautifulSoup import BeautifulSoup\n>>> soup = BeautifulSoup('''<div class=\"profile-row clearfix\"><div class=\"profile-row-header\">Member Since</div><div class=\"profile-information\">January 2010</div></div>\n... <div class=\"profile-row clearfix\"><div class=\"profile-row-header\">AIGA Chapter</div><...
[ 3 ]
[]
[]
[ "beautifulsoup", "find", "html", "python", "web_scraping" ]
stackoverflow_0006566000_beautifulsoup_find_html_python_web_scraping.txt
Q: Python closure with side-effects I'm wondering if it's possible for a closure in Python to manipulate variables in its namespace. You might call this side-effects because the state is being changed outside the closure itself. I'd like to do something like this def closureMaker(): x = 0 def closure(): x+=1 ...
Python closure with side-effects
I'm wondering if it's possible for a closure in Python to manipulate variables in its namespace. You might call this side-effects because the state is being changed outside the closure itself. I'd like to do something like this def closureMaker(): x = 0 def closure(): x+=1 print x return closure a = clos...
[ "You can't do exactly that in Python 2.x, but you can use a trick to get the same effect: use a mutable object such as a list.\ndef closureMaker():\n x = [0]\n def closure():\n x[0] += 1\n print x[0]\n return closure\n\nYou can also make x an object with a named attribute, or a dictionary. Th...
[ 17, 5 ]
[]
[]
[ "closures", "python", "side_effects" ]
stackoverflow_0006566227_closures_python_side_effects.txt
Q: Is there a preferred Python gui to use I'm attempting to convert a Python application I coded using the cmd module into a gui. Initially, I came across EasyGui. But after giving it a try, I find that it is very limited, the gui screens are not consistent, and overall not easy on the eyes. I read about IronPython (...
Is there a preferred Python gui to use
I'm attempting to convert a Python application I coded using the cmd module into a gui. Initially, I came across EasyGui. But after giving it a try, I find that it is very limited, the gui screens are not consistent, and overall not easy on the eyes. I read about IronPython (Python + .NET), but cannot find adequate doc...
[ "Tkinter is in the standard library, works on all platforms, and is fairly simple and lightweight, but it looks a bit clunky.\nWxPython tries to use platform widgets, so it looks a bit better, but it's a separate library. On Linux, I still find it doesn't look quite right.\nPyQt is a large, powerful framework - it ...
[ 5, 1, 0 ]
[]
[]
[ "python", "user_interface" ]
stackoverflow_0006566264_python_user_interface.txt
Q: Prevent automatic type conversion in ctypes callback functions When wrapping Python functions with a CFUNCTYPE type, I've found that the non-pointer types are automatically converted as though their value attribute was called. How can I suppress this automatic conversion? from ctypes import * funcspec = CFUNCTYPE...
Prevent automatic type conversion in ctypes callback functions
When wrapping Python functions with a CFUNCTYPE type, I've found that the non-pointer types are automatically converted as though their value attribute was called. How can I suppress this automatic conversion? from ctypes import * funcspec = CFUNCTYPE(c_int, c_int, POINTER(c_int)) @funcspec def callback(the_int, the_...
[ "This is a bit of a hack, but it might work for you. Hopefully someone else will chime in with a cleaner way..\nfrom ctypes import *\n\nclass c_int_hack(c_int):\n def from_param(self, *args):\n return self\n\nfuncspec = CFUNCTYPE(c_int, c_int_hack, POINTER(c_int))\n\n@funcspec\ndef callback(the_int, the_i...
[ 3, 1 ]
[]
[]
[ "callback", "ctypes", "python", "python_3.x", "type_conversion" ]
stackoverflow_0006273381_callback_ctypes_python_python_3.x_type_conversion.txt
Q: perl equivalent of python array.array(typecode, ..) I am trying to translate a python script to perl but currently stuck at couple of code snipets. For instance how to write following python code in perl? (without using any perl array related packages) # packet here is a binary string data = array.array( 'h', ( or...
perl equivalent of python array.array(typecode, ..)
I am trying to translate a python script to perl but currently stuck at couple of code snipets. For instance how to write following python code in perl? (without using any perl array related packages) # packet here is a binary string data = array.array( 'h', ( ord( packet[i] ) for i in range( start, end ) ) ) FILE.writ...
[ "edit\nYou need to clarify what you're saying. On my python (2.7.2), this is wrong:\nFILE.write(data)\n\nbecause data needs to be a string. I think what you mean to say instead is:\ndata.tofile(FILE)\n\nAnyway, is this what you want?\nprint pack(\"s*\", unpack(\"C*\", \"abcd\"))\n# piped through xxd => 0000000: 610...
[ 5 ]
[]
[]
[ "arrays", "perl", "python", "types" ]
stackoverflow_0006566387_arrays_perl_python_types.txt
Q: macports didn't place python_select in /opt/local/bin I've uninstalled and reinstalled python_select using MacPorts and yet it won't show up in /opt/local/bin. Consequently, I get a "command not found" error when attempting to run it. Yet MacPorts insists that it is installed. Have even tried uninstall -f and port...
macports didn't place python_select in /opt/local/bin
I've uninstalled and reinstalled python_select using MacPorts and yet it won't show up in /opt/local/bin. Consequently, I get a "command not found" error when attempting to run it. Yet MacPorts insists that it is installed. Have even tried uninstall -f and port clean --all python_select. Is there a more drastic step to...
[ "It seems that python_select has been deprecated:\n\n\"python_select\" (and other standalone *_select scripts) is gone.\nUse \"sudo port select python python26\" etc. \n\n", "sudo port select --set python python25\n\nThis will set the Python alias (/opt/local/bin/python) to python25\nIf you're not sure which vers...
[ 28, 11 ]
[]
[]
[ "macports", "python" ]
stackoverflow_0006152765_macports_python.txt
Q: how to understand "cursor" correctly I'm trying to apply cursor to my app, however, the document is not clear enough for me. Google's description for cursor http://code.google.com/appengine/docs/python/datastore/queries.html#Query_Cursors The cursor's position is defined as the location in the result list after ...
how to understand "cursor" correctly
I'm trying to apply cursor to my app, however, the document is not clear enough for me. Google's description for cursor http://code.google.com/appengine/docs/python/datastore/queries.html#Query_Cursors The cursor's position is defined as the location in the result list after the last result returned. A cursor is not ...
[ "Your understanding is more or less correct, but a cursor can't be thought of as simply adding filters. Supposing you have a result set ordered first by age, then by name. If your last returned result has age=30 and name=Bob, there's no set of criteria that will return exactly the results after that - age>=30 and n...
[ 3 ]
[]
[]
[ "google_app_engine", "gql", "python" ]
stackoverflow_0006557791_google_app_engine_gql_python.txt
Q: How to obtain all instances of a class within the current module I have a module foo that defines a class Foo, and instantiates a number of instances of this class. From other modules, I can import foo and obtain a list of the Foo objects instantiated by: [getattr(foo,f) for f in dir(f) if isinstance(getattr(foo,f...
How to obtain all instances of a class within the current module
I have a module foo that defines a class Foo, and instantiates a number of instances of this class. From other modules, I can import foo and obtain a list of the Foo objects instantiated by: [getattr(foo,f) for f in dir(f) if isinstance(getattr(foo,f), foo.Foo)] It would be convenient if I could do this from within th...
[ "\ngoal: \"import foo and obtain a list of the Foo objects instantiated by...\"\n\nYou don't need introspection at all. Imagine this is your class:\nclass Registered(object):\n _all = set()\n def __init__(self):\n self.__class__._all.add(self)\n\nDemo; instantiate a bunch of objects and refer to them:\...
[ 8 ]
[]
[]
[ "introspection", "module", "python" ]
stackoverflow_0006566767_introspection_module_python.txt
Q: retrieve C++object member pointer using Python I'm using box2d in my application. It has a class b2Body. It has a property void *userData and methods for it's accessing. In other words: we can store there some additional info about physic body. I want to store there some class object: MyClass *obj = new MyClass();...
retrieve C++object member pointer using Python
I'm using box2d in my application. It has a class b2Body. It has a property void *userData and methods for it's accessing. In other words: we can store there some additional info about physic body. I want to store there some class object: MyClass *obj = new MyClass(); b2Body body; body.SetUserData(obj); Now I have to ...
[ "You just have to do it C-style, i.e. pass the pointer to a function with returns the specific item you want. C++ objects aren't the same as python objects.\nAlso Python doesn't even have the definition of your c++ object, so even if they looked the same in memory, python could use it as it doesn't know what its in...
[ 1 ]
[]
[]
[ "boost", "c++", "pointers", "python" ]
stackoverflow_0006526697_boost_c++_pointers_python.txt
Q: realtime statistical analysis I need to do some real-time data analysis to monitor for operational errors. More specifically, I'm controlling a winch on a buoy which is lowering an instrument package down through the water. I need to detect if it has hit the bottom, and stop it if it has. I've got the following da...
realtime statistical analysis
I need to do some real-time data analysis to monitor for operational errors. More specifically, I'm controlling a winch on a buoy which is lowering an instrument package down through the water. I need to detect if it has hit the bottom, and stop it if it has. I've got the following data: depth of sensor, rate at which ...
[ "Your approach (comparing current derivative to mean derivative) is good, but could be improved. Most importantly, you really need to see your data before deciding how to analyze it:\n\nThese plots show:\nA) Your original data. Note: the rate of descent is not constant due to the spool diameter changing, and thus a...
[ 7, 1, 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0006362335_numpy_python.txt
Q: Python regex to match HTML I am trying to request a web page via urllib2 using a regex. Here is my code def Get(url): request = urllib2.Request(url) page = urlOpener.open(request) return page.read() page = Get(myurl) #page = "<html>.....</html>" #local string for test pattern = re.compile(r'^\s*(<tr>$...
Python regex to match HTML
I am trying to request a web page via urllib2 using a regex. Here is my code def Get(url): request = urllib2.Request(url) page = urlOpener.open(request) return page.read() page = Get(myurl) #page = "<html>.....</html>" #local string for test pattern = re.compile(r'^\s*(<tr>$\s*<td height="25.*?</tr>)$', re...
[ "Valid reservations about using regex on html aside, try this regex instead:\n(<tr>\\s*<td height=\"25.*?</tr>)\nYou were finding only matches at end of input $, and had problem terms at front of regex.\nThis match is a brittle - let's hope the web guy doesn't change the height of the rows...\n" ]
[ 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0006566851_python_regex.txt
Q: Doing database JOIN in django I want to do equivalent query as SELECT user_name, item_name FROM users, items WHERE users.favor_item_id = items.item_id, which is to return user_name and item_name pairs. In the database, one user can have multiple favoured items. I'm just curious what is a equivalent Django query fo...
Doing database JOIN in django
I want to do equivalent query as SELECT user_name, item_name FROM users, items WHERE users.favor_item_id = items.item_id, which is to return user_name and item_name pairs. In the database, one user can have multiple favoured items. I'm just curious what is a equivalent Django query for this SQL query?? My first thought...
[ "\n(or any ORM system)?\n\nReally? here's how you'd do it in sqlalchemy\nAssuming reasonable mapped classes (here, using declarative):\nBase = sqlalchemy.ext.declarative.declarative_base()\n\nclass Item(Base):\n __tablename__ = 'items'\n id = Column('item_id', Integer, primary_key=True)\n name = Column('i...
[ 2, 2 ]
[]
[]
[ "database", "django", "orm", "python", "sql" ]
stackoverflow_0006566893_database_django_orm_python_sql.txt
Q: Prepend script's directory to a string When writing throwaway scripts it's often needed to load a configuration file, image, or some such thing from the same directory as the script. Preferably this should continue to work correctly regardless of the directory the script is executed from, so we may not want to sim...
Prepend script's directory to a string
When writing throwaway scripts it's often needed to load a configuration file, image, or some such thing from the same directory as the script. Preferably this should continue to work correctly regardless of the directory the script is executed from, so we may not want to simply rely on the current working directory. S...
[ "I would personally just os.chdir into the script's directory whenever I execute it. It is just:\nimport os\nos.chdir(os.path.split(__file__)[0])\n\nHowever if you did want to refactor this thing into a library, you are in essence wanting a function that is aware of its caller's state. You thus have to make it \npr...
[ 4, 0, 0 ]
[]
[]
[ "file", "module", "path", "python" ]
stackoverflow_0006566642_file_module_path_python.txt
Q: Understanding list comprehension vs traditional loop and build I'm trying to nail my understanding and best use of Lists, I have come across list comprehension and read plenty about them, but am choking on one particular burning question. Given this challenge: def matrix_mult(m1, m2): """ >>> matrix_mult...
Understanding list comprehension vs traditional loop and build
I'm trying to nail my understanding and best use of Lists, I have come across list comprehension and read plenty about them, but am choking on one particular burning question. Given this challenge: def matrix_mult(m1, m2): """ >>> matrix_mult([[1, 2], [3, 4]], [[5, 6], [7, 8]]) [[19, 22], [43, 50]] ...
[ "List comprehension is simply a way of creating a list based on another list. (Or other iterable item)\nFor instance, if we have a list a = [1, 2, 5, 7], then we could create a list, b, containing the values of a doubled in two ways.\nWithout list comprehensions\nb = []\nfor e in a:\n b.append(2*e)\n\nWith list ...
[ 7, 3, 3, 1, 1 ]
[]
[]
[ "list_comprehension", "python" ]
stackoverflow_0006563314_list_comprehension_python.txt
Q: Can I make uuid's more random? I have a program that dispatches messages to separate processes. I need to balance the load, but not in very precise way, almost the same number is ok. Since every message has an uuid field, I want to do it by uuid value. After I tested the uuid randomness I found it to not be as ran...
Can I make uuid's more random?
I have a program that dispatches messages to separate processes. I need to balance the load, but not in very precise way, almost the same number is ok. Since every message has an uuid field, I want to do it by uuid value. After I tested the uuid randomness I found it to not be as random as I expexted. I have the last o...
[ "UUIDs are not meant to be random, just unique. If your balancer needs to be keyed off of them, it should run them through a hash function first to get the randomness you want:\nimport hashlib\nactually_random = hashlib.sha1(uuid).digest()\n\n", "Your testing methodology doesn't make any sense (see below). But fi...
[ 8, 6, 2, 1 ]
[]
[]
[ "algorithm", "load_balancing", "python", "uuid" ]
stackoverflow_0006567309_algorithm_load_balancing_python_uuid.txt
Q: Unable to set the value of a SelectControl element I am trying to get machine-parsable bus schedule data by submitting a form with mechanize. However, I am stymied by the mechanize syntax for setting import mechanize br = mechanize.Browser() br.open("http://www.planibus.sto.ca/HastinfoWeb/StartTimetableForm.aspx...
Unable to set the value of a SelectControl element
I am trying to get machine-parsable bus schedule data by submitting a form with mechanize. However, I am stymied by the mechanize syntax for setting import mechanize br = mechanize.Browser() br.open("http://www.planibus.sto.ca/HastinfoWeb/StartTimetableForm.aspx") br.select_form(name="TimetableQueryForm") br["RouteDi...
[ "3 isn't one of the available select options, the options I see are\n<option value=\"4\">4</option>\n<option value=\"5\">5</option>\n<option value=\"6\">6</option>\n<option value=\"7\">7</option>\n<option value=\"8\">8</option>\n<option value=\"9\">9</option>\n<option value=\"10\">10</option>\n<option value=\"11\">...
[ 1 ]
[]
[]
[ "mechanize", "python" ]
stackoverflow_0006566874_mechanize_python.txt
Q: the problem about detecting usb device I need detect an usb device when it had been plugged and unplugged, and I write a python programme with dbus. But it is very odd the device would be mounted three times at least when it is plugged or unplugged the monitor code is following: device = dbus.Interface...
the problem about detecting usb device
I need detect an usb device when it had been plugged and unplugged, and I write a python programme with dbus. But it is very odd the device would be mounted three times at least when it is plugged or unplugged the monitor code is following: device = dbus.Interface(self.bus.get_object("org.freedesktop.Hal", ...
[ "I am not familiar with dbus, but look at the device names you are getting:\nusb_device_413c_2003_noserial\nusb_device_413c_2003_noserial_if0\nusb_device_413c_2003_noserial_if0_logicaldev_input\n\nThe first device probably represents the USB device as a whole. The second device most likely represents Interface 0 o...
[ 0 ]
[]
[]
[ "dbus", "python", "usb" ]
stackoverflow_0006565187_dbus_python_usb.txt
Q: Fastest Way to (1) not insert duplicate entry (2) consolidate duplicates in Mongo DB? (1) What's the fastest way to check if an item I'm about to "insert" into a MongoDB collection is unique (and if so not insert it) (2) For an existing database, what's the fastest way to look at all the entries and remove duplica...
Fastest Way to (1) not insert duplicate entry (2) consolidate duplicates in Mongo DB?
(1) What's the fastest way to check if an item I'm about to "insert" into a MongoDB collection is unique (and if so not insert it) (2) For an existing database, what's the fastest way to look at all the entries and remove duplicates but keep one copy i.e. like a "set" function: {a,b,c,a,a,b} -> {a,b,c} I am aware that...
[ "(1) Create a unique index on the related columns and catch the error upon insertion time\n" ]
[ 2 ]
[]
[]
[ "mongodb", "python" ]
stackoverflow_0006567511_mongodb_python.txt
Q: reverse engineering python to strings Question: is it possible to reverse engineer python objects into a string? Info: I'm working on a project right now that distributes my prof's research across several dozen computers instead of just his. Being a good programmer I'm making it a generalized program that can be ...
reverse engineering python to strings
Question: is it possible to reverse engineer python objects into a string? Info: I'm working on a project right now that distributes my prof's research across several dozen computers instead of just his. Being a good programmer I'm making it a generalized program that can be used for more than just his specific progra...
[ "Although it's not a good approach, you can pickle only the __code__ from the function...\n>>> def foo():\n... print \"Hello\"\n\n>>> import pickle\n>>> code = pickle.dumps(foo.__code__)\n>>> def bar():\n... pass\n\n>>> bar()\n>>> bar.__code__ = pickle.loads(code)\n>>> bar()\nHello\n\n", "With marshal mod...
[ 1, 0 ]
[]
[]
[ "import", "python", "reverse_engineering" ]
stackoverflow_0006565293_import_python_reverse_engineering.txt
Q: What's being used to check code coverage in Django? Django doesn't appear to have built in support for code coverage. Is therea defacto-standard tool for checking it in Django 1.3? A: Ned Batchelder's coverage.py is the authoritative tool for test coverage in python.
What's being used to check code coverage in Django?
Django doesn't appear to have built in support for code coverage. Is therea defacto-standard tool for checking it in Django 1.3?
[ "Ned Batchelder's coverage.py is the authoritative tool for test coverage in python.\n" ]
[ 6 ]
[]
[]
[ "code_coverage", "python", "testing" ]
stackoverflow_0006567819_code_coverage_python_testing.txt
Q: How to traverse a list of the following conditions a = [(2,3),(4,1),(2,8),(2,1),(3,4)] How to traverse a list of the following conditions according to the first tuple from small to large order If the first tuple in accordance with the same first two descending order I can sort it using Python sorted like this: ...
How to traverse a list of the following conditions
a = [(2,3),(4,1),(2,8),(2,1),(3,4)] How to traverse a list of the following conditions according to the first tuple from small to large order If the first tuple in accordance with the same first two descending order I can sort it using Python sorted like this: sorted(a, key=lambda d: d[0], reverse=True) but how to ...
[ "sorted(..., key=lambda x: (x[0], -x[1]))\n\n", "Ignacio's answer works well for numbers which seems to be what the OP needs. If the unary - can't be applied to the field to be reversed, you can use the Reversinator\neg.\nclass Reversinator(object):\n def __init__(self, obj):\n self.obj = obj\n def _...
[ 3, 1 ]
[]
[]
[ "list", "python", "sorting" ]
stackoverflow_0006567666_list_python_sorting.txt
Q: how to get selected value from wxlistbox i have a wxlistbox.i need to get the selected value from the wxlistbox now i get only id from self.lvnames.GetSelections(). but i need value instead of id.How?Please Help Me... my listbox declaration is self.lvnames=wx.ListBox(panel,-1,(10,40),(210,180),self.names, wx.LB_S...
how to get selected value from wxlistbox
i have a wxlistbox.i need to get the selected value from the wxlistbox now i get only id from self.lvnames.GetSelections(). but i need value instead of id.How?Please Help Me... my listbox declaration is self.lvnames=wx.ListBox(panel,-1,(10,40),(210,180),self.names, wx.LB_SINGLE)
[ "self.lvnames.GetString(self.lvnames.GetSelection())\n\nYou will get an error if you call this and there is nothign selected, so you can keep this in a try... except block\n" ]
[ 6 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0006567871_python_wxpython.txt
Q: migrating from django-cms beta3 to 2.1.3 (stable) Hey guys, Im trying to migrate django-cms from version 2.1.0 beta3 to 2.1.3 (stable), i have read many posts that recommend South for this, unfortunately i have never done anything with south, and i didn't have it installed when creating my projects, so i have foll...
migrating from django-cms beta3 to 2.1.3 (stable)
Hey guys, Im trying to migrate django-cms from version 2.1.0 beta3 to 2.1.3 (stable), i have read many posts that recommend South for this, unfortunately i have never done anything with south, and i didn't have it installed when creating my projects, so i have followed many solutions that include running: python manage...
[ "I use this sequence when db changes and we need to do schemamigration using South:\n ./manage.py schemamigration your_app_name --auto\n\nNote, than database should fit your models, otherwise you'll get errors.\nThen, after you get success message and invitation to migration, you do:\n ./manage.py migrate\n\n...
[ 1 ]
[]
[]
[ "django", "django_cms", "django_south", "python" ]
stackoverflow_0006185103_django_django_cms_django_south_python.txt
Q: How to make file upload facultative with Deform and Colander? I would like to render a form containing a sequence of files, representing different images of a product. Providing files should be facultative, so the form should validate even in the absence of files. How can I do this ? Here is the colander schema I...
How to make file upload facultative with Deform and Colander?
I would like to render a form containing a sequence of files, representing different images of a product. Providing files should be facultative, so the form should validate even in the absence of files. How can I do this ? Here is the colander schema I use: import colander import deform from deform import...
[ "You might try \"missing = colander.null\".\n" ]
[ 5 ]
[]
[]
[ "colander", "deform", "pyramid", "python" ]
stackoverflow_0006563546_colander_deform_pyramid_python.txt
Q: python editor/IDE that shows available functions and more importantly their documentation f = open(filename, 'r') strings = f.read().lower() I want a python editor/ide that works like visual studio. In the above after typing 'f.' it shows me the list of available functions and their documentation(DO NOT WAIT FOR...
python editor/IDE that shows available functions and more importantly their documentation
f = open(filename, 'r') strings = f.read().lower() I want a python editor/ide that works like visual studio. In the above after typing 'f.' it shows me the list of available functions and their documentation(DO NOT WAIT FOR ctrl-space). Just like visual express C#. Also preferably it shows autocomplete lists of all v...
[ "Try to take a look at PyCharm. It not open source but it is quite cheap and powerful IDE:\nhttp://www.jetbrains.com/pycharm/\nhttp://www.jetbrains.com/pycharm/features/index.html\n\nCode completion for keywords, classes,\n variables, etc. — Ctrl+Space. Editor\n suggestions are context-aware and\n suggest most a...
[ 4, 2, 1, 1 ]
[]
[]
[ "ide", "python" ]
stackoverflow_0006567713_ide_python.txt
Q: c++0x std::shared_ptr vs. boost::shared_ptr I have a c++ code which heavily uses shared_ptr and STL. A common header says #include<boost/shared_ptr.hpp> using boost::shared_ptr; // for shared_ptr using namespace std; // for STL I wanted to switch to c++0x now to make use of the language features, using gcc ...
c++0x std::shared_ptr vs. boost::shared_ptr
I have a c++ code which heavily uses shared_ptr and STL. A common header says #include<boost/shared_ptr.hpp> using boost::shared_ptr; // for shared_ptr using namespace std; // for STL I wanted to switch to c++0x now to make use of the language features, using gcc 4.6 with -std=c++0x. There is however std::shared...
[ "You need to the define the freestanding function 'get_pointer' for your shared pointer class for it to work with Boost Python. (Note that this enables you to write your own shared pointer, and still work with Boost Python: this is a conscious design effort to prevent tight coupling of distinct Boost libraries).\nY...
[ 3 ]
[]
[]
[ "boost", "c++11", "python", "python_c_api", "shared_ptr" ]
stackoverflow_0006568952_boost_c++11_python_python_c_api_shared_ptr.txt
Q: Python 3.1.2 + Snow Leopard + lxml + XMLSchema I'd like to use lxml library to validate XML Schemas in Python 3.1.2. Since the Snow Leopard MAC OS comes with the Python 2.6.1 installed, firstly, I downloaded the Python 3.1.2 automated installer at http://www.python.org/ftp/python/3.1.2/python-3.1.2-macosx10.3-2010...
Python 3.1.2 + Snow Leopard + lxml + XMLSchema
I'd like to use lxml library to validate XML Schemas in Python 3.1.2. Since the Snow Leopard MAC OS comes with the Python 2.6.1 installed, firstly, I downloaded the Python 3.1.2 automated installer at http://www.python.org/ftp/python/3.1.2/python-3.1.2-macosx10.3-2010-03-24.dmg and installed it. Secondly, I downloaded ...
[ "If you are going to build lxml from source, you need to build it entirely with the desired Python. And, in general, you cannot just move site-packages from one Python instance to another, especially Python 2 vs Python 3. First, undo whatever copy or move you did into the Python 3 site-packages directory. If you...
[ 1, 0 ]
[]
[]
[ "lxml", "osx_snow_leopard", "python", "python_3.x", "xsd" ]
stackoverflow_0003195067_lxml_osx_snow_leopard_python_python_3.x_xsd.txt