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: Build a web client integrated facebook chat? I'm using Google App Engine and I'm interested in creating a web site integrated facebook chat. I read Integrating with Facebook Chat and with what I read, I think their example code only works for desktop applications. I tried some applications integrated facebook chat...
Build a web client integrated facebook chat?
I'm using Google App Engine and I'm interested in creating a web site integrated facebook chat. I read Integrating with Facebook Chat and with what I read, I think their example code only works for desktop applications. I tried some applications integrated facebook chat such as pidgin, meebo... There is a web client na...
[ "Well, Google App Engine has a XMPP feature, it could probably be what you need.\n" ]
[ 0 ]
[]
[]
[ "facebook_chat", "google_app_engine", "python" ]
stackoverflow_0004213244_facebook_chat_google_app_engine_python.txt
Q: difference between an object property and type property Some one to help me this, What is the difference between an object property and type property? if possible with an example in python.. thanks! A: class A: class_property = 10 def __init__(self): self.object_property = 20 The difference is that...
difference between an object property and type property
Some one to help me this, What is the difference between an object property and type property? if possible with an example in python.. thanks!
[ "class A:\n class_property = 10\n\n def __init__(self):\n self.object_property = 20\n\nThe difference is that you can access class_property through class A:\nprint A.class_property\n\nbut you can access object_property only through an instance of A:\na = A()\nprint a.object_property\n\n" ]
[ 4 ]
[]
[]
[ "properties", "python", "types" ]
stackoverflow_0004213697_properties_python_types.txt
Q: Python, url from request I am trying to get the url of the page I just fetched - as it can change after redirects... opener = urllib2.build_opener(redirect_handler.MyHTTPRedirectHandler()) opener.addheaders = [('Accept-encoding', 'gzip')] self.response = opener.open(url) self.page_c...
Python, url from request
I am trying to get the url of the page I just fetched - as it can change after redirects... opener = urllib2.build_opener(redirect_handler.MyHTTPRedirectHandler()) opener.addheaders = [('Accept-encoding', 'gzip')] self.response = opener.open(url) self.page_contents = self.response.read()...
[ "This is done with\nself.response.geturl()\n\n" ]
[ 1 ]
[]
[]
[ "python", "redirect", "urllib2" ]
stackoverflow_0004213676_python_redirect_urllib2.txt
Q: Blocking HTML tags in a webpage So, I have a web 2.0 site I'm building with a lot of user input but as with any web 2.0 site, I'm gonna have trouble with spam. Easiest way in my case as far as I'm aware is to block any HTML tags. Users do not need formatting and I'll use for fixing spacing. But I don't think ther...
Blocking HTML tags in a webpage
So, I have a web 2.0 site I'm building with a lot of user input but as with any web 2.0 site, I'm gonna have trouble with spam. Easiest way in my case as far as I'm aware is to block any HTML tags. Users do not need formatting and I'll use for fixing spacing. But I don't think there's any blocking tags, xmb sounds per...
[ "In Django, you can escape (encode) the special HTML characters like < and > so tags can be displayed as readable text, but don't function as HTML :\nfrom django.utils.html import escape\nprint escape('<div class=\"q\">Q & A</div>')\n\nNote that your template variables may have already been escaped, you may want to...
[ 3, 2 ]
[]
[]
[ "django", "html", "python" ]
stackoverflow_0004213884_django_html_python.txt
Q: Running a Command in Tomcat CGI using Python I've encountered and weired behaviour when running python in Tomcat-CGI. All things workfine expect calling a this command subprocess.Popen('"C:\Program Files\AutoIt3\Aut2Exe\Aut2exe.exe" /in "C:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps\python\install...
Running a Command in Tomcat CGI using Python
I've encountered and weired behaviour when running python in Tomcat-CGI. All things workfine expect calling a this command subprocess.Popen('"C:\Program Files\AutoIt3\Aut2Exe\Aut2exe.exe" /in "C:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps\python\install.au3" /out "C:\Program Files\Apache Software Found...
[ "I do not hnow much about TomCat and your environment, but I would say that your\n<subprocess.Popen object at 0x0094BC10>\n\nis returnvalue of subprocess.Popen() call.\nI would try to move the subprocess.Popen() somewhere, where its returnvalue is not captured into your html (if what you want is eliminate the retur...
[ 1 ]
[]
[]
[ "cgi", "python", "tomcat" ]
stackoverflow_0004213909_cgi_python_tomcat.txt
Q: Facing problem with XLWT and XLRD - Reading and writing simultaneously I am facing a problem with xlrd and xlwt. Pasting the sample code below. from xlwt import Workbook, Formula, XFStyle import xlrd book = Workbook() sheet1 = book.add_sheet('Sheet 1') myFontStyle = XFStyle() myFontStyle.num_format_str = '0.00' s...
Facing problem with XLWT and XLRD - Reading and writing simultaneously
I am facing a problem with xlrd and xlwt. Pasting the sample code below. from xlwt import Workbook, Formula, XFStyle import xlrd book = Workbook() sheet1 = book.add_sheet('Sheet 1') myFontStyle = XFStyle() myFontStyle.num_format_str = '0.00' sheet1.write(0,0,10, myFontStyle) sheet1.write(0,1,20, myFontStyle) sheet1.wr...
[ "Here is the answer I gave to the same question on the python-excel google-group yesterday.\n[Background: I'm the author/maintainer of xlrd and the maintainer of xlwt]\nNeither xlrd nor xlwt contains a formula evaluation engine. This is in common with other packages which are free (in any sense) and written in an i...
[ 8, 2 ]
[]
[]
[ "excel", "python", "xlrd", "xlwt" ]
stackoverflow_0004198365_excel_python_xlrd_xlwt.txt
Q: IPython on Windows - No highlighting or Auto-complete this has been an issue for a long time for me, but as I mainly develop using Linux I never really cared much about this problem till now. iPython on Windows lacks various features. I really miss color highlighting and auto-completion. Edit: fixed highlighting ...
IPython on Windows - No highlighting or Auto-complete
this has been an issue for a long time for me, but as I mainly develop using Linux I never really cared much about this problem till now. iPython on Windows lacks various features. I really miss color highlighting and auto-completion. Edit: fixed highlighting by installing pyreadline pip install pyreadline Anyone a...
[ "You need to install PyReadline,\ndocumentation is here.\n" ]
[ 21 ]
[]
[]
[ "django", "django_shell", "ipython", "python", "windows" ]
stackoverflow_0004214354_django_django_shell_ipython_python_windows.txt
Q: Use file like objects for Tk().iconbitmap() I am writing a program using Tkinter that is to be eventually compiled into an exe using py2exe. I want to include an icon with it for use on the windows. It will be the same one as I have packed as the icon for the exe. Is there a way to include the icon in Tkinter, eit...
Use file like objects for Tk().iconbitmap()
I am writing a program using Tkinter that is to be eventually compiled into an exe using py2exe. I want to include an icon with it for use on the windows. It will be the same one as I have packed as the icon for the exe. Is there a way to include the icon in Tkinter, either by locating the exe file or using a file-like...
[ "Tk images have a -data option which lets you embed the image within the code. You just have to base64-encode the image. I think the image has to originally be in the GIF format. \nHere's a working example:\nimport Tkinter as tk\nroot = tk.Tk()\ndata = '''R0lGODlhIAAgALMAAAAAAAAAgHCAkC6LV76+vvXeswD/ANzc3DLNMubm+v/6...
[ 3, 2 ]
[]
[]
[ "py2exe", "python", "tkinter" ]
stackoverflow_0004211064_py2exe_python_tkinter.txt
Q: how to retrieve field value (values are itself string)in given line using regular expression in python I am newbie to python,i am facing below issue please help me: I read line by line from one file, each line having field name and its value, now i have to find out field name and filevalue in the line.example of ...
how to retrieve field value (values are itself string)in given line using regular expression in python
I am newbie to python,i am facing below issue please help me: I read line by line from one file, each line having field name and its value, now i have to find out field name and filevalue in the line.example of line is: line=" A= 4 | B='567' |c=4|D='aaa' " Since some field values are itself a string so I am unable to...
[ "The simplest solution I can think of is converting each line into a dictionary. I assume that you don't have any quote marks or | marks in your strings (see my comments on the question).\nresult={} # Initialize a dictionary\nfor line in open('input.txt'): # Read file line by line in a memory-e...
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004213300_python.txt
Q: Python loop for image and pil module I'm using PIL and Image modes in Python. I want to create an image with this code: imagesize = (12,12) image = Image.new("RGB",imagesize,color=None) I will use this function to put pixels on my image: .putpixel(xy, color) color is in a list of tuples. For exemple: RGB = [((25...
Python loop for image and pil module
I'm using PIL and Image modes in Python. I want to create an image with this code: imagesize = (12,12) image = Image.new("RGB",imagesize,color=None) I will use this function to put pixels on my image: .putpixel(xy, color) color is in a list of tuples. For exemple: RGB = [((255, 255, 255),(207, 103, 36),(204, 93, 21),...
[ "Ok, my comment from above should've really gone into an answer. I should catch some sleep. You can basically just put your pixel data into the image at once. The putdata method of a PIL.Image accepts a list of tuples that make up the pixels of the images. So:\nimg = PIL.Image.new(\"RGB\", (12, 12))\nimg.show() # s...
[ 2, 1, 1, 1 ]
[]
[]
[ "python", "python_imaging_library" ]
stackoverflow_0004214382_python_python_imaging_library.txt
Q: Reducing memory footprint with multiprocessing? One of my applications runs about 100 workers. It started out as a threading application, but performance (latency) issues were hit. So I converted those workers to multiprocessing.Processes. The benchmark below shows that the reduction in load was achieved at the co...
Reducing memory footprint with multiprocessing?
One of my applications runs about 100 workers. It started out as a threading application, but performance (latency) issues were hit. So I converted those workers to multiprocessing.Processes. The benchmark below shows that the reduction in load was achieved at the cost of more memory usage (factor 6). So where precisel...
[ "My understanding is that with dynamic languages, like Python, copy-on-write is not as effective as a lot more memory gets written to (and therefore copied) after forking. As the Python interpretor progresses through the program there's a lot more going on than just your code. For example reference-counting - ver...
[ 3 ]
[]
[]
[ "benchmarking", "memory_management", "multiprocessing", "multithreading", "python" ]
stackoverflow_0004214775_benchmarking_memory_management_multiprocessing_multithreading_python.txt
Q: How to use Post_save in Django I am trying to add points to a User's profile after they submit a comment- using the Django comment framework. I think I need to use a post_save but am not sure to be perfectly honest. Here is what I have as a method in my models.py: def add_points(request, Comment): if Comment....
How to use Post_save in Django
I am trying to add points to a User's profile after they submit a comment- using the Django comment framework. I think I need to use a post_save but am not sure to be perfectly honest. Here is what I have as a method in my models.py: def add_points(request, Comment): if Comment.post_save(): request.user.ge...
[ "Unfortunately this makes no sense at all.\nFirstly, this can't be a method, as it doesn't have self as the first parameter.\nSecondly, it seems to be taking the class, not an instance. You can't save the class itself, only an instance of it.\nThirdly, post_save is not a method of the model (unless you've defined o...
[ 2 ]
[]
[]
[ "django", "django_comments", "django_models", "python" ]
stackoverflow_0004214680_django_django_comments_django_models_python.txt
Q: i have a string variable which comes with function names, how do I call the function in Python? I have a string variable which comes with different function names, and I have a file which contains an often different set of functions which matchs the content of the string, how do I call that function in Python? Ex...
i have a string variable which comes with function names, how do I call the function in Python?
I have a string variable which comes with different function names, and I have a file which contains an often different set of functions which matchs the content of the string, how do I call that function in Python? Example: In File 1 def function1: ... def function2: ... def function3: ... In File 2 functionname = "...
[ "myfunction = getattr(mymodule, functionname)\nmyfunction()\n\n", "eval(\"function2\")()\ngetattr(<module>, fname)()\n", "name = 'function2'\n\nassert re.match('^(?i)[_a-z][_a-z0-9]*$', name)\n\neval(name)()\n\n" ]
[ 6, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004214261_python.txt
Q: UnicodeDecodeError while running Django dev server UnicodeDecodeError Appears while trying to access any of the files from site media folder. Full traceback presented in debug mode: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/site-media/img/image.png Django Version: 1.2.3 Python Version: 2...
UnicodeDecodeError while running Django dev server
UnicodeDecodeError Appears while trying to access any of the files from site media folder. Full traceback presented in debug mode: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/site-media/img/image.png Django Version: 1.2.3 Python Version: 2.7.0 Installed Applications: ['django.contrib.auth', 'd...
[ "It seems to be a problem in Python 2.7 mimetypes.py. Look at the following discussion thread:\nhttp://groups.google.com/group/django-users/browse_thread/thread/613909b35a7462a0\nThere is a link to a russian article which says when google-translated:\n\nThe presence of the standard library\n source Python-and allo...
[ 5 ]
[]
[]
[ "django", "encoding", "python" ]
stackoverflow_0004214151_django_encoding_python.txt
Q: Transition from small scripts to bigger apps is not easy I believe that readability and the KISS principle are the most important things in programming. That's why I use Python :) And here is exact situation, which I encounter very often: Say, I have a nice and clean script, which is a wrapper for database handlin...
Transition from small scripts to bigger apps is not easy
I believe that readability and the KISS principle are the most important things in programming. That's why I use Python :) And here is exact situation, which I encounter very often: Say, I have a nice and clean script, which is a wrapper for database handling: import database_schema as schema loader = schema.Loader("sq...
[ "A module is a Python object with arbitrarily named attributes that you can bind and reference. The Python code for a module named mod normally resides in a file named mod.py. When you try to import it, a new namespace is created that contains all the attributes of that module.\nThough all said, it is not the same ...
[ 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003861916_python.txt
Q: Parsing an xml file and storing it into a database Is there a generic/automatic way in R or in python to parse xml files with its nodes and attributes, automatically generate mysql tables for storing that information and then populate those tables. A: Regarding Is there a generic/automatic way in R to parse x...
Parsing an xml file and storing it into a database
Is there a generic/automatic way in R or in python to parse xml files with its nodes and attributes, automatically generate mysql tables for storing that information and then populate those tables.
[ "Regarding\n\nIs there a generic/automatic way in R\n to parse xml files with its nodes and\n attributes, automatically generate\n mysql tables for storing that\n information and then populate those\n tables.\n\nthe answer is a good old yes you can, at least in R. \nThe XML package for R can read XML document...
[ 5, 4, 1, 0 ]
[]
[]
[ "mysql", "python", "r", "xml" ]
stackoverflow_0004213696_mysql_python_r_xml.txt
Q: kill process with python I need to make a script that gets from the user the following: 1) Process name (on linux). 2) The log file name that this process write to it. It needs to kill the process and verify that the process is down. Change the log file name to a new file name with the time and date. And then ru...
kill process with python
I need to make a script that gets from the user the following: 1) Process name (on linux). 2) The log file name that this process write to it. It needs to kill the process and verify that the process is down. Change the log file name to a new file name with the time and date. And then run the process again, verify th...
[ "You can retrieve the process id (PID) given it name using pgrep command like this:\nimport subprocess\nimport signal\nimport os\nfrom datetime import datetime as dt\n\n\nprocess_name = sys.argv[1]\nlog_file_name = sys.argv[2]\n\n\nproc = subprocess.Popen([\"pgrep\", process_name], stdout=subprocess.PIPE) \n\n# Kil...
[ 21, 2 ]
[]
[]
[ "kill", "linux", "process", "python" ]
stackoverflow_0004214773_kill_linux_process_python.txt
Q: Any benefits of turning libraries for Django into an App? When developing some functionality for use with django. In this case a middleware and some other utils like a decorator. Is there any upside of making it into a Django App. The library has no models, so there is no point in a models.py (which you need to ma...
Any benefits of turning libraries for Django into an App?
When developing some functionality for use with django. In this case a middleware and some other utils like a decorator. Is there any upside of making it into a Django App. The library has no models, so there is no point in a models.py (which you need to make django see it as an app), or putting into INSTALLED_APPS. Bu...
[ "You'll have to make it an app if you want to provide templates, template tags or filters with your library. Otherwise, Django won't pick them up.\n", "In my opinion, there is no benefits for middleware and decorators. My rule of thumb: If it has a model and/or views, I'll make it an app..\nEven for custom templa...
[ 2, 1, 0 ]
[]
[]
[ "django", "django_apps", "python" ]
stackoverflow_0004213138_django_django_apps_python.txt
Q: Why does this get a syntax error when exec() is called? I have a database of questions, and a few of those questions have need of special validation. So, I added a field to my model called py_validation and when those questions are answered, I validate them by running the code that is stored in py_validation. Wh...
Why does this get a syntax error when exec() is called?
I have a database of questions, and a few of those questions have need of special validation. So, I added a field to my model called py_validation and when those questions are answered, I validate them by running the code that is stored in py_validation. When I paste the code into the interpereter, it works correctly...
[ "Turns out to have a simple answer. The string contained \\r characters that python was not happy swallowing. The answer came as I was trying to figure out how to make a file like object to read the string from. The solution is:\ndef do_py_validate(field, value):\n exec field.py_validation.replace('\\r', '')\...
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0004215660_python.txt
Q: Can't "define" two databases in the same file of Python? I've just started learning Python and I'm slowly getting the hang of it, but I've faced a problem. I'm trying to make a simple website with articles using Google's App Launcher SDK. Now, everything worked fine when I followed the little guide in Google's sit...
Can't "define" two databases in the same file of Python?
I've just started learning Python and I'm slowly getting the hang of it, but I've faced a problem. I'm trying to make a simple website with articles using Google's App Launcher SDK. Now, everything worked fine when I followed the little guide in Google's site, but now I want to create another database: class Articles(d...
[ "It's not that you've defined two databases, but that you've tried to create two classes called Articles. Python can't keep both of them in its head at once, so once you made class Articles(webapp.RequestHandler), it replaced class Articles(db.Model).\nwebapp.RequestHandler doesn't have an all() method, and you've ...
[ 7, 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0004215694_google_app_engine_python.txt
Q: Change content of multiline file into a list How can I parse through the following file, and turn each line to an element of a list (there is a whitespace at the beginning of each line) ? Unfortunately I've always sucked at regex :/ So turn this: 32.42.4.120', '32.42.4.127 32.42.5.128', '32.42.5.255 32.42.15.13...
Change content of multiline file into a list
How can I parse through the following file, and turn each line to an element of a list (there is a whitespace at the beginning of each line) ? Unfortunately I've always sucked at regex :/ So turn this: 32.42.4.120', '32.42.4.127 32.42.5.128', '32.42.5.255 32.42.15.136', '32.42.15.143 32.58.129.0', '32.58.129.7 32....
[ "no regex needed:\nl = []\n\nwith open(\"name_file\", \"r\") as f:\n for line in f:\n l.append(line.split(\", \"))\n\nif you want to remove first space and to have tuple you can do:\nl = []\n\nwith open(\"name_file\", \"r\") as f:\n for line in f:\n data = line.split(\", \")\n l.append((data[0...
[ 1, 1, 1 ]
[]
[]
[ "list", "parsing", "python", "regex" ]
stackoverflow_0004215840_list_parsing_python_regex.txt
Q: Python Generator Function Names -- is a prefix helpful? Most functions are easy to name. Generally, a function name is based on what it does or the type of result it produces. In the case of a generator function, however, the result could be a iterable over some other type. def sometype( iterable ): for x i...
Python Generator Function Names -- is a prefix helpful?
Most functions are easy to name. Generally, a function name is based on what it does or the type of result it produces. In the case of a generator function, however, the result could be a iterable over some other type. def sometype( iterable ): for x in iterable: yield some_transformation( x ) The somet...
[ "Python dicts have iter* methods. And lxml trees also have an iter method.\nReading \nfor node in doc.iter():\n\nseems familiar, so\nfollowing that pattern, I'd consider naming the a generator of sometypes sometypes_iter\nso that I could write analgously, \nfor item in sometypes_iter():\n\nPython provides a sorted ...
[ 7 ]
[]
[]
[ "functional_programming", "generator", "hungarian_notation", "python" ]
stackoverflow_0004215906_functional_programming_generator_hungarian_notation_python.txt
Q: Passing data to j_security_check with python I have a j_security_check page on a server, and I need to pass data to it. I use Python urllib2 module, sending POST-request with j_username and j_password as parameters. The problem is that I have HTTPError 408 as a response: "The time allowed for the login process has...
Passing data to j_security_check with python
I have a j_security_check page on a server, and I need to pass data to it. I use Python urllib2 module, sending POST-request with j_username and j_password as parameters. The problem is that I have HTTPError 408 as a response: "The time allowed for the login process has been exceeded". What should I do with it?
[ "You could try GETing the login page first and storing the cookie.\nThis j_security_check-thingie looks like acegi security stuff.\nimport urllib, urllib2\n\nopener = urllib2.build_opener(urllib2.HTTPCookieProcessor)\nurllib2.install_opener(opener)\nurllib2.urlopen('http://server/login_form/')\nurllib2.urlopen('htt...
[ 2 ]
[]
[]
[ "j_security_check", "python", "urllib2" ]
stackoverflow_0004173016_j_security_check_python_urllib2.txt
Q: Python development under Mac I've been developing python web apps using django and appengine. I'm planning on buying a macbook to develop iPhone apps. I wonder if I will be able to develop my python apps without too much changes on a mac , or if keeping them on a PC will be better? Thanks A: Macs run Unix, Unix ...
Python development under Mac
I've been developing python web apps using django and appengine. I'm planning on buying a macbook to develop iPhone apps. I wonder if I will be able to develop my python apps without too much changes on a mac , or if keeping them on a PC will be better? Thanks
[ "Macs run Unix, Unix makes python development even easier! (IMHO)\nIn other news: one of python's big selling points is that it's multi-platform, it can run as well on Windows as on Linux as on a Mac. Heck, here's a list of other platforms it can run on.\nAll that to say, you can move your python projects back and...
[ 3, 1, 0, 0, 0 ]
[]
[]
[ "macos", "python" ]
stackoverflow_0004215164_macos_python.txt
Q: Page auto-update like in Twitter I wanna add page auto-update on my web site. It's written in Python and jquery, so I wanna try Twisted (or another COMET thing). The problem is about I don't know what exactly I need and what docs I have to read. A: Two options for using Twisted for COMET: Orbited Divmod Athena ...
Page auto-update like in Twitter
I wanna add page auto-update on my web site. It's written in Python and jquery, so I wanna try Twisted (or another COMET thing). The problem is about I don't know what exactly I need and what docs I have to read.
[ "Two options for using Twisted for COMET:\n\nOrbited\nDivmod Athena\n\nBoth of these have tutorials you'll have to read and work through, which won't fit into this small answer area, but you should be able to find them fairly easily. Good luck!\n", "use an ajax call with a setInterval, add new content - if any -...
[ 3, 1 ]
[]
[]
[ "jquery", "python", "twisted", "twitter" ]
stackoverflow_0004215816_jquery_python_twisted_twitter.txt
Q: Paramiko SFTP problems when no password is used I need to upload some files using SFTP, this works from the command line: $sftp myuser@my_remote_host Connected to my_remote_host sftp> This is my Paramiko script: #!/usr/bin/env python import paramiko import sys import os host = "my_remote_host" port = 22 transpo...
Paramiko SFTP problems when no password is used
I need to upload some files using SFTP, this works from the command line: $sftp myuser@my_remote_host Connected to my_remote_host sftp> This is my Paramiko script: #!/usr/bin/env python import paramiko import sys import os host = "my_remote_host" port = 22 transport = paramiko.Transport((host, port)) username = "my...
[ "In your first example, you can't authenticate with only a username, so the session can't be started.\nI can't tell why your privatekey example isn't working without some more information. Is it possible that its the incorrect key for that server? SSH on the command line may be trying multiple keys, or getting it f...
[ 2 ]
[]
[]
[ "paramiko", "python" ]
stackoverflow_0004209397_paramiko_python.txt
Q: What is causing paramiko.SSHException: Invalid packet blocking? When I attempt to connect to one of our internal servers using paramiko (inside of fabric, for what it's worth) I get this error: Retrieving packages from server p-websvr-004 [p-websvr-004] run: /usr/sbin/pkg_info -aD|grep "Information for" starting t...
What is causing paramiko.SSHException: Invalid packet blocking?
When I attempt to connect to one of our internal servers using paramiko (inside of fabric, for what it's worth) I get this error: Retrieving packages from server p-websvr-004 [p-websvr-004] run: /usr/sbin/pkg_info -aD|grep "Information for" starting thread (client mode): 0x179f090L Banner: -----------------------------...
[ "First obvious question, how is this host different than the rest?\nBy the looks of it, it could be a bug in the SSH server. Does openssh on the command line work, and is it using a different cipher?\n" ]
[ 0 ]
[]
[]
[ "paramiko", "python", "ssh" ]
stackoverflow_0003834688_paramiko_python_ssh.txt
Q: Execute background process from django that can't be interrupted by the web server I'm seeing all kinds of threads like this and they have accepted answers, and yet I'm still stuck on this. I have a view that should start a backup procedure, and I got it to the point where the view returns, and the process is stil...
Execute background process from django that can't be interrupted by the web server
I'm seeing all kinds of threads like this and they have accepted answers, and yet I'm still stuck on this. I have a view that should start a backup procedure, and I got it to the point where the view returns, and the process is still running in the background, however if apache is restarted, the backup process then die...
[ "You need to use a completely separate process for the backup. The best way to do this is to use a message queue - the view puts the backup request on the queue, and a separate listener picks it up and runs the backup, independently of Apache.\nCelery is a distributed task manager that deals with all this for you, ...
[ 8, 2 ]
[]
[]
[ "apache", "background", "django", "linux", "python" ]
stackoverflow_0004208624_apache_background_django_linux_python.txt
Q: Check integer base representation I define an integer like this: x = 0xFF But when i ask for its value to the interpreter i get: 255 Is there a way to force the interpreter to return me the value the same way I defined it? Is there a way to check the base representation for an integer? A: No. Neither Python n...
Check integer base representation
I define an integer like this: x = 0xFF But when i ask for its value to the interpreter i get: 255 Is there a way to force the interpreter to return me the value the same way I defined it? Is there a way to check the base representation for an integer?
[ "No. Neither Python nor any other language I know stores the base you write an integer literal in. 0xFF is indistinguishable from 255. These are both converted to the same underlying representation: binary.\n\nIf you want to remember a base then you need a different type than int. Perhaps store the integers in stri...
[ 4, 2, 1, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004216398_python.txt
Q: Python and ctypes: how to correctly pass "pointer-to-pointer" into DLL? I have a DLL that allocates memory and returns it. Function in DLL is like this: void Foo( unsigned char** ppMem, int* pSize ) { * pSize = 4; * ppMem = malloc( * pSize ); for( int i = 0; i < * pSize; i ++ ) (* ppMem)[ i ] = i; } Also, i...
Python and ctypes: how to correctly pass "pointer-to-pointer" into DLL?
I have a DLL that allocates memory and returns it. Function in DLL is like this: void Foo( unsigned char** ppMem, int* pSize ) { * pSize = 4; * ppMem = malloc( * pSize ); for( int i = 0; i < * pSize; i ++ ) (* ppMem)[ i ] = i; } Also, i have a python code that access this function from my DLL: from ctypes import...
[ "Post actual code. The C/C++ code doesn't compile as either C or C++. The Python code has syntax errors (] ending function call Foo). The code below works. The main issue after fixing syntax and compiler errors was declaring the function __stdcall so windll could be used in the Python code. The other option is...
[ 33 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0004213095_ctypes_python.txt
Q: Problems with Python 2.7 + wxPython 2.8.11? Should I switch back to Python 2.6.5 + wx.Python 2.8.10.1? I'm currently using Python 2.7 + wxPython 2.8.11 on my windows machine. While trying to build a small project (which also uses comtypes and lets say any activex such as flashwindow) I'm getting the following erro...
Problems with Python 2.7 + wxPython 2.8.11? Should I switch back to Python 2.6.5 + wx.Python 2.8.10.1?
I'm currently using Python 2.7 + wxPython 2.8.11 on my windows machine. While trying to build a small project (which also uses comtypes and lets say any activex such as flashwindow) I'm getting the following error: >>>"c:\Program Files\Python_2.7\python.exe" setup.py py2exe running py2exe *** searching for required mod...
[ "I've tried the older version too but not of much help but it helped making things clear to me. While trying to bundle the things in executable I got this warning/error/message:\n*** copy extensions ***\n*** copy dlls ***\ncopying C:\\Program Files\\Python_2.6.5\\w9xpopen.exe -> c:\\wxpython\\test\\dist\ncopying C:...
[ 0 ]
[]
[]
[ "comtypes", "py2exe", "python", "wxpython" ]
stackoverflow_0004208853_comtypes_py2exe_python_wxpython.txt
Q: How to split a string (using regex?) depending on digit/ not digit I want to split a string into a list in python, depending on digit/ not digit. For example, 5 55+6+ 5/ should return ['5','55','+','6','+','5','/'] I have some code at the moment which loops through the characters in a string and tests them usin...
How to split a string (using regex?) depending on digit/ not digit
I want to split a string into a list in python, depending on digit/ not digit. For example, 5 55+6+ 5/ should return ['5','55','+','6','+','5','/'] I have some code at the moment which loops through the characters in a string and tests them using re.match("\d") or ("\D"). I was wondering if there was a better way of...
[ "Assuming the + between 6 and 5 needs to be matched (which you're missing),\n>>> import re\n>>> s = '5 55+6+ 5/'\n>>> re.findall(r'\\d+|[^\\d\\s]+', s)\n['5', '55', '+', '6', '+', '5', '/']\n\n", "this one is simplest one :)\nre.findall('\\d+|[^\\d]+','134aaaaa')\n\n", "Use findall or finditer:\n>>> re.findall(...
[ 5, 2, 1, 0 ]
[]
[]
[ "python", "regex", "string", "tokenize" ]
stackoverflow_0004218502_python_regex_string_tokenize.txt
Q: building a python module on windows using ms compiler I am trying to build the example that comes with the source distribution of python under PC\example_nt I copied example.c and setup.py to a directory C:\mymod When I run C:\Python27\python.exe setup.py install I get the error.... error: Unable to find vcvarsall...
building a python module on windows using ms compiler
I am trying to build the example that comes with the source distribution of python under PC\example_nt I copied example.c and setup.py to a directory C:\mymod When I run C:\Python27\python.exe setup.py install I get the error.... error: Unable to find vcvarsall.bat I did some digging around in distutils and saw that it...
[ "Generally speaking you have to build the python modules using the same version of VS as python was built with. You have several options:\n\nUse Python2.6, which i think is VS8 (or an even earlier version, I'm sure there was a change between 2.5 and 2.6)\nUse VS9. I assume you can't because the proprietary library ...
[ 1 ]
[]
[]
[ "distutils", "python", "python_2.7", "visual_studio", "windows" ]
stackoverflow_0004218613_distutils_python_python_2.7_visual_studio_windows.txt
Q: twisted not detecting client disconnects Does anybody have experience with this? I have a twisted app. The clients connect to the server. I added a feature so that if a client connects to a server, but there's already a client from that IP address running, it disconnects the new client. Once in a while, I shutdown...
twisted not detecting client disconnects
Does anybody have experience with this? I have a twisted app. The clients connect to the server. I added a feature so that if a client connects to a server, but there's already a client from that IP address running, it disconnects the new client. Once in a while, I shutdown a client computer (or VM, to be precise) with...
[ "This is a Twisted FAQ, even though it doesn't really have anything to do with Twisted specifically.\n", "Heh I can't believe I forgot all that I learned in networking class...\n(2:09:44 PM) coworker: this is the expected behaviour\n(2:10:15 PM) coworker: the server has no way to know if someone dies, or is just ...
[ 5, 2 ]
[]
[]
[ "network_programming", "networking", "python", "twisted" ]
stackoverflow_0004218169_network_programming_networking_python_twisted.txt
Q: Wait for a twisted service to start before starting another I have written a proxy server that uses twisted's application framework. At it's core there it uses a DHT to resolve things. The DHT client takes a few seconds to start, so i want to make sure that the proxy only accepts connections after the DHT is ready...
Wait for a twisted service to start before starting another
I have written a proxy server that uses twisted's application framework. At it's core there it uses a DHT to resolve things. The DHT client takes a few seconds to start, so i want to make sure that the proxy only accepts connections after the DHT is ready. # there is a class like class EntangledDHT(object): # conn...
[ "Don't call serv.setServiceParent(service.IService(application)) right away. Instead, wait to call it in your callback to dht.ready. This will cause it to be started if the application service is already running.\nAlso, it doesn't look like dht itself is an IService. It should be; or rather, the thing that calls...
[ 2 ]
[]
[]
[ "python", "twisted", "twisted.application" ]
stackoverflow_0004218064_python_twisted_twisted.application.txt
Q: Set admin username to input field at Django admin I'm developing a system based on Django admin. So all models could be edited also only from admin site. Model has a char field 'user'. I want to set current logged in admin username (or firstname, or lastname) as default value to 'user' field. How could I implement...
Set admin username to input field at Django admin
I'm developing a system based on Django admin. So all models could be edited also only from admin site. Model has a char field 'user'. I want to set current logged in admin username (or firstname, or lastname) as default value to 'user' field. How could I implement this? Default values are set as parameters when defini...
[ "I found this recipe helpful: http://code.djangoproject.com/wiki/CookBookNewformsAdminAndUser\n", "This is how you do it on the form level and not the save http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield%5Ffor%5Fforeignkey\n" ]
[ 1, 1 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0004159659_django_django_admin_python.txt
Q: What is causing urllib2.urlopen() to connect via proxy? I'm trying to read a URL within our corporate network. Spesifically the server I'm contacting is in one office and the client PC is in another: print(urlopen(r"http://london.mycompany/mydir/").read()) Whenever I run this function I get: Traceback (most recen...
What is causing urllib2.urlopen() to connect via proxy?
I'm trying to read a URL within our corporate network. Spesifically the server I'm contacting is in one office and the client PC is in another: print(urlopen(r"http://london.mycompany/mydir/").read()) Whenever I run this function I get: Traceback (most recent call last): File "<stdin>", line 1, in ? File "C:\Python2...
[ "It reads from the system settings. Use urllib.FancyURLOpener:\nopener = urllib.FancyURLopener({})\nf = opener.open(\"http://london.mycompany/mydir/\")\nf.read()\n\n" ]
[ 2 ]
[]
[]
[ "http", "networking", "python" ]
stackoverflow_0004218809_http_networking_python.txt
Q: Google App Engine compatibility layer I'm planning an application running on Google App Engine. The only worry I would have is portability. Or just the option to have the app run on a local, private cluster. I expected an option for Google App Engine applications to run on other systems, a compatibility layer, to...
Google App Engine compatibility layer
I'm planning an application running on Google App Engine. The only worry I would have is portability. Or just the option to have the app run on a local, private cluster. I expected an option for Google App Engine applications to run on other systems, a compatibility layer, to spring up. I could imagine a GAE compatibl...
[ "The appscale project is designed to do exactly this. See https://github.com/AppScale/appscale/wiki\n", "\nI could imagine a GAE compatible framework utilizing Amazon SimpleDB or CouchDB \n to offer near 100% compatibility\n\nGAE/J uses DataNucleus for persistence. DataNucleus also has plugins for RDBMS, LDAP, ...
[ 6, 4, 2, 1, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0001589743_google_app_engine_python.txt
Q: ANSI graphic codes and Python I was browsing the Django source code and I saw this function: def colorize(text='', opts=(), **kwargs): """ Returns your text, enclosed in ANSI graphics codes. Depends on the keyword arguments 'fg' and 'bg', and the contents of the opts tuple/list. Returns the R...
ANSI graphic codes and Python
I was browsing the Django source code and I saw this function: def colorize(text='', opts=(), **kwargs): """ Returns your text, enclosed in ANSI graphics codes. Depends on the keyword arguments 'fg' and 'bg', and the contents of the opts tuple/list. Returns the RESET code if no parameters are give...
[ "It's that you have many terms undefined, because it relies on several variables defined outside of the function.\nInstead just \nimport django.utils.termcolors as termcolors\nred_hello = termcolors.colorize(\"Hello\", fg='red') # '\\x1b[31mHello\\x1b[0m'\nprint red_hello\n\nOr just also copy the first few lines of...
[ 1 ]
[]
[]
[ "ansi", "python" ]
stackoverflow_0004219057_ansi_python.txt
Q: Can't understand a line in a "Collective intelligence" program I'm working through "Programming collective intelligence". In chapter 4, Toby Segaran builds an artificial neural network. The following function appears on page of the book: def generatehiddennode(self,wordids,urls): if len(wordids)>3: return None ...
Can't understand a line in a "Collective intelligence" program
I'm working through "Programming collective intelligence". In chapter 4, Toby Segaran builds an artificial neural network. The following function appears on page of the book: def generatehiddennode(self,wordids,urls): if len(wordids)>3: return None # Check if we already created a node for this set of words sorted...
[ "For a published book, that's pretty terrible code! (You can download all the examples for the book from here; the relevant file is chapter4/nn.py.)\n\nNo docstring. What is this function supposed to do? From its name, we can guess that it's generating one of the nodes in the \"hidden layer\" of a neural network, ...
[ 6, 1, 0 ]
[]
[]
[ "debugging", "python" ]
stackoverflow_0004216108_debugging_python.txt
Q: how to build a python proxy server on google appengine I live in China and the Great Firewall blocked Youtube and twitter. So I want to build a proxy server on google appengine in python to bypass that. Does anyone know any open source GAE project on that? Thx~ A: You may try gappproxy http://code.google.com/p/g...
how to build a python proxy server on google appengine
I live in China and the Great Firewall blocked Youtube and twitter. So I want to build a proxy server on google appengine in python to bypass that. Does anyone know any open source GAE project on that? Thx~
[ "You may try gappproxy http://code.google.com/p/gappproxy/\nBut since the keyword gappproxy is blocked by censors, which means you cannot visit any url containing the keyword in China, you may first find a web proxy like http://4624.info to visit the project homepage.\nBy the way, you don't have to use those tools ...
[ 4, 1 ]
[]
[]
[ "google_app_engine", "proxy", "python" ]
stackoverflow_0002264583_google_app_engine_proxy_python.txt
Q: Importing classes in python I have a little module that creates a window (program1). I'd like to import this into another python program of mine (program2). How would I make it so I can make so program1 makes a window when referred to by program2? The module I'd like to import(program1). import Tkinter class Cla...
Importing classes in python
I have a little module that creates a window (program1). I'd like to import this into another python program of mine (program2). How would I make it so I can make so program1 makes a window when referred to by program2? The module I'd like to import(program1). import Tkinter class Class(Tkinter.Tk): def __init__...
[ "If you want to run the mainloop from program2, then:\nimport program1\napp = program1.Class(None)\napp.mainloop()\n\nor, for less duplication:\n# program1.py\n...\ndef main():\n app = class(None)\n app.mainloop()\n\nif __name__ == \"__main__\":\n main()\n\nand then\n# program2.py\nimport program1\nprogram1.main...
[ 4 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0004219716_python_tkinter.txt
Q: Why fmod(1.0,0.1) == .1? I experienced this phenomenon in Python first, but it turned out that it is the common answer, for example MS Excel gives this. Wolfram Alpha gives an interesting schizoid answer, where it states that the rational approximation of zero is 1/5. ( 1.0 mod 0.1 ) On the other hand, if I implem...
Why fmod(1.0,0.1) == .1?
I experienced this phenomenon in Python first, but it turned out that it is the common answer, for example MS Excel gives this. Wolfram Alpha gives an interesting schizoid answer, where it states that the rational approximation of zero is 1/5. ( 1.0 mod 0.1 ) On the other hand, if I implement the definition by hand it ...
[ "Because 0.1 isn't 0.1; that value isn't representable in double precision, so it gets rounded to the nearest double-precision number, which is exactly:\n0.1000000000000000055511151231257827021181583404541015625\n\nWhen you call fmod, you get the remainder of division by the value listed above, which is exactly:\n0...
[ 23, 1, 1, 0, 0, 0 ]
[]
[]
[ "floating_point", "math", "python" ]
stackoverflow_0004218961_floating_point_math_python.txt
Q: Sorting data for plotting in mplot3d I have been using mplot3d (part of matplotlib) for some various 3d plotting, and it has been performing the job admirably. However, I have run into a new problem. Mplot3d expects data to be sorted in a certain fashion, to plot a wireframe. For example, it likes something like...
Sorting data for plotting in mplot3d
I have been using mplot3d (part of matplotlib) for some various 3d plotting, and it has been performing the job admirably. However, I have run into a new problem. Mplot3d expects data to be sorted in a certain fashion, to plot a wireframe. For example, it likes something like this: x = array([[1, 2, 3], [1,...
[ "If I understand you correctly, you just want to do this: x[1::2, :] = x[1::2, ::-1]. \nThere are a few kinks... If you don't make an intermediate copy of x it doesn't quite do what you'd expect due to the way broadcasting works in numpy. \nNonetheless, it's still pretty simple to do with basic indexing:\nimport ...
[ 2 ]
[]
[]
[ "matplotlib", "numpy", "python", "sorting" ]
stackoverflow_0004219723_matplotlib_numpy_python_sorting.txt
Q: Convert float 27.7 to 27.70 can anyone tell me a simple way to print out a float 27.7 as 27.70 ? thanks. A: a = 27.7 print '%.2f' % a 27.70 A: If you're worrying about number of digits after point, you probably need use decimal.Decimal Cite from the docs: Decimal numbers can be represented exactly. In contras...
Convert float 27.7 to 27.70
can anyone tell me a simple way to print out a float 27.7 as 27.70 ? thanks.
[ "a = 27.7\nprint '%.2f' % a\n27.70\n\n", "If you're worrying about number of digits after point, you probably need use decimal.Decimal Cite from the docs:\n\nDecimal numbers can be represented exactly. In contrast, numbers like 1.1 and 2.2 do not have an exact representations in binary floating point. End users t...
[ 8, 2 ]
[]
[]
[ "python" ]
stackoverflow_0004220110_python.txt
Q: How can I fetch() more than 1MB on Google App Engine? Google App Engine limits urlfetch.fetch() responses to 1MB. Is there any workaround of this (switching to paid version maybe)? I'm using Python and if it's possible to provide an example that would be great. A: With the brand new SDK 1.4.0 you can download 32...
How can I fetch() more than 1MB on Google App Engine?
Google App Engine limits urlfetch.fetch() responses to 1MB. Is there any workaround of this (switching to paid version maybe)? I'm using Python and if it's possible to provide an example that would be great.
[ "With the brand new SDK 1.4.0 you can download 32MByte; keep in mind that you still have the 10 seconds Deadline limit though ;-) . deadline can be up to a maximum of 60 seconds for request handlers and 10 minutes for tasks queue and cron job handlers.\n\nURLFetch allowed response size has\n been increased, up to ...
[ 3, 2 ]
[]
[]
[ "google_app_engine", "python", "urlfetch" ]
stackoverflow_0004109255_google_app_engine_python_urlfetch.txt
Q: Best method to locate object with opencv What is the most efficient way using opencv and python to locate and return the coordinates of a single object that has a constant color? I have seen a few ways to do so using c++, but info on object location using python is sparse. A: I am not sure what you are looking f...
Best method to locate object with opencv
What is the most efficient way using opencv and python to locate and return the coordinates of a single object that has a constant color? I have seen a few ways to do so using c++, but info on object location using python is sparse.
[ "I am not sure what you are looking for exactly, but I think you should have a look at the Haar classification.\nSee here for example:\nhttp://cgi.cse.unsw.edu.au/~cs4411/wiki/index.php?title=OpenCV_Guide#Haar_Classifier\n", "To be more specific if you have an object with single colour you can look at the camshif...
[ 1, 1 ]
[]
[]
[ "location", "object", "opencv", "python" ]
stackoverflow_0004220271_location_object_opencv_python.txt
Q: Python/Tkinter: bind to event related to currently selected menu item Wondering if there's a menu event I can bind to that's related to the currently selected menu item? By menu item I mean the items that show up in a popup menu like New, Open, Save, etc. Use case: I would like to update a statusbar area of our ap...
Python/Tkinter: bind to event related to currently selected menu item
Wondering if there's a menu event I can bind to that's related to the currently selected menu item? By menu item I mean the items that show up in a popup menu like New, Open, Save, etc. Use case: I would like to update a statusbar area of our application with a description of the currently selected menu item. Any ideas...
[ "You need to bind to the <<MenuSelect>> event.\n" ]
[ 2 ]
[ "There's an <Enter> event that is triggered when the mouse pointer enters a widget's space. Depending on how you're building your menu, you may be able to use it.\nSee http://www.pythonware.com/library/tkinter/introduction/events-and-bindings.htm for more\n" ]
[ -1 ]
[ "menu", "python", "tkinter" ]
stackoverflow_0004220441_menu_python_tkinter.txt
Q: Terminating raw_input() if other text displays I have a simple server application I made in Python using SocketServer, it has a very primitive command line type input system. My main problem here is that when the server receives a message, it prints it to the screen. This is all fine and good except that the raw_i...
Terminating raw_input() if other text displays
I have a simple server application I made in Python using SocketServer, it has a very primitive command line type input system. My main problem here is that when the server receives a message, it prints it to the screen. This is all fine and good except that the raw_input function is still waiting for text to entered a...
[ "As far as I know, this isn't possible because raw_input accepts input from the python command console. There are, however, some ways to get around it that may not be expected:\n1 - Instead of using the console, create a simple Tkinter window with the output and an input line. Create a custom print function that ap...
[ 1 ]
[]
[]
[ "python", "raw_input" ]
stackoverflow_0004220702_python_raw_input.txt
Q: pySerial freezing after reading 3 times We are programming a pic and we've diagnosed that if we send data to serial port while its trying to send data to us, the program will lock up (both our python code and hyperterminal will crash when tested). It worked in hyperterminal and inputting it slowly (>.5 seconds bet...
pySerial freezing after reading 3 times
We are programming a pic and we've diagnosed that if we send data to serial port while its trying to send data to us, the program will lock up (both our python code and hyperterminal will crash when tested). It worked in hyperterminal and inputting it slowly (>.5 seconds between strokes), and would crash when the keybo...
[ "(This answer assumes that you are using a PIC16, suggested by the names of certain registers.) \nIn short, it looks like a buffer overflow coupled with a bug in that loop in receiveData. The fact that it's freezing after three characters are sent in short succession might be explained by p117 of the manual:\n\nIt ...
[ 2, 1 ]
[]
[]
[ "pic", "pyserial", "python", "serial_port" ]
stackoverflow_0004219868_pic_pyserial_python_serial_port.txt
Q: Splitting a string into a list in python I have a long string of characters which I want to split into a list of the individual characters. I want to include the whitespaces as members of the list too. How do I do this? A: you can do: list('foo') spaces will be treated as list members (though not grouped togeth...
Splitting a string into a list in python
I have a long string of characters which I want to split into a list of the individual characters. I want to include the whitespaces as members of the list too. How do I do this?
[ "you can do:\nlist('foo')\n\nspaces will be treated as list members (though not grouped together, but you didn't specify you needed that) \n>>> list('foo')\n['f', 'o', 'o']\n>>> list('f oo')\n['f', ' ', 'o', 'o']\n\n", "Here some comparision on string and list of strings, and another way to make list out of st...
[ 12, 0, 0 ]
[]
[]
[ "python", "split", "string" ]
stackoverflow_0004216489_python_split_string.txt
Q: python regex grouping Given string s = '(A /something_1)(B /something_2)(C /something_3),/,(D /something_4)(D /something_5)' I would like to get this output: (C /something_3),/,(D /something_4)(D /something_5) I keep matching the whole string s, instead of getting above substring. I am using re.search(r'(\(C.*\)),...
python regex grouping
Given string s = '(A /something_1)(B /something_2)(C /something_3),/,(D /something_4)(D /something_5)' I would like to get this output: (C /something_3),/,(D /something_4)(D /something_5) I keep matching the whole string s, instead of getting above substring. I am using re.search(r'(\(C.*\)),/,(\(D.*\))+') Any help is...
[ "You're just about there - re.search(r'(\\(C.*\\)),/,(\\(D.*\\))+', s).group() will get you what you want.\n>>> import re\n>>> s = '(A /something_1)(B /something_2)(C /something_3),/,(D /something_4)(D /something_5)'\n>>> re.search(r'(\\(C.*\\)),/,(\\(D.*\\))+', s).group()\n'(C /something_3),/,(D /something_4)(D /s...
[ 4, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0004221534_python_regex.txt
Q: How to set up "front page" documentation on PYPI for a project? I would like to add basic documentation content to the front page of PYPI of my module like it's done, for example, here: http://pypi.python.org/pypi/Jinja2. Right now the askbot download page has a default look and does not have much useful info, how...
How to set up "front page" documentation on PYPI for a project?
I would like to add basic documentation content to the front page of PYPI of my module like it's done, for example, here: http://pypi.python.org/pypi/Jinja2. Right now the askbot download page has a default look and does not have much useful info, how can it be added? That is - which parts of the distribution package f...
[ "Did you take a look at : http://pypi.python.org/pypi/an_example_pypi_project\nAlso PyPI attempts to parse the \"long_description\" from your meta-data as ReStructuredText. You could use that to provide a good information rendering.\n", "If you're logged in you can edit the \"Description\" section of your package...
[ 5, 1 ]
[]
[]
[ "packaging", "pypi", "python" ]
stackoverflow_0004221555_packaging_pypi_python.txt
Q: Python Numpy nan_to_num help I'm having some trouble with Numpy's nan_to_num function: I've got an array where the last column contains fewer elements than the other columns, and when I import it into Python, it places 'nan's to fill out the array. That's just fine until I need to do some other things that get tri...
Python Numpy nan_to_num help
I'm having some trouble with Numpy's nan_to_num function: I've got an array where the last column contains fewer elements than the other columns, and when I import it into Python, it places 'nan's to fill out the array. That's just fine until I need to do some other things that get tripped-up by the 'nan's. I'm trying ...
[ "You haven't changed the value of a. Try this:\na = numpy.array([[1, nan, 3]])\na = numpy.nan_to_num(a)\nprint a\n\n" ]
[ 4 ]
[]
[]
[ "function", "numpy", "python" ]
stackoverflow_0004221475_function_numpy_python.txt
Q: How do i get the username and email when someone logins to my site using google or openid? What does google return? i used pinax, the user who login my site, use openid, is successful now. i only want to get the username and email when they return . the google openid url is :https://www.google.com/accounts/o8/i...
How do i get the username and email when someone logins to my site using google or openid? What does google return?
i used pinax, the user who login my site, use openid, is successful now. i only want to get the username and email when they return . the google openid url is :https://www.google.com/accounts/o8/id and yahoo openid url is :http://yahoo.com/ How can i get it?
[ "Use http://code.google.com/p/django-openid/ (documentation available at http://django-openid.googlecode.com/svn/trunk/openid.html)\n", "There are two main methods to do this. One is using the \"simple\nregistration\" (sreg) extension of OpenID. This seems like the easiest\nway, and while it worked when using my...
[ 1, 1, 0 ]
[]
[]
[ "django", "openid", "pinax", "python" ]
stackoverflow_0002264669_django_openid_pinax_python.txt
Q: How do I add tags to certain strings in python using re.sub? I'm trying to add tags to some given query strings, and the tags should wrap around all the matching strings. For example, I want to wrap tags around all the words that match the query iphone games mac in the sentence I love downloading iPhone games fr...
How do I add tags to certain strings in python using re.sub?
I'm trying to add tags to some given query strings, and the tags should wrap around all the matching strings. For example, I want to wrap tags around all the words that match the query iphone games mac in the sentence I love downloading iPhone games from my mac. It should be I love downloading <em>iPhone games</em> f...
[ "First of all, to get the spaces as you want them, replace \\s* with \\s*? to make it non-greedy.\nFirst fix:\n>>> re.compile(r'(((iphone|games|mac)\\s*?)+)', re.I).sub(r'<em>\\1</em>', sentence)\n'I love downloading <em>iPhone</em> <em>games</em> from my <em>mac</em>.'\n\nUnfortunately, once the \\s* is non-greedy...
[ 5, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0004221509_python_regex.txt
Q: Python: sqlite OR statement Is there an OR sqlite statement? I've been trying to google it, but google seems to be filtering out the OR. For example if I wanted to find someone in this table (people) people: +--fname--+--lname--+--has_squirrel--+ |Eric |Schmidt |0 | +---------+---------+--------...
Python: sqlite OR statement
Is there an OR sqlite statement? I've been trying to google it, but google seems to be filtering out the OR. For example if I wanted to find someone in this table (people) people: +--fname--+--lname--+--has_squirrel--+ |Eric |Schmidt |0 | +---------+---------+----------------+ |Elvis |Presley |1 ...
[ "It would be one of those :\nSELECT * FROM people WHERE fname IN ('Elvis', 'Richard');\nSELECT * FROM people WHERE fname = 'Elvis' OR fname = 'Richard';\n\nI'm surprised your first query even works, and in your second, or 'Richard' basically means or 1=1, which is always true, for every row in your table.\nYour com...
[ 21, 3, 0, 0, 0 ]
[]
[]
[ "linux", "python", "sql", "sqlite", "ubuntu" ]
stackoverflow_0004221956_linux_python_sql_sqlite_ubuntu.txt
Q: Why pysqlite does not work properly? I tried to install pysqlite. Some suspicious things start to appear during the installation. Why I typed: python setup.py build I got the following message in the end: src/module.c:286: error: ‘SQLITE_PRAGMA’ undeclared here (not in a function) src/module.c:287: error: ‘SQLITE...
Why pysqlite does not work properly?
I tried to install pysqlite. Some suspicious things start to appear during the installation. Why I typed: python setup.py build I got the following message in the end: src/module.c:286: error: ‘SQLITE_PRAGMA’ undeclared here (not in a function) src/module.c:287: error: ‘SQLITE_READ’ undeclared here (not in a function)...
[ "\nI just ignored the last line and decided to continue.\n\nYou can't just ignore the last line. It was telling you there was an error, so it couldn't compile. The next thing you ran told you it couldn't install because it couldn't compile. Then, your python told you it couldn't run the code because it wasn't insta...
[ 3, 2, 2 ]
[]
[]
[ "installation", "pysqlite", "python", "sqlite" ]
stackoverflow_0001460136_installation_pysqlite_python_sqlite.txt
Q: ActivePython and MySQLdb I have installed ActivePython and am trying to import MySQLdb >> import mySQLdb gives me an error stating No module called MySQLdb I have tried searching but all the resources out there explain how to set up the mySQLdb for unix, not for windows, can you please tell me how I can do that ...
ActivePython and MySQLdb
I have installed ActivePython and am trying to import MySQLdb >> import mySQLdb gives me an error stating No module called MySQLdb I have tried searching but all the resources out there explain how to set up the mySQLdb for unix, not for windows, can you please tell me how I can do that with ActivePython? I am also p...
[ "You can find a detailed HOWTO over here\n", "To install MySQL-Python,\npypm install mysql-python\n\n" ]
[ 0, 0 ]
[]
[]
[ "activepython", "mysql", "python" ]
stackoverflow_0002551856_activepython_mysql_python.txt
Q: Get and set data on Google App Engine How can I store some data on Google App Engine? I'm using Django. A: Assuming you don't want to just write web form pages to do this, you might want to take a look at http://code.google.com/appengine/docs/python/tools/uploadingdata.html which explains a few different ways t...
Get and set data on Google App Engine
How can I store some data on Google App Engine? I'm using Django.
[ "Assuming you don't want to just write web form pages to do this, you might want to take a look at http://code.google.com/appengine/docs/python/tools/uploadingdata.html which explains a few different ways to import/export data from the appengine datastore.\n", "You can use google app engine helper. Django cannot ...
[ 0, 0 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0002656876_django_google_app_engine_python.txt
Q: Python/Urllib2/Threading: Single download thread faster than multiple download threads. Why? i am working on a project that requires me to create multiple threads to download a large remote file. I have done this already but i cannot understand while it takes a longer amount of time to download a the file with mul...
Python/Urllib2/Threading: Single download thread faster than multiple download threads. Why?
i am working on a project that requires me to create multiple threads to download a large remote file. I have done this already but i cannot understand while it takes a longer amount of time to download a the file with multiple threads compared to using just a single thread. I used my xampp localhost to carry out the t...
[ "9 women can't combine to make a baby in one month. If you have 10 threads, they each have only 10% the bandwidth of a single thread, and there is the additional overhead for context switching, etc. \n", "Python threading use something call the GIL (Golbal Interpreter Lock) that sometime degrade the programs ex...
[ 4, 1, 1 ]
[]
[]
[ "download", "multithreading", "python", "urllib2" ]
stackoverflow_0004219134_download_multithreading_python_urllib2.txt
Q: Python Program to use the resources of systems over internet? i am fairly new to python , was wondering if i could remotely connect to another system over net , both the systems have different ISPs . can i write a program to connect to that system and use it resources , ofcourse with that systems permission. PS: i...
Python Program to use the resources of systems over internet?
i am fairly new to python , was wondering if i could remotely connect to another system over net , both the systems have different ISPs . can i write a program to connect to that system and use it resources , ofcourse with that systems permission. PS: it kinda sounds like hacking into system without permission , but i ...
[ "What you're describing sounds a lot like RPC (Remote Procedure Calls). Python has libraries that handle RPC using XML to pass parameters and results (which frees you from dealing with binary format issues), which are xmlrpclib on the client side and SimpleXMLRPCServer or DocXMLRPCServer on the server end.\nIt's on...
[ 1, 0 ]
[]
[]
[ "networking", "python" ]
stackoverflow_0004222595_networking_python.txt
Q: how stackless python can be fast for concurrency? stackless python didn't take a good usage of multi-core, so where is the point it should be faster than python thread/multiprocessing ? all the benchmark use stackless python tasklet to compare with python thread lock and queue, that's unfair, cause lock always has...
how stackless python can be fast for concurrency?
stackless python didn't take a good usage of multi-core, so where is the point it should be faster than python thread/multiprocessing ? all the benchmark use stackless python tasklet to compare with python thread lock and queue, that's unfair, cause lock always has low efficiency see, if use single thread function ca...
[ "Focus on functionality first, and performance second (unless you know you have the need). \nMost of the time on a server is spent with I/O, so multi-cores do not help so much. If it is mostly I/O that you are working with, multi-threading python may be the simplest answer. \nIf the server requests are CPU intens...
[ 2, 0 ]
[]
[]
[ "concurrency", "python", "python_stackless", "stackless" ]
stackoverflow_0001854278_concurrency_python_python_stackless_stackless.txt
Q: Celery with non-homogenous tasks I have two celery workers, worker 1 has tasks A and B, worker 2 with tasks A, B, and C. If I submit a task C, it doesn't seem to be executed in the celery worker that has task C; is there some way I can make sure that only worker 2 gets assigned tasks C? A: I'd take a look at rou...
Celery with non-homogenous tasks
I have two celery workers, worker 1 has tasks A and B, worker 2 with tasks A, B, and C. If I submit a task C, it doesn't seem to be executed in the celery worker that has task C; is there some way I can make sure that only worker 2 gets assigned tasks C?
[ "I'd take a look at routing tasks in the documentation. You can create queues with specific topics, and specify which worker(s) can handle which queue(s).\n" ]
[ 3 ]
[]
[]
[ "celery", "celery_task", "python", "task" ]
stackoverflow_0004222386_celery_celery_task_python_task.txt
Q: What are the first steps in order to start with Django/Python 2.7? I have installed Python 2.7 for Windows, and downloaded Django-1.2.3. Now, I want to build my first website with them. How can I get to the first hello world page, in a browser? Can I use Apache/XAMPP to go to http://localhost ? What are the base p...
What are the first steps in order to start with Django/Python 2.7?
I have installed Python 2.7 for Windows, and downloaded Django-1.2.3. Now, I want to build my first website with them. How can I get to the first hello world page, in a browser? Can I use Apache/XAMPP to go to http://localhost ? What are the base principles to get a website working? Thank you
[ "Just read the excellent and thorough Django tutorial. Django comes with a built-in simple web-server that you can run your websites on. It's just a Python script you run, and then you go to a port on localhost (by default port 8000). It's really quite simple and well-explained in the tutorial.\nSpecifically, look ...
[ 5, 0 ]
[]
[]
[ "django", "python", "webserver" ]
stackoverflow_0004223070_django_python_webserver.txt
Q: Multi line log parsing for service times in PHP/Python What's the best way to parse a multi line log file that require contextual knowledge from previous lines in php and/or python? ex. Date Time ID Call 1/1/10 00:00:00 1234 Start 1/1/10 00:00:01 1234 ServiceCall A Starts 1/1/10 00:00:05 1234 ServiceCa...
Multi line log parsing for service times in PHP/Python
What's the best way to parse a multi line log file that require contextual knowledge from previous lines in php and/or python? ex. Date Time ID Call 1/1/10 00:00:00 1234 Start 1/1/10 00:00:01 1234 ServiceCall A Starts 1/1/10 00:00:05 1234 ServiceCall B Starts 1/1/10 00:00:06 1234 ServiceCall A Finishes 1/1/...
[ "I can think of two different ways of doing this.\n1) You can use a finite state machine to process the file line by line. When you hit a Start line, mark the time. When you hit a Stop line with the same ID, diff the time and report.\n2) Use PHP's Perl-Compatible Regular Expressions with the m modifier to match a...
[ 0, 0, 0 ]
[]
[]
[ "multiline", "php", "python" ]
stackoverflow_0004221965_multiline_php_python.txt
Q: How to handle Out of memory with Python I have huge dictionaries that I manipulate. More than 10 Million words are hashed. Its is too slow and some time it goes out of memory. Is there a better way to handle these huge data structure ? A: Yes. It's called a database. Since a dictionary was working for you (asi...
How to handle Out of memory with Python
I have huge dictionaries that I manipulate. More than 10 Million words are hashed. Its is too slow and some time it goes out of memory. Is there a better way to handle these huge data structure ?
[ "Yes. It's called a database. Since a dictionary was working for you (aside from memory concerns) I would suppose that an sqlite database would work fine for you. You can use the sqlite3 quite easily and it is very well documented.\nOf course this will only be a good solution if you can represent the values as some...
[ 9, 1 ]
[]
[]
[ "nlp", "python" ]
stackoverflow_0004223130_nlp_python.txt
Q: Opencv + blobs in python I need a bit of help with blobs in opencv (python). This is the thing: I've already written the preprocessing functions that work properly, they isolate the areas of interest and return a thresholded image, where these areas are white, the rest is black. The thing is, I'm only interested i...
Opencv + blobs in python
I need a bit of help with blobs in opencv (python). This is the thing: I've already written the preprocessing functions that work properly, they isolate the areas of interest and return a thresholded image, where these areas are white, the rest is black. The thing is, I'm only interested in the white areas but no matte...
[ "CvSet is a class - so not sure what second line is doing. Also no Blobs as native in Python - is this a cv.CvSet or a cv.CvSeq sequence that is being returned ?\nor are you finding contours after thresholding - then traversing them as in contours.py example ? which may be a better approach...\n" ]
[ 0 ]
[]
[]
[ "blobs", "opencv", "python" ]
stackoverflow_0004197242_blobs_opencv_python.txt
Q: Which registry / environment (or other) settings does urllib2.urlopen use to determine proxy settings? Following on from this question: What is causing urllib2.urlopen() to connect via proxy? I'd like to know which operating system & environmental settings can affect urllib2.urlopen? For example, I've noticed that...
Which registry / environment (or other) settings does urllib2.urlopen use to determine proxy settings?
Following on from this question: What is causing urllib2.urlopen() to connect via proxy? I'd like to know which operating system & environmental settings can affect urllib2.urlopen? For example, I've noticed that on some machines within our very large corporation urllib2.urlopen insists on connecting via a proxy. This ...
[ "You can see the exact code, but as the docs say the registry section is Internet Settings:\nHKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\n\n" ]
[ 2 ]
[]
[]
[ "networking", "python", "urllib2", "urlopen" ]
stackoverflow_0004223801_networking_python_urllib2_urlopen.txt
Q: django and csrf_token problem I have a little problem with the token in django. When I write a POST form and add {{csrf_token}}, when I submit it the token is checked . But when I send a POST request (in ajax) and add the paramater manually csrfmiddlewaretoken , the token is not checked. But I don't know why ? T...
django and csrf_token problem
I have a little problem with the token in django. When I write a POST form and add {{csrf_token}}, when I submit it the token is checked . But when I send a POST request (in ajax) and add the paramater manually csrfmiddlewaretoken , the token is not checked. But I don't know why ? Thanks.
[ "AJAX requests are not checked for CSRF: the browser's same origin policy means that CSRF attacks are much harder. See the explanation in the docs.\n" ]
[ 6 ]
[]
[]
[ "django", "python", "token" ]
stackoverflow_0004223719_django_python_token.txt
Q: Django: When doing an include of URL's, should I specify project.app or just app When including an app's URL's in the project's urls.py, my coding partner does it this way: ('^stops/', include('stops.urls')) However, Django documentation specifies the following syntax: ('^clients/', include('project_name.app_name...
Django: When doing an include of URL's, should I specify project.app or just app
When including an app's URL's in the project's urls.py, my coding partner does it this way: ('^stops/', include('stops.urls')) However, Django documentation specifies the following syntax: ('^clients/', include('project_name.app_name.urls')) His way has worked. Is there a reason to specify the project name at all?
[ "It depends on your PYTHONPATH setting and the structure of your projects and apps.\nWe have many, many projects. Each with several apps. All are on our PYTHONPATH, so the project name is essential.\nIf you have only one project, and the top-level project directory is on your PYTHONPATH, then each app can be reso...
[ 2, 1, 0 ]
[]
[]
[ "django", "django_urls", "python" ]
stackoverflow_0004221070_django_django_urls_python.txt
Q: Any reason there are no returned value from set.add Current, since the returned value from set.add is always None. I have to do the following. if 1 in s: print 'already found' return s.add(1) Would it be nice if I can if not s.add(1): print 'already found' return A: >>> None == False False >>> N...
Any reason there are no returned value from set.add
Current, since the returned value from set.add is always None. I have to do the following. if 1 in s: print 'already found' return s.add(1) Would it be nice if I can if not s.add(1): print 'already found' return
[ ">>> None == False\nFalse\n>>> None == True\nFalse\n>>> None == None\nTrue\n>>> not None\nTrue\n\nIf s.add always returns None, then your condition will always be True. But since s is a set, just add the value to it. You can't have duplicate values in a set, by definition :\n>>> a = set()\n>>> a.add(1)\n>>> a\n{1}\...
[ 7, 4 ]
[]
[]
[ "python" ]
stackoverflow_0004221968_python.txt
Q: Python interpreter embedded in the application fails to load native modules I have an application that statically links to libpython.a (2.7). From within the application's interpreter I try importing time module (time.so), which fails with: ImportError: ./time.so: undefined symbol: PyExc_IOError So, this module h...
Python interpreter embedded in the application fails to load native modules
I have an application that statically links to libpython.a (2.7). From within the application's interpreter I try importing time module (time.so), which fails with: ImportError: ./time.so: undefined symbol: PyExc_IOError So, this module has unresolved symbols: nm -D time.so | grep PyExc_IOError U PyExc_IOErro...
[ "Besides making sure all of libpython is included in your binary, you also need to make sure the symbols in the library are exposed to shared objects being loaded. When you're linking libpython (statically) into your main binary this means you need the --export-dynamic linker argument (so -Wl,--export-dynamic or -X...
[ 2 ]
[]
[]
[ "c", "linux", "python" ]
stackoverflow_0004223312_c_linux_python.txt
Q: calling a function from dll in python I am trying to make a call from python to a dll but am getting an access violation.Can some please tell me how to use ctypes correctly in the following code. GetItems is supposed return a struct that looks like this struct ITEM { unsigned short id; unsigned char i; unsigne...
calling a function from dll in python
I am trying to make a call from python to a dll but am getting an access violation.Can some please tell me how to use ctypes correctly in the following code. GetItems is supposed return a struct that looks like this struct ITEM { unsigned short id; unsigned char i; unsigned int c; unsigned int f; unsigned int p; ...
[ "First off, you're calling get_item, while your class only has get_inventory_item defined, and you're discarding the result, and capitalization of myDLL is inconsistent.\nYou need to define a Ctypes type for your struct, like this:\nclass ITEM(ctypes.Structure):\n _fields_ = [(\"id\", c_ushort),\n ...
[ 0 ]
[]
[]
[ "ctypes", "dll", "python" ]
stackoverflow_0004224331_ctypes_dll_python.txt
Q: Implementing sub-table (view into a table): designing class relationship I'm using Python 3, but the question isn't really tied to the specific language. I have class Table that implements a table with a primary key. An instance of that class contains the actual data (which is very large). I want to allow users to...
Implementing sub-table (view into a table): designing class relationship
I'm using Python 3, but the question isn't really tied to the specific language. I have class Table that implements a table with a primary key. An instance of that class contains the actual data (which is very large). I want to allow users to create a sub-table by providing a filter for the rows of the Table. I don't w...
[ "I'm going to use the following (I omitted many methods such as sort, which work quite well in this arrangement; also omitted error handling):\nclass Table:\n def __init__(self, *columns, pkey = None):\n self.pkey = pkey\n self.__columns = columns\n self.__data = {}\n\n def __contains__(s...
[ 1 ]
[]
[]
[ "data_structures", "design_patterns", "oop", "python", "python_3.x" ]
stackoverflow_0004219032_data_structures_design_patterns_oop_python_python_3.x.txt
Q: Python libxml2 parsing xml having Chinese characters i encountered encoding problems when using libxml2 in python to parse Chinese charactors # coding=utf8 import libxml2 def output(data): doc = libxml2.parseMemory(data, len(data)) ctxt = doc.xpathNewContext() res_rslt = ctxt.xpathEval("/r/e/attribute::Name...
Python libxml2 parsing xml having Chinese characters
i encountered encoding problems when using libxml2 in python to parse Chinese charactors # coding=utf8 import libxml2 def output(data): doc = libxml2.parseMemory(data, len(data)) ctxt = doc.xpathNewContext() res_rslt = ctxt.xpathEval("/r/e/attribute::Name") print res_rslt[0] data = '''<r><e RoleID="3247" Nam...
[ "With lxml, things are easier and they work. It is Pythonic binding for the libxml2 library and works wonderfully.\n>>> from lxml import etree\n>>> x = etree.fromstring('''<r><e RoleID=\"3247\" Name=\"中文\"></e></r>''')\n>>> name = x[0].get('Name')\n>>> print name\n中文\n\nAnd yes, XPath is also supported. The documen...
[ 2, 0 ]
[]
[]
[ "encoding", "libxml2", "python", "utf_8" ]
stackoverflow_0004225045_encoding_libxml2_python_utf_8.txt
Q: How to insert a string(Fri Nov 19 16:23:54 +0800 2010) into a table field whose type is TIMESTAMP? I'm using Python and MYSQLdb to connect to Mysql. and now i need to insert a string "Fri Nov 19 16:23:54 +0800 2010" into a field, how can i do? A: You can parse that sting with Python time.strptime() method and th...
How to insert a string(Fri Nov 19 16:23:54 +0800 2010) into a table field whose type is TIMESTAMP?
I'm using Python and MYSQLdb to connect to Mysql. and now i need to insert a string "Fri Nov 19 16:23:54 +0800 2010" into a field, how can i do?
[ "You can parse that sting with Python time.strptime() method and then convert it to string required by MySQL using strftime(). Unfortunately my Python 2.6 cannot handle %z directive, but you can check on your implementation that code:\nimport datetime\n\ndef test_dt(d, f):\n dt = datetime.datetime.strptime(d, f)...
[ 1 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0004224710_mysql_python.txt
Q: Adding column In table with Python Im trying to create a logging output using python 2.6. The data come a database. What I would like to do is add a column to all rows with a time stamp = strftime("%Y-%m-%d %H:%M:%S"). There are about 50 rows. Then drop into a csv table. .append and .extend seem to add rows but ...
Adding column In table with Python
Im trying to create a logging output using python 2.6. The data come a database. What I would like to do is add a column to all rows with a time stamp = strftime("%Y-%m-%d %H:%M:%S"). There are about 50 rows. Then drop into a csv table. .append and .extend seem to add rows but not columns. Is there an easy way to do ...
[ "A quick example:\nIf you have a two-dimensional list like\nl = [[1,2,3,4],\n [5,6,7,8],\n [9,10,11,12]]\n\nthen l.append(13) gets you\nl = [[1,2,3,4],\n [5,6,7,8],\n [9,10,11,12],\n 13]\n\nwhich I assume is what you mean by \"it adds rows, not columns\".\nYou probably want l[0].append(13) which...
[ 4 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0004225358_logging_python.txt
Q: container where values expire in python I am after a thread safe Python container where the values are automatically removed after a time. Does such a class exist? A: Here is a thread safe version of ExpireCounter: import datetime import collections import threading class ExpireCounter: """Tracks how many e...
container where values expire in python
I am after a thread safe Python container where the values are automatically removed after a time. Does such a class exist?
[ "Here is a thread safe version of ExpireCounter:\nimport datetime\nimport collections\nimport threading\n\nclass ExpireCounter:\n \"\"\"Tracks how many events were added in the preceding time period\n \"\"\"\n\n def __init__(self, timeout=1):\n self.lock=threading.Lock() \n self.timeou...
[ 8, 0, 0 ]
[]
[]
[ "containers", "multithreading", "python", "timeout" ]
stackoverflow_0004219843_containers_multithreading_python_timeout.txt
Q: python tcp socketserver and the differences between windows and unix clients I feel this is a very basic question, but my google-fu is not yielding any specific hits. My problem is related to socket communication differences between windows and unix tcp clients. If i serve up the very basic tcp server code below, ...
python tcp socketserver and the differences between windows and unix clients
I feel this is a very basic question, but my google-fu is not yielding any specific hits. My problem is related to socket communication differences between windows and unix tcp clients. If i serve up the very basic tcp server code below, and establish a connection via bsd/macos/linux via telnet or netcat (eg telnet rem...
[ "It works as expected (programs don't do what we wanted, they do what we told them to do). If your question is how to make windows XP telnet send CRLF, you can set the appropriate option:\ntelnet\nset ?\nset crlf\nopen <host> <port>\n\nBut I think you should re-consider your code, because the server doesn't read a ...
[ 1 ]
[]
[]
[ "client", "python", "socketserver", "tcp" ]
stackoverflow_0004225426_client_python_socketserver_tcp.txt
Q: Why can I update a list slice but not a string slice in python? Just curious more than anything why python will allow me to update a slice of a list but not a string? >>> s = "abc" >>> s[1:2] 'b' >>> s[1:3] 'bc' >>> s[1:3] = "aa" >>> l = [1,2,3] >>> l[1:3] [2, 3] >>> l[1:3] = [9,0] >>> l [1, 9, 0] Is there a go...
Why can I update a list slice but not a string slice in python?
Just curious more than anything why python will allow me to update a slice of a list but not a string? >>> s = "abc" >>> s[1:2] 'b' >>> s[1:3] 'bc' >>> s[1:3] = "aa" >>> l = [1,2,3] >>> l[1:3] [2, 3] >>> l[1:3] = [9,0] >>> l [1, 9, 0] Is there a good reason for this? (I am sure there is.)
[ "Because in python, strings are immutable.\n", "Python distinguishes mutable and immutable data types. Making strings immutable is a general design decision in Python. Integers are immutable, you can't change the value of 42. Strings are also considered values in Python, so you can't change \"fourty-two\" to s...
[ 9, 5 ]
[]
[]
[ "python", "slice", "string" ]
stackoverflow_0004225743_python_slice_string.txt
Q: Long integer to 16 character Hex for Google Reader sync Python Code h = "%s"%("0000000000000000%x"%(i&0xffffffffffffffff))[16:] I'd like to know how this would be done in PHP. The application is for google reader syncronization. An initial sync list comes with numeric values, but the actual article id hex. Examp...
Long integer to 16 character Hex for Google Reader sync
Python Code h = "%s"%("0000000000000000%x"%(i&0xffffffffffffffff))[16:] I'd like to know how this would be done in PHP. The application is for google reader syncronization. An initial sync list comes with numeric values, but the actual article id hex. Example Long Integer = 8643979098044673995 Example Google Reader A...
[ "sprintf(\"%016x\", 8643979098044673995);\n\n" ]
[ 2 ]
[]
[]
[ "php", "python" ]
stackoverflow_0004225926_php_python.txt
Q: Twisted, FTP, and "streaming" large files I'm attempting to implement what can best be described as "an FTP interface to an HTTP API". Essentially, there is an existing REST API that can be used to manage a user's files for a site, and I'm building a mediator server that re-exposes this API as an FTP server. So ...
Twisted, FTP, and "streaming" large files
I'm attempting to implement what can best be described as "an FTP interface to an HTTP API". Essentially, there is an existing REST API that can be used to manage a user's files for a site, and I'm building a mediator server that re-exposes this API as an FTP server. So you can login with, say, Filezilla and list you...
[ "\nI thought I could use some sort of two-ended buffer object to transport the chunks between the HTTP and FTP, by using the buffer object as the file-like object required by ftp._FileReader, but that's quickly proving not to work, as the consumer from the send call almost immediately closes the buffer (because it'...
[ 2 ]
[]
[]
[ "ftp", "python", "twisted" ]
stackoverflow_0004222293_ftp_python_twisted.txt
Q: regarding backslash from postgresql i have a noob question. I have a record in a table that looks like '\1abc' I then use this string as a regex replacement in re.sub("([0-9])",thereplacement,"2") I'm a little confused with the backslashes. The string i got back was "\\1abc" A: Are you using python interactivly?...
regarding backslash from postgresql
i have a noob question. I have a record in a table that looks like '\1abc' I then use this string as a regex replacement in re.sub("([0-9])",thereplacement,"2") I'm a little confused with the backslashes. The string i got back was "\\1abc"
[ "Are you using python interactivly?\nIn regular string you need to escape backslashes in your code, or use r\"...\" (Link to docs). If you are running python interactivly and don't assign the results from your database to a variable, it'll be printed out using it's __repr__() method.\n>>> s = \"\\\\1abc\"\n>>> s\n'...
[ 2, 2 ]
[]
[]
[ "postgresql", "python" ]
stackoverflow_0004224400_postgresql_python.txt
Q: Python mechanize login to website I'm trying to log into a website using Python and Mechanize, however, I'm running into trouble when trying to get the POST data to behave as I want. Essentially I want to replicate this using mechanize and Python: wget --quiet --save-cookies cookiejar --keep-session-cookies --post...
Python mechanize login to website
I'm trying to log into a website using Python and Mechanize, however, I'm running into trouble when trying to get the POST data to behave as I want. Essentially I want to replicate this using mechanize and Python: wget --quiet --save-cookies cookiejar --keep-session-cookies --post-data "action=login&login_nick=USERNAME...
[ "Mechanize seems to urlencode the strings anyway, so there's no point in fighting it. This is the final solution (obviously not syntactically valid, but hopefully you get the idea).\nimport mechanize\n\nself.browser = mechanize.Browser()\nself.browser.open(self.url)\nself.browser.select_form(name=\"login\")\n\nself...
[ 9 ]
[]
[]
[ "mechanize", "python", "webforms" ]
stackoverflow_0004225721_mechanize_python_webforms.txt
Q: Scan for secured pdf documents I've currently run into the need to find which pdfs within a directory are "Secured Documents". All of the pdfs should be unsecured, and convertible via xpdf, however, this is not the case. How could I scan through all the pdfs in a directory to find out whether or not they are secur...
Scan for secured pdf documents
I've currently run into the need to find which pdfs within a directory are "Secured Documents". All of the pdfs should be unsecured, and convertible via xpdf, however, this is not the case. How could I scan through all the pdfs in a directory to find out whether or not they are secured?
[ "pyPdf supports decrypting PDFs. Its PdfFileReader class has an isEncrypted attribute.\nimport pyPdf\nif pyPdf.PdfFileReader(open(\"file_name.pdf\", 'rb')).isEncrypted:\n print \"Rut ro, it's encrypted.\"\n # skip file? Write to a log?\nelse:\n print \"We're clear.\"\n # Do stuff with the file.\n\n" ]
[ 1 ]
[]
[]
[ "python", "xpdf" ]
stackoverflow_0004226479_python_xpdf.txt
Q: for-if without list comprehension in one line can this be written in one line without List Comprehensions? for x in vec: if x > 3: ... ... A: No, you can't. The Python language reference states: Compound statements consist of one or more ‘clauses.’ A clause consists of a header and a ...
for-if without list comprehension in one line
can this be written in one line without List Comprehensions? for x in vec: if x > 3: ... ...
[ "No, you can't. The Python language reference states:\n\nCompound statements consist of one or\n more ‘clauses.’ A clause consists of a\n header and a ‘suite.’ The clause\n headers of a particular compound\n statement are all at the same\n indentation level. Each clause header\n begins with a uniquely identif...
[ 3, 3, 0, 0 ]
[ "You can imagine somethings like this : \ndef do_something(value):\n ...\n\ndef do_otherthing(value):\n ...\n\n\nfor x in t: do_something(x) if x>3 else do_otherthing(x)\n\n" ]
[ -1 ]
[ "list_comprehension", "python" ]
stackoverflow_0004226523_list_comprehension_python.txt
Q: Prevent python shelve corruption How should I prevent corruption in a shelve file? Should the shelve be closed most of the time and then opened only when I need to read or edit a value? A: If safety of your persistent objects is of high importance in your project, using shelve is not a good idea. Neither is p...
Prevent python shelve corruption
How should I prevent corruption in a shelve file? Should the shelve be closed most of the time and then opened only when I need to read or edit a value?
[ "If safety of your persistent objects is of high importance in your project, using shelve is not a good idea. Neither is pickling objects and manually writing them into files.\nConsider that real databases invest huge resources (brainpower and code) to be safe in case of failures. So keep your data in a real DB. Th...
[ 6 ]
[]
[]
[ "python", "shelve" ]
stackoverflow_0004226580_python_shelve.txt
Q: Is it possible to edit doc files with Python? I have a set of .doc files which I want to perform some simple changes to (e.g. set the font of all the text in each file to be arial). I don't want to do all the operations manually. I thought I'll try to automate it with a Python script. Is it a complicated task? How...
Is it possible to edit doc files with Python?
I have a set of .doc files which I want to perform some simple changes to (e.g. set the font of all the text in each file to be arial). I don't want to do all the operations manually. I thought I'll try to automate it with a Python script. Is it a complicated task? How is it done? I use Python 3.
[ "The Python docx module should be helpful. \n(2nd time this question was asked today!)\n" ]
[ 5 ]
[]
[]
[ "ms_word", "python" ]
stackoverflow_0004226824_ms_word_python.txt
Q: ImportError when trying to run a python unittest with pydev I am getting the following error when trying to run a module as a python unittest with PyDev. Finding files... ['C:\\Projectos\\spa\\sensor\\src\\test\\test_sensor.py'] ... done Importing test modules ... Traceback (most recent call last): File "C:\ecli...
ImportError when trying to run a python unittest with pydev
I am getting the following error when trying to run a module as a python unittest with PyDev. Finding files... ['C:\\Projectos\\spa\\sensor\\src\\test\\test_sensor.py'] ... done Importing test modules ... Traceback (most recent call last): File "C:\eclipse\plugins\org.python.pydev.debug_1.6.3.2010100513\pysrc\runfile...
[ "Turns out pydev does not play well with cygwin's python.\nInstalled python 2.7 for windows and it works.\n" ]
[ 0 ]
[]
[]
[ "eclipse", "pydev", "python", "unit_testing" ]
stackoverflow_0004225927_eclipse_pydev_python_unit_testing.txt
Q: Resizing and stretching a NumPy array I am working in Python and I have a NumPy array like this: [1,5,9] [2,7,3] [8,4,6] How do I stretch it to something like the following? [1,1,5,5,9,9] [1,1,5,5,9,9] [2,2,7,7,3,3] [2,2,7,7,3,3] [8,8,4,4,6,6] [8,8,4,4,6,6] These are just some example arrays, I will actually be ...
Resizing and stretching a NumPy array
I am working in Python and I have a NumPy array like this: [1,5,9] [2,7,3] [8,4,6] How do I stretch it to something like the following? [1,1,5,5,9,9] [1,1,5,5,9,9] [2,2,7,7,3,3] [2,2,7,7,3,3] [8,8,4,4,6,6] [8,8,4,4,6,6] These are just some example arrays, I will actually be resizing several sizes of arrays, not just ...
[ "@KennyTM's answer is very slick, and really works for your case but as an alternative that might offer a bit more flexibility for expanding arrays try np.repeat:\n>>> a = np.array([[1, 5, 9],\n [2, 7, 3],\n [8, 4, 6]])\n\n>>> np.repeat(a,2, axis=1)\narray([[1, 1, 5, 5, 9, 9],\n [2, ...
[ 42, 19, 2 ]
[]
[]
[ "arrays", "numpy", "python", "resize", "stretch" ]
stackoverflow_0004226386_arrays_numpy_python_resize_stretch.txt
Q: Language choices for writing very fast abstractions interfacing with Python? I have a system currently written in Python that can be separated into backend and frontend layers. Python is too slow, so I want to rewrite the backend in a fast compiled language while keeping the frontend in Python, in a way that lets ...
Language choices for writing very fast abstractions interfacing with Python?
I have a system currently written in Python that can be separated into backend and frontend layers. Python is too slow, so I want to rewrite the backend in a fast compiled language while keeping the frontend in Python, in a way that lets the backend functionality be called from Python. What are the best choices to do s...
[ "C++ with SWIG can generate all of the glue code you need. So long as you avoid excessive jumps between C++ and python it'll be as fast as your C++. SWIG interfaces are usually fairly straightforward to generate unless you're doing something \"odd\". \n", "If you used Jython you could call into Java back-end rout...
[ 7, 2, 1 ]
[]
[]
[ "boost_python", "c++", "java", "python" ]
stackoverflow_0004188273_boost_python_c++_java_python.txt
Q: CLI Piano Synthesizer? I've been working on a music improvisation program for a class I'm taking, and I need to be able to show what it can do to a class. Currently, the program outputs notes in scientific format and chords in brackets (I use Python). Here's an example of the output: C5 D4 [D#5, D#4] Is there any...
CLI Piano Synthesizer?
I've been working on a music improvisation program for a class I'm taking, and I need to be able to show what it can do to a class. Currently, the program outputs notes in scientific format and chords in brackets (I use Python). Here's an example of the output: C5 D4 [D#5, D#4] Is there any CLI software that I can use...
[ "There are a whole bunch of resources that might be useful to you here. If it does't need to run in real time, you might be happiest just writing a standard midi file and using some other software to actually render the playback.\n", "I don't know of a program that does that. Though I have written a program that ...
[ 1, 0 ]
[]
[]
[ "command_line", "linux", "macos", "piano", "python" ]
stackoverflow_0004227408_command_line_linux_macos_piano_python.txt
Q: Forward slash in Python replace() I have been working on an anagram solver in Python 2.7 and came across a curiosity that I haven't been able to find an explanation for. The program reads from a file which contains a list of anagrams in a format like so: # anagram # anagram # anagram . . . etc Reading th...
Forward slash in Python replace()
I have been working on an anagram solver in Python 2.7 and came across a curiosity that I haven't been able to find an explanation for. The program reads from a file which contains a list of anagrams in a format like so: # anagram # anagram # anagram . . . etc Reading this directly into a string, Python obvio...
[ "Try this:\n[s.lstrip('#\\t') for s in file.read().split('\\n')]\n\nPython does not treat a # specially in any way whatsoever inside a string, you don't need to escape it.\n", "Did you change anything else when you replaced your '#' with '/#'? Try running your program again, exactly as it is, but removing the /. ...
[ 3, 0 ]
[]
[]
[ "python", "replace", "string" ]
stackoverflow_0004227373_python_replace_string.txt
Q: override method of class in python I'd like to override a class method, not creating subclass/extending from a class. An example: from django.contrib import admin class NewModelAdmin(admin.ModelAdmin): def formfield_for_dbfield(self, db_field, **kwargs): # some custom stuff Now I don't want to change...
override method of class in python
I'd like to override a class method, not creating subclass/extending from a class. An example: from django.contrib import admin class NewModelAdmin(admin.ModelAdmin): def formfield_for_dbfield(self, db_field, **kwargs): # some custom stuff Now I don't want to change all the classes (aka Models) which exte...
[ "I'm not 100% clear with what you want to do, and why you don't want to create a new subclass or have a method of a different name.\nBut in general in python you can do something like:\nclass MyClass(object):\n def print_hello(self):\n print \"not hello\"\n\ndef real_print_hello():\n print \"hello\"\n\...
[ 4, 3, 3, 2, 1, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004226864_django_python.txt
Q: How to automatically Import all subclasses of a root class in Python? I'd like to know if it is possible to automatically import all subclasses of a class in python without writing import subclassxy for every subclass. A: You cannot, in general. The interpreter has no way of knowing whether or not a specific pac...
How to automatically Import all subclasses of a root class in Python?
I'd like to know if it is possible to automatically import all subclasses of a class in python without writing import subclassxy for every subclass.
[ "You cannot, in general. The interpreter has no way of knowing whether or not a specific package defines a subclass of your class of interest. In principle, you can write a new package or module tomorrow defining a new subclass. It will now need to get imported. For the interpreter to keep track of all of this woul...
[ 3, 3, 1, 1 ]
[]
[]
[ "class", "import", "python" ]
stackoverflow_0004227418_class_import_python.txt
Q: Python scientific: interrupt differential equation solving with a condition I am currently solving a system of differential equation under python using odeint to simulate charged particles in a field (the source comes from this package): time = np.linspace(0, 5, 1000) def sm(x, t): return np.array([x[1], eta...
Python scientific: interrupt differential equation solving with a condition
I am currently solving a system of differential equation under python using odeint to simulate charged particles in a field (the source comes from this package): time = np.linspace(0, 5, 1000) def sm(x, t): return np.array([x[1], eta*Ez0(x[0])]) traj = odeint(sm,[0,1.], time) It works fine but I would like to s...
[ "If you write a custom extension of the odeint function, you could have your function raise a particular exception when it's finished. Doing it in Python might make it substantially slower, but I think you write the same thing in C or Cython. Note that I haven't tested the following.\nclass ThatsEnoughOfThat(Except...
[ 1 ]
[]
[]
[ "numpy", "python", "scipy" ]
stackoverflow_0004227481_numpy_python_scipy.txt
Q: Python MySQL Standard What is the "standard" way of using mysql in python. I define standard as something that won't go away for a long time. import _mysql db = _mysql.connect(host, user, pass, db); db.query("sql"); vs import MySQLdb db = MySQLdb.connect(host, user, pass, db); cursor = db.cursor(); cursor.exe...
Python MySQL Standard
What is the "standard" way of using mysql in python. I define standard as something that won't go away for a long time. import _mysql db = _mysql.connect(host, user, pass, db); db.query("sql"); vs import MySQLdb db = MySQLdb.connect(host, user, pass, db); cursor = db.cursor(); cursor.execute("sql"); Obviously My...
[ "The standard way of dealing with relational database engines is defined by DB-API as described in PEP 249.\n", "I use \nimport MySQLdb\n\nWhich really isn't supported. On the PC, if you install the latest Python, it can be a problem to find. \n" ]
[ 4, 0 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0004227999_mysql_python.txt
Q: Python "IOError: [Errno 22] Invalid argument" when using cPickle to write large array to network drive EDIT: At the suggestion of J. F. Sebastian, I can get the same error much more simply: Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)] Type "copyright", "credits" or "license" for mor...
Python "IOError: [Errno 22] Invalid argument" when using cPickle to write large array to network drive
EDIT: At the suggestion of J. F. Sebastian, I can get the same error much more simply: Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)] Type "copyright", "credits" or "license" for more information. IPython 0.10 -- An enhanced Interactive Python. ? -> Introduction and overview of IP...
[ "I believe the problem is related to:\nhttp://support.microsoft.com/default.aspx?scid=kb;en-us;899149\n...so, just try:\nopen(r'z:\\test.bin','w+b').write('a'*67080064)\n*Note the argument: 'w+b'\n" ]
[ 16 ]
[]
[]
[ "ioerror", "nas", "pickle", "python" ]
stackoverflow_0004226941_ioerror_nas_pickle_python.txt
Q: how can i select these elements from the following horrible html using xpath and lxml? i want to select the following strings from this html using just lxml and some clever xpath. The strings will change but the surrounding html will not. i need... 19/11/2010 AAAAAA/01 Normal United Kingdom This description may c...
how can i select these elements from the following horrible html using xpath and lxml?
i want to select the following strings from this html using just lxml and some clever xpath. The strings will change but the surrounding html will not. i need... 19/11/2010 AAAAAA/01 Normal United Kingdom This description may contains <bold>html</bold> but i still need all of it! from... ... <p> <strong>Date:</st...
[ "Very ugly! With this properly wellformed input:\n<html>\n<p>\n <strong>Date:</strong> 19/11/2010<br/>\n <strong>Ref:</strong> AAAAAA/01<br/>\n <b>Type:</b> Normal<br/>\n <b>Country:</b> United Kingdom<br/>\n</p>\n<hr/>\n<p>\n <br/>\n <b>1. Title:</b> The Title<br/>\n <b>2. Description: </b> Th...
[ 2, 0 ]
[]
[]
[ "html", "lxml", "python", "xpath" ]
stackoverflow_0004227303_html_lxml_python_xpath.txt