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: Python urllib2 sending a post I want to open a page then find a number and multiply by another random number and then submit it to the page So what I'm doing is saving the page as a html then finding the 2 numbers multiplying it then sending it as a post but post = urllib.urlencode({'answer': goal, 'submit': 'Subm...
Python urllib2 sending a post
I want to open a page then find a number and multiply by another random number and then submit it to the page So what I'm doing is saving the page as a html then finding the 2 numbers multiplying it then sending it as a post but post = urllib.urlencode({'answer': goal, 'submit': 'Submit+Answer'}) req2 = urllib2.Request...
[ "You might want to use something like mechanize, which enables stateful web browsing in Python. You could use it to load a URL, read a value from a page, perform the multiplication, place that number into a form on the page, and then submit it.\nDoes that sound like what you're trying to do? This page gives some in...
[ 4, 0 ]
[]
[]
[ "post", "python", "urllib2" ]
stackoverflow_0007152107_post_python_urllib2.txt
Q: Python: if not val, vs if val is None I've always coded in the style of if not value, however, a few guides have brought to my attention that while this style works, it seems to have 2 potential problems: It's not completely readable; if value is None is surely more understandable. This can have implications late...
Python: if not val, vs if val is None
I've always coded in the style of if not value, however, a few guides have brought to my attention that while this style works, it seems to have 2 potential problems: It's not completely readable; if value is None is surely more understandable. This can have implications later (and cause subtle bugs), since things lik...
[ "Use a comparison to None if that's what you want. Use \"if not value\" if you just want to check if the value is considered false (empty list, none, false).\nI find \"if not value\" to be cleaner looking and Pythonic.\nAlso, be careful with lists. You should not use is when comparing for an empty list. If you know...
[ 49, 34, 7, 5, 2 ]
[]
[]
[ "boolean", "comparison", "python", "readability" ]
stackoverflow_0007152441_boolean_comparison_python_readability.txt
Q: Reading a python UUID byte string in C++? I have a string of 16 bytes in python created from the uuid.bytes method, something like: 'I\x9e|T\r\xad@\x80\x986m\x00\x1c\x07z0' for example, that I am passing to a C++ file. Is there a way for me to read that from the C++ side and reconstruct the UUID? I was going t...
Reading a python UUID byte string in C++?
I have a string of 16 bytes in python created from the uuid.bytes method, something like: 'I\x9e|T\r\xad@\x80\x986m\x00\x1c\x07z0' for example, that I am passing to a C++ file. Is there a way for me to read that from the C++ side and reconstruct the UUID? I was going to read it into a 16-char array since a char = 1...
[ "Something like this (untested)\nchar to_hex(int x)\n{\n return x < 10 ? x + '0' : (x - 10) + 'A';\n}\n\nchar bytes[16];\n...\nstd::string uuid;\nfor (int i = 0; i < 16; ++i)\n{\n uuid += to_hex((bytes[i] >> 4) & 0x0F);\n uuid += to_hex(bytes[i] & 0x0F);\n}\n\n", "I'd use:\nUUID.hex\n\nunless you need it in a ...
[ 1, 0 ]
[]
[]
[ "byte", "c++", "python", "uuid" ]
stackoverflow_0007153171_byte_c++_python_uuid.txt
Q: compare one column to another in csv file in Python Hi i want to compare column a of a csv file with column b of the same csv file as follows: column a: 8,67,55,32,44,70,9,10,79,21 column b: 22, 45, 6, 22, 3, 22, 6, 7,22,5 i want the user to enter a number lets say: '8' usin rawinput command. Then search number...
compare one column to another in csv file in Python
Hi i want to compare column a of a csv file with column b of the same csv file as follows: column a: 8,67,55,32,44,70,9,10,79,21 column b: 22, 45, 6, 22, 3, 22, 6, 7,22,5 i want the user to enter a number lets say: '8' usin rawinput command. Then search number corresponding to 8 in other coulmn(b). This should give ...
[ "I would create a dictionary (lets call it dictA) for the incoming data where the keys are the column a numbers and the values column b.\nI would also create a second dictionary (dictB) where the keys are the column b numbers and the values are lists of the corresponding values from column a.\nSo for the example yo...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007153051_python.txt
Q: python __str__ for an object While trying to figure out how BeautifulSoup works, I incidentally learnt the __str__ method (I'm new to python). So if I did not misperceived then the __str__ method helps to shape how the class will be represented if printed out. For instance: class Foo: def __str__(self): ...
python __str__ for an object
While trying to figure out how BeautifulSoup works, I incidentally learnt the __str__ method (I'm new to python). So if I did not misperceived then the __str__ method helps to shape how the class will be represented if printed out. For instance: class Foo: def __str__(self): return "bar" >>> x = Foo() >>> ...
[ "You need to subclass the item you're pretty-printing.\nfrom itertools import chain\n\nclass PrintableList(list): # for a list of dicts\n def __str__(self):\n return '. '.join(' '.join(str(x) for x in\n chain.from_iterable(zip((item[0], 'is', 'and'), item[1])))\n for item in (ite...
[ 22, 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007152312_python.txt
Q: Celery result.get times out I have two different django projects say projA and projB, each have its own celery daemon running on separate queues but same vhost, projA have a task taskA and projB have a task taskB, I try to run taskB from inside taskA e.g. @task(routing_key='taskA') def taskA(event_id): # do so...
Celery result.get times out
I have two different django projects say projA and projB, each have its own celery daemon running on separate queues but same vhost, projA have a task taskA and projB have a task taskB, I try to run taskB from inside taskA e.g. @task(routing_key='taskA') def taskA(event_id): # do some work , then call taskB and wai...
[ "Setting the result back-end fixed the problem\nCELERY_RESULT_BACKEND = \"amqp\"\nCELERY_AMQP_TASK_RESULT_EXPIRES = 1000 \n\nIMO if result back-end is not set result.get should throw error or at-least log a warning\nThough celery 2.3 does throw error as described here https://github.com/ask/django-celery/issues/66\...
[ 1 ]
[]
[]
[ "celery", "django_celery", "python" ]
stackoverflow_0007111040_celery_django_celery_python.txt
Q: For loop is 'printed' every time I hit refresh I build simple webpage using CherryPy and Jinja2 The webserver python file: import cherrypy from jinja2 import Environment, FileSystemLoader from soltyslib import listFiles env = Environment(loader=FileSystemLoader('templates')) class HelloWorld(object): @cherr...
For loop is 'printed' every time I hit refresh
I build simple webpage using CherryPy and Jinja2 The webserver python file: import cherrypy from jinja2 import Environment, FileSystemLoader from soltyslib import listFiles env = Environment(loader=FileSystemLoader('templates')) class HelloWorld(object): @cherrypy.expose def index(self): ...
[ "Your problem is \n def listFiles(cdir, fileslist=[]):\n\nYou're reusing the same list on every call, because default arguments are evaluated only when the function is defined, not every time it's called. See \"Least Astonishment\" and the Mutable Default Argument for a long discussion if this behavior.\nDo\n def l...
[ 4, 0, 0 ]
[]
[]
[ "cherrypy", "jinja2", "python" ]
stackoverflow_0007153697_cherrypy_jinja2_python.txt
Q: $_SERVER headers are missing in PHP but present in Python I'm behind a transparent proxy which always adds the HTTP_X_FORWARDED_FOR header. When I dump the headers out using PHP the header is missing. But Python works.. lol Python: remote_addr = os.environ.get('HTTP_X_FORWARDED_FOR', os.environ.get('REMOTE_ADDR',...
$_SERVER headers are missing in PHP but present in Python
I'm behind a transparent proxy which always adds the HTTP_X_FORWARDED_FOR header. When I dump the headers out using PHP the header is missing. But Python works.. lol Python: remote_addr = os.environ.get('HTTP_X_FORWARDED_FOR', os.environ.get('REMOTE_ADDR', '')) PHP: print_r($_SERVER['HTTP_X_FORWARDED_FOR']); print_r(...
[ "You are using FastCGI. PHP isn't at ease with this, though it's making progress. With PHP 5.3 came php-fpm, with 5.4 will come HTTP headers for FastCGI. See the changelog of apache_request_headers or getAllHeaders().\nThough there's no pure PHP solution, the first note of the previous link contains a workaround: u...
[ 3 ]
[]
[]
[ "apache", "ip", "php", "python" ]
stackoverflow_0007141566_apache_ip_php_python.txt
Q: Querying by related object value I am setting up a simple billing system, where I have a table that lists users and the day they are supposed to be billed. Each user only has one row of this table associated with them. I need to query the database on a daily basis to get a list of users to be billed on that day. T...
Querying by related object value
I am setting up a simple billing system, where I have a table that lists users and the day they are supposed to be billed. Each user only has one row of this table associated with them. I need to query the database on a daily basis to get a list of users to be billed on that day. The model is: class BillingDay(models.M...
[ "User.objects.filter(billingday__day=1)\n\nJust as a note, though, you might want to rethink how you're setting this up before you get too far down the rabbit hole. Will users have multiple billing days? My guess would be no. If that's the case, there's no reason for a BillingDay model. It only adds complexity and ...
[ 4 ]
[]
[]
[ "django", "django_models", "django_queryset", "python" ]
stackoverflow_0007153894_django_django_models_django_queryset_python.txt
Q: ImporError with 'Hello World' example from Panda3d I just finished installing Panda3d on my Mac, a 3d Python game engine, but when I try to run the hello world example with ppython helloworld.py I get an issue: Traceback (most recent call last): File "helloworld.py", line 1, in <module> from direct.showbase...
ImporError with 'Hello World' example from Panda3d
I just finished installing Panda3d on my Mac, a 3d Python game engine, but when I try to run the hello world example with ppython helloworld.py I get an issue: Traceback (most recent call last): File "helloworld.py", line 1, in <module> from direct.showbase.ShoHewBase import ShowBase File "dstroot/pythoncode/D...
[ "Per the \"Troubleshooting\" section of the Panda3D Getting-Started page, you probably need to install the Nvidia Cg toolkit.\n" ]
[ 3 ]
[]
[]
[ "panda3d", "python" ]
stackoverflow_0007153955_panda3d_python.txt
Q: Extracting an amplitude list from *.wav file for use in Python I'm having a little bit of programing and conversion trouble. I'm designing an AI to recognize notes played by instruments and need to extract the raw sound data from a wave file. My objective is to perform a FFT operation over chunks of time in the fi...
Extracting an amplitude list from *.wav file for use in Python
I'm having a little bit of programing and conversion trouble. I'm designing an AI to recognize notes played by instruments and need to extract the raw sound data from a wave file. My objective is to perform a FFT operation over chunks of time in the file for use by the AI. For this I need an amplitude list of the audio...
[ "The default Python wave module isn't very thorough. You might try the one included in scipy as an alternative. \nCheck out: Reading *.wav files in Python\nIf you're going to do any numerical heavy lifting with the audio, scipy might be your best option anyway. \n", "I believe Python can read .dat files. You can...
[ 3, 2 ]
[]
[]
[ "amplitude", "fft", "frequency", "python", "wav" ]
stackoverflow_0004890619_amplitude_fft_frequency_python_wav.txt
Q: Floating point vs integer performance When developing a programming language, is distinguishing between ints and floats important? I noticed in the case of R that while they do allow for strict integer types, one mainly deals with numeric types which can be floats or ints. Are there performance benefits? Edit I'm ...
Floating point vs integer performance
When developing a programming language, is distinguishing between ints and floats important? I noticed in the case of R that while they do allow for strict integer types, one mainly deals with numeric types which can be floats or ints. Are there performance benefits? Edit I'm also interested in learning more about when...
[ "If you're talking about performance: For most purposes, there is no performance difference. You can probably still measure one in purely number-crunching code compiled to machine code, and for slightly less math-intense code on hardware that doesn't have a dedicated FPU (i.e. mostly embedded stuff). But for Python...
[ 4 ]
[]
[]
[ "double", "floating_point", "integer", "python" ]
stackoverflow_0007154101_double_floating_point_integer_python.txt
Q: python Help with calculating the average and std on excel files im trying to calculate the average and std for x, y, and z column for about 50 excel files that i saved in a folder. each excel files has x values in the first column, y in the second, and z in the third column. im using this script, but it kept givin...
python Help with calculating the average and std on excel files
im trying to calculate the average and std for x, y, and z column for about 50 excel files that i saved in a folder. each excel files has x values in the first column, y in the second, and z in the third column. im using this script, but it kept giving me error. All the files are saved as ".xls". please help and if you...
[ "Do it step by step to verify that you are able to read something from the xls-files. Use the hardcoded absolute path to the file. BTW, code looks ok (as far as I can tell) Error is probably in the xls-file...\nSomething like:\nimport xlrd\nwb = xlrd.open_workbook('myworkbook.xls')\n\n#Get the first sheet either b...
[ 0, 0 ]
[]
[]
[ "python", "xlrd" ]
stackoverflow_0007152286_python_xlrd.txt
Q: How can I set a true/false variable with if? It's kinda hard to explain, but I will try my best. I have this part on my code def hideConsole(): hideConsole = win32console.GetConsoleWindow() win32gui.ShowWindow(hideConsole, 0) which hides the console, and I have this part to enable it def onKeyboardEvent(e...
How can I set a true/false variable with if?
It's kinda hard to explain, but I will try my best. I have this part on my code def hideConsole(): hideConsole = win32console.GetConsoleWindow() win32gui.ShowWindow(hideConsole, 0) which hides the console, and I have this part to enable it def onKeyboardEvent(event): if event.KeyID == 192 and event.Alt == ...
[ "With a boolean variable, something like this:\nclass Console(object):\n def __init__(self):\n self.is_hidden = False\n self.handle = win32console.GetConsoleWindow()\n\n def toggle(self):\n win32gui.ShowWindow(self.handle, 1 if self.is_hidden else 0)\n self.is_hidden = not self....
[ 1, 1, 0, 0, 0 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0007154171_python_windows.txt
Q: How to use interpolation to calculate a force based on angle I am trying to make a python script that will output a force based on a measured angle. The inputs are time, the curve and the angle, but I am having trouble using interpolation to fit the force to the curve. I looked at scipy.interpolate, but I'm not su...
How to use interpolation to calculate a force based on angle
I am trying to make a python script that will output a force based on a measured angle. The inputs are time, the curve and the angle, but I am having trouble using interpolation to fit the force to the curve. I looked at scipy.interpolate, but I'm not sure it will help me because the points aren't evenly spaced.
[ "numpy.interp does not require your points to be evenly distributed. I'm not certain if you mean by \"The inputs are time, the curve and the angle\" that you have three independent variables, if so you will have to adapt it quite a bit... But for one-variable problems, interp is the way to go.\n" ]
[ 0 ]
[]
[]
[ "angle", "curve", "interpolation", "python" ]
stackoverflow_0007151354_angle_curve_interpolation_python.txt
Q: Savetxt file for images properties in a loop in python I create a program that calculates number os pixels of certain value of temperature in a Satellite image. I used: for infile in glob.glob(*.tif) for open all .tif images in a loop.The program is working fine, and print in the terminal de name and de pixels ...
Savetxt file for images properties in a loop in python
I create a program that calculates number os pixels of certain value of temperature in a Satellite image. I used: for infile in glob.glob(*.tif) for open all .tif images in a loop.The program is working fine, and print in the terminal de name and de pixels number of all images. But when i use: np.savetxt("pixels.txt...
[ "As agf notes, there isn't any error as such in the few lines you've provided, but from your description I think you are calling np.savetxt for each image? If so, you'll overwrite pixels.txt on each pass. You want to either store all the data in some temporary list and write it at the end:\npixeldata = []\nfor inf...
[ 0 ]
[]
[]
[ "image", "python" ]
stackoverflow_0007148632_image_python.txt
Q: How can search the files that I'm returning below In this code below, I'm using Paramiko to login remotely to an embedded site server and retrieve all .log and .txt files and place them in a folder on my local machine to search for potential pin # that may be in the clear. In the second piece of code, this is part...
How can search the files that I'm returning below
In this code below, I'm using Paramiko to login remotely to an embedded site server and retrieve all .log and .txt files and place them in a folder on my local machine to search for potential pin # that may be in the clear. In the second piece of code, this is part of a script that can unzip .tgz files and perform sear...
[ "paramiko has inbuilt classes that do exactly what you're trying to do in your first code section.\napath = '/'\napattern = '\"*.txt\" -o -name \"*.log\"' \nrawcommand = 'find {path} -name \"*.txt\" -o -name \"*.log\"' #{pattern}\ncommand = rawcommand.format(path=apath, pattern=apattern)\nstdin, stdout, stderr = ss...
[ 0, 0 ]
[]
[]
[ "paramiko", "python" ]
stackoverflow_0007152042_paramiko_python.txt
Q: Python Django byte string from database printing as string I have the following byte string inside a database field: "G\xb0A\x12C\xa4\xf3@\x03/|\xda\x86\x15\x92\x11\x08\xe4?\xd23\xd5<\x90\xf1\xab\x1a\xe5\xae\x15;\xef\x98\x93\xf8\x14\x85\x08Fw\x18fn\x97\xca\x84\xc6\xaf\'\xedm\xf2B\x8c\x10\xd7+\xbeM\x9e\xe7\xc6;\x98...
Python Django byte string from database printing as string
I have the following byte string inside a database field: "G\xb0A\x12C\xa4\xf3@\x03/|\xda\x86\x15\x92\x11\x08\xe4?\xd23\xd5<\x90\xf1\xab\x1a\xe5\xae\x15;\xef\x98\x93\xf8\x14\x85\x08Fw\x18fn\x97\xca\x84\xc6\xaf\'\xedm\xf2B\x8c\x10\xd7+\xbeM\x9e\xe7\xc6;\x98P\xc6\t\xb3\xef\x0b\x87\xa6\x0fd\xf9J\xea=\x03a\xb5\x19\xff{X\x1...
[ "I'm guessing this is the difference between str() and repr().\n", "If the data has structure you can use struct\nOr you can use xdrlib\n" ]
[ 2, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007154204_django_python.txt
Q: How do I retrieve objects linked through Django generic relations and determine their types? Here is my models.py: class Player(models.Model): name = models.CharField(max_length=100) #...fields... comment = models.generic.GenericRelation(Comment) class Game(models.Model): name = models.CharFiel...
How do I retrieve objects linked through Django generic relations and determine their types?
Here is my models.py: class Player(models.Model): name = models.CharField(max_length=100) #...fields... comment = models.generic.GenericRelation(Comment) class Game(models.Model): name = models.CharField(max_length=100) #...other fields... comment = models.generic.GenericRelation(Comment) ...
[ "The documentation for generic relations in Django can be found here https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#generic-relations\nYou should be able to access the content_object like so:\nlinked_object = CommentInstance.content_object\n\nIf you want to find out the what sort of object this is,...
[ 3 ]
[]
[]
[ "database", "django", "django_models", "foreign_key_relationship", "python" ]
stackoverflow_0007019028_database_django_django_models_foreign_key_relationship_python.txt
Q: How do I remove entries within a Counter object with a loop without invoking a RuntimeError? from collections import * ignore = ['the','a','if','in','it','of','or'] ArtofWarCounter = Counter(ArtofWarLIST) for word in ArtofWarCounter: if word in ignore: del ArtofWarCounter[word] ArtofWarCounter is a Co...
How do I remove entries within a Counter object with a loop without invoking a RuntimeError?
from collections import * ignore = ['the','a','if','in','it','of','or'] ArtofWarCounter = Counter(ArtofWarLIST) for word in ArtofWarCounter: if word in ignore: del ArtofWarCounter[word] ArtofWarCounter is a Counter object containing all the words from the Art of War. I'm trying to have words in ignore dele...
[ "Don't loop over all words of a dict to find a entry, dicts are much better at lookups. \nYou loop over the ignore list and remove the entries that exist:\nignore = ['the','a','if','in','it','of','or']\nfor word in ignore:\n if word in ArtofWarCounter:\n del ArtofWarCounter[word]\n\n", "For minimal code...
[ 19, 18, 1 ]
[ "Use a counter, traverse the loop backwards (last to first), remove as needed. Loop until zero.\n" ]
[ -2 ]
[ "collections", "containers", "counter", "python" ]
stackoverflow_0007154312_collections_containers_counter_python.txt
Q: Is it possible get all context nodes used to evalute xpath result? Is it possible get all context nodes used to evalute xpath result ? In below code: test_xml = """ <r> <a/> <a> <b/> </a> <a> <b/> </a> </r> """ test_root = lxml.etree.fromstring(test_xml) res = test_root.xpath("/...
Is it possible get all context nodes used to evalute xpath result?
Is it possible get all context nodes used to evalute xpath result ? In below code: test_xml = """ <r> <a/> <a> <b/> </a> <a> <b/> </a> </r> """ test_root = lxml.etree.fromstring(test_xml) res = test_root.xpath("//following-sibling::*[1]/b") for node in res: print test_root.getroo...
[ "I reversed the xpath for each stage to get which items would be evaluated in the result:\nfor node in res:\n j = node.xpath('./parent::*')[0]\n k = j.xpath('./preceding-sibling::*[1]')[0]\n # You didn't specify these but they were used in the evaluation\n ancestors = k.xpath('./ancestor::*')\n for i...
[ 1, 0 ]
[]
[]
[ "lxml", "python", "xpath" ]
stackoverflow_0002133527_lxml_python_xpath.txt
Q: How to include page in PDF in PDF document in Python I am using reportlab toolkit in Python to generate some reports in PDF format. I want to use some predefined parts of documents already published in PDF format to be included in generated PDF file. Is it possible (and how) to accomplish this in reportlab or in p...
How to include page in PDF in PDF document in Python
I am using reportlab toolkit in Python to generate some reports in PDF format. I want to use some predefined parts of documents already published in PDF format to be included in generated PDF file. Is it possible (and how) to accomplish this in reportlab or in python library? I know I can use some other tools like PDF ...
[ "I'm currently using PyPDF to read, write, and combine existing PDF's and ReportLab to generate new content. Using the two package seemed to work better than any single package I was able to find.\n", "If you want to place existing PDF pages in your Reportlab documents I recommend pdfrw. Unlike PageCatcher it is...
[ 6, 2, 1 ]
[]
[]
[ "pdf", "pdf_generation", "python", "reportlab" ]
stackoverflow_0000673288_pdf_pdf_generation_python_reportlab.txt
Q: matplotlib slider redraw does not update figtext I used sliders in matplotlib to update a few graphs based on GUI input. All my graphs update well. But when I use figtext, I have the problem that the updated text will write over the existing one. import numpy as np import pylab as p from matplotlib.widgets import...
matplotlib slider redraw does not update figtext
I used sliders in matplotlib to update a few graphs based on GUI input. All my graphs update well. But when I use figtext, I have the problem that the updated text will write over the existing one. import numpy as np import pylab as p from matplotlib.widgets import Slider p.subplot(111) x = np.arange(0,500,1) f = np...
[ "Every time you call p.figtext(0.5, 0.65, str(slider1.val)) you are creating a new Text object which is being written on top of the previous ones. What you should do is save a reference to the first Text object and update its contents by calling its set_text() method. I have updated your code with a working exampl...
[ 4 ]
[]
[]
[ "matplotlib", "python", "slider" ]
stackoverflow_0007153969_matplotlib_python_slider.txt
Q: equivalent connection for postgres and sqlite Is there an equivalent way to connect to a postgres database in a similar way that sqlite connects to a database using python? For example, in sqlite, a connection will be defined by conn = sqlite3.connect(curruser.dbname). What is the similar connection syntax for pos...
equivalent connection for postgres and sqlite
Is there an equivalent way to connect to a postgres database in a similar way that sqlite connects to a database using python? For example, in sqlite, a connection will be defined by conn = sqlite3.connect(curruser.dbname). What is the similar connection syntax for postgres?
[ "You can use the psycopg connector then, and the connection syntax will be similar, except that you'll need to specify some more information in a connection string:\nconn_string = \"host='localhost' dbname='my_database' user='postgres' password='secret'\"\nconn = psycopg2.connect(conn_string)\n\nHere are some examp...
[ 6 ]
[]
[]
[ "postgresql", "python", "sqlite" ]
stackoverflow_0007155069_postgresql_python_sqlite.txt
Q: How can I highlight regex matches in Python? How might I highlight the matches in regex in the sentence? I figure that I could use the locations of the matches like I would get from this: s = "This is a sentence where I talk about interesting stuff like sencha tea." spans = [m.span() for m in re.finditer(r'sen\w+'...
How can I highlight regex matches in Python?
How might I highlight the matches in regex in the sentence? I figure that I could use the locations of the matches like I would get from this: s = "This is a sentence where I talk about interesting stuff like sencha tea." spans = [m.span() for m in re.finditer(r'sen\w+', s)] But how do I force the terminal to change t...
[ "There are several terminal color packages available such as termstyle or termcolor. I like colorama, which works on Windows as well.\nHere's an example of doing what you want with colorama:\nfrom colorama import init, Fore\nimport re\n\ninit() # only necessary on Windows\ns = \"This is a sentence where I talk abo...
[ 14, 4 ]
[]
[]
[ "editor", "python" ]
stackoverflow_0007154972_editor_python.txt
Q: Applying SVD throws a Memory Error instantaneously? I am trying to apply SVD on my matrix (3241 x 12596) that was obtained after some text processing (with the ultimate goal of performing Latent Semantic Analysis) and I am unable to understand why this is happening as my 64-bit machine has 16GB RAM. The moment svd...
Applying SVD throws a Memory Error instantaneously?
I am trying to apply SVD on my matrix (3241 x 12596) that was obtained after some text processing (with the ultimate goal of performing Latent Semantic Analysis) and I am unable to understand why this is happening as my 64-bit machine has 16GB RAM. The moment svd(self.A) is called, it throws an error. The precise error...
[ "Yes, the full_matrices parameter to scipy.linalg.svd is important: your input is highly rank-deficient (rank max 3,241), so you don't want to allocate the entire 12,596 x 12,596 matrix for V!\nMore importantly, matrices coming from text processing are likely very sparse. The scipy.linalg.svd is dense and doesn't o...
[ 12, 2 ]
[]
[]
[ "memory", "nlp", "numpy", "python", "scipy" ]
stackoverflow_0007143723_memory_nlp_numpy_python_scipy.txt
Q: What's a good way to examine audio with python and split it between high, mid and low pitches for visualizaton? So, I'm planning on trying out making a light organ with an Arduino and Python, communicating over serial to control the brightness of several LEDs. The computer will use the microphone or a playing MP3...
What's a good way to examine audio with python and split it between high, mid and low pitches for visualizaton?
So, I'm planning on trying out making a light organ with an Arduino and Python, communicating over serial to control the brightness of several LEDs. The computer will use the microphone or a playing MP3 to generate the data. I'm not so sure how to handle the audio processing. What's a good option for python that can ...
[ "If you're not committed to using Python, you should also look at using PureData (PD) to handle the audio analysis. Interfacing PD to the Arduino is already a solved problem, and there are a lot of pre-existing components that make working with audio easy.\n", "Try http://wiki.python.org/moin/Audio for links to v...
[ 1, 0, 0 ]
[]
[]
[ "audio", "python" ]
stackoverflow_0007154280_audio_python.txt
Q: Matching a simple string using Regex? If I have a string like this: *select 65* description How could I extract the bit after the asterisk and the number using regex in Python? I need something that would yield select and 65 from the above string. All of them follow this convention: *[lowercase specifier] [integ...
Matching a simple string using Regex?
If I have a string like this: *select 65* description How could I extract the bit after the asterisk and the number using regex in Python? I need something that would yield select and 65 from the above string. All of them follow this convention: *[lowercase specifier] [integer]* description
[ "You could use this regular expression:\n^\\*([a-z]+)\\s+([0-9]+)\\*\n\nIn Python, you can match regular expressions with the re module. Thus:\nimport re\n\nmy_string = \"\"\"*select 65* description\"\"\"\nmatch = re.match(r\"^\\*([a-z]+)\\s+([0-9]+)\\*\", my_string)\nspecifier = match.group(1)\ninteger = int(match...
[ 4, 1, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007155152_python_regex.txt
Q: How to create comparison tables in Python I want to generate comparison tables like this by using Python. alt text http://img714.imageshack.us/img714/5677/22862352.png Can you suggest any library to do this? A: That's surely the output of TeX. It would take all of 60 minutes to learn enough TeX (or, better yet...
How to create comparison tables in Python
I want to generate comparison tables like this by using Python. alt text http://img714.imageshack.us/img714/5677/22862352.png Can you suggest any library to do this?
[ "That's surely the output of TeX. It would take all of 60 minutes to learn enough TeX (or, better yet, LaTeX) to spit out tables like that.\n", "Reportlab has some great tools for creating and formatting tables. The only drawback from your perspective is that it outputs to PDF, so you would need an intermediate s...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002308561_python.txt
Q: Python: Passing socket by reference I am new to python and I am having to code my 1st task in python. I promise that I will learn it inside out after I finish this but I need your help now. My code is currently looks like this: comSocket.send("\r") sleep(1) comSocket.send("\r") sleep(2) comSocket.settimeout(8) try...
Python: Passing socket by reference
I am new to python and I am having to code my 1st task in python. I promise that I will learn it inside out after I finish this but I need your help now. My code is currently looks like this: comSocket.send("\r") sleep(1) comSocket.send("\r") sleep(2) comSocket.settimeout(8) try: comSocket.recv(256) except socket.ti...
[ "A guess at what you're trying for:\ndef send_and_receive(message, socket):\n socket.send(message)\n return socket.recv(256) # number is timeout\n\nthen put your try:except: around your call to this method.\n", "A simple solution would be\ndef socketCom(comSocket, length, message, time):\n comSocket.send...
[ 3, 2, 1 ]
[]
[]
[ "python", "scope", "sockets" ]
stackoverflow_0006666798_python_scope_sockets.txt
Q: Server Topology Help - Django and Twisted Possibility? I am currently working on a complex web interface and backend, that will need to address several issues. Scalablility multiple deployments of varying load demands Very structured authorization groups Different views for different user groups admin panel ...
Server Topology Help - Django and Twisted Possibility?
I am currently working on a complex web interface and backend, that will need to address several issues. Scalablility multiple deployments of varying load demands Very structured authorization groups Different views for different user groups admin panel user/content management Large managed database current ...
[ "You can definitely use Twisted with Django. Several projects have used the two together to good effect. twistd web --wsgi provides a basic way to get it set up, and there's a great example with more bells and whistles, like static content by Alex Clemesha on github.\n" ]
[ 1 ]
[]
[]
[ "django", "python", "twisted", "web_applications" ]
stackoverflow_0007155031_django_python_twisted_web_applications.txt
Q: python struct unpack into a dict struct.unpack will unpack data into a tuple. Is there an equivalent that will store data into a dict instead? In my particular problem, I am dealing with a fixed-width binary format. I want to be able, in one fell swoop, to unpack and store the values in a dict (currently I manua...
python struct unpack into a dict
struct.unpack will unpack data into a tuple. Is there an equivalent that will store data into a dict instead? In my particular problem, I am dealing with a fixed-width binary format. I want to be able, in one fell swoop, to unpack and store the values in a dict (currently I manually walk through the list and assign d...
[ "If you're on 2.6 or newer you can use namedtuple + struct.pack/unpack like this:\nimport collections\nimport struct\n\nPoint = collections.namedtuple(\"Point\", \"x y z\")\n\ndata = Point(x=1, y=2, z=3)\n\npacked_data = struct.pack(\"hhh\", *data)\ndata = Point(*struct.unpack(\"hhh\", packed_data))\n\nprint data.x...
[ 10, 8, 6 ]
[]
[]
[ "python", "unpack" ]
stackoverflow_0007155447_python_unpack.txt
Q: NumPy: Find sorted indices from a masked 2D array above and below a threshold I have a 2D masked array of values that I need to sort from lowest to highest. For example: import numpy as np # Make a random masked array >>> ar = np.ma.array(np.round(np.random.normal(50, 10, 20), 1), mask=np.ran...
NumPy: Find sorted indices from a masked 2D array above and below a threshold
I have a 2D masked array of values that I need to sort from lowest to highest. For example: import numpy as np # Make a random masked array >>> ar = np.ma.array(np.round(np.random.normal(50, 10, 20), 1), mask=np.random.binomial(1, .2, 20)).reshape((4,5)) >>> print(ar) [[-- 51.9 38.3 46.8 43.3] [5...
[ "to use where:\nimport numpy as np\nnp.random.seed(0)\n# Make a random masked array\nar = np.ma.array(np.round(np.random.normal(50, 10, 20), 1),\n mask=np.random.binomial(1, .2, 20)).reshape((4,5))\n# Sort the array from lowest to highest, with a flattened index\nsorted_ind = ar.argsort(axis=Non...
[ 5, 3 ]
[]
[]
[ "indices", "numpy", "python" ]
stackoverflow_0007154979_indices_numpy_python.txt
Q: How can I get an array of alternating values in python? Simple question here: I'm trying to get an array that alternates values (1, -1, 1, -1.....) for a given length. np.repeat just gives me (1, 1, 1, 1,-1, -1,-1, -1). Thoughts? A: I like @Benjamin's solution. An alternative though is: import numpy as np a ...
How can I get an array of alternating values in python?
Simple question here: I'm trying to get an array that alternates values (1, -1, 1, -1.....) for a given length. np.repeat just gives me (1, 1, 1, 1,-1, -1,-1, -1). Thoughts?
[ "I like @Benjamin's solution. An alternative though is:\nimport numpy as np\na = np.empty((15,))\na[::2] = 1\na[1::2] = -1\n\nThis also allows for odd-length lists.\nEDIT: Also just to note speeds, for a array of 10000 elements\nimport numpy as np\nfrom timeit import Timer\n\nif __name__ == '__main__':\n\n setup...
[ 27, 16, 7, 6, 5, 3, 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0007154739_numpy_python.txt
Q: how to get entities which don't have certain attribute in datastore I'm trying to make an appraisal system This is my class class Goal(db.Expando): GID = db.IntegerProperty(required=True) description = db.TextProperty(required=True) time = db.FloatProperty(required=True) weight = db.IntegerProperty(require...
how to get entities which don't have certain attribute in datastore
I'm trying to make an appraisal system This is my class class Goal(db.Expando): GID = db.IntegerProperty(required=True) description = db.TextProperty(required=True) time = db.FloatProperty(required=True) weight = db.IntegerProperty(required=True) Emp = db.UserProperty(auto_current_user=True) Status = db.Boo...
[ "You explicitly can't do this. As the documentation states:\n\nIt is not possible to query for entities that are missing a given property.\n\nInstead, create a property for is_assessed which defaults to False, and query on that.\n", "could you not simply add another field for when employee_assessed = db.user...\n...
[ 4, 0, 0 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0007146335_google_app_engine_google_cloud_datastore_python.txt
Q: Numbered paragraphs with reportlab I'm trying to use reportlab, but I'm finding the user guide not clear enough.. (maybe it's just me) I have the following code for item in content: text = item.name p = Paragraph(text,style,'*') and it renders exactly as expected. But what if I want numbering in...
Numbered paragraphs with reportlab
I'm trying to use reportlab, but I'm finding the user guide not clear enough.. (maybe it's just me) I have the following code for item in content: text = item.name p = Paragraph(text,style,'*') and it renders exactly as expected. But what if I want numbering instead of bullets? The user guide is real...
[ "The User Guide has a part on this. If I understand correctly, you have to use a <seq/> tag instead of a bullet point for trivial numbering (each occurance counts one up). For more complex numbering see pages 73/74.\nExample, as far as I understand, you put things like <b> </b> for bold textand <seq/> inline:\nfrom...
[ 2, 1 ]
[]
[]
[ "pdf_generation", "python", "reportlab" ]
stackoverflow_0004272153_pdf_generation_python_reportlab.txt
Q: Help calculating Avg and std for excel files saved as CSV I have about 20 excel files saved as CSV in a single folder. Each excel file has numbers saved in the first, second and third columns. I was trying to read the first column for all of the files, second column for all of the file, and third column for all of...
Help calculating Avg and std for excel files saved as CSV
I have about 20 excel files saved as CSV in a single folder. Each excel file has numbers saved in the first, second and third columns. I was trying to read the first column for all of the files, second column for all of the file, and third column for all of the files using CSV module in python, and calulate the average...
[ "A list comprehension works kinda like a backwards for-loop that automatically constructs a list for you. If you nest these with the \"columns\" on the inside and the \"rows\" on the outside you should get a matrix thingy (nested list structure): \nnums = [[int(val) for val in line.split(',')] for line in my_file.r...
[ 2 ]
[]
[]
[ "csv", "python", "python_3.x", "statistics" ]
stackoverflow_0007155930_csv_python_python_3.x_statistics.txt
Q: PyGTK, wxPython or Tkinter? I'm starting to develop interfaces for my python applications , but I've seen that there are diferents tools to do it, so I would like to know which could be the best, I need something, easy, portable and pretty results. I hope that you can help me. A: Pick the one you like, there's ...
PyGTK, wxPython or Tkinter?
I'm starting to develop interfaces for my python applications , but I've seen that there are diferents tools to do it, so I would like to know which could be the best, I need something, easy, portable and pretty results. I hope that you can help me.
[ "Pick the one you like, there's no \"the best\" here.\nPersonally I like PyQt4, because I like QT4, and py2exe works perfectly fine with it, wxPython is another good thing, but it does not work very well under Windows, see my question here: wx.App (wxPython) crash when calling\nYou can check some application develo...
[ 1, 1 ]
[]
[]
[ "pygtk", "python", "tkinter", "user_interface", "wxpython" ]
stackoverflow_0007156002_pygtk_python_tkinter_user_interface_wxpython.txt
Q: Table-column addressing in Python Often I select data from a SQLite database into a list of dictionaries using something like: conn.row_factory = sqlite3.Row c = conn.cursor() selection = c.execute('select * from myTable') dataset = selection.fetchall() dataset1 = [dict(row) for row in dataset] However, given my ...
Table-column addressing in Python
Often I select data from a SQLite database into a list of dictionaries using something like: conn.row_factory = sqlite3.Row c = conn.cursor() selection = c.execute('select * from myTable') dataset = selection.fetchall() dataset1 = [dict(row) for row in dataset] However, given my database background (Foxpro, SQL-server...
[ "I fought the row['column'] syntax for a while, but in the end I prefer it. It has two distinct advantages:\n\nrow['class'] is correct syntax, but row.class is not; keywords cannot directly be used as property names.\nAnd, more generally, if you ever craft a query whose column names are not valid property names (t...
[ 2 ]
[]
[]
[ "database", "python", "sqlite" ]
stackoverflow_0007156153_database_python_sqlite.txt
Q: pygtk how to embed external application within my pygtk GUI I'm desiging a pygtk GUI and want to embed an external application into it. Does anyone have any idea how this can be done? A: It depends on what application you are trying to embed into yours, but if the other app is a GTK app (or one that supports the...
pygtk how to embed external application within my pygtk GUI
I'm desiging a pygtk GUI and want to embed an external application into it. Does anyone have any idea how this can be done?
[ "It depends on what application you are trying to embed into yours, but if the other app is a GTK app (or one that supports the XEMBED protocol), you should be able to do this with gtk.Plug and gtk.Socket. The PyGTK tutorial has a section explaining how to do this:\nhttp://www.pygtk.org/pygtk2tutorial/sec-PlugsAndS...
[ 4, 3, 1, 0 ]
[]
[]
[ "embedding", "pygtk", "python" ]
stackoverflow_0002023698_embedding_pygtk_python.txt
Q: How to read and write to a python program through vb.net I am currently making a GUI for Minecraft Coder Pack. MCP works off a system of batch files that launch python programs. I want to be able to read and write to these cmd windows throught vb.net. So that I can tell when a process has finished or to answer a y...
How to read and write to a python program through vb.net
I am currently making a GUI for Minecraft Coder Pack. MCP works off a system of batch files that launch python programs. I want to be able to read and write to these cmd windows throught vb.net. So that I can tell when a process has finished or to answer a yes, no question i nthe python program, with a gui from vb.net ...
[ "You may be able to write from vb.net to a text file (input.txt, for example), then use \"<\" to use input.txt for input on the command line and \">\" to send the command line output to another file (output.txt, for example). Then you can read output.txt from vb.net.\nruntime\\bin\\python\\python_mcp zruntime\\clea...
[ 0 ]
[]
[]
[ ".net", "python", "vb.net" ]
stackoverflow_0007011646_.net_python_vb.net.txt
Q: Python filter for postfix I am trying to make a simple Python filter for postfix, to add in a 'Reply-to' header to certain messages. What I've done so far is to take the email from stdin, and parse it into an email object like so: raw = sys.stdin.readlines() msg = email.message_from_string(''.join(raw)) Then I've...
Python filter for postfix
I am trying to make a simple Python filter for postfix, to add in a 'Reply-to' header to certain messages. What I've done so far is to take the email from stdin, and parse it into an email object like so: raw = sys.stdin.readlines() msg = email.message_from_string(''.join(raw)) Then I've played with headers etc. msg.a...
[ "You should be able to use both methods, but smtplib.SMTP() is more flexible and makes the error handling easier. \nIf you need an example, have a look at my framework for python filters:\nhttps://github.com/gryphius/fuglu/blob/master/fuglu/src/fuglu/connectors/smtpconnector.py#L67\nthe re_inject method does exactl...
[ 4 ]
[]
[]
[ "email", "filter", "postfix_mta", "python" ]
stackoverflow_0007153411_email_filter_postfix_mta_python.txt
Q: Tokenizing complex input I'm attempting to tokenize the following input in Python: text = 'This @example@ is "neither":/defn/neither complete[1] *nor* trite, *though _simple_*.' I would like to produce something like the following while avoiding use of the regular expressions: tokens = [ ('text', 'This ')...
Tokenizing complex input
I'm attempting to tokenize the following input in Python: text = 'This @example@ is "neither":/defn/neither complete[1] *nor* trite, *though _simple_*.' I would like to produce something like the following while avoiding use of the regular expressions: tokens = [ ('text', 'This '), ('enter', 'code'), ...
[ "Well, here's a more complete parser with sufficient extensibility to do whatever I may need in the future. It only took three hours. It's not terribly speedy, but generally the output of the class of parser I'm writing is heavily cached anyway. Even with this tokenizer and parser in place, my full engine still ...
[ 1 ]
[]
[]
[ "parsing", "python", "stream", "text", "tokenize" ]
stackoverflow_0007142934_parsing_python_stream_text_tokenize.txt
Q: python - How to transform a html file into a human-readable txt file? I have a lot of html files look like this: <font face="Garmond,Helvetica,Times" size="2" color="#330066"> <b> Summary: </b> &nbsp;According to the complaint filed January 04, 2011, over a six-week period in December 2007 and January 2008, six h...
python - How to transform a html file into a human-readable txt file?
I have a lot of html files look like this: <font face="Garmond,Helvetica,Times" size="2" color="#330066"> <b> Summary: </b> &nbsp;According to the complaint filed January 04, 2011, over a six-week period in December 2007 and January 2008, six healthcare related hedge funds managed by Defendant FrontPoint Partners LLC ...
[ "You can use Scrapely.\n\nScrapely is a library for extracting structured data from HTML pages. Given some example web pages and the data to be extracted, scrapely constructs a parser for all similar pages.\n\nhttp://github.com/scrapy/scrapely\n", "To accomplish this task, you can use the help of a Python library...
[ 3, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007155881_python.txt
Q: Wildcard not working in subprocess call using shlex Language: Python v2.6.2 OS: AIX 5.3 I'm using Python to restore some files from a backup to a test system - all commands are called in the manner below, however some just plain don't want to work. #!/usr/bin/python import subprocess, shlex cmd = 'sudo rm -rf /wo...
Wildcard not working in subprocess call using shlex
Language: Python v2.6.2 OS: AIX 5.3 I'm using Python to restore some files from a backup to a test system - all commands are called in the manner below, however some just plain don't want to work. #!/usr/bin/python import subprocess, shlex cmd = 'sudo rm -rf /work/TEST/*' arg = shlex.split(cmd) # This does not work p...
[ "For replacing the * with what it means, you either need the shell or you need the glob module. So the easiest way would be shell=True (if the command is constant, I do not see any security holes).\nAnother approach would be\n#!/usr/bin/python\nimport subprocess\nimport shlex\nimport glob\n\ncmd = 'sudo rm -rf /wor...
[ 4 ]
[]
[]
[ "python", "shlex", "subprocess" ]
stackoverflow_0007156892_python_shlex_subprocess.txt
Q: How to install Python for Apache on Windows? I'm looking for the fast, easy (all default settings) way of installing Python on my windows machine so that Apache can use it. I currently have a Windows 7 installation with Apache and PHP working. I want to try and make some simple web pages in Python, just to play ar...
How to install Python for Apache on Windows?
I'm looking for the fast, easy (all default settings) way of installing Python on my windows machine so that Apache can use it. I currently have a Windows 7 installation with Apache and PHP working. I want to try and make some simple web pages in Python, just to play around with Python for a bit and learn a thing or tw...
[ "First of all, especially in the web sector it's better to stay with python 2 (2.7) for now. Lots of frameworks and libraries are not py3-ready yet.\nThen you might want to use mod_wsgi instead of mod_python which is deprecated and not available in binary form for recent python versions (and using old python versio...
[ 4, 3 ]
[]
[]
[ "apache", "python", "windows" ]
stackoverflow_0007157565_apache_python_windows.txt
Q: Renaming filenames using python I need to simply add the word "_Manual" onto the end of all the files i have in a specific directory Here is the script i am using at the moment - i have no experience with python so this script is a frankenstine of other scripts i had lying around! It doesn't give any error message...
Renaming filenames using python
I need to simply add the word "_Manual" onto the end of all the files i have in a specific directory Here is the script i am using at the moment - i have no experience with python so this script is a frankenstine of other scripts i had lying around! It doesn't give any error messages but it also doesnt work.. folder = ...
[ "os.rename requires a source and destination filename. The variable filename contains your current filename (e.g., \"something.txt\"), whereas your split separates that into something and txt. As the source file to rename, you then only specify something, which fails silently.\nInstead, you want to rename the file ...
[ 5, 4, 3, 0 ]
[]
[]
[ "python", "renaming" ]
stackoverflow_0007157340_python_renaming.txt
Q: Store django forms.MultipleChoiceField in Models directly Say I have choices defined as follows: choices = (('1','a'), ('2','b'), ('3','c')) And a form that renders and inputs these values in a MultipleChoiceField, class Form1(forms.Form): field = forms.MultipleChoiceField(choices=choice...
Store django forms.MultipleChoiceField in Models directly
Say I have choices defined as follows: choices = (('1','a'), ('2','b'), ('3','c')) And a form that renders and inputs these values in a MultipleChoiceField, class Form1(forms.Form): field = forms.MultipleChoiceField(choices=choices) What is the right way to store field in a model. I can of c...
[ "The first thing I would consider is better normalization of your database schema; if a single instance of your model can have multiple values for this field, the field perhaps should be a linked model with a ForeignKey instead.\nIf you're using Postgres, you could also use an ARRAY field; Django now has built-in s...
[ 11, 1 ]
[]
[]
[ "django", "django_forms", "django_models", "python" ]
stackoverflow_0001399622_django_django_forms_django_models_python.txt
Q: How to customize display url after jquery POST? I'm using Freebase Suggest, a JQuery search form: <script type="text/javascript"> $(function() { $("#game-search").suggest({type:'/games/game'}).bind("fb-select", function(e, data) { $("#game-id").val(data.id); $("#game-name").val(data.name); }); ...
How to customize display url after jquery POST?
I'm using Freebase Suggest, a JQuery search form: <script type="text/javascript"> $(function() { $("#game-search").suggest({type:'/games/game'}).bind("fb-select", function(e, data) { $("#game-id").val(data.id); $("#game-name").val(data.name); }); }); </script> <form name="input" action="/game" meth...
[ "first you should configure the app.yaml:\n- url: /game/(.*?)/(.*?)\nscript: game/yourgame.py\n\nthen in your yourgame.py redirect the post to permalink url:\nself.redirect('/game/your permalink url')\n\n" ]
[ 0 ]
[]
[]
[ "django", "freebase", "google_app_engine", "jquery", "python" ]
stackoverflow_0004731308_django_freebase_google_app_engine_jquery_python.txt
Q: Ruby Vs Python - Socket Libraries I have a concept I'd like to work on that requires the use of low-level sockets (i.e.: no frameworks or wrappers, just the standard send/recv pattern included in most standard libraries. I'm familiar with both Ruby and Python, and from my (limited) experience they seem to have si...
Ruby Vs Python - Socket Libraries
I have a concept I'd like to work on that requires the use of low-level sockets (i.e.: no frameworks or wrappers, just the standard send/recv pattern included in most standard libraries. I'm familiar with both Ruby and Python, and from my (limited) experience they seem to have similar socket libraries. What I'd like t...
[ "What a language you know better, that'll fit your needs.\n", "Both language offer a very thin wrapper above the underlying OS socket library. You won't get much difference. \n" ]
[ 0, 0 ]
[]
[]
[ "python", "ruby", "sockets", "tcp", "udp" ]
stackoverflow_0007156837_python_ruby_sockets_tcp_udp.txt
Q: matplotlib backends - do I care? >>> import matplotlib >>> print matplotlib.rcsetup.all_backends [u'GTK', u'GTKAgg', u'GTKCairo', u'MacOSX', u'Qt4Agg', u'Qt5Agg', u'TkAgg', u'WX', u'WXAgg', u'CocoaAgg', u'GTK3Cairo', u'GTK3Agg', u'WebAgg', u'nbAgg', u'agg', u'cairo', u'emf', u'gdk', u'pdf', u'pgf', u'ps', u'svg', ...
matplotlib backends - do I care?
>>> import matplotlib >>> print matplotlib.rcsetup.all_backends [u'GTK', u'GTKAgg', u'GTKCairo', u'MacOSX', u'Qt4Agg', u'Qt5Agg', u'TkAgg', u'WX', u'WXAgg', u'CocoaAgg', u'GTK3Cairo', u'GTK3Agg', u'WebAgg', u'nbAgg', u'agg', u'cairo', u'emf', u'gdk', u'pdf', u'pgf', u'ps', u'svg', u'template'] Look at all those backen...
[ "The backend mainly matters if you're embedding matplotlib in an application, in which case you need to use a backend (GTK, Qt, TkInter, WxWindows) which matches the toolkit you're using to build your application. If you're also using matplotlib in a simple interactive way, you'll also want to use a backend which m...
[ 51 ]
[]
[]
[ "backend", "matplotlib", "python" ]
stackoverflow_0007156058_backend_matplotlib_python.txt
Q: Installation of pygtk not working I am running on Windows (64bit version) and have python 2.7 (also 64 bit) installed. I downloaded the all-in-one installer for pygtk for python 2.7, but when I run it, it shows "python 2.7 could not be located on your system". Why is it so when I already have python 2.7 installed?...
Installation of pygtk not working
I am running on Windows (64bit version) and have python 2.7 (also 64 bit) installed. I downloaded the all-in-one installer for pygtk for python 2.7, but when I run it, it shows "python 2.7 could not be located on your system". Why is it so when I already have python 2.7 installed?
[ "Currently, the all-in-one installer binaries here are compiled against 32 bits python only. There is no 64 bits binary in there. Install python 2.7 32 bits on your windows and it should work.\nAlternatively, you could grab a C compiler, and then try to compile the installer sources. That's a lot harder though.\n",...
[ 10, 1 ]
[]
[]
[ "64_bit", "installation", "pygtk", "python" ]
stackoverflow_0005401864_64_bit_installation_pygtk_python.txt
Q: Why does qwt-5.2 think I don't have QtSvg for x86_64 installed? I'm trying to build Quantum GIS from source but am running into a problem with one of the dependencies. I need to make and install PyQwt and am getting the following compilation error: $ make g++ -headerpad_max_install_names -single_module -dynamiclib...
Why does qwt-5.2 think I don't have QtSvg for x86_64 installed?
I'm trying to build Quantum GIS from source but am running into a problem with one of the dependencies. I need to make and install PyQwt and am getting the following compilation error: $ make g++ -headerpad_max_install_names -single_module -dynamiclib -o libqwt_designer_plugin.dylib obj/qwt_designer_plugin.o obj/qwt_de...
[ "Not sure it's the answer, but it looks on your link line that you don't have the QtSvg framework.\nHave your tried adding -framework QtSvg on your link command ? \n" ]
[ 0 ]
[]
[]
[ "macos", "python", "qgis", "qt" ]
stackoverflow_0006990836_macos_python_qgis_qt.txt
Q: Diagonal stacking in numpy? So numpy has some convenience functions for combining several arrays into one, e.g. hstack and vstack. I'm wondering if there's something similar but for stacking the component arrays diagonally? Say I have N arrays of shape (n_i, m_i), and I want to combine them into a single array of ...
Diagonal stacking in numpy?
So numpy has some convenience functions for combining several arrays into one, e.g. hstack and vstack. I'm wondering if there's something similar but for stacking the component arrays diagonally? Say I have N arrays of shape (n_i, m_i), and I want to combine them into a single array of size (sum_{1,N}n_i, sum_{1,N}m_i)...
[ "It does seem block_diag does exactly what you want. So if for some reason you can't update scipy, then here is the source from v0.8.0 if you wish to simply define it!\nimport numpy as np\n\ndef block_diag(*arrs):\n \"\"\"Create a block diagonal matrix from the provided arrays.\n\n Given the inputs `A`, `B` ...
[ 12 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0007158098_numpy_python.txt
Q: Running Python scripts from Perl scripts I have a complex state machine in Perl which would be call the perl library module supporting different functionality. Each of the library modules are called sequentially based on state machine in perl. But now I have one of the library module (consisting of many API) in py...
Running Python scripts from Perl scripts
I have a complex state machine in Perl which would be call the perl library module supporting different functionality. Each of the library modules are called sequentially based on state machine in perl. But now I have one of the library module (consisting of many API) in python scripts which is needs to be called from ...
[ "There is an Inline::Python on CPAN, but personally I have been unable to get that to work. Other than that, you can't. You will need to create a wrapper script (in Python) which does the calls you need and call that as a separate process. Depending on how the app is structured, you might have to pass data throu...
[ 1 ]
[]
[]
[ "perl", "python" ]
stackoverflow_0007156524_perl_python.txt
Q: django media path problem I am having some problems in figuring out the media path problem in django. In the settings.py file, I have ADMIN_MEDIA_PREFIX = '/media/admin/'. So certain css and js files like forms.css,RelatedObjectLookup.js files are having the path like this /media/admin/js/admin/RelatedObjectLookup...
django media path problem
I am having some problems in figuring out the media path problem in django. In the settings.py file, I have ADMIN_MEDIA_PREFIX = '/media/admin/'. So certain css and js files like forms.css,RelatedObjectLookup.js files are having the path like this /media/admin/js/admin/RelatedObjectLookup.js and /media/admin/css/forms...
[ "Have a look at the AdminMediaHandler that is used by the runserver command. As you can see, the AdminMediaHandler doesn't log anything.\n", "The ADMIN_MEDIA_PREFIX is an URL path. If you are running the server with runserver, Django's server takes care of resolving requests to http://localhost/media/admin/whatev...
[ 2, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007158204_django_python.txt
Q: What's best Python open source library to draw chart? What's best open source library in Python to draw chart/diagram? 2D is necessary, and 3D is good if provided together. and it has to accept simple input data format like csv. I googled one called: matplotlib, how is it and any others? It should be best in term...
What's best Python open source library to draw chart?
What's best open source library in Python to draw chart/diagram? 2D is necessary, and 3D is good if provided together. and it has to accept simple input data format like csv. I googled one called: matplotlib, how is it and any others? It should be best in terms of the reliability, performance, simple use and easy inte...
[ "From the official python wiki:\n\nOver the years many different plotting modules and packages have been\n developed for Python. For most of that time there was no clear\n favorite package, but recently matplotlib has become the most widely\n used.\n\nmatplotlib highlights for me:\n\neasy to learn (based on matl...
[ 12 ]
[]
[]
[ "charts", "python" ]
stackoverflow_0007158809_charts_python.txt
Q: How can my HTML file pass JavaScript results back to a Python script that calls it? I have a python script and this python script shall call an html-file (i.e. a web page) stored locally on the computer. The html-file does some calculations (jquery,javascript and so on) and should pass the result back to the pytho...
How can my HTML file pass JavaScript results back to a Python script that calls it?
I have a python script and this python script shall call an html-file (i.e. a web page) stored locally on the computer. The html-file does some calculations (jquery,javascript and so on) and should pass the result back to the python script. I don't want to change the setting (python script calls html-file and result is...
[ "If you want to execute the javascript in the HTML file, you will need to implement a full javascript runtime in Python (there might be existing ones or ports from other languages of course.) An HTML file is not an executable, and most environments don't have an interpreter for it either, except browsers.\nIf you c...
[ 3, 1, 0, 0 ]
[]
[]
[ "html", "javascript", "javascript_engine", "python" ]
stackoverflow_0007158635_html_javascript_javascript_engine_python.txt
Q: Creating simple form with qt-designer and pyqt I'm trying to run my first application in pyqt. My form looks fine when I'm doing preview in designer: http://imageshack.us/photo/my-images/171/screenshotuw.png/ But if I'm showing it from my script I got: http://imageshack.us/photo/my-images/268/screenshot1hwn.png/ A...
Creating simple form with qt-designer and pyqt
I'm trying to run my first application in pyqt. My form looks fine when I'm doing preview in designer: http://imageshack.us/photo/my-images/171/screenshotuw.png/ But if I'm showing it from my script I got: http://imageshack.us/photo/my-images/268/screenshot1hwn.png/ And information in terminal: QLayout: Attempting ...
[ "I would say that you have designed a QWidget in the designer, and you create a QMainWindow.\nReplace\nclass MyForm(QtGui.QMainWindow)\n\nby\nclass MyForm(QtGui.QWidget)\n\n" ]
[ 13 ]
[]
[]
[ "designer", "pyqt", "python", "qt_designer", "user_interface" ]
stackoverflow_0007159003_designer_pyqt_python_qt_designer_user_interface.txt
Q: Specifying model Meta data through decorators (django) The problem: I wish to use Postgres Schemas to separate the tables of different parts of my django app at database level. Aside You can skip this section, but I think it's helpful to add context to these things. My app is working on a database of existing data...
Specifying model Meta data through decorators (django)
The problem: I wish to use Postgres Schemas to separate the tables of different parts of my django app at database level. Aside You can skip this section, but I think it's helpful to add context to these things. My app is working on a database of existing data (stored in the public schema, helpfully), which it's very i...
[ "\nI didn't really want to have to write this for every single model in my app - \n for a start, it doesn't seem pythonic, \n\nThat's false. Some things have to be written down explicitly. \"Explicit is better than Implicit\".\n\nand also there's every chance of me forgetting when I have to add a new model\n\nTh...
[ 2 ]
[]
[]
[ "decorator", "django", "python" ]
stackoverflow_0007158837_decorator_django_python.txt
Q: How can I connect to a Windows VM, and send Win32 commands? (Python) I have a VM of Windows opened, and I'd like to able to move the cursor to a (x,y) coordinate and click, or click + sendkeys. so 2 questions: 1) Best way to create a headless Windows VM with set resolution?] 2) How can I execute code or ideally co...
How can I connect to a Windows VM, and send Win32 commands? (Python)
I have a VM of Windows opened, and I'd like to able to move the cursor to a (x,y) coordinate and click, or click + sendkeys. so 2 questions: 1) Best way to create a headless Windows VM with set resolution?] 2) How can I execute code or ideally control it with a Python API from the host(Linux) machine? edit: I'm trying ...
[ "Let's look at http://sikuli.org/. I think it can be solution for you. \n" ]
[ 0 ]
[]
[]
[ "linux", "python", "virtual_machine", "windows" ]
stackoverflow_0007155928_linux_python_virtual_machine_windows.txt
Q: Bresenham line doesn't terminate I've implemented the Bresenham algorithm from Wikipedia in python but for some lines it doesn't work, like from 1,0 to 0,1 it doesn't stop and keeps going on to make a super long line def line(x0, y0, x1, y1): dx = x1 - x0 dy = y1 - y0 sx = x0 < x1 and 1 or -1 sy = ...
Bresenham line doesn't terminate
I've implemented the Bresenham algorithm from Wikipedia in python but for some lines it doesn't work, like from 1,0 to 0,1 it doesn't stop and keeps going on to make a super long line def line(x0, y0, x1, y1): dx = x1 - x0 dy = y1 - y0 sx = x0 < x1 and 1 or -1 sy = y0 < y1 and 1 or -1 err = dx - dy ...
[ "You are missing the call to abs in the initialization of dx and dy:\ndx = abs(x1 - x0)\ndy = abs(y1 - y0)\n\n", "You have a type in \"if e2 > -dy:\". The minus sign is wrong.\n" ]
[ 1, 0 ]
[]
[]
[ "bresenham", "graphics", "python" ]
stackoverflow_0007159228_bresenham_graphics_python.txt
Q: POST request via urllib/urllib2? Before you say anything, I've looked around SO and the solutions didn't work. I need to make a post request to a login script in Python. The URL looks like http://example.com/index.php?act=login, then it accepts username and password via POST. Could anyone help me with this? I've ...
POST request via urllib/urllib2?
Before you say anything, I've looked around SO and the solutions didn't work. I need to make a post request to a login script in Python. The URL looks like http://example.com/index.php?act=login, then it accepts username and password via POST. Could anyone help me with this? I've tried: import urllib, urllib2, cookiel...
[ "You will probably need to look at the HTML source to find out what the login form action URL is. Sometimes it is the same as the page URL itself, but it's probably different. But since you haven't shown actual URLs, we can't help you there.\nThe <form> element might look something like:\n<form method=\"POST\" acti...
[ 1 ]
[]
[]
[ "post", "python", "request", "urllib", "urllib2" ]
stackoverflow_0007159376_post_python_request_urllib_urllib2.txt
Q: accessing threads by name I'm trying to implement some basic threading in my script and I need to check whether the thread already exist or not, I've found how to set names but cannot figure out how to use is_alive function by name class History(threading.Thread): def __init__(self): threading.Thread._...
accessing threads by name
I'm trying to implement some basic threading in my script and I need to check whether the thread already exist or not, I've found how to set names but cannot figure out how to use is_alive function by name class History(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self...
[ "The is_alive method does not take any arguments. You don't use is_alive by name. Instead, just call t.is_alive()\nto check if the thread t is alive.\nclass History(threading.Thread):\n def __init__(self,*args,**kwargs):\n threading.Thread.__init__(self,*args,**kwargs)\n\n def run(self):\n #do s...
[ 2 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0007159380_multithreading_python.txt
Q: Python: Creating multiple text files from a list of article titles I have a long list of article titles stored in a text file, and I would like to loop through the list, creating text files, each one titled according to the list. So inside C:/articles.txt I have... Monday Tuesday Wednesday Thursday etc... and...
Python: Creating multiple text files from a list of article titles
I have a long list of article titles stored in a text file, and I would like to loop through the list, creating text files, each one titled according to the list. So inside C:/articles.txt I have... Monday Tuesday Wednesday Thursday etc... and I would like text files generated titled... Monday.txt Tuesday.txt etc....
[ "You need to remove \\n (new line character) from file name using lines.strip().\noutput = open((lines.strip())+'.txt','w')\n\n", "Focusing just on the specific error, your filenames have a \"\\n\" embedded within them. Try replacing (lines)+'.txt' with lines.strip() + '.txt'.\n", "You have a new line symbol on...
[ 2, 1, 1, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007159456_python.txt
Q: How do we use sin,cos,tan generically (including user-defined types) in Python? Edit: Let me try to reword and improve my question. The old version is attached at the bottom. What I am looking for is a way to express and use free functions in a type-generic way. Examples: abs(x) # maps to x.__abs__() next(x) # ma...
How do we use sin,cos,tan generically (including user-defined types) in Python?
Edit: Let me try to reword and improve my question. The old version is attached at the bottom. What I am looking for is a way to express and use free functions in a type-generic way. Examples: abs(x) # maps to x.__abs__() next(x) # maps to x.__next__() at least in Python 3 -x # maps to x.__neg__() In these cases...
[ "you can do this, but it works backwards. you implement __float__() in your new type and then sin() will work with your class.\nin other words, you don't adapt sine to work on other types; you adapt those types so that they work with sine.\nthis is better because it forces consistency. if there is no obvious mapp...
[ 5, 4, 1, 0, 0 ]
[]
[]
[ "python", "user_defined_types" ]
stackoverflow_0007151776_python_user_defined_types.txt
Q: How to perform HTTP 303 redirect with urllib2 in Python? I have a URL to fetch, that gives a HTTP 303 redirect : import urllib2 as web import sys url='http://sample.com' try: handle=web.urlopen(url) except web.HTTPError, e: print e.code sys.exit(1) data=handle.read() print 'Result :' print data So, the abov...
How to perform HTTP 303 redirect with urllib2 in Python?
I have a URL to fetch, that gives a HTTP 303 redirect : import urllib2 as web import sys url='http://sample.com' try: handle=web.urlopen(url) except web.HTTPError, e: print e.code sys.exit(1) data=handle.read() print 'Result :' print data So, the above code prints 303 as a result, it's a 303 redirect. I want tha...
[ "urllib2 should follow 303 redirects by default. Use the following example to test:\nimport urllib2\nurl = 'http://phihag.de/2011/so/303/'\nprint(urllib2.urlopen(url).read())\n\nIf the above code prints out the content of example.net, but your URL doesn't, the URL in question is not resolving to a correct 303 redir...
[ 3, 0 ]
[]
[]
[ "http_error", "python", "redirect", "urllib2" ]
stackoverflow_0007158312_http_error_python_redirect_urllib2.txt
Q: Python - For a url, how to check if the webserver is available or exists ? (confused) For a url entered by the user : check that is any webserver hosting the domain name or not ? For example : url='laksjdfaksdfjajdfaljewoifjadslkjflkasjrlwkejk.com' Now, the above url does-not exists, so there is no point of che...
Python - For a url, how to check if the webserver is available or exists ? (confused)
For a url entered by the user : check that is any webserver hosting the domain name or not ? For example : url='laksjdfaksdfjajdfaljewoifjadslkjflkasjrlwkejk.com' Now, the above url does-not exists, so there is no point of check for any HTTP error codes since, no server is there that will reply back. So, how to de...
[ "This should open the url for you; obviously change how you want to say that the url has failed to open. The docs are: http://docs.python.org/library/urllib2.html\nfrom urllib2 import *\n\nreq = Request(url)\n\n# Try to open the url\ntry: \n reponse = urlopen(req)\nexcept HTTPError, e:\n url = None\nexcept UR...
[ 2 ]
[]
[]
[ "python", "urllib", "urllib2", "webserver" ]
stackoverflow_0007159631_python_urllib_urllib2_webserver.txt
Q: Can't seem to dump a mysql database I seem to be having a problem. I have a view where I can allow staff users to download the MySQL database for that program, however it is not working at all. I get an error which says Errno 2] No such file or directory: '/usr/local/src/djcode/c2duo_mms/backup.gz'. I don't know ...
Can't seem to dump a mysql database
I seem to be having a problem. I have a view where I can allow staff users to download the MySQL database for that program, however it is not working at all. I get an error which says Errno 2] No such file or directory: '/usr/local/src/djcode/c2duo_mms/backup.gz'. I don't know why I get the error, but it the likely an...
[ "Use a full path here:\n os.popen3(\"mysqldump --add-drop-table -u \" + settings.DATABASE_USER + \" -p\" + settings.DATABASE_PASSWORD + \" \" + settings.DATABASE_NAME + \" > backup.sql\")\n\ni.e. Where you are saving down the sql.\n", "Try something like this:\nimport subprocess \ncommand = \"mysqldump -u *us...
[ 1, 1, 0, -1 ]
[]
[]
[ "database", "django", "mysql", "mysqldump", "python" ]
stackoverflow_0006927274_database_django_mysql_mysqldump_python.txt
Q: Web scraping urlopen in python I am trying to get the data from this website: http://www.boursorama.com/includes/cours/last_transactions.phtml?symbole=1xEURUS It seems like urlopen don't get the html code and I don't understand why. It goes like: html = urllib.request.urlopen("http://www.boursorama.com/includes/co...
Web scraping urlopen in python
I am trying to get the data from this website: http://www.boursorama.com/includes/cours/last_transactions.phtml?symbole=1xEURUS It seems like urlopen don't get the html code and I don't understand why. It goes like: html = urllib.request.urlopen("http://www.boursorama.com/includes/cours/last_transactions.phtml?symbole=...
[ "Personally , I write:\n# Python 2.7\n\nimport urllib\n\nurl = 'http://www.boursorama.com/includes/cours/last_transactions.phtml?symbole=1xEURUS'\nsock = urllib.urlopen(url)\ncontent = sock.read() \nsock.close()\n\nprint content\n\nEt si tu parles français,.. bonjour sur stackoverflow.com !\nupdate 1\nIn fact, I pr...
[ 4, 4, 2 ]
[]
[]
[ "python", "urlopen" ]
stackoverflow_0007158353_python_urlopen.txt
Q: Custom packet over TCP/IP? I'm new in Python programming but i have a big problem: how can i custom packet over TCP/IP in Python. Any solutions ? A: You are probably looking for something like scapy.
Custom packet over TCP/IP?
I'm new in Python programming but i have a big problem: how can i custom packet over TCP/IP in Python. Any solutions ?
[ "You are probably looking for something like scapy.\n" ]
[ 0 ]
[]
[]
[ "packet", "python", "tcp" ]
stackoverflow_0007159581_packet_python_tcp.txt
Q: Best python style for complex one-liners I recently wrote a rather ugly looking one-liner, and was wondering if it is better python style to break it up into multiple lines, or leave it as a commented one-liner. I looked in PEP 8, but it did not mention anything about this This is the code I wrote: def getlink(url...
Best python style for complex one-liners
I recently wrote a rather ugly looking one-liner, and was wondering if it is better python style to break it up into multiple lines, or leave it as a commented one-liner. I looked in PEP 8, but it did not mention anything about this This is the code I wrote: def getlink(url): return(urllib.urlopen(url).readlines()[...
[ "My vote would be based on readability. I find your one-liner quicker to digest than the multi-line example. \nOne-liners are great as long as it fits in one eye-ful, and collectively they perform one distinct task.\nPersonally, I would write that as:\ndef getlink(url):\n content = urllib.urlopen(url).readlines(...
[ 19, 3, 2, 2, 1, 1 ]
[]
[]
[ "coding_style", "python" ]
stackoverflow_0007158141_coding_style_python.txt
Q: Where to get boost/python.hpp? I found some project used python.hpp as #include<boost/python.hpp>, but this file is not included in the project, where can I get this file? I have done some basic search but didn't get the answer. A: Download boost here: http://www.boost.org/ On linux distributions, usually packa...
Where to get boost/python.hpp?
I found some project used python.hpp as #include<boost/python.hpp>, but this file is not included in the project, where can I get this file? I have done some basic search but didn't get the answer.
[ "Download boost here:\nhttp://www.boost.org/\n\nOn linux distributions, usually packages exist:\nsudo apt-get install libboost-python1.42-dev\n\nor just install all:\nsudo apt-get install boost-1-47-0 libboost-all-dev\n\n" ]
[ 4 ]
[]
[]
[ "boost", "python" ]
stackoverflow_0007160608_boost_python.txt
Q: How to write a tuple of floats to the file space separated with only one call to write in python? Lets suppose that I have a list of floats and I want to write it in a file. I am using python. I want all the elements to be space separated and I don't want to use more than one call to write function. Follwoing code...
How to write a tuple of floats to the file space separated with only one call to write in python?
Lets suppose that I have a list of floats and I want to write it in a file. I am using python. I want all the elements to be space separated and I don't want to use more than one call to write function. Follwoing code illustrate writing it but it is comma separated... arr [-12.0, 1.7, -5.5, 4.0] f = open("data....
[ "Since the elements of arr are not strings, you have to convert them to strings before joining:\nwith open(\"data.dat\",\"w\") as f:\n f.write(' '.join(map(str,arr)))\n\nPS. Since this question is tagged as numpy, note that you could also use np.savetxt:\nnp.savetxt('data.dat',(arr,),delimiter=' ',fmt='%g')\n\n"...
[ 6, 2 ]
[]
[]
[ "numpy", "python", "scipy" ]
stackoverflow_0007160802_numpy_python_scipy.txt
Q: How do I (quickly) thumbnail 300 images with PyQT4? I'm working (still) on a book binding application, and to make it aesthetically pleasing, I've added a thumbnail to every page you drag in. It works just fine, but the only problem is that when I drag in a whole book (i.e. 400 images), it freezes completely until...
How do I (quickly) thumbnail 300 images with PyQT4?
I'm working (still) on a book binding application, and to make it aesthetically pleasing, I've added a thumbnail to every page you drag in. It works just fine, but the only problem is that when I drag in a whole book (i.e. 400 images), it freezes completely until it's done. Here's my simple drop code: def fileDrop...
[ "You could try to make the thumbnailing faster, but that would only increase the size of the book that you could drop before you'd notice the problem. The answers are to either only thumbnail a page as it's displayed, or relegate the thumbnailing to a background thread and update the display as each is finished.\n"...
[ 5, 0 ]
[]
[]
[ "drag_and_drop", "pyqt4", "python", "thumbnails" ]
stackoverflow_0004589390_drag_and_drop_pyqt4_python_thumbnails.txt
Q: sound monitoring using python I'm trying to write a script using Python that will check if another program on my computer makes a sound. Can't seem to find a clear solution for this. Any help is appreciated. Thanks! A: Unfortunately I don't think what you want exists, but you may have some luck looking through...
sound monitoring using python
I'm trying to write a script using Python that will check if another program on my computer makes a sound. Can't seem to find a clear solution for this. Any help is appreciated. Thanks!
[ "Unfortunately I don't think what you want exists, but you may have some luck looking through this list: http://wiki.python.org/moin/PythonInMusic\n" ]
[ 0 ]
[]
[]
[ "audio", "python" ]
stackoverflow_0007160501_audio_python.txt
Q: Executing batch file from Python causes infinite loop I have this python code: import os os.system("cleanup.bat") and this is my cleanup.bat file: sc delete service1 sc delete service2 reg delete "HKEY_LOCAL_MACHINE\SOFTWARE\Key1" /f reg delete "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Key2" /f EXIT However, wh...
Executing batch file from Python causes infinite loop
I have this python code: import os os.system("cleanup.bat") and this is my cleanup.bat file: sc delete service1 sc delete service2 reg delete "HKEY_LOCAL_MACHINE\SOFTWARE\Key1" /f reg delete "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Key2" /f EXIT However, when I run my python code, my batch file loops infinitely. Wh...
[ "On my system, there already is a cleanup.bat in system32. It looks like a leftover of some installation. \nDo not rely on the path nor the file extension association. A BAT file is not executable, it is interpreted by cmd.exe. \nChange your Python code to this\nimport os\nos.system(\"cmd.exe /c .\\\\cleanup.bat\")...
[ 0 ]
[]
[]
[ "batch_file", "python" ]
stackoverflow_0006763768_batch_file_python.txt
Q: Catching all exceptions in Python In Python, what's the best way to catch "all" exceptions? except: # do stuff with sys.exc_info()[1] except BaseException as exc: except Exception as exc: The catch may be executing in a thread. My aim is to log any exception that might be thrown by normal code without masking a...
Catching all exceptions in Python
In Python, what's the best way to catch "all" exceptions? except: # do stuff with sys.exc_info()[1] except BaseException as exc: except Exception as exc: The catch may be executing in a thread. My aim is to log any exception that might be thrown by normal code without masking any special Python exceptions, such as t...
[ "\nexcept Exception: vs except BaseException::\nThe difference between catching Exception and BaseException is that according to the exception hierarchy exception like SystemExit, KeyboardInterrupt and GeneratorExit will not be caught when using except Exception because they inherit directly from BaseException.\nex...
[ 63, 30 ]
[ "In order to avoid masking basic exceptions, you need to \"re-raise\" any exceptions which aren't the ones which you explicitly want to handle, e.g. (adapted from 8. Errors and Exceptions):\n\nimport sys\ntry:\n # do something that could throw an exception:\nexcept IOError as (errno, strerror):\n print \"I/O ...
[ -1 ]
[ "catch_all", "exception_handling", "multithreading", "python", "python_3.x" ]
stackoverflow_0007160983_catch_all_exception_handling_multithreading_python_python_3.x.txt
Q: web scraping without refreshing webpage I would like to extract the data from this website: http://webcharts.fxserver.com/pairs/activePairs.php?profile=CMSForexWebQuotes1-D I obtained the url with firebug and i did extract the data from the htmlcode with urlopen and regexes. but I have to do an urlopen each second...
web scraping without refreshing webpage
I would like to extract the data from this website: http://webcharts.fxserver.com/pairs/activePairs.php?profile=CMSForexWebQuotes1-D I obtained the url with firebug and i did extract the data from the htmlcode with urlopen and regexes. but I have to do an urlopen each second to refresh the data inside the html code Wha...
[ "The data actually comes from this page: \nhttp://webcharts.fxserver.com/pairs/activePairsFeed.php?day=percent&week=percent&unit=&protocol=2&version=1314105399&pairs%5B%5D=EUR%2FUSD&pairs%5B%5D=GBP%2FUSD&pairs%5B%5D=USD%2FJPY&pairs%5B%5D=GBP%2FJPY&pairs%5B%5D=GBP%2FCHF&pairs%5B%5D=USD%2FCAD&pairs%5B%5D=EUR%2FJPY&pa...
[ 2 ]
[]
[]
[ "ajax", "python" ]
stackoverflow_0007161437_ajax_python.txt
Q: Speed up often used Django random query I've got a query set up that puts 28 random records from a database into a JSON response. This page is hit often, every few seconds, but is currently too slow for my liking. In the JSON response I have: ID's Usernames a Base64 thumbnail These all come from three linked tab...
Speed up often used Django random query
I've got a query set up that puts 28 random records from a database into a JSON response. This page is hit often, every few seconds, but is currently too slow for my liking. In the JSON response I have: ID's Usernames a Base64 thumbnail These all come from three linked tables. I'd be keen to hear of some other soluti...
[ "Django supports a variety of caching methods, both built-in and memcached. I would select one of the methods in the documentation, and create a specific view for your json response. You could then use the @cache_page decorator and specify a particular time.\nfrom django.views.decorators.cache import cache_page\n\n...
[ 4, 0 ]
[]
[]
[ "cloud_hosting", "django", "memcached", "python", "rackspace_cloud" ]
stackoverflow_0007159852_cloud_hosting_django_memcached_python_rackspace_cloud.txt
Q: PHP Curl code to urlfetch in python - need help This is my PHP Code with Curl . I need to do the same function using urlfetch in GAE Python. How can pass all these parameter to urlfetch. Please help me. $curl = curl_init(); $timeout = 30; // Logining to my TNT curl_setopt ($curl, CURLOPT_URL, "https...
PHP Curl code to urlfetch in python - need help
This is my PHP Code with Curl . I need to do the same function using urlfetch in GAE Python. How can pass all these parameter to urlfetch. Please help me. $curl = curl_init(); $timeout = 30; // Logining to my TNT curl_setopt ($curl, CURLOPT_URL, "https://my.tnt.com/myTNT/login/LoginInitial.do?cmd=1&navig...
[ "I suspect that your php code is using a \"cookie jar\" like what is available in the mechanize library. \nI've used mechanize before for basic scraping of websites, but not actually to log in, so I can't say 100% that it will work for you but I think it's your best shot.\n" ]
[ 0 ]
[]
[]
[ "curl", "google_app_engine", "python", "urlfetch" ]
stackoverflow_0007156272_curl_google_app_engine_python_urlfetch.txt
Q: multiprocessing in python My question might be quite vague. I am looking for some reasonable approach to perform my task. I have developed a webpage where the user uploads a file used as an input file for my code developed in python. When the input file is submitted through the webpage, it is saved in a temporary...
multiprocessing in python
My question might be quite vague. I am looking for some reasonable approach to perform my task. I have developed a webpage where the user uploads a file used as an input file for my code developed in python. When the input file is submitted through the webpage, it is saved in a temporary folder from where the daemon c...
[ "I use a SQL table to perform such a thing, because my users may launch dozens of tasks alltogether if I do not limit them. \nWhen a new file shows up, a daemon writes its name in the table (with allsort of other information such as size, date, time, user, ...)\nAnother daemon is then reading the table, getting the...
[ 0 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0007149287_multiprocessing_python.txt
Q: How to communicate with Erlang code from Python code? Let say I have Erlang "enterprise application": -module(hello). -export([start/0]). start() -> spawn(fun() -> loop() end). loop() -> receive hello -> io:format("Hello, World!~n"), loop(); goodbye -> ok end. Is there a way to run it ...
How to communicate with Erlang code from Python code?
Let say I have Erlang "enterprise application": -module(hello). -export([start/0]). start() -> spawn(fun() -> loop() end). loop() -> receive hello -> io:format("Hello, World!~n"), loop(); goodbye -> ok end. Is there a way to run it from Python code? So that I can get the "Hello, World!" tex...
[ "What you are looking for is Py-Interface, it implements an Erlang compatible Node in Python.\n\nThe py_interface provides the possibility to create a node that may be\n used for communication with other Erlang nodes.\n\nIf you have a one-shot command line program that is written in Erlang and just want to execute...
[ 6, 0, 0 ]
[ "If you need Erlang to execute something within Python, its better you create an escript. The escript is then called by your python Script. The Erlang escript will spit the output you want to your python script if say you pipe them like this:\n\n\nbash-3.2$ escript Your_Erlang_script.escript | python_script.py\n\nI...
[ -1 ]
[ "erlang", "python" ]
stackoverflow_0007160239_erlang_python.txt
Q: python class act like a list Why the following code returns empty after I have added several items in it? class Con(list): def __init__(self): pass def __str__(self): return ' '.join(self) def add(self, value) self.append(value) i for i in range(10): Con().add(i) >>> print Con(...
python class act like a list
Why the following code returns empty after I have added several items in it? class Con(list): def __init__(self): pass def __str__(self): return ' '.join(self) def add(self, value) self.append(value) i for i in range(10): Con().add(i) >>> print Con() # empty space instead of: 0 1 2 ...
[ "You're always creating a new instance of con in each iteration of your loop. You have to create the instance before the loop and add to that instance. Furthermore, you're creating another new instance in the print statement, so that'll turn up empty as well.\n", "You're creating 11 instances of Con by calling Co...
[ 8, 5, 2 ]
[]
[]
[ "class", "list", "python" ]
stackoverflow_0007161925_class_list_python.txt
Q: Import program in other folders with Python I want to import a Python program from 2 different folders: Prog1 from the path /home/francis/docs/folder1/ Prog2 from the path /home/francis/docs/folder2/ How do I import these two Programs in my main program situated in /home/francis/docs/folder3/? A: Add this to t...
Import program in other folders with Python
I want to import a Python program from 2 different folders: Prog1 from the path /home/francis/docs/folder1/ Prog2 from the path /home/francis/docs/folder2/ How do I import these two Programs in my main program situated in /home/francis/docs/folder3/?
[ "Add this to the top of your Prog3:\nimport sys\nsys.path.append('/home/francis/docs/folder1/')\nsys.path.append('/home/francis/docs/folder2/')\nimport Prog1\nimport Prog2\n\n", "See also another related question:\nHow to import modules from different folders in Python?\nAnd http://docs.python.org/tutorial/module...
[ 4, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007147418_python.txt
Q: what is statically typed in RPython? It is often stated that RPython (a subset of Python) is statically typed. (E.g. on Wikipedia.) Initially, I wondered how they would add that to Python and thought that they might have added the requirement to add statements such as assert isinstance(arg1, ...) at the beginning ...
what is statically typed in RPython?
It is often stated that RPython (a subset of Python) is statically typed. (E.g. on Wikipedia.) Initially, I wondered how they would add that to Python and thought that they might have added the requirement to add statements such as assert isinstance(arg1, ...) at the beginning of each function (but I couldn't really be...
[ "\nSo, do function arguments also count as variables?\n\nOf course they do. They always do in pretty much every language.\n\nOr in what sense is RPython statically typed? Or is this actually misstated?\n\nThe statement is correct. RPython is not Python. Well, it's a subset of it and can be run as Python code. But w...
[ 15, 4 ]
[]
[]
[ "pypy", "python", "rpython", "static_typing" ]
stackoverflow_0007161856_pypy_python_rpython_static_typing.txt
Q: temporal interpolation of artery angiogram images sequences I have many sets of medical image sequences of the artery on the heart. Each set of sequenced medical images shows the position of the artery as the heart pumps. Each set is taken from different views and has different amount of images taken. I want to do...
temporal interpolation of artery angiogram images sequences
I have many sets of medical image sequences of the artery on the heart. Each set of sequenced medical images shows the position of the artery as the heart pumps. Each set is taken from different views and has different amount of images taken. I want to do a temporal interpolation based on time (i was told that the time...
[ "If you imagine each of the images as a still photo the frame number would be a sequence number that shows what order the images should be displayed in to produce a movie from the stills. If the images are stored in an array it would be the array index of the individul frame in question.\n" ]
[ 0 ]
[]
[]
[ "interpolation", "python" ]
stackoverflow_0007162351_interpolation_python.txt
Q: How to refine list of directories to remove subdirectories of newly added directory I have a list of directories, eg: direc_list = [r'C:\test', r'C:\test2\subdir'] I then want to add another directory to the list new_direc = r'C:\test2' How can I correctly remove any subdirectories of this new directory in my l...
How to refine list of directories to remove subdirectories of newly added directory
I have a list of directories, eg: direc_list = [r'C:\test', r'C:\test2\subdir'] I then want to add another directory to the list new_direc = r'C:\test2' How can I correctly remove any subdirectories of this new directory in my list? After adding r'C:\test2' my output should be so that direc_list >>> [r'C:\test', r'...
[ "Use str.startswith() as in:\nfor direc in direc_list:\n if direc.startswith(new_direc):\n dir_list.remove(direc)\n\nDepending upon input, might want to check out something like, os.path.abspath(path) to normalize your paths so they match up better.\n", "Maybe simply add an path seperator after the path...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007162697_python.txt
Q: Test speed of two scripts I'd like to test the speed of a bash script and a Python script. How would I get the time it took to run them? A: If you're on Linux (or another UN*X), try time: The time command runs the specified program command with the given arguments. When command finishes, time wr...
Test speed of two scripts
I'd like to test the speed of a bash script and a Python script. How would I get the time it took to run them?
[ "If you're on Linux (or another UN*X), try time:\n\nThe time command runs the specified program command with the given\n arguments. When command finishes, time writes a message to standard\n error giving timing statistics about this program run. These statis-\n tics consist of (...
[ 3, 0, 0 ]
[]
[]
[ "bash", "performance", "python", "testing" ]
stackoverflow_0007162812_bash_performance_python_testing.txt
Q: Extract items from n-line chunks in a file, count frequency of items for each chunk, Python I have a text file containing 5-line chunks of tab-delimited lines: 1 \t DESCRIPTION \t SENTENCE \t ITEMS 1 \t DESCRIPTION \t SENTENCE \t ITEMS 1 \t DESCRIPTION \t SENTENCE \t ITEMS 1 \t DESCRIPTION \t SENTENCE \t I...
Extract items from n-line chunks in a file, count frequency of items for each chunk, Python
I have a text file containing 5-line chunks of tab-delimited lines: 1 \t DESCRIPTION \t SENTENCE \t ITEMS 1 \t DESCRIPTION \t SENTENCE \t ITEMS 1 \t DESCRIPTION \t SENTENCE \t ITEMS 1 \t DESCRIPTION \t SENTENCE \t ITEMS 1 \t DESCRIPTION \t SENTENCE \t ITEMS 2 \t DESCRIPTION \t SENTENCE \t ITEMS 2 \t DESCR...
[ "Using python 2.7\n#!/usr/bin/env python\n\nimport collections\n\nchunks={}\n\nwith open('input') as fd:\n for line in fd:\n line=line.split()\n if not line:\n continue\n if chunks.has_key(line[0]):\n for i in line[3:]:\n chunks[line[0]].append(i.replace(...
[ 1, 1, 0, 0 ]
[]
[]
[ "python", "text_processing" ]
stackoverflow_0007162215_python_text_processing.txt
Q: pass session cookies in http header with python urllib2? I'm trying to write a simple script to log into Wikipedia and perform some actions on my user page, using the Mediawiki api. However, I never seem to get past the first login request (from this page: https://en.wikipedia.org/wiki/Wikipedia:Creating_a_bot#Log...
pass session cookies in http header with python urllib2?
I'm trying to write a simple script to log into Wikipedia and perform some actions on my user page, using the Mediawiki api. However, I never seem to get past the first login request (from this page: https://en.wikipedia.org/wiki/Wikipedia:Creating_a_bot#Logging_in). I don't think the session cookie that I set is being...
[ "The latest version of requests has support for sessions (as well as being really simple to use and generally great):\nwith requests.session() as s: \n s.post(url, data=user_data)\n r = s.get(url_2)\n\n" ]
[ 14 ]
[]
[]
[ "cookies", "http", "python", "wikipedia_api" ]
stackoverflow_0007162850_cookies_http_python_wikipedia_api.txt
Q: How to find anything that matches excluding a certain string? I'm trying to get a match but am having trouble with the syntax, below I am using python but it can be any language, i just need the correct regex syntax: import re p = re.compile('foo%22([^%22])*') input = "foo%22somedata%2Bgoeshere%22testbarbaz" res...
How to find anything that matches excluding a certain string?
I'm trying to get a match but am having trouble with the syntax, below I am using python but it can be any language, i just need the correct regex syntax: import re p = re.compile('foo%22([^%22])*') input = "foo%22somedata%2Bgoeshere%22testbarbaz" result = re.findall(p, input) I'm trying to extract "somedata%2Bgoesh...
[ "Use positive lookahead:\n>>> import re\n>>> input = \"foo%22somedata%2Bgoeshere%22testbarbaz\"\n>>> re.findall('foo%22.*?(?=%22)', input)\n['foo%22somedata%2Bgoeshere']\n\n", "Why do you need a regex? Simply do a split on %22\n>>> input.split(\"%22\")\n['foo', 'somedata%2Bgoeshere', 'testbarbaz']\n\nthe stuff yo...
[ 4, 4, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007162924_python_regex.txt
Q: how to import list from file in python I have a file like f = [1,1,2,2,2,3,3,4,5] and i would like to import this file like a list So that it is treated as a list. e.g say i have two files, one contain f = [1,1,1,1,1] and the second contain d = [2,2,2,2,2] and i would like to zip(i,j) for i in f and for j in d. f ...
how to import list from file in python
I have a file like f = [1,1,2,2,2,3,3,4,5] and i would like to import this file like a list So that it is treated as a list. e.g say i have two files, one contain f = [1,1,1,1,1] and the second contain d = [2,2,2,2,2] and i would like to zip(i,j) for i in f and for j in d. f = file('f.txt') d = file('d.txt') for i in ...
[ "ast.literal_eval is a safe way to evaluate strings as Python literals (e.g. strings, numbers, tuples, lists, dicts, booleans, and None):\nimport ast\nwith open('f.txt') as f:\n with open('d.txt') as d:\n flist=ast.literal_eval(f.read())\n dlist=ast.literal_eval(d.read())\n print(zip(flist,d...
[ 5, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007163024_python.txt
Q: Google Calendar API (Python) send_event_notifications not sending emails Having an issue: the gdata.calendar.data.CalendarEventEntry.send_event_notifications setting is not working (not sending out the emails): event = gdata.calendar.data.CalendarEventEntry() event.title = atom.data.Title(text='test event') ev...
Google Calendar API (Python) send_event_notifications not sending emails
Having an issue: the gdata.calendar.data.CalendarEventEntry.send_event_notifications setting is not working (not sending out the emails): event = gdata.calendar.data.CalendarEventEntry() event.title = atom.data.Title(text='test event') event.when.append(gdata.calendar.data.When(start=<start date>,end=<end date>)) ...
[ "Ok, here is the solution posted by Alain from Google:\nThere was a bug in the Calendar XML namespace formatting which has been \nfixed in the repository: \nhttp://code.google.com/p/gdata-python-client/source/detail?spec=svnff... \nPlease use the repository version instead of the release as many fixes are \npushed ...
[ 1 ]
[]
[]
[ "api", "calendar", "gdata", "python" ]
stackoverflow_0007152821_api_calendar_gdata_python.txt
Q: Executing JavaScript with Python without X I want to parse a html-page that unfortunately requires JavaScript to show any content. In order to do so I use a small python-script that pulls the html-code of the page, but after that I have to execute the JavaScript in a DOM-context which seems pretty hard. To make it...
Executing JavaScript with Python without X
I want to parse a html-page that unfortunately requires JavaScript to show any content. In order to do so I use a small python-script that pulls the html-code of the page, but after that I have to execute the JavaScript in a DOM-context which seems pretty hard. To make it even harder I want to use it in a server enviro...
[ "You can simulate a browser environment using EnvJS. However, in order to make use of it, you will have to embed some kind of JavaScript runtime (e.g. Rhino) in your program (or spawn one as an external process).\n", "You could try using Xvfb to have a fake frame buffer, so you won't need to run X11 (though it m...
[ 3, 2, 1, 0, 0 ]
[]
[]
[ "javascript", "python" ]
stackoverflow_0004661753_javascript_python.txt
Q: Python Imports, Paths, Directories & Modules Let me start by saying I've done extensive research over the course of the past week and have not yet found actual answers to these questions - just some fuzzy answers that don't really explain what is going on. If that's just cause I missed what I was looking for, I'm...
Python Imports, Paths, Directories & Modules
Let me start by saying I've done extensive research over the course of the past week and have not yet found actual answers to these questions - just some fuzzy answers that don't really explain what is going on. If that's just cause I missed what I was looking for, I'm sorry - please just point me in the correct direc...
[ "First off, you will find all the information you need in section 6 of The Python Tutorial.\n\n\n(1) Does python deal differently with imports on packages & modules that exist in the pythonpath than when you are trying to import from your current directory?\n\nNo, it doesn't. Actually, Python always searches sys.p...
[ 9, 0 ]
[]
[]
[ "module", "package", "python" ]
stackoverflow_0007163204_module_package_python.txt
Q: Best Python GIS library? I am looking for recommendations as to the best Python GIS library currently available based on the following (subjective) criteria: Ease of use / Pythonic interface / Documentation Power in terms of available features today, and potentially in the future (is it still being developed or d...
Best Python GIS library?
I am looking for recommendations as to the best Python GIS library currently available based on the following (subjective) criteria: Ease of use / Pythonic interface / Documentation Power in terms of available features today, and potentially in the future (is it still being developed or dead). So far I have looked at...
[ "In 2011, this is how you check a project's vital signs: https://github.com/sgillies/shapely/commits/master/.\nIn my honest opinion (disclaimer: I am the lead developer and manual author), Shapely's documentation is right up there with any other GIS software; maybe not quite as good as the PostGIS manual (crême de ...
[ 6, 3 ]
[]
[]
[ "gis", "python" ]
stackoverflow_0007157076_gis_python.txt
Q: Getting stdout from a tcpdump subprocess after terminating it I am running tcpdump in a subprocess like this: pcap_process = subprocess.Popen(['tcpdump', '-s 0', '-w -', 'tcp'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) The -w - argument is important: it tells tcpdump to p...
Getting stdout from a tcpdump subprocess after terminating it
I am running tcpdump in a subprocess like this: pcap_process = subprocess.Popen(['tcpdump', '-s 0', '-w -', 'tcp'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) The -w - argument is important: it tells tcpdump to print the resulting .pcap file to stdout. I then go on to access a w...
[ "Instead of using tcpdump, it's often advisable to use PCAP directly, or Scapy.\nIf that isn't an option, simply call communicate after terminate - killing a process does not kill data in the pipes to it. However, don't forget to separate arguments in the creation of the subprocess ([,'-w', '-'] instead of [... , '...
[ 8 ]
[]
[]
[ "python", "subprocess", "tcpdump" ]
stackoverflow_0007163877_python_subprocess_tcpdump.txt
Q: Proper Exiting of While Loop on Error I'm curious what is the 'proper' pythonic way of handling this error with a while loop. I could simply check the string to see if it has a [-1] character beforehand in this example, but the actual code this example of my problem is based on is much more complicated. try: w...
Proper Exiting of While Loop on Error
I'm curious what is the 'proper' pythonic way of handling this error with a while loop. I could simply check the string to see if it has a [-1] character beforehand in this example, but the actual code this example of my problem is based on is much more complicated. try: while mystring[-1] == '!' #Will throw an err...
[ "For your example, you could simply do something like:\nwhile mystring and mystring[-1] == '!':\n print(\"Exclamation!\")\n mystring = mystring[:-1]\nreturn mystring\n\nThis will work because it will short-circuit and end the loop if mystring is empty, so you will never try to access the -1 index of an empty ...
[ 3, 3, 2 ]
[]
[]
[ "python", "while_loop" ]
stackoverflow_0007163517_python_while_loop.txt
Q: fromstring() -> tostring() modifies the overall HTML structure I am trying to use lxml.html for writing a cleanup routine to remove empty DIV elements having no content. During the debugging I noticed that a standard tostring() -> fromstring() iteration modifies my HTML. Firstly it removes the outer body tag and s...
fromstring() -> tostring() modifies the overall HTML structure
I am trying to use lxml.html for writing a cleanup routine to remove empty DIV elements having no content. During the debugging I noticed that a standard tostring() -> fromstring() iteration modifies my HTML. Firstly it removes the outer body tag and secondly it changes the DIV structure. Why? (Pdb) from lxml.html impo...
[ "That's correct. While your example is well-formed, it is not valid html so lxml tries to correct it to the best of its ability. In particular the div element can't be nested inside p elements and the root tag cannot be body. Use the etree module instead:\nfrom lxml.etree import fromstring, tostring\n\n" ]
[ 3 ]
[]
[]
[ "html", "lxml", "python" ]
stackoverflow_0007164093_html_lxml_python.txt