content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: How does files get copy/cut/paste using clipboard operations (ctrl-c /ctrl-v) Was trying to use win32clipboard to do the copy paste operations for text (till now), and was able to do it with ease.But now am wondering how does the copy/paste operations would be accomplished for folders/files etc through that. I am ...
How does files get copy/cut/paste using clipboard operations (ctrl-c /ctrl-v)
Was trying to use win32clipboard to do the copy paste operations for text (till now), and was able to do it with ease.But now am wondering how does the copy/paste operations would be accomplished for folders/files etc through that. I am using python to achieve the same. Could not also find any relevant formats for that...
[ "Windows copy/paste stores things as OLE objects (http://en.wikipedia.org/wiki/Object_Linking_and_Embedding)\nYou need a python package to deal with OLE. This thread might help- How do I script an OLE component using Python?\n", "When you copy a shell object (e.g. a file or a folder) to the clipboard, the shell ...
[ 0, 0 ]
[]
[]
[ "copy_paste", "python", "pywin32", "winapi" ]
stackoverflow_0005016874_copy_paste_python_pywin32_winapi.txt
Q: What does underscoring methods connote? I am relatively new to the Python language and encountered this in doing the following: help(list) Here is what I encountered: __add__(...) | x.__add__(y) <==> x+y | | __contains__(...) | x.__contains__(y) <==> y in x | | __delitem__(...) | x.__delitem_...
What does underscoring methods connote?
I am relatively new to the Python language and encountered this in doing the following: help(list) Here is what I encountered: __add__(...) | x.__add__(y) <==> x+y | | __contains__(...) | x.__contains__(y) <==> y in x | | __delitem__(...) | x.__delitem__(y) <==> del x[y] Regarding these, what are...
[ "See the Python style guide for a comprehensive explanation.\nIn practice:\nthe following special forms using leading or trailing\nunderscores are recognized (these can generally be combined with any case\nconvention):\n\n- _single_leading_underscore: weak \"internal use\" indicator. E.g. \"from M\n import *\" do...
[ 10, 3, 2, 0, 0, 0 ]
[]
[]
[ "double_underscore", "python" ]
stackoverflow_0005017282_double_underscore_python.txt
Q: Ruby LESS gem equivalent in Python The Ruby LESS gem looks awesome - and I am working on a Python/Pylons web project where it would be highly useful. CSS is, as someone we're all familiar with recently wrote about, clunky in some important ways. So I'd like to make it easier on myself. Is there an existing Pytho...
Ruby LESS gem equivalent in Python
The Ruby LESS gem looks awesome - and I am working on a Python/Pylons web project where it would be highly useful. CSS is, as someone we're all familiar with recently wrote about, clunky in some important ways. So I'd like to make it easier on myself. Is there an existing Python module or library that provides parall...
[ "I have need for a Python lesscss compiler too, so have started work on one here: http://code.google.com/p/lesscss-python/\nVersion 0.0.1 has been released, with no support for namespaces/accessors. It is probably riddled with bugs too.\nPlease feel free to chip in with bug reports/coding or have a look at less-js ...
[ 15, 4, 4, 2 ]
[]
[]
[ "css", "less", "pylons", "python", "ruby" ]
stackoverflow_0002770560_css_less_pylons_python_ruby.txt
Q: CURL / Ruby Alternative in Python to fetch data from API I want to get data from an API using Python. The API documentation give examples in CURL and Ruby. I would be very happy if you can post code snippets on how to do the following things with Python. To get authentication token: Curl example: curl -X POST -d "...
CURL / Ruby Alternative in Python to fetch data from API
I want to get data from an API using Python. The API documentation give examples in CURL and Ruby. I would be very happy if you can post code snippets on how to do the following things with Python. To get authentication token: Curl example: curl -X POST -d "{\"username\" : \"user@sample.com\", \"password\":\"sample\"}"...
[ "Which part exactly did you not understand after reading the urllib2 documentation?\nI do not know my Ruby, but from the looks of it just involves sending GET request and POST requests in json format and parsing the responses. This is quite trivial with simplejson and urllib2.\n", "This is not a port but it looks...
[ 2, 2 ]
[]
[]
[ "api", "curl", "python", "ruby", "urllib2" ]
stackoverflow_0005015749_api_curl_python_ruby_urllib2.txt
Q: Need file tracking program Does anybody know is there any open source program or web app for file tracking (not version control, much simpler, add name of new file, add user, add users to some file, set privileges to user,track revision of file, notify user for change - most of time it will work with .doc files) ...
Need file tracking program
Does anybody know is there any open source program or web app for file tracking (not version control, much simpler, add name of new file, add user, add users to some file, set privileges to user,track revision of file, notify user for change - most of time it will work with .doc files) writen in Java, Python, C# or Ha...
[ "It sounds like you want both version control and a web interface to it. One approach would be something like gitit/darcsit, a wiki/cms system with a git or darcs backend: http://gitit.net/\n", "Im not exactly sure what you mean by it, but there are tools/utilitys such as git that can be used for tracking changes...
[ 3, 0, 0 ]
[]
[]
[ "c#", "haskell", "java", "python" ]
stackoverflow_0005014871_c#_haskell_java_python.txt
Q: Simple wxPython Frame Contents Resizing - Ratio? I have a wxPython app with one frame and one panel. On that panel are a number of static boxes, each of which has buttons and textboxes. I have just begun reading about sizers, but they seem like they might be more than what I need, or it could that they are exactl...
Simple wxPython Frame Contents Resizing - Ratio?
I have a wxPython app with one frame and one panel. On that panel are a number of static boxes, each of which has buttons and textboxes. I have just begun reading about sizers, but they seem like they might be more than what I need, or it could that they are exactly what I need but I don't know how to use them correct...
[ "For complex layouts, I sketch it out on a piece of paper. Then I draw boxes around the widgets in different ways to decide what sizers to use. You can nest pretty much any sizer inside another one. If the controls naturally fit in a grid, then using a grid sizer of some sort is probably alright. If not, then use B...
[ 1 ]
[]
[]
[ "boxsizer", "python", "wxpython" ]
stackoverflow_0005012257_boxsizer_python_wxpython.txt
Q: python + win32: simple way to run a process and print its error code? I'm running Windows XP and want to run a process and print its exit code. I don't have a C compiler, nor do I want to use one. I do have Python though, so I figure it's probably the easiest way to do this. How can I write a quick python script t...
python + win32: simple way to run a process and print its error code?
I'm running Windows XP and want to run a process and print its exit code. I don't have a C compiler, nor do I want to use one. I do have Python though, so I figure it's probably the easiest way to do this. How can I write a quick python script to run a process and print its exit code?
[ "never mind, found it in the subprocess module:\n import subprocess;\n retcode = subprocess.call([\"ls\",\"-l\"])\n\n", "Subprocess has all your answers\n>>> import subprocess\n>>> command = ['foo.exe', 'arg1', 'arg2']\n>>> process = subprocess.Popen(command, shell=True)\n\n" ]
[ 5, 1 ]
[]
[]
[ "python", "winapi" ]
stackoverflow_0005018217_python_winapi.txt
Q: include image files in Django templates shows broken link? All, I've tried the tips found on the forum. Unfortunately i'm still stuck. The image doesn't appear in the template. As far as i've traced the errors now they are twofold: 1) one where the picture should appear there is still a broke link and an error m...
include image files in Django templates shows broken link?
All, I've tried the tips found on the forum. Unfortunately i'm still stuck. The image doesn't appear in the template. As far as i've traced the errors now they are twofold: 1) one where the picture should appear there is still a broke link and an error message: Failed to load resource: the server responded with a sta...
[ "What's your template looking like? It's should be something like:\n<img src=\"{{ MEDIA_URL }}Point3D/grafiek/laptop.jpg\" alt=\"\" />\n\nI'm guessing the right path for your image should be http://127.0.0.1:8000/media/Point3D/grafiek/laptop.jpg\n", "Permission denied on /media/ is exactly what is supposed to hap...
[ 1, 1, 1, 1 ]
[]
[]
[ "django", "image", "matplotlib", "png", "python" ]
stackoverflow_0005016864_django_image_matplotlib_png_python.txt
Q: python: best way to verify conditions and raise Exception hi i have to verify if a vector contains all 0 or 1 and if not raise exception: def assert_all_zero_or_one(vector): if set(vector)=={0}: return 0 if set(vector)=={1}: return 1 raise TypeError with this exceution assert_all_zero_or_one([1,1,1]) ...
python: best way to verify conditions and raise Exception
hi i have to verify if a vector contains all 0 or 1 and if not raise exception: def assert_all_zero_or_one(vector): if set(vector)=={0}: return 0 if set(vector)=={1}: return 1 raise TypeError with this exceution assert_all_zero_or_one([1,1,1]) # return 1 assert_all_zero_or_one([0,0]) # return 0 assert_all_...
[ "I think your solution conveys your intent well. You could also do\ndef assert_all_zero_or_one(vector):\n if set(vector) not in ({0}, {1}): raise TypeError\n return vector[0]\n\nso you build set(vector) only once, but I think yours is easier to understand.\n", "How's this?\ndef assert_all_zero_or_one(vector...
[ 4, 4, 3, 1, 0 ]
[]
[]
[ "exception", "if_statement", "python" ]
stackoverflow_0005015775_exception_if_statement_python.txt
Q: Matplotlib Legend Height in pixels I need to know the size of the legend in pixels. I seem to only be able to get height = 1. from any function... I've tried the following this returns 1. height = legend.get_frame().get_bbox_to_anchor().height this returns [0,0],[1.,1.] box = legend.get_window_extent().get_points...
Matplotlib Legend Height in pixels
I need to know the size of the legend in pixels. I seem to only be able to get height = 1. from any function... I've tried the following this returns 1. height = legend.get_frame().get_bbox_to_anchor().height this returns [0,0],[1.,1.] box = legend.get_window_extent().get_points() this also returns [0,0],[1.,1.] box...
[ "This is because you haven't yet drawn the canvas.\nPixel values simply don't exist in matplotlib (or rather, they exist, have no relation to the screen or other output) until the canvas is drawn.\nThere are a number of reasons for this, but I'll skip them at the moment. Suffice it to say that matplotlib tries to s...
[ 5 ]
[]
[]
[ "legend", "matplotlib", "python" ]
stackoverflow_0005014609_legend_matplotlib_python.txt
Q: Redland python bindings.Unexpected print ot triples I have the below code in python: import RDF parser = RDF.Parser() model=RDF.Model() stream=parser.parse_into_model(model,"file:./zoo/zoo.rdf") list = [] for triple in model: print triple.subject, triple.predicate, triple.object list.append([ triple.su...
Redland python bindings.Unexpected print ot triples
I have the below code in python: import RDF parser = RDF.Parser() model=RDF.Model() stream=parser.parse_into_model(model,"file:./zoo/zoo.rdf") list = [] for triple in model: print triple.subject, triple.predicate, triple.object list.append([ triple.subject , triple.predicate , triple.object ] ) print len(l...
[ "Try\nfor k in list:\n print map(str, k)\n\n", "Try\nfor k in list:\n print str(k)\n\n" ]
[ 1, 0 ]
[]
[]
[ "python", "redland" ]
stackoverflow_0005018178_python_redland.txt
Q: Manipulating Native Windows Boarders with wxPython In windows there is an icon and title in the upper left hand corner of the native boarder. I was wondering if it was possible to remove the icon and title, yet keep the icon and title that is displayed in the task bar using wxPython. A: I don't think that's pos...
Manipulating Native Windows Boarders with wxPython
In windows there is an icon and title in the upper left hand corner of the native boarder. I was wondering if it was possible to remove the icon and title, yet keep the icon and title that is displayed in the task bar using wxPython.
[ "I don't think that's possible because wxPython is wrapping the native widget. You might be able to simulate it what you want using a custom wx.Dialog by messing with the style flags you pass it.\n" ]
[ 1 ]
[]
[]
[ "python", "windows_7", "wxpython" ]
stackoverflow_0005011731_python_windows_7_wxpython.txt
Q: Python: send a mail in html with sendmail Can someone tell me how to send a mail in a HTML format with sendmail in python? I would like to send this: <pre>some code</pre> Python version is 2.4.3 and can't be updated. A: # assemble the mail content from email.MIMEMultipart import MIMEMultipart from email.MIMETex...
Python: send a mail in html with sendmail
Can someone tell me how to send a mail in a HTML format with sendmail in python? I would like to send this: <pre>some code</pre> Python version is 2.4.3 and can't be updated.
[ "# assemble the mail content\nfrom email.MIMEMultipart import MIMEMultipart\nfrom email.MIMEText import MIMEText\nmessage = MIMEMultipart('alternative')\nmessage.add_header('Subject', 'subject goes here')\n# add a few more add_header calls here for things like \"To\", \"Cc\", \"From\"\nmessage.attach(MIMEText('some...
[ 4, 1, 0, 0 ]
[]
[]
[ "python", "sendmail" ]
stackoverflow_0005002824_python_sendmail.txt
Q: Python: should I use eval, exec or ..? I am trying to make the following statement more flexible: for posting in page.findAll(attrs = {"id": re.compile(r'''post\d+''')}): The following part is retrieved dynamically from a CSV file and stored in a string (for example the string called test). The CSV is stored in ...
Python: should I use eval, exec or ..?
I am trying to make the following statement more flexible: for posting in page.findAll(attrs = {"id": re.compile(r'''post\d+''')}): The following part is retrieved dynamically from a CSV file and stored in a string (for example the string called test). The CSV is stored in a secure location, accessible for admins onl...
[ "If you want to run code from user input (file contents are input), you'll need eval or exec, by these names or some other (specifically, you need exec for statements - assignment is a statement).\nBut you don't want to (and shouldn't) do that, because that's evil, insecure, totally unnecessary, etc. Drop the assig...
[ 5, 1, 1, 0 ]
[]
[]
[ "eval", "exec", "python" ]
stackoverflow_0005019264_eval_exec_python.txt
Q: How do I use Django 1.2 templates in my Google App Engine project? Can anyone suggest a detailed resource for including django 1.2 templating in our GAE apps? So far I have found docs describing how to zip up the django files and add them to our project docs on running native django projects in GA docs about in...
How do I use Django 1.2 templates in my Google App Engine project?
Can anyone suggest a detailed resource for including django 1.2 templating in our GAE apps? So far I have found docs describing how to zip up the django files and add them to our project docs on running native django projects in GA docs about including 1.0 and 1.1 libraries into our projects but nothing yet describ...
[ "I used this:\nfrom google.appengine.dist import use_library\nuse_library('django', '1.1')\nfrom google.appengine.ext.webapp import template\n\nIn this case I used 1.1 version but I think it should work the same for 1.2.\n", "I had the same problem a while ago - I wanted to use version 1.2 version for templates i...
[ 3, 0 ]
[]
[]
[ "django", "django_templates", "google_app_engine", "python" ]
stackoverflow_0004557716_django_django_templates_google_app_engine_python.txt
Q: subprocess.popen and psql I have Django application which needs to call psql. I do this in a celery thread which looks like this: @task() def insert_sqldump_threaded(username, database, file): host = database.server.db_address work = subprocess.Popen([settings.PSQL, "-f%s" % file, ...
subprocess.popen and psql
I have Django application which needs to call psql. I do this in a celery thread which looks like this: @task() def insert_sqldump_threaded(username, database, file): host = database.server.db_address work = subprocess.Popen([settings.PSQL, "-f%s" % file, "-d%s...
[ "I think postgresql needs other environment variables that you clear when you pass env. You can simply change os.environ or make a copy of it beforehand as in the following code:\nimport os\n@task()\ndef insert_sqldump_threaded(username, database, file):\n d = dict(os.environ)\n d['PGPASSFILE'] = settings.DB_PASS...
[ 3, 0 ]
[]
[]
[ "django", "postgresql", "psql", "python", "subprocess" ]
stackoverflow_0005019722_django_postgresql_psql_python_subprocess.txt
Q: Python decorator for simple recursion? In standard library or elsewhere? I'm looking for a Python decorator that can make a function recursive. I find myself writing a lot of functions like this: def xyz(data): if not isinstance(data, TypeThatDenotesSingularity): return map(xyz, data) return singul...
Python decorator for simple recursion? In standard library or elsewhere?
I'm looking for a Python decorator that can make a function recursive. I find myself writing a lot of functions like this: def xyz(data): if not isinstance(data, TypeThatDenotesSingularity): return map(xyz, data) return singular_xyz(data) I figure there must be a decorator out there somewhere (in the s...
[ "How about this:\ndef recursive(stop_type):\n def _inner(func):\n def _recursive(data, *args, **kw):\n if not isinstance(data, stop_type):\n return map(_recursive, data)\n return func(data, *args, **kw)\n return _recursive\n return _inner\n\nExplanation of ho...
[ 3, 1 ]
[]
[]
[ "decorator", "python", "recursion" ]
stackoverflow_0005019650_decorator_python_recursion.txt
Q: Can someone explain how this code snippet works, i know it finds the transpose of a list of lists but I am having a tough time finding how def transposed(lists): if not lists: return [] return map(lambda *row: list(row), *lists) A: Let's assume list1 = [0, 1, 2] list2 = [3, 4, 5] list3 = [6, 7, 8] lists = ...
Can someone explain how this code snippet works, i know it finds the transpose of a list of lists but I am having a tough time finding how
def transposed(lists): if not lists: return [] return map(lambda *row: list(row), *lists)
[ "Let's assume\nlist1 = [0, 1, 2]\nlist2 = [3, 4, 5]\nlist3 = [6, 7, 8]\nlists = [list1, list2, list3]\n\nThen the call\nmap(lambda *row: list(row), *lists)\n\nis equivalent to\nmap(lambda *row: list(row), list1, list2, list3)\n\nFrom the documentation of map(), we can see it applies the given lambda function to the...
[ 4, 1 ]
[]
[]
[ "dictionary", "list", "python", "transpose" ]
stackoverflow_0005019927_dictionary_list_python_transpose.txt
Q: Python - writing lines from file into IRC buffer Ok, so I am trying to write a Python script for XCHAT that will allow me to type "/hookcommand filename" and then will print that file line by line into my irc buffer. EDIT: Here is what I have now __module_name__ = "scroll.py" __module_version__ = "1.0" __module_d...
Python - writing lines from file into IRC buffer
Ok, so I am trying to write a Python script for XCHAT that will allow me to type "/hookcommand filename" and then will print that file line by line into my irc buffer. EDIT: Here is what I have now __module_name__ = "scroll.py" __module_version__ = "1.0" __module_description__ = "script to scroll contents of txt file ...
[ "Well, your first problem is that you're referring to a variable ascii before you define it:\nascii = gg(ascii)\n\nTry making that:\nascii = gg(word[0])\n\nNext, you're opening each file returned by glob... only to do absolutely nothing with them. I'm not going to give you the code for this: please try to work out ...
[ 1 ]
[]
[]
[ "glob", "irc", "python", "scripting", "text" ]
stackoverflow_0005019974_glob_irc_python_scripting_text.txt
Q: Configure GAE application app.yaml for subdomains I have some subdomains with my domain on GAE. They are, for example, blog.mysite.com, projects.mysite.com and docs.mysite.com. As it is configured now, they all are processed with such settings in main.py: def main(): applications = { 'blog.mysite.com':...
Configure GAE application app.yaml for subdomains
I have some subdomains with my domain on GAE. They are, for example, blog.mysite.com, projects.mysite.com and docs.mysite.com. As it is configured now, they all are processed with such settings in main.py: def main(): applications = { 'blog.mysite.com': webapp.WSGIApplication([('/', BlogHandler)]), ...
[ "This is not exactly an answer to your question but you may want to look into webapp2. It is a drop-in replacement for Google's webapp that adds some really useful features, including a new routing system that can route by domain.\nCheck out the routes.py file for examples. You'd want DomainRoute:\n SUBDOMAIN_RE...
[ 8, 1 ]
[]
[]
[ "google_app_engine", "python", "yaml" ]
stackoverflow_0005015882_google_app_engine_python_yaml.txt
Q: Rails model inheritance It will be simplest to explain with code example, in Python I can do so to achieve model inheritance: """Image model""" from sqlalchemy import Column, ForeignKey from sqlalchemy.types import Integer, String, Text from miasto_3d.model.meta import Base class Image(Base): __tablename__ = ...
Rails model inheritance
It will be simplest to explain with code example, in Python I can do so to achieve model inheritance: """Image model""" from sqlalchemy import Column, ForeignKey from sqlalchemy.types import Integer, String, Text from miasto_3d.model.meta import Base class Image(Base): __tablename__ = "image" image_id = Column...
[ "It looks like you're wanting either a polymorphic association or perhaps single table inheritance.\n", "Since you don't define database fields in the model, you cannot inherit database schema in this way - all your fields will need to be specified per table in a migration. You probably should use paperclip, if o...
[ 2, 0 ]
[]
[]
[ "python", "ruby", "ruby_on_rails" ]
stackoverflow_0005019447_python_ruby_ruby_on_rails.txt
Q: Python using 'with' to delete a file after use I am using an explicitly named file as a temporary file. In order to make sure I delete the file correctly I've had to create a wrapper class for open(). This seems to work but A] is it safe? B] is there a better way? import os string1 = """1. text line 2. text l...
Python using 'with' to delete a file after use
I am using an explicitly named file as a temporary file. In order to make sure I delete the file correctly I've had to create a wrapper class for open(). This seems to work but A] is it safe? B] is there a better way? import os string1 = """1. text line 2. text line 3. text line 4. text line 5. text line """ class...
[ "I guess you can do a bit simpler with contextlib.contextmanager:\nfrom contextlib import contextmanager\n\n@contextmanager\ndef tempOpen( path, mode ):\n # if this fails there is nothing left to do anyways\n file = open(path, mode)\n\n try:\n yield file\n finally:\n file.close()\n ...
[ 10 ]
[]
[]
[ "python" ]
stackoverflow_0005019209_python.txt
Q: Find files (but ignore them in certain folders) I want to find files of a specific type in a certain directory. The directory has lots and lots of subfolders and I want to ignore certain ones. I am using the following code- def locate(pattern, root=os.curdir): '''Locate all files matching supplied filename pat...
Find files (but ignore them in certain folders)
I want to find files of a specific type in a certain directory. The directory has lots and lots of subfolders and I want to ignore certain ones. I am using the following code- def locate(pattern, root=os.curdir): '''Locate all files matching supplied filename pattern in and below supplied root directory.''' ...
[ "If you want to ignore some subdirectories while walking with os.walk, you can mutate the value of \"dirs\". E.g.\nignored = [\"foo\", \"bar\"]\nfor path, dirs, files in os.walk(os.path.abspath(root)):\n for dir in ignored:\n if dir in dirs: dirs.remove(dir)\n for filename in fnmatch.filter(files, patt...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0005019727_python.txt
Q: Strange string concatenation on Python 2.5 in Windows This code - for ss_key in sd.keys(): print str(sd[ss_key]) + ' ' + ss_key prints the output as expected i.e. converts the int value of ss_key and prints the value and key on the same line. But this code - for ii_key in id.keys(): print ii_key + ' ' + ...
Strange string concatenation on Python 2.5 in Windows
This code - for ss_key in sd.keys(): print str(sd[ss_key]) + ' ' + ss_key prints the output as expected i.e. converts the int value of ss_key and prints the value and key on the same line. But this code - for ii_key in id.keys(): print ii_key + ' ' + str(id[ii_key]), prints key1 and then goes to a newline to...
[ "I suppose that ii_key is a string, and the newline is part of that string. Try printing ii_key.rstrip().\n", "You can check if your data contains linefeeds or other unwanted whitespaces by adding\nprint repr(ii_key)\nThis will print linefeeds and other special characters in escaped form (e.g. \"\\n\").\n" ]
[ 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005017354_python.txt
Q: kill a process in windows python 2.5 How do i kill a process in windows (xp 32 bits) in python 2.5? Someone on stackoverlow posted on how to import ctypes and do it but I don't have a ctypes module. I am running the process in the following way- ex=Execution(cmd) #do something ex.proc.kill() This gives me an e...
kill a process in windows python 2.5
How do i kill a process in windows (xp 32 bits) in python 2.5? Someone on stackoverlow posted on how to import ctypes and do it but I don't have a ctypes module. I am running the process in the following way- ex=Execution(cmd) #do something ex.proc.kill() This gives me an error saying Popen object has no attribute ...
[ "Among others, I found two ways:\n\nhttp://metazin.wordpress.com/2008/08/09/how-to-kill-a-process-in-windows-using-python/\nhttps://blogs.oracle.com/rajkumar/entry/how_to_kill_a_process\n\nThe latter uses the subprocess module in conjunction with taskkill. The former win32api.TerminateProcess.\n", "Popen.kill() i...
[ 3, 0 ]
[]
[]
[ "kill", "process", "python", "windows" ]
stackoverflow_0005020139_kill_process_python_windows.txt
Q: Can someone explain these few lines of python code file name __init__.py import os, unittest # figure all the modules available dir = os.path.split(__file__)[0] This prints the current directory, as file points points to the current file name mods = {} dont know what this does, but i can guess this creates a li...
Can someone explain these few lines of python code file name __init__.py
import os, unittest # figure all the modules available dir = os.path.split(__file__)[0] This prints the current directory, as file points points to the current file name mods = {} dont know what this does, but i can guess this creates a list ? or an array ? l = [] I guess this also creates an array and assigns it l...
[ "Broadly, he's listing the files in the directory which end with .py, then adds those names to the content listing of the of the package (__all__). He goes on the import those scripts by name (using __import__), then makes that list of modules (objects representing scripts) into a group of unit-tests (unittest.Test...
[ 2, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005020349_python.txt
Q: Python: itertools.islice not working in a loop I have code like this: #opened file f goto_line = num_lines #Total number of lines while not found: line_str = next(itertools.islice(f, goto_line - 1, goto_line)) goto_line = goto_line/2 #checks for data, sets found to True if needed line_str is correct the ...
Python: itertools.islice not working in a loop
I have code like this: #opened file f goto_line = num_lines #Total number of lines while not found: line_str = next(itertools.islice(f, goto_line - 1, goto_line)) goto_line = goto_line/2 #checks for data, sets found to True if needed line_str is correct the first pass, but every pass after that is reading a d...
[ "Python iterators can be consumed only once. This is easiest seen by example. The following code\nfrom itertools import islice\na = range(10)\ni = iter(a)\nprint list(islice(i, 1, 3))\nprint list(islice(i, 1, 3))\nprint list(islice(i, 1, 3))\nprint list(islice(i, 1, 3))\n\nprints\n[1, 2]\n[4, 5]\n[7, 8]\n[]\n\nTh...
[ 5, 0 ]
[]
[]
[ "file_io", "python", "python_itertools" ]
stackoverflow_0005020444_file_io_python_python_itertools.txt
Q: Get method wrapped in a descriptor with getattr I have the following descriptor, which saves the configuration inside my class after a method which is annotated with @saveconfig is called: class saveconfig(object): def __init__(self, f): self.f = f def __get__(self, instance, owner): def w...
Get method wrapped in a descriptor with getattr
I have the following descriptor, which saves the configuration inside my class after a method which is annotated with @saveconfig is called: class saveconfig(object): def __init__(self, f): self.f = f def __get__(self, instance, owner): def wrapper(*args): self.f(instance, *args) ...
[ "I'm still not 100% sure I fully understand your problem. You say that \"Since i cannot get the original method, i don't know how many parameters it has to map them\", but you don't need access to the original method to call by variable number of arguments (since the decorator has *args). You can do something like ...
[ 2, 1 ]
[]
[]
[ "descriptor", "python" ]
stackoverflow_0005020210_descriptor_python.txt
Q: Python quits after a constructor is called My code seems to be failing after the constructor is called. Here is my code - it is failing on the c = create_control_point() line in main(): from brisa.core.reactors import install_default_reactor reactor = install_default_reactor() print reactor from brisa.core.threa...
Python quits after a constructor is called
My code seems to be failing after the constructor is called. Here is my code - it is failing on the c = create_control_point() line in main(): from brisa.core.reactors import install_default_reactor reactor = install_default_reactor() print reactor from brisa.core.threaded_call import run_async_function from brisa.up...
[ "Since it's dying on the ControlPoint initialization, have you tried the following in the interpreter?\nfrom brisa.upnp.control_point.control_point import ControlPoint\nc = ControlPoint()\n\nIf that works, then there's something else at play.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0005020732_python.txt
Q: Are there any 'gotchas' with this Python pattern? Here's the pattern I'm thinking of using: class Dicty(dict): def __init__(self): self.__dict__ = self d = Dicty() d.foo = 'bar' print d['foo'] >>> bar d['foo'] = 'baz' print d.foo >>> 'baz' Generally, I prefer the semantics of object attribute ...
Are there any 'gotchas' with this Python pattern?
Here's the pattern I'm thinking of using: class Dicty(dict): def __init__(self): self.__dict__ = self d = Dicty() d.foo = 'bar' print d['foo'] >>> bar d['foo'] = 'baz' print d.foo >>> 'baz' Generally, I prefer the semantics of object attribute access over dict get/set access, but there are some cir...
[ "Here's a less \"hacky\" way to achieve the same effect:\nclass Dicty(dict):\n def __getattr__(self, key):\n return self[key]\n\n def __setattr__(self, key, value):\n self[key] = value\nI think that your way may work fine as well, but setting the __dict__ attribute like that seems a bit iffy sty...
[ 10, 3, 2 ]
[]
[]
[ "coding_style", "python" ]
stackoverflow_0005021041_coding_style_python.txt
Q: Python ftplib and storbinary Trying to understand how the ftplib works. I am trying to save a file to a FTP server and implement a callback. The documentation says: FTP.storbinary(command, file[, blocksize, callback, rest]) callback function is defined as in the documentation: The callback function is called for...
Python ftplib and storbinary
Trying to understand how the ftplib works. I am trying to save a file to a FTP server and implement a callback. The documentation says: FTP.storbinary(command, file[, blocksize, callback, rest]) callback function is defined as in the documentation: The callback function is called for each block of data received, wi...
[ "If your callback is\ndef handle(block):\n f.write(block)\n print \".\", \n\nPython has first class functions that can be passed as params- this is the point of a callback- you you pass the function as param to the storbinary call-\nftp.storbinary(command=\"stor someFileNameOnServer\", file=open(\"localFile\"...
[ 5 ]
[]
[]
[ "ftplib", "python" ]
stackoverflow_0005021132_ftplib_python.txt
Q: Python binary search always returns target not found value I've written the following code to do a binary search for a value, target, in a list or tuple, collection. def binary(collection, target): """Binary search Takes a sorted list or tuple, collection, then searches for target Returns -1 if item is...
Python binary search always returns target not found value
I've written the following code to do a binary search for a value, target, in a list or tuple, collection. def binary(collection, target): """Binary search Takes a sorted list or tuple, collection, then searches for target Returns -1 if item isn't found. """ length = len(collection) minimum = 0 ...
[ "You have this condition backwards:\nelif collection[pivot] > target:\n\nSwitch it and the search works:\nelif collection[pivot] < target:\n\nFor what it's worth, I figured this out by adding a printout to your search to see what's happening. When in doubt, add a printout:\n>>> binary([1, 2, 3], 1)\n(min=0, max=2, ...
[ 4, 1 ]
[]
[]
[ "binary_search", "python", "search" ]
stackoverflow_0003689891_binary_search_python_search.txt
Q: Python - Is isolation via generic try blocks bad? Say I have some complex code where I have nested try blocks with the generic except Exception, e because I need to isolate certain (sometimes unknown) failures from causing a long running program to halt. Those failures are usually not important enough to halt th...
Python - Is isolation via generic try blocks bad?
Say I have some complex code where I have nested try blocks with the generic except Exception, e because I need to isolate certain (sometimes unknown) failures from causing a long running program to halt. Those failures are usually not important enough to halt the program, but I want to catch them so I can log them a...
[ "Small methods which do not use try...catch, but are used in larger methods/functions which wrap them in try...catch is the usual solution.\nThis would easily allow tests to check the exceptions.\n" ]
[ 1 ]
[]
[]
[ "exception", "python" ]
stackoverflow_0005021417_exception_python.txt
Q: Why does the context hang around after a with statement? I would like to know why a file object opened using with statement or in a block, remains in scope after exit. Are <closed file> objects ever cleaned up? >>> with open('test.txt','w') as f: ... f.write('test') ... >>> f <closed file 'test.txt', mode 'w'...
Why does the context hang around after a with statement?
I would like to know why a file object opened using with statement or in a block, remains in scope after exit. Are <closed file> objects ever cleaned up? >>> with open('test.txt','w') as f: ... f.write('test') ... >>> f <closed file 'test.txt', mode 'w' at 0x00E014F0> >>> f.close() >>> if True: ... fal = ope...
[ "In Python new scopes (aka namespaces) are only created for modules, classes and functions, but not for any other statement, especially not for with and if blocks. Identifiers bound within the body of with or for statements are consequently bound in the inner-most surrounding scope, which is the top-level scope of...
[ 16, 4, 2, 0, 0 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0005021528_file_io_python.txt
Q: large set of data, interpolation I am looking for a "method" to get a formula, formula which comes from fitting a set of data (3000 point). I was using Legendre polynomial, but for > 20 points it gives not exact values. I can write chi2 test, but algorithm needs a loot of time to calculate N parameters, and at the...
large set of data, interpolation
I am looking for a "method" to get a formula, formula which comes from fitting a set of data (3000 point). I was using Legendre polynomial, but for > 20 points it gives not exact values. I can write chi2 test, but algorithm needs a loot of time to calculate N parameters, and at the beginning I don't know how the functi...
[ "How about a polynomial fit:\nhttp://docs.scipy.org/doc/numpy/reference/generated/numpy.polyfit.html\nor some other interpolation scheme:\nhttp://docs.scipy.org/doc/scipy/reference/tutorial/interpolate.html\nIt is difficult to recommend a suitable method without knowing more about the dataset and something about ho...
[ 3, 3, 0, 0 ]
[]
[]
[ "data_fitting", "numpy", "python", "scipy" ]
stackoverflow_0005021921_data_fitting_numpy_python_scipy.txt
Q: Thread & Queue vs Serial performance I though it'll be interesting to look at threads and queues, so I've written 2 scripts, one will break a file up and encrypt each chunk in a thread, the other will do it serially. I'm still very new to python and don't really know why the treading script takes so much longer. ...
Thread & Queue vs Serial performance
I though it'll be interesting to look at threads and queues, so I've written 2 scripts, one will break a file up and encrypt each chunk in a thread, the other will do it serially. I'm still very new to python and don't really know why the treading script takes so much longer. Threaded Script: #!/usr/bin/env python fr...
[ "Threads are not a magical way to speed up programs - splitting work into threads will usually slow it down unless the program is spending a significant part of its time waiting for I/O. Each new thread adds more overhead to the code in splitting the work up, and more overhead in the OS in switching between threa...
[ 1, 1, 1, 0, 0 ]
[]
[]
[ "encryption", "multithreading", "performance", "python", "queue" ]
stackoverflow_0001728477_encryption_multithreading_performance_python_queue.txt
Q: using %s to change the name of a list Is there a way to change the name of a list using %s? Here's an example: dict1[key]=value for x in dict1.keys(): %s %(x)profile=[] if dict1[x]=1: %s %(x)profile.append('yes') This code didn't work, but I'm looking for something that will give me 'n' lists, on...
using %s to change the name of a list
Is there a way to change the name of a list using %s? Here's an example: dict1[key]=value for x in dict1.keys(): %s %(x)profile=[] if dict1[x]=1: %s %(x)profile.append('yes') This code didn't work, but I'm looking for something that will give me 'n' lists, one for each x in dict1.keys().
[ "Short answer: no.\nLong answer: no, you can't do exactly that but if you're a little more clear with your intentions (it's hard to tell with your pseudocode what you're looking to do), there is certainly a way you can do what you need to do even though you can't do what you're trying to do\nShort and dangerous ans...
[ 5, 0, 0 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0005021197_dictionary_list_python.txt
Q: How to draw a line outside of an axis in matplotlib (in figure coordinates) Matplotlib has a function that writes text in figure coordinates (.figtext()) Is there a way to do the same but for drawing lines? In particular my goal is to draw lines to group some ticks on the y-axis together. A: Tested in python 3.8...
How to draw a line outside of an axis in matplotlib (in figure coordinates)
Matplotlib has a function that writes text in figure coordinates (.figtext()) Is there a way to do the same but for drawing lines? In particular my goal is to draw lines to group some ticks on the y-axis together.
[ "\nTested in python 3.8.12, matplotlib 3.4.3\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.lines import Line2D\n\nx = np.linspace(0,10,100)\ny = np.sin(x)*(1+x)\n\nfig, ax = plt.subplots()\nax.plot(x,y,label='a')\n\n# new clear axis overlay with 0-1 limits\nax2 = plt.axes([0,0,1,1], faceco...
[ 20 ]
[]
[]
[ "matplotlib", "plot", "python" ]
stackoverflow_0005021663_matplotlib_plot_python.txt
Q: File transmission over TCP with Python I'm currently working on a python project, that requires file transmission from a client to a server via the Python socket. Here is my current code, that however doesn't transmit the whole file, but there are always some bites missing, or additional bytes, according to the fi...
File transmission over TCP with Python
I'm currently working on a python project, that requires file transmission from a client to a server via the Python socket. Here is my current code, that however doesn't transmit the whole file, but there are always some bites missing, or additional bytes, according to the file sizes. _con and con are connection wrappe...
[ "While the first problem you have is with not writing the last chunk of data received to the output file, you have a few other problems.\nYour current problem can be fixed by changing the if statement to something like the following:\nif (rec.endswith(b'FIN')):\n writefile.write(rec[:-3]) # Ignore the last 3 byt...
[ 6, 0 ]
[]
[]
[ "python", "tcp" ]
stackoverflow_0005020658_python_tcp.txt
Q: Using bytearray in Python How can I implement the below code (ActionScript) in Python? var bytes:ByteArray = new ByteArray(); var text:String = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Vivamus etc."; bytes.writeUTFBytes(text); // write the text to the ByteArray trace("The length of the ByteArray...
Using bytearray in Python
How can I implement the below code (ActionScript) in Python? var bytes:ByteArray = new ByteArray(); var text:String = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Vivamus etc."; bytes.writeUTFBytes(text); // write the text to the ByteArray trace("The length of the ByteArray is: " + bytes.length); // 7...
[ "try:\n index = bytes.index('a')\n print \"Found letter a in position\", index\n # we substract 1 because the array is 0-indexed.\n print \"Bytes available:\", len(bytes) - index - 1\nexcept ValueError:\n print \"Letter a not found\"\n\nThis solution is much clearer and human-readable than the Action...
[ 2, 1 ]
[]
[]
[ "actionscript", "bytearray", "python" ]
stackoverflow_0005022556_actionscript_bytearray_python.txt
Q: Problems with Python's file.write() method and string handling The problem I am having at this point in time (being new to Python) is writing strings to a text file. The issue I'm experiencing is one where either the strings don't have linebreaks inbetween them or there is a linebreak after every character. Code t...
Problems with Python's file.write() method and string handling
The problem I am having at this point in time (being new to Python) is writing strings to a text file. The issue I'm experiencing is one where either the strings don't have linebreaks inbetween them or there is a linebreak after every character. Code to follow: import string, io FileName = input("Arb file name (.txt):...
[ "You have to write the '\\n' after each line, since you're stripping the original '\\n';\nYour idea of using '\\n'.join() doesn't work because it will use\\n to join the string, inserting it between each char of the string. You need a single \\n after each name, instead.\nimport string, io\n\nFileName = input(\"Arb...
[ 2, 1 ]
[]
[]
[ "file", "list", "python", "string" ]
stackoverflow_0005022572_file_list_python_string.txt
Q: Python subclass inheritance I am trying to build some classes that inherit from a parent class, which contains subclasses that inherit from other parent classes. But when I change attributes in the subclasses in any children, the change affects all child classes. I am looking to avoid having to create instances, a...
Python subclass inheritance
I am trying to build some classes that inherit from a parent class, which contains subclasses that inherit from other parent classes. But when I change attributes in the subclasses in any children, the change affects all child classes. I am looking to avoid having to create instances, as I am using that feature later. ...
[ "The behaviour you are seeing is exactly what you should expect. When you define a class\n>>> class Foo(object): pass\n...\n\nyou can modify that class -- not instances of it, the class itself -- because the class is just another object, stored in the variable Foo. So, for instance, you can get and set attributes o...
[ 10, 3, 1, 1, 0 ]
[]
[]
[ "inheritance", "python" ]
stackoverflow_0005022506_inheritance_python.txt
Q: From: "1 hour ago", To: timedelta + accuracy Is there a function to 'reverse humanize' times? For example, given (strings): '1 minute ago' '7 hours ago' '5 days ago' '2 months ago' Could return (apologies for the pseudo-code): datetime.now() - timedelta (1 minute), accuracy (60 seconds) datetime.now() - timedel...
From: "1 hour ago", To: timedelta + accuracy
Is there a function to 'reverse humanize' times? For example, given (strings): '1 minute ago' '7 hours ago' '5 days ago' '2 months ago' Could return (apologies for the pseudo-code): datetime.now() - timedelta (1 minute), accuracy (60 seconds) datetime.now() - timedelta (7 hours), accuracy (1 hour) datetime.now() - t...
[ "I've been using parsedatetime and it's worked rather well for me. The home page lists some formats it can handle, e.g.:\n\nin 5 minutes\n5 minutes from now\n2 hours before noon\n2 days from tomorrow \n\nThe major downside I've found is that it has no sense of timezones.\nIn case it's worth anything, here's a wrapp...
[ 2, 2 ]
[]
[]
[ "datetime", "humanize", "python", "time" ]
stackoverflow_0004839642_datetime_humanize_python_time.txt
Q: How do I take several Python lists of numbers and find the latest occurrence of a specific element? I have four time series of the same length. When one element is missing, it has a value of 0. What is the idiomatic way to find the index of the latest occurrence of 0 in any of the lists? A: If timeseries is a...
How do I take several Python lists of numbers and find the latest occurrence of a specific element?
I have four time series of the same length. When one element is missing, it has a value of 0. What is the idiomatic way to find the index of the latest occurrence of 0 in any of the lists?
[ "If timeseries is a list containing the four timeseries, you could reverse each timeseries, use zip to group together 4-tuple time-slices, and enumerate to record the index. \n# timeseries=[range(1,5),range(1,5),range(1,5),range(1,5)] \nfor idx,data in enumerate(zip(*[ts[::-1] for ts in timeseries])):\n if no...
[ 1, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005022179_python.txt
Q: Batch file renaming – inserting text from a list (in Python or Java) I'm finishing a business card production flow (excel > xml > indesign > single page pdfs) and I would like to insert the employees' names in the filenames. What I have now: BusinessCard_01_Blue.pdf BusinessCard_02_Blue.pdf BusinessCard_03_Blue.pd...
Batch file renaming – inserting text from a list (in Python or Java)
I'm finishing a business card production flow (excel > xml > indesign > single page pdfs) and I would like to insert the employees' names in the filenames. What I have now: BusinessCard_01_Blue.pdf BusinessCard_02_Blue.pdf BusinessCard_03_Blue.pdf (they are gonna go up to the hundreds) What I need (I can manipulate th...
[ "Granted you have a map where to look at the right name you could do something like this in Java:\nList<Files> originalFiles = ... \nfor( File f : originalFiles ) { \n f.renameTo( new File( getNameFor( f ) ) );\n}\n\nAnd define the getNameFor to something like:\npublic String getNameFor( File f ) { \n Map<St...
[ 2, 2, 0, 0 ]
[]
[]
[ "file_rename", "java", "python" ]
stackoverflow_0005022777_file_rename_java_python.txt
Q: How can I get the last-modified time with python3 urllib? I'm porting over a program of mine from python2 to python3, and I'm hitting the following error: AttributeError: 'HTTPMessage' object has no attribute 'getdate' Here's the code: conn = urllib.request.urlopen(fileslist, timeout=30) last_modified = conn.info(...
How can I get the last-modified time with python3 urllib?
I'm porting over a program of mine from python2 to python3, and I'm hitting the following error: AttributeError: 'HTTPMessage' object has no attribute 'getdate' Here's the code: conn = urllib.request.urlopen(fileslist, timeout=30) last_modified = conn.info().getdate('last-modified') This section worked under python 2....
[ "conn.headers['last-modified'] works under both Python 2 and Python 3. Comparing filestamps seems reasonable to me.\n" ]
[ 16 ]
[]
[]
[ "python", "python_2.7", "python_3.x", "urllib" ]
stackoverflow_0005022083_python_python_2.7_python_3.x_urllib.txt
Q: request.POST['time'] must be a datefield() I'm very new to django, maybe I'm asking something very elemental. I have the following code : crush.time = request.POST['time'] this 'time' post value is a timefield and I need to process as a time value, but all I got is that crush.time is a string, and then I got the ...
request.POST['time'] must be a datefield()
I'm very new to django, maybe I'm asking something very elemental. I have the following code : crush.time = request.POST['time'] this 'time' post value is a timefield and I need to process as a time value, but all I got is that crush.time is a string, and then I got the following error when I try to process: 'unicode'...
[ "The POST multidictionary contains strings - it does not know about python data types. You have to parse it into a datetime object. look at the datetime documentation.\n", "Assuming your 'time' field is in the form H:M:S or H:M, then you could create a django form to do the parsing work for you (keep in mind you ...
[ 1, 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005020713_django_python.txt
Q: mod_wsgi daemon mode, WSGIApplicationGroup and Python interpreter separation I have Apache with 2 virtual hosts, each having a Django site attached using mod_wsgi, daemon mode, like this: <VirtualHost 123.123.123.123:80> WSGIDaemonProcess a.com user=x group=x processes=5 threads=1 WSGIProcessGroup a.com ...
mod_wsgi daemon mode, WSGIApplicationGroup and Python interpreter separation
I have Apache with 2 virtual hosts, each having a Django site attached using mod_wsgi, daemon mode, like this: <VirtualHost 123.123.123.123:80> WSGIDaemonProcess a.com user=x group=x processes=5 threads=1 WSGIProcessGroup a.com WSGIApplicationGroup %{GLOBAL} </VirtualHost> <VirtualHost 123.123.123.123:80> ...
[ "The 'pid' value is different. They are in different processes.\n" ]
[ 7 ]
[]
[]
[ "apache", "mod_wsgi", "python" ]
stackoverflow_0005021424_apache_mod_wsgi_python.txt
Q: get email using openid and python I'm trying to get an e-mail address from an OpenId request using the following form below and web.py. I get an OpenId hash back, but I don't see anything related to an e-mail in my apache environment--just a openid_identity_hash. This is my html form using web.py. <input type...
get email using openid and python
I'm trying to get an e-mail address from an OpenId request using the following form below and web.py. I get an OpenId hash back, but I don't see anything related to an e-mail in my apache environment--just a openid_identity_hash. This is my html form using web.py. <input type="text" name="openid" value="" style="b...
[ "@voodo , Try setting these values. \nopenid.ns=http://specs.openid.net/auth/2.0&\nopenid.ns.alias3=http://openid.net/srv/ax/1.0&\nopenid.alias3.if_available=alias1,alias2,alias3&\nopenid.alias3.required=alias4&\nopenid.alias3.mode=fetch_request&\nopenid.alias3.type.alias1=http://schema.openid.net/namePerson&\nopen...
[ 0 ]
[]
[]
[ "authentication", "email", "openid", "python" ]
stackoverflow_0005018215_authentication_email_openid_python.txt
Q: Creating a slug field in database tied to name field I have a django project for which I'm trying to update the database tables without using any migration tools. I'm adding a 'slug' field to a model which simply references it's name, and I was intending on doing so by replicating what was in another table that a...
Creating a slug field in database tied to name field
I have a django project for which I'm trying to update the database tables without using any migration tools. I'm adding a 'slug' field to a model which simply references it's name, and I was intending on doing so by replicating what was in another table that already has a slug for. So, I have an existing table 'gym' ...
[ "from django.template.defaultfilters import slugify\n\nclass Wall(Model):\n name = CharField(max_length=60)\n slug = CharField(max_length=60, unique=True)\n ...\n\n def save(self, *args, **kwargs):\n if self.slug == '':\n self.slug = slugify(self.name)\n super(Wall, self).save(*...
[ 0 ]
[]
[]
[ "django", "django_models", "foreign_keys", "mysql", "python" ]
stackoverflow_0004960820_django_django_models_foreign_keys_mysql_python.txt
Q: jQuery encodes my data in a different way on server than on localhost? I've a function like this: function flush_changes() { jQuery('#save-changes').replaceWith('<span id="save-changes">Saving..</span>'); var changes = new Array(); for (var i=0; i<edited_users.length; i++) { ...
jQuery encodes my data in a different way on server than on localhost?
I've a function like this: function flush_changes() { jQuery('#save-changes').replaceWith('<span id="save-changes">Saving..</span>'); var changes = new Array(); for (var i=0; i<edited_users.length; i++) { changes.push({ id: edited_users[i], ...
[ "you are sending a json data to server, you must see how your server script get this data and how it decodes them. For example on php I use json_decode for converting json to arrays or objects, may in your production server this process is automatic (by configuration). Also remember to use encodeuricomponent on tex...
[ 0 ]
[]
[]
[ "ajax", "jquery", "python", "turbogears" ]
stackoverflow_0005023171_ajax_jquery_python_turbogears.txt
Q: Quick way to validate and convert Audio Files with Python? For a website i am developing in django i need users to be able to upload .wav or .aif files. I, of course, have to make sure these files really are what they pretend to be - audiofiles. The files then are provided on the webpage, where i need them to be e...
Quick way to validate and convert Audio Files with Python?
For a website i am developing in django i need users to be able to upload .wav or .aif files. I, of course, have to make sure these files really are what they pretend to be - audiofiles. The files then are provided on the webpage, where i need them to be either .ogg or .mp3 While searching for a solution i stumbled a...
[ "Not strictly a pythonic answer, but perhaps take a look at sox which is a simple command line audio file converter. It can do resampling of audio files for you as well.\nCheck out the command line options of sox for details. This will of course involve calling the external program using the subprocess module(or ...
[ 0 ]
[]
[]
[ "audio", "django", "python" ]
stackoverflow_0005021889_audio_django_python.txt
Q: Django charfield compose default value How can I add a composed default value to a charfield? Example class Myclass(xxx): type = models.ForeignKey(somewhere) code = models.CharField(default=("current id of MyClass wich is autoincremented + type value")) Is it possible? A: To do so, you override the save method ...
Django charfield compose default value
How can I add a composed default value to a charfield? Example class Myclass(xxx): type = models.ForeignKey(somewhere) code = models.CharField(default=("current id of MyClass wich is autoincremented + type value")) Is it possible?
[ "To do so, you override the save method on your model.\nclass MyClass(models.Model):\n ...\n\n def save(self):\n super(Myclass,self).save()\n if not self.code:\n self.code = str(self.id) + str(self.type_id)\n self.save()\n\nThere is stuff you need to take care, like making ...
[ 2, 2, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0005012814_django_django_models_python.txt
Q: How do I measure the memory usage of an object in python? I have a python class foo that contains: data (ints, floats) lists (of ints, of floats, and of other objects) dictionaries (of ints, of floats, of other objects) Assuming that there are no back-references (cycles), is there an easy way to measure the tota...
How do I measure the memory usage of an object in python?
I have a python class foo that contains: data (ints, floats) lists (of ints, of floats, and of other objects) dictionaries (of ints, of floats, of other objects) Assuming that there are no back-references (cycles), is there an easy way to measure the total memory usage of a foo object ? Essentially, I am looking for ...
[ "Try Pympler, which describes itself as \"A development tool to measure, monitor and analyze the memory behavior of Python objects.\"\nSomething along the lines of\n>>> import pympler\n>>> print pympler.asizeof.asizeof(your_object)\n\nhas been helpful to me in the past.\nSee examples from the official documentation...
[ 23, 1 ]
[]
[]
[ "memory_management", "python" ]
stackoverflow_0005022725_memory_management_python.txt
Q: Stream rdiff - delta differencing? I have a product that does online backups using rdiff. What currently happens is: Copy the file to a staging area (so the file won't disappear or be modified while we work on it) Hashes the original file, and computes an rdiff signature (used for delta differencing) Computes an ...
Stream rdiff - delta differencing?
I have a product that does online backups using rdiff. What currently happens is: Copy the file to a staging area (so the file won't disappear or be modified while we work on it) Hashes the original file, and computes an rdiff signature (used for delta differencing) Computes an rdiff delta difference (if we have no pr...
[ "You can probably skip step 1 completely. The file can't be deleted while it's open, and choosing appropriate locking flags when opening it can prevent it from being modified as well. For example, the CreateFile function takes a dwShareMode argument.\nYou need to compute the entire rdiff signature before you can st...
[ 0 ]
[]
[]
[ "backup_strategies", "delta", "diff", "python" ]
stackoverflow_0005021793_backup_strategies_delta_diff_python.txt
Q: Python split data from socket I'm trying to figure out how to split data received from a socket. I have the sockets working and I can get the data correctly but I now want to split the data retrieved and obtain the last string. Here is what I'm trying(data is the data received from the socket) split = data.split('...
Python split data from socket
I'm trying to figure out how to split data received from a socket. I have the sockets working and I can get the data correctly but I now want to split the data retrieved and obtain the last string. Here is what I'm trying(data is the data received from the socket) split = data.split(' ') print split print split[-1] Bu...
[ "The following works for me:\n>>> data = \"chdir /\"\n>>> a = data.split(\" \")\n>>> a\n['chdir', '/']\n>>> a[-1]\n'/'\n\nThis appears to be what you're looking for. The reason your code doesn't work likely lies with the exact content of data.\nNote that using .split(\" \") is slightly different than .split() when ...
[ 1, 0 ]
[]
[]
[ "python", "sockets", "split" ]
stackoverflow_0005023679_python_sockets_split.txt
Q: merge join two generators in python i want to merge two kyoto cabinet b-tree databases by key. (kyoto cabinet python api ). the resulting list should contain each unique key (and its value) of any of the two input dbs. the following code works but i think its ugly. left_generator/right_generator are two cursor obj...
merge join two generators in python
i want to merge two kyoto cabinet b-tree databases by key. (kyoto cabinet python api ). the resulting list should contain each unique key (and its value) of any of the two input dbs. the following code works but i think its ugly. left_generator/right_generator are two cursor objects. its especially odd that get() retur...
[ "I think this is what you need; orderedMerge is based on Gnibbler's code but adds a custom key function and a unique argument,\nimport kyotocabinet\nimport collections\nimport heapq\n\nclass IterableCursor(kyotocabinet.Cursor, collections.Iterator):\n def __init__(self, *args, **kwargs):\n kyotocabinet.Cu...
[ 5, 2 ]
[]
[]
[ "generator", "python" ]
stackoverflow_0005023266_generator_python.txt
Q: A way to pass milions of items in python to C program many times in rapid succesion I've wrote a python script that need to pass millions of items to a C program and receive its output many times in a short period (pass from 1 up to 10 millions of vertices data (integer index and 2 float coords) rapidly 500 times,...
A way to pass milions of items in python to C program many times in rapid succesion
I've wrote a python script that need to pass millions of items to a C program and receive its output many times in a short period (pass from 1 up to 10 millions of vertices data (integer index and 2 float coords) rapidly 500 times, and each time the python script call the C program, i need to store the returned values ...
[ "Using ctypes or Cython to wrap your C functions is definitely the way to go. That way, you won't even need to copy the data between the C and Python code -- both the C and the Python part run within the same process and access the same data. Let's stick with ctypes, since this is what you suggested. Additionall...
[ 7, 1, 0, 0, 0, 0, 0 ]
[]
[]
[ "c", "ctypes", "extend", "python", "shared_libraries" ]
stackoverflow_0004997831_c_ctypes_extend_python_shared_libraries.txt
Q: how is this a non-sequence? I'm running a list comprehension of a list of numbers as strings so for example the list looks like this vals = ['0.13', '324', '0.23432'] and try a list comprehension like this: best = [x for x in vals > 0.02] and I get a TypeError: iteration over non-sequence. Isn't a list a sequenc...
how is this a non-sequence?
I'm running a list comprehension of a list of numbers as strings so for example the list looks like this vals = ['0.13', '324', '0.23432'] and try a list comprehension like this: best = [x for x in vals > 0.02] and I get a TypeError: iteration over non-sequence. Isn't a list a sequence that should be the first thing ...
[ "You need to check if each item is greater than '0.02', not whether the sequence is greater.\nbest = [x for x in vals if x > '0.02']\n\nYour original expression, [x for x in vals > '0.02'] is parsed as [x for x in (vals > '0.02')]. Since vals > '0.02' is a boolean value, and not a sequence, it's not possible to ite...
[ 8, 4, 2, 1 ]
[]
[]
[ "list", "list_comprehension", "python", "sequences" ]
stackoverflow_0005024059_list_list_comprehension_python_sequences.txt
Q: Debugging server script like python? I'm new to 'network' programming. I've done throughout the Google app engine tutorial and I'm trying to make my own application which is guestbook. It has a server script on Google app engine and client app is running on iPhone. But how do I check if the server is received my m...
Debugging server script like python?
I'm new to 'network' programming. I've done throughout the Google app engine tutorial and I'm trying to make my own application which is guestbook. It has a server script on Google app engine and client app is running on iPhone. But how do I check if the server is received my message from iPhone? or How do I debug the...
[ "In your code you should be using tons of logging calls. In the app engine dashboard for your app there is an option to view logs, and all of your logging calls will show up in there (and can be filtered in various ways).\nThere are also ways to run dev_appserver.py and debug locally using software like PyDev, but ...
[ 3 ]
[]
[]
[ "google_app_engine", "network_programming", "networking", "python" ]
stackoverflow_0005024077_google_app_engine_network_programming_networking_python.txt
Q: initialization problem in Python The error is given at the end: from brisa.core.reactors import install_default_reactor reactor = install_default_reactor() print reactor from brisa.upnp.control_point.control_point import ControlPoint def on_new_device(dev): print 'Got new device:', dev...
initialization problem in Python
The error is given at the end: from brisa.core.reactors import install_default_reactor reactor = install_default_reactor() print reactor from brisa.upnp.control_point.control_point import ControlPoint def on_new_device(dev): print 'Got new device:', dev.udn print "Type 'list' to see...
[ "If this is anything like some other event-based libraries such as Twisted, you want to get the reactor's main running before you do much of anything else.\nDrop the call to reactor.main in your main function. Then, instead of just calling main in your if at the bottom, do this:\nif __name__ == \"__main__\":\n ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0005023983_python.txt
Q: Map over csv in python I'm trying to use "map" on a csv file in python. However, the line map(lambda x: x, reseller_csv) gives nothing. I've tried iterating over the csv object, and it works fine and can print the rows. Here's the code. # imports import csv # Opens files ifile = open('C:\Users\josh.SCL\Desktop\Re...
Map over csv in python
I'm trying to use "map" on a csv file in python. However, the line map(lambda x: x, reseller_csv) gives nothing. I've tried iterating over the csv object, and it works fine and can print the rows. Here's the code. # imports import csv # Opens files ifile = open('C:\Users\josh.SCL\Desktop\Records.csv', 'r') ofile = ope...
[ "A csv.DictReader is a use-once gadget. You probably ran it a second time.\n>>> import csv\n>>> iterable = ['Reseller,cost', 'fred,100', 'joe,99']\n>>> reseller_csv = csv.DictReader(iterable)\n>>> map(lambda x: x.get('Reseller'), reseller_csv)\n['fred', 'joe']\n>>> map(lambda x: x.get('Reseller'), reseller_csv)\n[]...
[ 4, 0, 0 ]
[]
[]
[ "csv", "lambda", "map", "python" ]
stackoverflow_0005023374_csv_lambda_map_python.txt
Q: Python and GAE Timezone Conversion Using Django. One of my model has a DateProperty attribute which is set by default as date.today(). The GAE doco states that DateProperty fields are automatically converted to UTC times before being stored. After my object has been stored, i would like to convert back its date to...
Python and GAE Timezone Conversion
Using Django. One of my model has a DateProperty attribute which is set by default as date.today(). The GAE doco states that DateProperty fields are automatically converted to UTC times before being stored. After my object has been stored, i would like to convert back its date to Melbourne time and use that as a string...
[ "I fixed the problem by replacing DateProperty to DateTimeProperty and the following code:\ndef convert_date(self):\n tz = pytz.timezone(TIMEZONE)\n dt = tz.normalize(tz.localize(self.date)).astimezone(tz)\n return dt.strftime('%Y-%m-%d')\n\n" ]
[ 0 ]
[]
[]
[ "date", "python", "time", "timezone" ]
stackoverflow_0005023830_date_python_time_timezone.txt
Q: a simple django template error this is my code : var next_lat={{ o|return_next_element:forloop.counter0|return_element:'latitude'|floatformat:"6"}} var next_lng={{ o|return_next_element:forloop.counter0|return_element:'longitude'|floatformat:"6"}} and it show this error : return_element requires 1 arguments, 0 p...
a simple django template error
this is my code : var next_lat={{ o|return_next_element:forloop.counter0|return_element:'latitude'|floatformat:"6"}} var next_lng={{ o|return_next_element:forloop.counter0|return_element:'longitude'|floatformat:"6"}} and it show this error : return_element requires 1 arguments, 0 provided what can i do , thanks
[ "you're not really giving us much to go on here. but could it be that return_next_element returns nothing, and therefore return_element has nothing to work with?\n" ]
[ 1 ]
[]
[]
[ "django", "python", "templates" ]
stackoverflow_0005024376_django_python_templates.txt
Q: Understanding the behavior of Python's set The documentation for the built-in type set says: class set([iterable]) Return a new set or frozenset object whose elements are taken from iterable. The elements of a set must be hashable. That is all right but why does this work: >>> l = range(10) >>> s = set(l) ...
Understanding the behavior of Python's set
The documentation for the built-in type set says: class set([iterable]) Return a new set or frozenset object whose elements are taken from iterable. The elements of a set must be hashable. That is all right but why does this work: >>> l = range(10) >>> s = set(l) >>> s set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) And ...
[ "When you initialize a set, you provide a list of values that must each be hashable.\ns = set()\ns.add([10])\n\nis the same as\ns = set([[10]])\n\nwhich throws the same error that you're seeing right now.\n", "In [13]: (2).__hash__\nOut[13]: <method-wrapper '__hash__' of int object at 0x9f61d84>\n\nIn [14]: ([2])...
[ 17, 5, 5, 1, 1, 0 ]
[]
[]
[ "python", "set" ]
stackoverflow_0005022247_python_set.txt
Q: PyRSS2Gen and embedding html in description tag I want to format the content of the description using html tags. When I try to enclose the content in <![CDATA[content<p>here]]> it doesn't work properly, as it escapes some of the brackets, displaying O.K. in some RSS viewers, but displaying the ]]> in others. If I...
PyRSS2Gen and embedding html in description tag
I want to format the content of the description using html tags. When I try to enclose the content in <![CDATA[content<p>here]]> it doesn't work properly, as it escapes some of the brackets, displaying O.K. in some RSS viewers, but displaying the ]]> in others. If I try to avoid the CDATA and use escaped characters th...
[ "According to examples in the RSS 2.0 specification you can use both CDATA and the escapes \"Encoding & item-level descriptions\".\n", "I looked into my problem some more and the problem is that PyRSS2Gen uses python's sax library, which has no concept of CDATA, at least when writing out XML. My solution was just...
[ 0, 0 ]
[]
[]
[ "cdata", "python", "rss" ]
stackoverflow_0004987182_cdata_python_rss.txt
Q: Python 2.6, what does the % mean in this context? def f(x): return x % 2 != 0 and x % 3 != 0 Just learning the language, I thought % was for string formatting? Found on the official tutorial: http://docs.python.org/release/2.6.1/tutorial/datastructures.html A: In the context of numbers it means modulo -- ...
Python 2.6, what does the % mean in this context?
def f(x): return x % 2 != 0 and x % 3 != 0 Just learning the language, I thought % was for string formatting? Found on the official tutorial: http://docs.python.org/release/2.6.1/tutorial/datastructures.html
[ "In the context of numbers it means modulo -- the remainder you get when you divide x by 2 is x % 2.\n", "That, my friend, would be the modulo operator:\nhttp://en.wikipedia.org/wiki/Modulo_operation for what that is and http://docs.python.org/reference/expressions.html#binary-arithmetic-operations for all binary...
[ 8, 2, 0 ]
[]
[]
[ "modulo", "python", "syntax" ]
stackoverflow_0005024608_modulo_python_syntax.txt
Q: Generating a shaded button using PIL I am trying automatically generate buttons to a menu using PIL in python. The button should be small rectangular and have a little gradient from one color to another, and a little text in it. Is PIL the best way to do this, or is Cairo a better alternative? Any suggestion to ho...
Generating a shaded button using PIL
I am trying automatically generate buttons to a menu using PIL in python. The button should be small rectangular and have a little gradient from one color to another, and a little text in it. Is PIL the best way to do this, or is Cairo a better alternative? Any suggestion to how I can accomplish this without having a i...
[ "You can do this entirely with PIL if you start with a single pre-made white-to-black gradient image (that you've made in some other program) and then use the ImageChops module to manipulate this together with your primary image to get what you want.\nFor example to if you want to fade from red to blue: multiply re...
[ 1, 0 ]
[]
[]
[ "cairo", "python", "python_imaging_library" ]
stackoverflow_0005022891_cairo_python_python_imaging_library.txt
Q: Python interfacing with C library - How to have a null c pointer I have the following old c code. const char *c[3]; c[0] = "ABC"; c[1] = "EFG"; c[2] = 0; c_function(c); Now, I need to use Python to call old c function. I have the following code. c_names = (c_char_p * 3)() c_names[0] = "ABC"; c_names[1] = "EFG"; /...
Python interfacing with C library - How to have a null c pointer
I have the following old c code. const char *c[3]; c[0] = "ABC"; c[1] = "EFG"; c[2] = 0; c_function(c); Now, I need to use Python to call old c function. I have the following code. c_names = (c_char_p * 3)() c_names[0] = "ABC"; c_names[1] = "EFG"; // c[2] = 0?? libc = CDLL("c_library.dll") libc.c_function(c_names) Ma...
[ "pointer = None\n\nhttp://docs.python.org/library/ctypes.html\ncheck 15.16.1.3. Calling functions\n", "None and 0 both work:\n>>> import ctypes\n>>> x=ctypes.c_char_p(0)\n>>> x\nc_char_p(None)\n>>> x=ctypes.c_char_p(None)\n>>> x\nc_char_p(None)\n\n" ]
[ 2, 2 ]
[]
[]
[ "c", "ctypes", "python" ]
stackoverflow_0005024776_c_ctypes_python.txt
Q: I'm parsing an HTML using lxml, but I only want a small subset of tags. What's the most efficient way to do this? I'd prefer not to build the entire tree in memory and just pick the elements I'm looking for. A: You could always use PyQuery; a JQuery like library for quick xml and xhtml manipulation.
I'm parsing an HTML using lxml, but I only want a small subset of tags. What's the most efficient way to do this?
I'd prefer not to build the entire tree in memory and just pick the elements I'm looking for.
[ "You could always use PyQuery; a JQuery like library for quick xml and xhtml manipulation.\n" ]
[ 0 ]
[]
[]
[ "html", "html_parsing", "lxml", "python" ]
stackoverflow_0005024876_html_html_parsing_lxml_python.txt
Q: Avoiding previous files I have a directory with a lot of sub directories. I am running through these directories and finding some files and running some commands on these files. How can I place a pointer to where i finish at? Sometimes the process gets disrupted and the next time I run the program, I want to start...
Avoiding previous files
I have a directory with a lot of sub directories. I am running through these directories and finding some files and running some commands on these files. How can I place a pointer to where i finish at? Sometimes the process gets disrupted and the next time I run the program, I want to start at where I left off. def loc...
[ "There are a couple ways you could do it… But probably the simplest is creating, eg, a new file along side each of the files that has already been processed, then checking for it. For example:\nfor filename in locate(\"*.dll\"):\n if os.path.exists(filename + \".processed\"):\n continue\n process(filen...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005021918_python.txt
Q: What is the role of handler.py in App Engine bulk upload/download? I was reading the Google App Engine tutorial for bulk upload/download. Could somebody please tell me what is the role of the script : 'handler.py' that has to be specified in the app.yaml file ? The documentation does not specifically talk about th...
What is the role of handler.py in App Engine bulk upload/download?
I was reading the Google App Engine tutorial for bulk upload/download. Could somebody please tell me what is the role of the script : 'handler.py' that has to be specified in the app.yaml file ? The documentation does not specifically talk about the role of this script.
[ "In the remote_api the handler.py is the script that will let locally executing python code access the remote app's datastore (after you've provided administrator authentication). Bulk loader needs it to push and pull data to/from your datastore.\nI recommend using the builtins directive instead of adding that ent...
[ 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005025042_google_app_engine_python.txt
Q: How do I create a 'notify me of followup comments via e-mail' button in Django? I want to create a check box that my users (either login or anonymous users) can click that sends an email when a new comment is added to a post. As a side note I would also like to send an email to the Author of the post too. Thanks! ...
How do I create a 'notify me of followup comments via e-mail' button in Django?
I want to create a check box that my users (either login or anonymous users) can click that sends an email when a new comment is added to a post. As a side note I would also like to send an email to the Author of the post too. Thanks!
[ "Use the django.contrib.comments.signals.comment_was_posted signal. For an example, see http://timothyfletcher.com/blog/django-comment-email-notifications/\n" ]
[ 1 ]
[]
[]
[ "comments", "django", "email", "notifications", "python" ]
stackoverflow_0005025216_comments_django_email_notifications_python.txt
Q: A resilient, actually working CSV implementation for non-ascii? [Update] Appreciate the answers and input all around, but working code would be most welcome. If you can supply code that can read the sample files you are king (or queen). [Update 2] Thanks for the excellent answers and discussion. What I need to do ...
A resilient, actually working CSV implementation for non-ascii?
[Update] Appreciate the answers and input all around, but working code would be most welcome. If you can supply code that can read the sample files you are king (or queen). [Update 2] Thanks for the excellent answers and discussion. What I need to do with these is to read them in, parse them, and save parts of them in ...
[ "You are attempting to apply a solution to a different problem. Note this: \ndef utf_8_encoder(unicode_csv_data) \nYou are feeding it str objects.\nThe problems with reading your non-ASCII CSV files is that you don't know the encoding and you don't know the delimiter. If you do know the encoding (and it's an ASCI...
[ 16, 2, 0, 0 ]
[]
[]
[ "encoding", "python", "unicode" ]
stackoverflow_0005020446_encoding_python_unicode.txt
Q: Validating Google Optimizer javascript code via HTMLParser I'm trying to include the Google Website Optimizer JavaScript code, below, in a Zope3 page template. It's used for for A/B testing. However, the template html parser, which I believe is the standard Python HTMLParser module, throws the following error: rai...
Validating Google Optimizer javascript code via HTMLParser
I'm trying to include the Google Website Optimizer JavaScript code, below, in a Zope3 page template. It's used for for A/B testing. However, the template html parser, which I believe is the standard Python HTMLParser module, throws the following error: raise PTRuntimeError(str(self._v_errors)) - Warning: Compilation fa...
[ "Given the parser's weakness, you could try breaking up the parts of the CDATA that it's trying to interpret as tags, e.g. where you now have </sc'+'ript>' try <'+'/sc'+'ript>' etc (+ does string catenation in JS, just like in Python, so it will put back together again the tags you break up this way, just like the ...
[ 1, 1, 0 ]
[ "One other option you have is to place the code in an external file and reference it instead of embedding it directly into the code. I've done this and it works well. That's always an easier way if you don't want the validator to crawl any javascript or css.\n" ]
[ -1 ]
[ "google_website_optimizer", "javascript", "python", "zope", "zpt" ]
stackoverflow_0001506496_google_website_optimizer_javascript_python_zope_zpt.txt
Q: Python 2.7 try and except ValueError I query user input which is expected to be an int by using int(raw_input(...)) However when the user doesn't enter an integer, i.e. just hits return, I get a ValueError. def inputValue(inputMatrix, rangeRows, rangeCols, defaultValue, playerValue): rowPos = int(raw_input("Pl...
Python 2.7 try and except ValueError
I query user input which is expected to be an int by using int(raw_input(...)) However when the user doesn't enter an integer, i.e. just hits return, I get a ValueError. def inputValue(inputMatrix, rangeRows, rangeCols, defaultValue, playerValue): rowPos = int(raw_input("Please enter the row, 0 indexed.")) colP...
[ "A quick and dirty solution is:\nparsed = False\nwhile not parsed:\n try:\n x = int(raw_input('Enter the value:'))\n parsed = True # we only get here if the previous line didn't throw an exception\n except ValueError:\n print 'Invalid value!'\n\nThis will keep prompting the user for input...
[ 37, 3, 1 ]
[]
[]
[ "exception_handling", "python" ]
stackoverflow_0005025399_exception_handling_python.txt
Q: Why does input() give a SyntaxError when I just press enter? I have the following python code: print 'This is a simple game.' input('Press enter to continue . . .') print 'Choose an option:' ... But when I press Enter button, I get the following error: Traceback (most recent call last): File "E:/4.Python/temp....
Why does input() give a SyntaxError when I just press enter?
I have the following python code: print 'This is a simple game.' input('Press enter to continue . . .') print 'Choose an option:' ... But when I press Enter button, I get the following error: Traceback (most recent call last): File "E:/4.Python/temp.py", line 2, in <module> input('Press enter to continue . . .'...
[ "For Python 2, you want raw_input, not input. The former will read a line. The latter will read a line and try to execute it, not advisable if you don't want your code being corrupted by the person entering data.\nFor example, they could do something like call arbitrary functions, as per the following example:\ndef...
[ 23, 4, 3, 2 ]
[]
[]
[ "python", "python_2.x" ]
stackoverflow_0005025920_python_python_2.x.txt
Q: How to read the time data from the csv file and plot a graph accordingly in python the time format is like this 47:48.1 and here 47 minutes 48 seconds 1 millisecond A: Something like this should get you started: import csv import datetime as dt import matplotlib.pyplot as plt x,y = [],[] csv_re...
How to read the time data from the csv file and plot a graph accordingly in python
the time format is like this 47:48.1 and here 47 minutes 48 seconds 1 millisecond
[ "Something like this should get you started:\nimport csv\nimport datetime as dt\nimport matplotlib.pyplot as plt\n\nx,y = [],[]\ncsv_reader = csv.reader(open('data.csv'))\nfor line in csv_reader:\n x.append(int(line[0]))\n y.append(dt.datetime.strptime(line[1],'%M:%S.%f'))\n\nfig = plt.figure()\nax = fig.add_...
[ 4, 1, 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0005025711_matplotlib_python.txt
Q: Currently Recieving a Key Error for JSON data retrieved from API in Python. What is going on? I am currently recieving a "Key Error" in Python, I have no idea what is going on. Here is my code: """ This is a program from http://www.masnun.me/2010/01/30/handling-json-in- python.html which I am using to experiment...
Currently Recieving a Key Error for JSON data retrieved from API in Python. What is going on?
I am currently recieving a "Key Error" in Python, I have no idea what is going on. Here is my code: """ This is a program from http://www.masnun.me/2010/01/30/handling-json-in- python.html which I am using to experiment with how to handle JSON data in python, currently the problem is that I have a bunch of JSON data ...
[ "Don't use d.has_key(k); it's slow and deprecated. Use k in d.\nDon't compare == None or != None, use is None or is not None.\nDon't waste keystrokes on d.get(k, None) -- None is the default. Use d.get(k)\nSo, use ... and x.get('latitude') is not None and ...\nUpdate running that query just now, I noticed that two ...
[ 6 ]
[]
[]
[ "json", "python" ]
stackoverflow_0005026135_json_python.txt
Q: Putting py2exe and matplotlib on a diet I'm currently working on an application that uses py2exe to make an exe file from a bit of Python code that utilizes matplotlib. It's working pretty well except that my executables are massive. Running the conversion script below it creates 43.5 mb package (the exe and its d...
Putting py2exe and matplotlib on a diet
I'm currently working on an application that uses py2exe to make an exe file from a bit of Python code that utilizes matplotlib. It's working pretty well except that my executables are massive. Running the conversion script below it creates 43.5 mb package (the exe and its dependencies). I know that there are probably ...
[ "If you're using matplotlib just to show some chart using default font etc you can just delete in dist/mpl-data folder all but matplotlib.conf and matplotlibrc.\nI did this and saved up abot 4MB on 12MB.\nWhy your dist is 43.5MB probably is not all due to matplotlib...\n" ]
[ 6 ]
[]
[]
[ "matplotlib", "optimization", "py2exe", "python", "tkinter" ]
stackoverflow_0005026543_matplotlib_optimization_py2exe_python_tkinter.txt
Q: How to create a synchronized object with Python multiprocessing? I am trouble figuring out how to make a synchronized Python object. I have a class called Observation and a class called Variable that basically looks like (code is simplified to show the essence): class Observation: def __init__(self, date, time...
How to create a synchronized object with Python multiprocessing?
I am trouble figuring out how to make a synchronized Python object. I have a class called Observation and a class called Variable that basically looks like (code is simplified to show the essence): class Observation: def __init__(self, date, time_unit, id, meta): self.date = date self.time_unit = ti...
[ "You are talking not about thread safety but about synchronization between separate processes and that's entirely different thing. Anyway, to start\n\ndifferent processes can update the obs variable in the object Variable.\n\nimplies that Variable is in shared memory, and you have to explicitly store objects there,...
[ 3 ]
[]
[]
[ "multiprocessing", "python", "synchronization", "thread_safety" ]
stackoverflow_0005022493_multiprocessing_python_synchronization_thread_safety.txt
Q: Python exception text on syntax errors (boost library) I've got this code snnipet (the whole program compiles and links correctly): ... try { boost::python::exec_file( "myscript.py", // this file contains a syntax error my_main_namespace, my_local_namespace ); return...
Python exception text on syntax errors (boost library)
I've got this code snnipet (the whole program compiles and links correctly): ... try { boost::python::exec_file( "myscript.py", // this file contains a syntax error my_main_namespace, my_local_namespace ); return true; } catch(const boost::python::error_already_set &) { P...
[ "From the documentation of PyErr_Fetch: \"The value and traceback object may be NULL even when the type object is not\". You should check whether pvalue is NULL or not before trying to extract the value.\nstd::string error;\nif(pvalue != NULL) {\n error = boost::python::extract<std::string>(pvalue);\n}\n\nIf you...
[ 4 ]
[]
[]
[ "boost_python", "c++", "exception", "python" ]
stackoverflow_0005026597_boost_python_c++_exception_python.txt
Q: shift between different objects in Blender using game engine i m working with game Engine(blender).. there are several objects and i need to shift between them on external input (potentiometer).. need functions(python) that can help me shift between objects(cube, sphere, etc).. A: see the Blender Python API docs...
shift between different objects in Blender using game engine
i m working with game Engine(blender).. there are several objects and i need to shift between them on external input (potentiometer).. need functions(python) that can help me shift between objects(cube, sphere, etc)..
[ "see the Blender Python API docs (specifically the Application Modules -> Data Access(bpy.data) section).\n" ]
[ 0 ]
[]
[]
[ "blender", "blender_2.50", "python" ]
stackoverflow_0005025713_blender_blender_2.50_python.txt
Q: how to get all the datastore results just with a key? I am pretty new to Python and GAE. Busy building a simple blog to learn. Was wondering, how can I get the datastore entries? This is how my DB object looks like : class BlogArticles(db.Model): author = db.UserProperty() article_name = db.StringProperty...
how to get all the datastore results just with a key?
I am pretty new to Python and GAE. Busy building a simple blog to learn. Was wondering, how can I get the datastore entries? This is how my DB object looks like : class BlogArticles(db.Model): author = db.UserProperty() article_name = db.StringProperty() article = db.TextProperty() date = db.DateTimePr...
[ "aah figured it out :)\nHere is how I did it...so simple.\n all_data = db.get(edit_article)\n article_name = all_data.article_name\n article = all_data.article\n\n" ]
[ 0 ]
[]
[]
[ "google_cloud_datastore", "python", "web_applications" ]
stackoverflow_0005027148_google_cloud_datastore_python_web_applications.txt
Q: web.py + subprocess = hang Here's my main file: import subprocess, time pipe = subprocess.PIPE popen = subprocess.Popen('pythonw -uB test_web_app.py', stdout=pipe) time.sleep(3) And here's test_web_app.py: import web class Handler: def GET(self): pass app = web.application(['/', 'Handler'], globals()) app.ru...
web.py + subprocess = hang
Here's my main file: import subprocess, time pipe = subprocess.PIPE popen = subprocess.Popen('pythonw -uB test_web_app.py', stdout=pipe) time.sleep(3) And here's test_web_app.py: import web class Handler: def GET(self): pass app = web.application(['/', 'Handler'], globals()) app.run() When I run the main file, t...
[ "You have not waited for the process. Once it's done, you have to call popen.wait. \nYou can check if the process is terminated using the poll method of the popen object to see if it has completed. \nIf you don't need the stdout of the web server process, you can simply ignore the stdout option. \n\nYou can use the...
[ 2, 1 ]
[]
[]
[ "freeze", "popen", "python", "subprocess", "web.py" ]
stackoverflow_0005026639_freeze_popen_python_subprocess_web.py.txt
Q: Python logging hijack sub-module logs to another file (Pylons) I have a pylons app myapp and I need all log messages from a submodule myapp.lib.submodule to be written to a different log file and not also in the main log file. Here's my current ini file, this way I get submodule messages in both accesslog and subm...
Python logging hijack sub-module logs to another file (Pylons)
I have a pylons app myapp and I need all log messages from a submodule myapp.lib.submodule to be written to a different log file and not also in the main log file. Here's my current ini file, this way I get submodule messages in both accesslog and submodulelog files: ... # Logging configuration [loggers] keys = root, r...
[ "You may use propagate flag for submodule logger to stop passing messages to ancestor loggers, like this:\n[logger_submodule] \nlevel = INFO ...
[ 2 ]
[]
[]
[ "logging", "pylons", "python" ]
stackoverflow_0005026485_logging_pylons_python.txt
Q: Oracle and Python - cx_Oracle DLL load failed Right I have Python 2.6.2 installed on my machine, I wish to access an Oracle 10g (10.2.0.1.0 to be precise) instance on the same network (not local machine) I've installed the cx_Oracle module v5.0.4 from http://prdownloads.sourceforge.net/cx-oracle/cx_Oracle-5.0.4-1...
Oracle and Python - cx_Oracle DLL load failed
Right I have Python 2.6.2 installed on my machine, I wish to access an Oracle 10g (10.2.0.1.0 to be precise) instance on the same network (not local machine) I've installed the cx_Oracle module v5.0.4 from http://prdownloads.sourceforge.net/cx-oracle/cx_Oracle-5.0.4-10g.win32-py2.6.msi?download However if I load the p...
[ "Ok it seems I needed to install the client version of oracle 10g. It's all fixed now :o)\n" ]
[ 1 ]
[]
[]
[ "cx_oracle", "oracle", "oracle10g", "python" ]
stackoverflow_0005026945_cx_oracle_oracle_oracle10g_python.txt
Q: How to pass data in Django via hyperlink in a table I want to display a list of objects in a table, no problem doing the table. I want to put links in the data displayed of one column in the template. The question is, how can I pass data in that link to the view?. For example in struts2 and JSPs, I used to do it t...
How to pass data in Django via hyperlink in a table
I want to display a list of objects in a table, no problem doing the table. I want to put links in the data displayed of one column in the template. The question is, how can I pass data in that link to the view?. For example in struts2 and JSPs, I used to do it this way (with param): <td class="nowrap"> ...
[ "Maybe you can simply add GET parameters to your url:\n<a href=\"{% url view-name %}?subjectID={{id}}\">your link</a>\n\nEven better would be a nice url design with arguments:\n<a href=\"{% url path.to.some_view subjectid=id action=action %}\">your link</a>\n\n" ]
[ 5 ]
[]
[]
[ "django", "hyperlink", "param", "python" ]
stackoverflow_0005027199_django_hyperlink_param_python.txt
Q: Django(trunk) and class based generic views: one form's initial data appearing in another one's I've run into a strange problem where data seems to persist accross different views and requests until the server gets restarted. I've managed to reduce the issue to the following code: # foobar/models.py from django.db...
Django(trunk) and class based generic views: one form's initial data appearing in another one's
I've run into a strange problem where data seems to persist accross different views and requests until the server gets restarted. I've managed to reduce the issue to the following code: # foobar/models.py from django.db import models class Foo(models.Model): bug = models.CharField(max_length=10) # foobar/forms.p...
[ "Because you're mutating the kwargs that are passed in, which come from class-level properties in the view class.\nInstead, copy them and update the copy:\ninitial_defaults = {'bug': 'no'}\ninitial_defaults.update(kwargs.get('initial', {}))\ndefaults = kwargs.copy()\ndefaults['initial'] = initial_defaults \n\n", ...
[ 1, 0 ]
[]
[]
[ "django", "django_class_based_views", "python" ]
stackoverflow_0005019070_django_django_class_based_views_python.txt
Q: Delete order number in django I have a list of order numbers. From my service order view, I can manually type in a field number to lookup for a order number to delete. This works well. order = models.Order.objects.get(pk=1219) if request.POST.get('delete'): order.delete() Now my question. I have an edit order...
Delete order number in django
I have a list of order numbers. From my service order view, I can manually type in a field number to lookup for a order number to delete. This works well. order = models.Order.objects.get(pk=1219) if request.POST.get('delete'): order.delete() Now my question. I have an edit order form with a url of /orders/edit/(?...
[ "You can accept multiple parameters from query string, like this:\n/quote/service_order/(\\d+)/(\\d+)\n\nThen in your view:\n# client_id - first parameter in braces from the url\n# order_id - 2nd parameter in braces from the url\ndef order_view(request, client_id, order_id):\n order = models.Order.objects.get(pk...
[ 1 ]
[]
[]
[ "django", "python", "views" ]
stackoverflow_0005027553_django_python_views.txt
Q: ggplot2 hell with rpy2-2.0.7 + python 2.6 + r 2.11 (windows 7) i am using rpy2-2.0.7 (i need this to work with windows 7, and compiling the binaries for the newer rpy2 versions is a mess) to push a two-column dataframe into r, create a few layers in ggplot2, and output the image into a <.png>. i have wasted coun...
ggplot2 hell with rpy2-2.0.7 + python 2.6 + r 2.11 (windows 7)
i am using rpy2-2.0.7 (i need this to work with windows 7, and compiling the binaries for the newer rpy2 versions is a mess) to push a two-column dataframe into r, create a few layers in ggplot2, and output the image into a <.png>. i have wasted countless hours fidgeting around with the syntax; i did manage to output...
[ "I use rpy2 solely through Nathaniel Smith's brilliant little module called rnumpy (see the \"API\" link at the rnumpy home page). With this you can do:\nfrom rnumpy import *\n\nr.library(\"ggplot2\")\n\npicpath = 'foo.png' \nname = [\"cat\",\"dog\",\"mouse\"]\nnums = [1.0,2.0,3.0]\n\nr[\"dataf\"] = r.data_frame(na...
[ 3, 2, 1 ]
[]
[]
[ "device", "ggplot2", "python", "r", "rpy2" ]
stackoverflow_0003515269_device_ggplot2_python_r_rpy2.txt
Q: django/python convert string which represents a python dictionary into a dictionary object I have a string which represents a python dictionary returned from a db table e.g. {'name': 'John', 'email': 'test@test.com'} where {'name': 'John', 'email': 'test@test.com'} is returned as a string from the db I then have ...
django/python convert string which represents a python dictionary into a dictionary object
I have a string which represents a python dictionary returned from a db table e.g. {'name': 'John', 'email': 'test@test.com'} where {'name': 'John', 'email': 'test@test.com'} is returned as a string from the db I then have a function which receives a dictionary as **kwargs e.g. def print_details(*args, **kwargs): ...
[ "ast.literal_eval is a very restricted, safer eval that only evals literals (e.g. dicts, tuple or list literal containing string, int, float, ... literals).\nA JSON parser would work as well for an even more restricted subset (bools are different, null instead of None, no tuples, perhaps even more). Again, the stan...
[ 6 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005028168_django_python.txt
Q: Easier Way to Write Python Console Programs (do args exist) So I have some code that has way too many of these in it try: if argv[4]: n = argv[4] except IndexError, e: n = raw_input("Enter n: ") Is there some easier way to do this? Basically a better way to check for input to exists and then if i...
Easier Way to Write Python Console Programs (do args exist)
So I have some code that has way too many of these in it try: if argv[4]: n = argv[4] except IndexError, e: n = raw_input("Enter n: ") Is there some easier way to do this? Basically a better way to check for input to exists and then if it doesn't act accordingly. Thanks
[ "Have a look at the argparse module (which does a lot more than is shown here):\nimport argparse\n\nparser = argparse.ArgumentParser(description='Process some integers.')\nparser.add_argument('integers', metavar='N', type=int, nargs='+',\n help='an integer for the accumulator')\nparser.add_argumen...
[ 3, 1, 1, 0, 0 ]
[]
[]
[ "console", "python" ]
stackoverflow_0005024866_console_python.txt
Q: python feedparser How would you parse xml data as follows with python feedparser <Book_API> <Contributor_List> <Display_Name>Jason</Display_Name> </Contributor_List> <Contributor_List> <Display_Name>John Smith</Display_Name> </Contributor_List> </Book_API> A: That doesn't look like any sort of RSS/ATOM feed. I w...
python feedparser
How would you parse xml data as follows with python feedparser <Book_API> <Contributor_List> <Display_Name>Jason</Display_Name> </Contributor_List> <Contributor_List> <Display_Name>John Smith</Display_Name> </Contributor_List> </Book_API>
[ "That doesn't look like any sort of RSS/ATOM feed. I wouldn't use feedparser at all for that, I would use lxml. In fact, feedparser can't make any sense of it and drops the \"Jason\" contributor in your example.\nfrom lxml import etree\n\ndata = <fetch the data somehow>\nroot = etree.parse(data)\n\nNow you have a t...
[ 4, 2 ]
[]
[]
[ "feedparser", "python" ]
stackoverflow_0005027290_feedparser_python.txt
Q: Python on windows: gtk import error. I'm having fun with python, and would like to learn gui programming. I installed pygtk, and gtk but I get this message when I try to import gtk: Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> import gtk File "C:\Python27\lib\site-packages\gtk-2.0\gt...
Python on windows: gtk import error.
I'm having fun with python, and would like to learn gui programming. I installed pygtk, and gtk but I get this message when I try to import gtk: Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> import gtk File "C:\Python27\lib\site-packages\gtk-2.0\gtk\__init__.py", line 40, in <module> from ...
[ "PyGTK itself has several dependencies (cairo et al), did you install all of them?\n" ]
[ 0 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0005026115_gtk_pygtk_python.txt
Q: Good xls exporter to generate excel sheets automatically with a few macros from any programming language? We have a system which generates reports in XLS using Spreadsheet_Excel_Writer for smaller files and in case of huge files we just export them as CSVs. We now want to export excel sheets which are multicolo...
Good xls exporter to generate excel sheets automatically with a few macros from any programming language?
We have a system which generates reports in XLS using Spreadsheet_Excel_Writer for smaller files and in case of huge files we just export them as CSVs. We now want to export excel sheets which are multicolor etc. as a part of report generation, which in excel could be done through a few macros. Is there any good e...
[ "It's your \"excel sheets with macros\" that is going to cause you all end of problems. If you're on a Windows platform, with Excel installed, then PHP's COM extension should allow you to do this. Otherwise, I'm nor aware of any PHP library which allows you to create macros... not even PHPExcel. I suspect the same ...
[ 0 ]
[]
[]
[ "java", "macros", "php", "python", "xls" ]
stackoverflow_0005028536_java_macros_php_python_xls.txt
Q: Python interprocess communication I have a Python application (with GUI, using PyQt4) that gets spawned by the user in several instances. The application is used to execute some long running tasks (about some hours to a few days), so I'm willing to add an extra "monitoring" application that will do things like: f...
Python interprocess communication
I have a Python application (with GUI, using PyQt4) that gets spawned by the user in several instances. The application is used to execute some long running tasks (about some hours to a few days), so I'm willing to add an extra "monitoring" application that will do things like: find all the running processes of the ot...
[ "\nBut this leads to having to open\n several unneeded sockets listening\n only on localhost, and having to\n create some kind of ports allocation\n mechanism to avoid two processes\n trying to listen on the same port\n\nNot quite. First, that's how most interprocess communication works, through sockets. Eithe...
[ 2, 2, 2 ]
[]
[]
[ "python", "rpc" ]
stackoverflow_0004924083_python_rpc.txt
Q: PHP Email Server How can I program my own email server in PHP, that listens for email and forward the messages to a URL? Is python more recommended for this? Regards, A: I suggest you to use an already developed email server software. There are some really well tested ones out there. You do not need to reinvent ...
PHP Email Server
How can I program my own email server in PHP, that listens for email and forward the messages to a URL? Is python more recommended for this? Regards,
[ "I suggest you to use an already developed email server software. There are some really well tested ones out there.\nYou do not need to reinvent the wheel. Save you that trouble! You may use one of the following\n\nprocmail\nsendmail\nthere are so many other solutions out there (igor milla mentioned a wikipedia sit...
[ 2 ]
[]
[]
[ "email", "linux", "php", "python" ]
stackoverflow_0005028929_email_linux_php_python.txt
Q: pymongo: possible to iterate result use next() and prev()? I have a database with a column "id", integer type. I am using: records = config.gSupei1Collection.find().sort([("id",pymongo.DESCENDING)]) To get the cursor, and then I use record = records[0] to get the largest ID record. I am wondering after I got 'reco...
pymongo: possible to iterate result use next() and prev()?
I have a database with a column "id", integer type. I am using: records = config.gSupei1Collection.find().sort([("id",pymongo.DESCENDING)]) To get the cursor, and then I use record = records[0] to get the largest ID record. I am wondering after I got 'record', can I use record.next(), record.prev() to get the record th...
[ "You can loop the records. Record is an actual document (a dict), not an iterator, but the result is.\nYou can do something like this:\nfor i, d in enumerate(records):\n print i, d\n\nOr if you want to use the returned records as an iterator, you can do something like:\nn = records.next()\n\nOr for forward compa...
[ 1 ]
[]
[]
[ "mongodb", "pymongo", "python" ]
stackoverflow_0005028959_mongodb_pymongo_python.txt
Q: What is python __get__ method good for? What can __get__ achieve that can't be done with with a getter method on the owning object? I can think of better separation of concerns but I guess there is more. A: It's used for descriptors. They are kind of like Python's getters/setters, and properties, but better. It'...
What is python __get__ method good for?
What can __get__ achieve that can't be done with with a getter method on the owning object? I can think of better separation of concerns but I guess there is more.
[ "It's used for descriptors. They are kind of like Python's getters/setters, and properties, but better. It's how Python implements the Uniform Access Principle.\nPython Descriptors\n", "Getter methods are ugly. It is much clearer to do:\nobj.foobar\n\nthan\nobj.get_foobar()\n\nSecondly, it used to implement stati...
[ 5, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005029352_python.txt