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: Sending image with post I want to fill some web-form with python script and send with POST-request. The problem is that form has fileuploading. I found this: poster for python. So, I came with FireBug at website with form and filled it. What I saw: values[action] add_save values[mod] blog values[depth] 2 values...
Sending image with post
I want to fill some web-form with python script and send with POST-request. The problem is that form has fileuploading. I found this: poster for python. So, I came with FireBug at website with form and filled it. What I saw: values[action] add_save values[mod] blog values[depth] 2 values[pid] 121 values[title] tit...
[ "I haven't used your approach before, but have successfully used MultipartPostHandler to do something similar. Abbreviated, an example would look like the following.\n\nimport MultipartPostHandler\nimport urllib2\n\nform_opener = urllib2.build_opener(MultipartPostHandler.MultipartPostHandler) \nurllib2.install_open...
[ 0, 0 ]
[]
[]
[ "forms", "image", "post", "poster", "python" ]
stackoverflow_0004432217_forms_image_post_poster_python.txt
Q: python about multiple %s in a string str = 'I love %s and %s, he loves %s and %s.' I want to use this format to display I love apple and pitch, he loves apple and pitch. Only add two variable please, but need a way to use it twice in one sentence. A: Use a dict: >>> s = 'I love %(x)s and %(y)s, he loves %(x)s...
python about multiple %s in a string
str = 'I love %s and %s, he loves %s and %s.' I want to use this format to display I love apple and pitch, he loves apple and pitch. Only add two variable please, but need a way to use it twice in one sentence.
[ "Use a dict:\n>>> s = 'I love %(x)s and %(y)s, he loves %(x)s and %(y)s.'\n>>> s % {\"x\" : \"apples\", \"y\" : \"oranges\"}\n'I love apples and oranges, he loves apples and oranges.'\n\nOr use the newer format function, which was introduced in 2.6:\n>>> s = 'I love {0} and {1}, she loves {0} and {1}'\n>>> s.format...
[ 25, 6 ]
[]
[]
[ "python", "string" ]
stackoverflow_0004435152_python_string.txt
Q: Python: Split list in array Just beginning with python and know enough to know I know nothing. I would like to find alternative ways of splitting a list into a list of dicts. Example list: data = ['**adjective:**', 'nice', 'kind', 'fine', '**noun:**', 'benefit', 'profit', 'advantage', 'avail', 'welfare', '...
Python: Split list in array
Just beginning with python and know enough to know I know nothing. I would like to find alternative ways of splitting a list into a list of dicts. Example list: data = ['**adjective:**', 'nice', 'kind', 'fine', '**noun:**', 'benefit', 'profit', 'advantage', 'avail', 'welfare', 'use', 'weal', '**adverb:...
[ "This might be as close at it gets to what you have asked:\nd = collections.defaultdict(list)\nfor s in data:\n if s.endswith(\":\"):\n key = s[:-1]\n else:\n d[key].append(s)\nprint d\n# defaultdict(<type 'list'>, \n# {'adjective': ['nice', 'kind', 'fine'], \n# 'noun': ['benefit', 'pro...
[ 10, 5, 1, 0, 0 ]
[]
[]
[ "dictionary", "list", "python", "split" ]
stackoverflow_0004432067_dictionary_list_python_split.txt
Q: MySQLdb error when using cursor.execute() I am using python and specifically MySQLdb to fill a database, although a code that was working until recently is throwing up an error after moving servers at work: The code is: cursor.execute("""SELECT Entry, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P FROM evaluation"...
MySQLdb error when using cursor.execute()
I am using python and specifically MySQLdb to fill a database, although a code that was working until recently is throwing up an error after moving servers at work: The code is: cursor.execute("""SELECT Entry, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P FROM evaluation""") result = cursor.fetchall() for record in ...
[ "It's a quick fix, but changing innodb_lock_wait_timeout might temporarily defer the \"Lock wait timeout exceeded\" issue. See doc. \nAny chance the MySQL version, engine(s), or config's changed when you \"moved servers\"?\nReading the results of SHOW ENGINE INNODB STATUS would alert you to any recent locking issue...
[ 3 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0004434889_mysql_python.txt
Q: Python file I/O with Tkinter I'm trying to open a .txt file with Python. I'm trying to fill a Tkinter text widget with the files contents. However with the following snippet, when I try to open the files contents and put it in a the text widget self.Te, nothing happens. Any clues? Snippet: self.Open = tkFile...
Python file I/O with Tkinter
I'm trying to open a .txt file with Python. I'm trying to fill a Tkinter text widget with the files contents. However with the following snippet, when I try to open the files contents and put it in a the text widget self.Te, nothing happens. Any clues? Snippet: self.Open = tkFileDialog.askopenfilename(initialdir=...
[ "Here is a working example:\n#!/usr/bin/env python\n\nfrom Tkinter import *\nfrom tkFileDialog import askopenfilename \n\nclass App:\n def __init__(self, master):\n frame = Frame(master)\n frame.pack()\n\n self.button = Button(frame, text=\"QUIT\", command=frame.quit)\n self.button...
[ 3 ]
[]
[]
[ "io", "python", "tkinter" ]
stackoverflow_0004435254_io_python_tkinter.txt
Q: How to get html tags from url? How would you get all the HTML tags from a URL and print them? A: import urllib print urllib.urlopen('http://www.example.com/blah').read() A: Fetch it (using mechanize, urllib or whatever else you want), parse what you get (using elementtree, BeautifulSoup, lxml or whatever else ...
How to get html tags from url?
How would you get all the HTML tags from a URL and print them?
[ "import urllib\nprint urllib.urlopen('http://www.example.com/blah').read()\n\n", "Fetch it (using mechanize, urllib or whatever else you want), parse what you get (using elementtree, BeautifulSoup, lxml or whatever else you want) and you have what you want. \n" ]
[ 3, 0 ]
[]
[]
[ "html", "printing", "python", "url" ]
stackoverflow_0004435882_html_printing_python_url.txt
Q: How to get html tags? Say I have a text file like this: <html><head>Headline<html><head>more words </script>even more words</script> <html><head>Headline<html><head>more words </script>even more words</script> How would I get just the tags into a list like this: <html> <head> <html> <head> </script> </script> <ht...
How to get html tags?
Say I have a text file like this: <html><head>Headline<html><head>more words </script>even more words</script> <html><head>Headline<html><head>more words </script>even more words</script> How would I get just the tags into a list like this: <html> <head> <html> <head> </script> </script> <html> <head> <html> <head> </...
[ "I think this is what you want:\nhtml_string = ''.join(input_file.readlines())\nmatches = re.findall('<.*?>', html_string)\nfor m in matches:\n print m\n\nHope this helps\n", "Python has a HTMLParser module for this.\nHere is some code which does what you want:\nfrom HTMLParser import HTMLParser\n\nclass MyHTM...
[ 6, 4 ]
[]
[]
[ "python" ]
stackoverflow_0004436008_python.txt
Q: Read content of RAR file into memory in Python I'm looking for a way to read specific files from a rar archive into memory. Specifically they are a collection of numbered image files (I'm writing a comic reader). While I can simply unrar these files and load them as needed (deleting them when done), I'd prefer t...
Read content of RAR file into memory in Python
I'm looking for a way to read specific files from a rar archive into memory. Specifically they are a collection of numbered image files (I'm writing a comic reader). While I can simply unrar these files and load them as needed (deleting them when done), I'd prefer to avoid that if possible. That all said, I'd prefer ...
[ "See the rarfile module:\n\nhttp://grue.l-t.ee/~marko/src/rarfile/README.html\nhttp://pypi.python.org/pypi/rarfile/\nhttps://github.com/markokr/rarfile\n\n", "The real answer is that there isn't a library, and you can't make one. You can use rarfile, or you can use 7zip unRAR (which is less free than 7zip, but s...
[ 9, 6, 3, 2, 1, 0, 0 ]
[]
[]
[ "linux", "python", "rar", "stream" ]
stackoverflow_0001185959_linux_python_rar_stream.txt
Q: why my django site in hosting (alwaysdata) cant show my page I have deployed Django at alwaysdata.com, this is my main page on http://zjm1126.alwaysdata.net/ : i change the index.html to index1.html, this file is not my file , my project is like this : example_project/ __init__.py manage.py public/ ...
why my django site in hosting (alwaysdata) cant show my page
I have deployed Django at alwaysdata.com, this is my main page on http://zjm1126.alwaysdata.net/ : i change the index.html to index1.html, this file is not my file , my project is like this : example_project/ __init__.py manage.py public/ django.fcgi .htaccess media/ settings.py...
[ "I think that you need to point your subdomain to the right directory : /example_project/public/ where your .htaccess and django.fcgi lives.\nalwaysdata has a forum http://forum.alwaysdata.com/ where you can ask question in english. The guys know their job very well and answer very quickly. \nI hope it helps\n", ...
[ 3, 0 ]
[]
[]
[ "django", "hosting", "python" ]
stackoverflow_0004435406_django_hosting_python.txt
Q: python simple iteration i would like to ask what is the best way to make simple iteration. suppose i want to repeat certain task 1000 times, which one of the following is the best? or is there a better way? for i in range(1000): do something with no reference to i i = 0 while i < 1000: do something with n...
python simple iteration
i would like to ask what is the best way to make simple iteration. suppose i want to repeat certain task 1000 times, which one of the following is the best? or is there a better way? for i in range(1000): do something with no reference to i i = 0 while i < 1000: do something with no reference to i i += 1 ...
[ "The first is considered idiomatic. In Python 2.x, use xrange instead of range.\n", "The for loop is more concise and more readable. while loops are rarely used in Python (with the exception of while True).\nA bit of idiomatic Python: if you're trying to do something a set number of times with a range (with no ne...
[ 8, 6, 5, 0 ]
[]
[]
[ "iteration", "python" ]
stackoverflow_0004436240_iteration_python.txt
Q: how to create a service in python in windows? I want to run a service in windows which will keep running in background and will run a cron with specific time. how i can do that in windows using python? A: Use pywin32. A tutorial was written (in 2005 mind you) here about how one might do that. A: Make sure win3...
how to create a service in python in windows?
I want to run a service in windows which will keep running in background and will run a cron with specific time. how i can do that in windows using python?
[ "Use pywin32. A tutorial was written (in 2005 mind you) here about how one might do that.\n", "Make sure win32 api is installed. Basically, you subclass the BasicNTService. The win32 package docs has some more information. I also have a working example in some code I wrote that does this.\nWindowsServer.py that a...
[ 3, 1, 0 ]
[]
[]
[ "cron", "python", "service", "window" ]
stackoverflow_0004436294_cron_python_service_window.txt
Q: Trouble sending data between PHP and Python I've been trying to set up a very basic search engine using the Whoosh modules in python called on from PHP. I had it working until I upgraded the modules for some additional features I needed. At which point an odd bug seemed to appear. Any print statement after the lin...
Trouble sending data between PHP and Python
I've been trying to set up a very basic search engine using the Whoosh modules in python called on from PHP. I had it working until I upgraded the modules for some additional features I needed. At which point an odd bug seemed to appear. Any print statement after the line "searcher = ixtemp.searcher()" is not being rec...
[ "Two things. Are you sure the script is completing? It could be hanging on the searcher() call. Second, I suppose searcher() could be redirecting stdout.\nMy guess is that your script isn't completing, or it's timing out or something.\nEDIT Looks like this code depends on the current working directory. You mention ...
[ 0, 0, 0 ]
[]
[]
[ "exec", "php", "python", "search", "whoosh" ]
stackoverflow_0004435619_exec_php_python_search_whoosh.txt
Q: Link encryption with django and python I'm having a download application and I want to encrypt the links for file downloads, so that the user doesn't know the id of the file. Furthermore I'd like to include date/time in the link, and check when serving the file if the link is still valid. There's a similar questio...
Link encryption with django and python
I'm having a download application and I want to encrypt the links for file downloads, so that the user doesn't know the id of the file. Furthermore I'd like to include date/time in the link, and check when serving the file if the link is still valid. There's a similar question asked here, but I'm running into problems ...
[ "Sounds like it would be easy, especially if you don't mind using the same encryption key forever. Just delimit a string (/ or : works as well as anything) for the file name, the date/time, and anything else you want to include, then encrypt and b64 it! Remember to use urlsafe_b64encode, not the regular b64encode, ...
[ 2, 1, 0, 0 ]
[]
[]
[ "django", "encryption", "hyperlink", "python" ]
stackoverflow_0004431922_django_encryption_hyperlink_python.txt
Q: comparing strings and decoded unicode in python3 I'm doing some socket/select programming and one of my events is triggered by the incoming byte string of 'OK'. I'm using utf_8 to encode everything sent from the server and decoding it on the client. However, my client comparisons aren't working and my if statement...
comparing strings and decoded unicode in python3
I'm doing some socket/select programming and one of my events is triggered by the incoming byte string of 'OK'. I'm using utf_8 to encode everything sent from the server and decoding it on the client. However, my client comparisons aren't working and my if statement never evaluates to true. Here is the code in question...
[ "TCP sockets don't have message boundaries. As your last comment says you are getting multiple messages in one long string. You are reponsible for queuing up data until you have a complete message, and then processing it as one complete message.\nEach time select says a socket has some data to read, append the da...
[ 1 ]
[]
[]
[ "encoding", "python", "select", "sockets" ]
stackoverflow_0004435724_encoding_python_select_sockets.txt
Q: Python: Regex help str = "a\b\c\dsdf\matchthis\erwe.txt" The last folder name. Match "matchthis" A: Without using regex, just do: >>> import os >>> my_str = "a/b/c/dsdf/matchthis/erwe.txt" >>> my_dir_path = os.path.dirname(my_str) >>> my_dir_path 'a/b/c/dsdf/matchthis' >>> my_dir_name = os.path.basename(my_dir_...
Python: Regex help
str = "a\b\c\dsdf\matchthis\erwe.txt" The last folder name. Match "matchthis"
[ "Without using regex, just do:\n>>> import os\n>>> my_str = \"a/b/c/dsdf/matchthis/erwe.txt\"\n>>> my_dir_path = os.path.dirname(my_str)\n>>> my_dir_path\n'a/b/c/dsdf/matchthis'\n>>> my_dir_name = os.path.basename(my_dir_path)\n>>> my_dir_name\n'matchthis'\n\n", "Better to use os.path.split(path) since it's platf...
[ 3, 2, 1, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0004436615_python_regex.txt
Q: Confirming the difference between import * and from xxx import * I was surprised to find out that import foo and from foo import * had different effects on global members. I wanted to confirm that my experiments are the correct behavior. In the first example, changing a member in module foo will reflect in a...
Confirming the difference between import * and from xxx import *
I was surprised to find out that import foo and from foo import * had different effects on global members. I wanted to confirm that my experiments are the correct behavior. In the first example, changing a member in module foo will reflect in all code that imports foo. However, changing that member in the later ...
[ "Yes, your observations are correct. This is a consequence of the way that binding works in Python.\nWhen one does \nimport foo\n\nthen foo becomes a global name that references the module foo. When one does\nfoo.bar = 7\n\nThen the reference is followed and the object foo is loaded. Then 7 is stored in the bar att...
[ 16, 4 ]
[]
[]
[ "python", "python_import" ]
stackoverflow_0004436401_python_python_import.txt
Q: How to create a service in Python in Windows? I have found http://code.activestate.com/recipes/576451-how-to-create-a-windows-service-in-python/ But that service does nothing. How can I use that service for running specific Python file? A: You can put your business code in SvcDoRun. The sample at your link just ...
How to create a service in Python in Windows?
I have found http://code.activestate.com/recipes/576451-how-to-create-a-windows-service-in-python/ But that service does nothing. How can I use that service for running specific Python file?
[ "You can put your business code in SvcDoRun. The sample at your link just logs a message every three seconds. Just don't forget to check self.hWaitStop periodically.\nSometimes it is convenient to create a worker thread and do all work on that thread, or maybe start a child process. An additional complication in th...
[ 1 ]
[]
[]
[ "python", "windows_services" ]
stackoverflow_0004436506_python_windows_services.txt
Q: Running a command with os.system(A) produces different output then running A in shell I have a hex to binary converter that I am using in a Python script... os.system("./HexToBinary " + str(sys.argv[1]) + "_hex " + str(sys.argv[1]) + "_binary") If I run my python script on file A_hex, it produces file A_binary. ...
Running a command with os.system(A) produces different output then running A in shell
I have a hex to binary converter that I am using in a Python script... os.system("./HexToBinary " + str(sys.argv[1]) + "_hex " + str(sys.argv[1]) + "_binary") If I run my python script on file A_hex, it produces file A_binary. But if I run this command directly in the command-line, on file AA_hex it produces AA_binar...
[ "I dont know if it is needed, but try wait, http://docs.python.org/library/os.html#os.wait\nalso, check the output of system, it may help tell you if something is wrong\n" ]
[ 1 ]
[]
[]
[ "python", "scripting", "shell", "unix" ]
stackoverflow_0004436858_python_scripting_shell_unix.txt
Q: how do I access model fields individually? suppose I have this model: id = models.AutoField(primary_key=True) datetime_from = models.DateTimeField('time') model = MyModel def read(self, request, id=0): if not id: id = 0 MyModel.object mmodel = MyModel.objects.filter(id__gt=id) retu...
how do I access model fields individually?
suppose I have this model: id = models.AutoField(primary_key=True) datetime_from = models.DateTimeField('time') model = MyModel def read(self, request, id=0): if not id: id = 0 MyModel.object mmodel = MyModel.objects.filter(id__gt=id) return mmodel My question is, how do I possible get...
[ "You don't need to create an id column yourself. The read method is not necessary, either. Just say\nfrom django.db import models\n\nclass MyModel(models.Model):\n datetime_from = models.DateTimeField('time')\n\nYou can then query the table like so\n>>> obj = MyModel.objects.get(id=<target id here>)\n>>> date = ...
[ 1 ]
[]
[]
[ "django", "model", "python" ]
stackoverflow_0004436959_django_model_python.txt
Q: How can I check if a file exists in a tar archive with Python? I would like to verify the existence of a given file in a tar archive with Python before I get it as a file-like object. I've tried it with isreg(), but probably I do something wrong. How can I check if a file exists in a tar archive with Python? I tri...
How can I check if a file exists in a tar archive with Python?
I would like to verify the existence of a given file in a tar archive with Python before I get it as a file-like object. I've tried it with isreg(), but probably I do something wrong. How can I check if a file exists in a tar archive with Python? I tried import tarfile tar = tarfile.open("sample.tar", "w") tar.add("t...
[ "If you really need to check, then you can test for membership using the getnames method and the in operator:\n>>> import tarfile\n>>> tar = tarfile.open(\"sample.tar\", \"w\")\n>>> \"sample.tar\" in tar.getnames()\nTrue\n\nHowever, I think that in Python (and dealing with file systems in general), catching excepti...
[ 6, 0, 0, 0 ]
[]
[]
[ "python", "tar", "tarfile" ]
stackoverflow_0004180384_python_tar_tarfile.txt
Q: how to treat ruby symbols in cross language object serialization I'm currently working on a project where I need to transfer objects from ruby to python and back again, obviously serialization is the way to go. I've looked at things like yaml but decided to write my own as I didn't want to deal with the dependenci...
how to treat ruby symbols in cross language object serialization
I'm currently working on a project where I need to transfer objects from ruby to python and back again, obviously serialization is the way to go. I've looked at things like yaml but decided to write my own as I didn't want to deal with the dependencies of the libraries and such when it came time to distribute. I've wr...
[ "Doesn't that depend on what your project needs? If symbols are important, you'll need some way to deal with them.\nI'm not a Ruby programmer, but from what I've just read, I think converting them to strings is probably easiest. The standard Python interpreter will reuse memory for identical short strings, which se...
[ 1, 0, 0 ]
[]
[]
[ "python", "ruby", "serialization", "symbols" ]
stackoverflow_0004432993_python_ruby_serialization_symbols.txt
Q: Differences between Go and Cython Today a great friend of mine asked me what are the main differences between the newest Go language and Cython, which is a set of C-extensions for Python. I don't have much knowledge on Python, can anyone tell me why Go is better/worse than Cython? A: Cython isn't really a langua...
Differences between Go and Cython
Today a great friend of mine asked me what are the main differences between the newest Go language and Cython, which is a set of C-extensions for Python. I don't have much knowledge on Python, can anyone tell me why Go is better/worse than Cython?
[ "Cython isn't really a language in the conventional sense. It is a preprocessor for building Python extensions that takes Python-like syntax (actually they strive for full Python compatibility) and produces C code (using the Python C API). Doing this they are able to include some special case optimisations, but the...
[ 9, 5, 4, 2, 1, 1 ]
[]
[]
[ "cython", "go", "python" ]
stackoverflow_0001743526_cython_go_python.txt
Q: how to find time using python? i want to run my function and then I want to find now's time using python. then lets say after 2 hours my function should run again. what should i do? A: There are several ways of finding the time in Python: import time print time.time() # unix timestamp, seconds from 1970 impo...
how to find time using python?
i want to run my function and then I want to find now's time using python. then lets say after 2 hours my function should run again. what should i do?
[ "There are several ways of finding the time in Python:\nimport time\nprint time.time() # unix timestamp, seconds from 1970\n\nimport datetime\nprint datetime.datetime.now()\n\ntime.sleep(7200) # sleep for 2 hours\n\n", "to determine current time, you can use pythons datetime module\nfrom datetime import datetime\...
[ 2, 2, 1, 0 ]
[]
[]
[ "function", "python", "time" ]
stackoverflow_0004437856_function_python_time.txt
Q: Invalid request URI while adding a video to playlist via youtube api I have been unable to overcome this error while trying to add a video to my playlist using the youtube gdata python api. gdata.service.RequestError: {'status': 400, 'body': 'Invalid request URI', 'reason': 'Bad Request'} This seems to be th...
Invalid request URI while adding a video to playlist via youtube api
I have been unable to overcome this error while trying to add a video to my playlist using the youtube gdata python api. gdata.service.RequestError: {'status': 400, 'body': 'Invalid request URI', 'reason': 'Bad Request'} This seems to be the same error, but there are no solutions as yet. Any help guys? import ge...
[ "Gdata seems to use v1 API. So, the relevant documentation is here: http://code.google.com/apis/youtube/1.0/developers_guide_protocol.html#Retrieving_a_playlist\nThis means, your \"playlist_uri\" should not take the value of \"lst.id.text\", but should take the \"feedLink\" element's \"href\" attribute in order to ...
[ 2 ]
[]
[]
[ "gdata_api", "python", "youtube_api" ]
stackoverflow_0004419061_gdata_api_python_youtube_api.txt
Q: How to start a django cms project I decided to take a look to django-cms. After looking at the docs I cloned the repository using git clone https://github.com/divio/django-cms.git Then I installed it using sudo python setup.py install I already have django 1.2.3 installed. I moved to the example directory an ran...
How to start a django cms project
I decided to take a look to django-cms. After looking at the docs I cloned the repository using git clone https://github.com/divio/django-cms.git Then I installed it using sudo python setup.py install I already have django 1.2.3 installed. I moved to the example directory an ran syncdb which created the following tab...
[ "django-cms uses South for database migrations. Models handled by South are not synced to the database using syncdb. You have to use manage.py migrate.\nSince you don't have any tables and data from django-cms to migrate, a faster solution would be this process:\n\ncomment out 'south' in your INSTALLED_APPS\nrun ma...
[ 7, 1, 0 ]
[]
[]
[ "django", "django_cms", "python" ]
stackoverflow_0004438258_django_django_cms_python.txt
Q: Python sorting question - given list of ['url', 'tag1', 'tag2',..]s and search specification ['tag3', 'tag1',...], return relevant url list I'm quite new to programming so I'm sure there's a terser way to pose this, but I'm trying to create a personal bookmarking program. Given multiple urls each with a list of ta...
Python sorting question - given list of ['url', 'tag1', 'tag2',..]s and search specification ['tag3', 'tag1',...], return relevant url list
I'm quite new to programming so I'm sure there's a terser way to pose this, but I'm trying to create a personal bookmarking program. Given multiple urls each with a list of tags ordered by relevance, I want to be able to create a search consisting of a list of tags that returns a list of most relevant urls. My first so...
[ "\n1) Is there a much more elegant/efficient way of doing this (embarrass me!)\n\nSure thing. The basic idea: quit trying to tell Python what to do, and just ask it for what you want.\ncontent = [\n {'url':'url1', 'taglist':['b','a','c','d']},\n {'url':'url2', 'taglist':['c','a','b','d']},\n {'url':'url3',...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004419955_python.txt
Q: scripting fruityloops or propellerheads reason from VB or Python? I have both Fruityloops and Propellerheads Reason software synths on my Windows PC. Any way I can get at and script these from either Visual Basic or Python? Or at least send Midi messages to the synths from code? Update : attempts to use something ...
scripting fruityloops or propellerheads reason from VB or Python?
I have both Fruityloops and Propellerheads Reason software synths on my Windows PC. Any way I can get at and script these from either Visual Basic or Python? Or at least send Midi messages to the synths from code? Update : attempts to use something like a "midi-mapper" (thanks for link MusiGenesis) don't seem to work. ...
[ "Both applications support MIDI. It's just that they don't see each other. \nIn order to send messages via MIDI between applications, you need to install a virtual midi port.\nThere are several freely available, but this one works: http://www.midiox.com/zip/MidiYokeSetup.msi\nYou'll get a virtual MIDI output port t...
[ 3, 2, 2, 1, 0, 0, 0 ]
[]
[]
[ "audio_player", "python", "vb.net" ]
stackoverflow_0000267628_audio_player_python_vb.net.txt
Q: MIT OCW Python Course in Highest Quality I am currently learning Python from MIT OCW courses ? Anyone who have used it might know this... where can I get the highest quality video to download from offline usage ? A: A question was posted earlier asking for a link to Handouts. It was answered here
MIT OCW Python Course in Highest Quality
I am currently learning Python from MIT OCW courses ? Anyone who have used it might know this... where can I get the highest quality video to download from offline usage ?
[ "A question was posted earlier asking for a link to Handouts. It was answered here\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0004439802_python.txt
Q: Replace text with regexp I have to replace text this way: Some data la-la-la [image=test.png] next data... Some data la-la-la 123 [image=test2.png] And replace that with: Some data la-la-la test.png next data... Some data la-la-la 123 test2.png I tried with re.sub method from python: for foo in re.search('(\[ima...
Replace text with regexp
I have to replace text this way: Some data la-la-la [image=test.png] next data... Some data la-la-la 123 [image=test2.png] And replace that with: Some data la-la-la test.png next data... Some data la-la-la 123 test2.png I tried with re.sub method from python: for foo in re.search('(\[image=(.*)\])', text): text = ...
[ "Seriously, did you read regex documentation or at least the howto?\n\n.search() returns a match object. You can't iterate over it.\n.sub() replaces all occurrences in the string at once. You can't replace one by one.\n\nOne idea:\nimport re\n\ntext = \"\"\"Some data la-la-la [image=test.png] next data...\nSome dat...
[ 4 ]
[]
[]
[ "python", "regex", "replace", "string" ]
stackoverflow_0004440076_python_regex_replace_string.txt
Q: Process Accessability I am trying to write some information into the file, which is located in ftp, and this file can be updated by number of people, but if at all i download a file from the ftp to my local machine, update it and then upload it back to ftp, and at the same time if some one else downloads the same ...
Process Accessability
I am trying to write some information into the file, which is located in ftp, and this file can be updated by number of people, but if at all i download a file from the ftp to my local machine, update it and then upload it back to ftp, and at the same time if some one else downloads the same file for the modification, ...
[ "Look at fuser\n", "It is unclear if you need to know for debugging purposes or to support a feature in the code but this is the method call to get the pid of the current executing process.\nimport os\n\nprint \"Process id:\",os.getpid()\n\nThis will simply dump the id to output and you can put other information ...
[ 1, 0 ]
[]
[]
[ "file", "operation", "python" ]
stackoverflow_0004439446_file_operation_python.txt
Q: telnetlib read_until() function confusion I am trying to automate some telnet actions with python3. So I started to use the build in telnetlib (not pexpect). Actually everything works so far but I do not understand completly how read_until works - actually the documentation says that you can set a timeout and if t...
telnetlib read_until() function confusion
I am trying to automate some telnet actions with python3. So I started to use the build in telnetlib (not pexpect). Actually everything works so far but I do not understand completly how read_until works - actually the documentation says that you can set a timeout and if the search string is not found the timeout sends...
[ "Yes, if your hostname is example.com, read_until will return something like weijwrgnerg hgqwv blather example.com. Except if it hasn't found the hostname after three seconds, it will just spit out whatever it's got by then: weijwrgnerg hg.\nSo I think you're doing it almost right. You probably want to re.escape y...
[ 1 ]
[]
[]
[ "python", "telnetlib" ]
stackoverflow_0004440231_python_telnetlib.txt
Q: Controlling Browser using Python? Is it possible to control a web browser like Firefox using Python? I would want to do things like launch the browser force clicks on URLs take screenshots etc. A: Selenium Remote Control is a project that comes very close to what you are after. It is really easy to get work...
Controlling Browser using Python?
Is it possible to control a web browser like Firefox using Python? I would want to do things like launch the browser force clicks on URLs take screenshots etc.
[ "Selenium Remote Control is a project that comes very close to what you are after. It is really easy to get working in Python with the selenium.webdriver subpackage that comes with it. Once upon a time, these were two projects. They've now been unified.\nInstallation\nSimple!\n$ pip install -U selenium\n\nUsage\n>>...
[ 26, 10, 3, 1, 0, 0 ]
[]
[]
[ "browser", "python", "webbrowser_control" ]
stackoverflow_0003369073_browser_python_webbrowser_control.txt
Q: Problems running code with Python IDLE I have been attempting to work an iCreate, roomba without a vacuum cleaner attached using Python 2.7.1 and have created working code. When I type each line in by hand it works perfectly, however when putting all the code in together it stalls and does not operate. import Crea...
Problems running code with Python IDLE
I have been attempting to work an iCreate, roomba without a vacuum cleaner attached using Python 2.7.1 and have created working code. When I type each line in by hand it works perfectly, however when putting all the code in together it stalls and does not operate. import Create import VideoCapture from PIL import Image...
[ "\nInstead if pasting the code into IDLE, save it into a file, and run it like this:\npython yourfile.py\nwhile 0 == 0: You might want while True: instead.\nred = Image.open(\"Red.jpeg\")\n(redr, redg, redb) = red.getpixel((0, 0)) is a very complex way of saying RED = (255, 0, 0)\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0004440068_python.txt
Q: Functions inside "for" iteration, Python I am a beginner and kinda lost with the code i have written. I am writing an add-on for some software, trying to extract some data from its classes. There is a list of statements that i am going through using operator for. I am interested in two types of statements called V...
Functions inside "for" iteration, Python
I am a beginner and kinda lost with the code i have written. I am writing an add-on for some software, trying to extract some data from its classes. There is a list of statements that i am going through using operator for. I am interested in two types of statements called VC_STATEMENT_LINMOTION and VC_STATEMENT_PTPMOTI...
[ "(Edit: I've updated the code to reflect new information in your post.)\nIf I understand your problem corrrectly, a simple description of what you're trying to achieve is this: you have a list of Statement instances in main_routine.Statements and you want to perform different code based on statement.Type. Here is t...
[ 2 ]
[]
[]
[ "for_loop", "function", "iteration", "python" ]
stackoverflow_0004440377_for_loop_function_iteration_python.txt
Q: How to hide COM object Dispatched from Python I'm using COM in Python and I want the object to run in background - hidden. With Excel I do: Import win32com.client Excel=win32com.client.Dispatch("Excel.Application") Excel.Visible=1 but my application do not have property .Visible - is there any other way to hide...
How to hide COM object Dispatched from Python
I'm using COM in Python and I want the object to run in background - hidden. With Excel I do: Import win32com.client Excel=win32com.client.Dispatch("Excel.Application") Excel.Visible=1 but my application do not have property .Visible - is there any other way to hide it? Maybe some special parameter to Dispatch? Than...
[ "If you know your application title or class, you can hide it via ShowWindow:\nimport win32com.client \nimport win32con\nimport win32gui\nimport time\n\nprint \"Start\"\nexcel = win32com.client.Dispatch(\"Excel.Application\") \nexcel.Visible = 1 # Visible via automation\ntime.sleep(2)\nhwnd = win32gui.FindWindow(...
[ 3 ]
[]
[]
[ "com", "python" ]
stackoverflow_0004439689_com_python.txt
Q: Python Tabs Fake or Real Many tutorial suggest users to use tab with width of 4 while 4 is made using spaces not real tab character. Using real tab also it works so why do people suggest to use spaces of 4 rather than real tab ? I'm a python beginner confused ???? [UPDATE] Thanks! I am now switching to spaces of 4...
Python Tabs Fake or Real
Many tutorial suggest users to use tab with width of 4 while 4 is made using spaces not real tab character. Using real tab also it works so why do people suggest to use spaces of 4 rather than real tab ? I'm a python beginner confused ???? [UPDATE] Thanks! I am now switching to spaces of 4. Added following to my .vimr...
[ "The Python compiler considers the tab character to be equivalent to indentation of 8 spaces. You can use tabs if you like but mixing tabs and spaces will lead to tricky-to-debug errors, which is why sticking with spaces is recommended.\n", "As soon as you allow a tab character into a file, you will end up in a s...
[ 2, 1, 1, 1 ]
[]
[]
[ "character_encoding", "python" ]
stackoverflow_0004440814_character_encoding_python.txt
Q: trouble with rpy2, rpart passing data correctly from python to r I am trying to run rpart through RPY2 using Python 2.6.5 and R 10.0. I create a data frame in python and pass it along but I get an error stating: Error in function (x) : binary operation on non-conformable arrays Traceback (most recent call last): ...
trouble with rpy2, rpart passing data correctly from python to r
I am trying to run rpart through RPY2 using Python 2.6.5 and R 10.0. I create a data frame in python and pass it along but I get an error stating: Error in function (x) : binary operation on non-conformable arrays Traceback (most recent call last): File "partitioningSANDBOX.py", line 86, in <module> model=r.rpar...
[ "The problem is related to R idiosyncratic code in rpart (to be precise, the following block, in particular the last line:\nm <- match.call(expand.dots = FALSE)\nm$model <- m$method <- m$control <- NULL\nm$x <- m$y <- m$parms <- m$... <- NULL\nm$cost <- NULL\nm$na.action <- na.action\nm[[1L]] <- as.name(\"model.fra...
[ 5 ]
[]
[]
[ "python", "r", "rpy2" ]
stackoverflow_0004434783_python_r_rpy2.txt
Q: Scaling a follower model The problem is somewhat similar to twitter/facebook's: followers and following users add items Subsequently you see the items added by all the people you are following. Problem A: how to keep the query for items added by people you are following working well with growing datasets? Proble...
Scaling a follower model
The problem is somewhat similar to twitter/facebook's: followers and following users add items Subsequently you see the items added by all the people you are following. Problem A: how to keep the query for items added by people you are following working well with growing datasets? Problem B: we are seeing geographica...
[ "Problem A: how to keep the query for items added by people you are following working well with growing datasets?\nstarting with a dataset of (who are my followers / who am i following); one could save these values as tuples and segmentate them across several SQL databases (though I doubt real segmentation is reall...
[ 1 ]
[]
[]
[ "django", "nosql", "partitioning", "python", "scaling" ]
stackoverflow_0004441209_django_nosql_partitioning_python_scaling.txt
Q: How to print errors in error log in Django? I have example code in view: try bla-bla-bla except return 500 status How to view error in this try in error.log for Django ( for example if Django run on mod-python in Apache ) ? A: this answer your question: Django Unhandled Exception A: Print to sys.stder...
How to print errors in error log in Django?
I have example code in view: try bla-bla-bla except return 500 status How to view error in this try in error.log for Django ( for example if Django run on mod-python in Apache ) ?
[ "this answer your question:\nDjango Unhandled Exception\n", "Print to sys.stderr, or better yet, use logging.\n" ]
[ 2, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004440736_django_python.txt
Q: pssh and known_hosts file when I use pssh, trying to access a remote machine which is not inside the UNIX known hosts file, pssh freeze after giving the password. After having added the host using a direct ssh command, pssh works. So is there an option to give to the pssh command in order to avoid this problem ? ...
pssh and known_hosts file
when I use pssh, trying to access a remote machine which is not inside the UNIX known hosts file, pssh freeze after giving the password. After having added the host using a direct ssh command, pssh works. So is there an option to give to the pssh command in order to avoid this problem ? Thanks for your help, Regards
[ "Try pssh -O StrictHostKeyChecking=no. This works for me.\nBy default ssh uses the value of \"ask\", which causes it to ask the user whether to continue connecting to unknown host. By setting the value to \"no\", you avoid the question, but are no longer protected against certain attacks. E.g. if you are connecting...
[ 18, 1 ]
[]
[]
[ "python", "ssh" ]
stackoverflow_0004437331_python_ssh.txt
Q: Why is Django admin login giving me 403 CSRF error? I am running Django 1.2.2 and I get the following error when I try to log in to the Django admin: Forbidden (403) CSRF verification failed. Request aborted. Reason given for failure: No CSRF or session cookie. ** I have made NO customization to the barebones ...
Why is Django admin login giving me 403 CSRF error?
I am running Django 1.2.2 and I get the following error when I try to log in to the Django admin: Forbidden (403) CSRF verification failed. Request aborted. Reason given for failure: No CSRF or session cookie. ** I have made NO customization to the barebones admin and when I inspect the source there is a CSRF token...
[ "I've had the same problem on Django 1.2.1 FINAL. Since I knew that Django on our production site would never be updated from 1.0 (for various reasons), I found a workaround which I implemented into my development version of settings.py, leaving the production settings.py untouched.\nCreate a middleware.py file in ...
[ 6, 5, 1 ]
[]
[]
[ "csrf", "django", "django_csrf", "python" ]
stackoverflow_0003678238_csrf_django_django_csrf_python.txt
Q: get the first 10 google results using googleapi I need to get the first 10 google results for example: ... query = urllib.urlencode({'q' : 'example'}) ... ... url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' \ ... % (query) ... search_results = urllib.urlopen(url) ... json = simplejson.loads(s...
get the first 10 google results using googleapi
I need to get the first 10 google results for example: ... query = urllib.urlencode({'q' : 'example'}) ... ... url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' \ ... % (query) ... search_results = urllib.urlopen(url) ... json = simplejson.loads(search_results.read()) ... results = json['responseDat...
[ "I've done it in the past, here is complete example (i'm not python guru, but it works):\n#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport sys, getopt\nimport urllib\nimport simplejson\n\nOPTIONS = (\"m:\", [\"min=\"])\n\ndef print_usage():\n s = \"usage: \" + sys.argv[0] + \" \"\n for o in OPTIONS[0]...
[ 3, 0 ]
[]
[]
[ "google_api", "json", "python" ]
stackoverflow_0004441812_google_api_json_python.txt
Q: Best practice for running a daily Python screen-scraping script 50 times (8.3 minutes total) per user? On the front-end, I have a PHP webapp that allows users to create a list of their websites (5 max). On the back-end, a Python script runs daily (and has ~10 iterations) for each website that the user registers. E...
Best practice for running a daily Python screen-scraping script 50 times (8.3 minutes total) per user?
On the front-end, I have a PHP webapp that allows users to create a list of their websites (5 max). On the back-end, a Python script runs daily (and has ~10 iterations) for each website that the user registers. Each script per website takes about 10 seconds to run through all iterations and finish its scraping. It then...
[ "You can make the PHP app place the URLs into a database (MySQL, Sqlite, etc.) or text file. Then, loop through the database/text file in your Python script. Use Cron to run the Python script every day.\nThere are lots of resources for learning the Cron syntax:\nhttp://google.com/search?q=cron+tutorial\n", "Do ...
[ 1, 0, 0 ]
[]
[]
[ "cron", "design_patterns", "php", "python", "screen_scraping" ]
stackoverflow_0004441933_cron_design_patterns_php_python_screen_scraping.txt
Q: sorting list in python accoeding to one dimension Possible Duplicate: Sorting a tuple that contains tuples hi I have a list that goes A=[[a,'3'],[g,'1'],[y,2]] I am looking for a quick way to arrange it according to the numbers (second dimension), so NewA=[[g,'1'],[y,'2'],[a,'3']] thanks ariel A: from operator...
sorting list in python accoeding to one dimension
Possible Duplicate: Sorting a tuple that contains tuples hi I have a list that goes A=[[a,'3'],[g,'1'],[y,2]] I am looking for a quick way to arrange it according to the numbers (second dimension), so NewA=[[g,'1'],[y,'2'],[a,'3']] thanks ariel
[ "from operator import itemgetter\nnewA = sorted(a, key=itemgetter(1))\n\n" ]
[ 2 ]
[]
[]
[ "python", "sorting" ]
stackoverflow_0004442123_python_sorting.txt
Q: SymPy substition with scalars doesn't work? from sympy import * x,y,s = symbols('xys') z = (1 - 2*x*x) w = (1 + 2*x*x) q = 2*x*x*2*y*y sub = {2*x*x: s} print w.subs(sub) print z.subs(sub) print q print q.subs(sub) The output I get: 1 + s 1 - 2*x**2 4*x**2*y**2 4*x**2*y**2 The output I expect: 1 + s 1 - s 4...
SymPy substition with scalars doesn't work?
from sympy import * x,y,s = symbols('xys') z = (1 - 2*x*x) w = (1 + 2*x*x) q = 2*x*x*2*y*y sub = {2*x*x: s} print w.subs(sub) print z.subs(sub) print q print q.subs(sub) The output I get: 1 + s 1 - 2*x**2 4*x**2*y**2 4*x**2*y**2 The output I expect: 1 + s 1 - s 4*x**2*y**2 2*y**2*s Do I do something wrong?
[ "Sympy seems to be inconsistent in what it matches. For instance, changing the sign on the matching substitution expression allows z to be matched with. I would consider adding this example to this issue. I would also try the Sympy mailing list. Remember, this project isn't even to version number 1.0 yet so things ...
[ 1 ]
[]
[]
[ "python", "substitution", "sympy" ]
stackoverflow_0004440477_python_substitution_sympy.txt
Q: Only print when run as script? Is there a better way to only print when run as a script, when __name__ == '__main__' ? I have some scripts that I also import and use parts of. Something like the below will work but is ugly, and would have to be defined in each script separately: def printif(s): if globals()['_...
Only print when run as script?
Is there a better way to only print when run as a script, when __name__ == '__main__' ? I have some scripts that I also import and use parts of. Something like the below will work but is ugly, and would have to be defined in each script separately: def printif(s): if globals()['__name__'] == '__main__': pri...
[ "run_as_script = False \n\ndef printif(s): \n if run_as_script: \n print (s)\n return\n\nif __name__ == '__main__': \n run_as_script = True\n\n", "In light of user318904's comment on my other answer, I'll provide an alternative (although this may not work in all cases, it might just be \"good ...
[ 5, 1, 0 ]
[]
[]
[ "logging", "python", "scripting" ]
stackoverflow_0004434915_logging_python_scripting.txt
Q: Python dbus can't find org.(gnome|freedesktop).ScreenSaver I'm trying to get python to interact with dbus and screensaver however it flatly refuses to do so no matter what. Perl seems to do alright with it but I write python, not perl (yet) Python 2.6.6 (r266:84292, Sep 15 2010, 16:22:56) [GCC 4.4.5] on linux2 Ty...
Python dbus can't find org.(gnome|freedesktop).ScreenSaver
I'm trying to get python to interact with dbus and screensaver however it flatly refuses to do so no matter what. Perl seems to do alright with it but I write python, not perl (yet) Python 2.6.6 (r266:84292, Sep 15 2010, 16:22:56) [GCC 4.4.5] on linux2 Type "help", "copyright", "credits" or "license" for more informat...
[ "In [36]: import dbus\n\nIn [37]: bus = dbus.SessionBus()\n\nIn [38]: bus.get_object('org.gnome.ScreenSaver','/org/gnome/ScreenSaver')\nOut[38]: <ProxyObject wrapping <dbus._dbus.SessionBus (session) at 0xa41e38c> :1.24 /org/gnome/ScreenSaver at 0xa4a3b0c>\n\n" ]
[ 4 ]
[]
[]
[ "dbus", "gnome", "python" ]
stackoverflow_0004442584_dbus_gnome_python.txt
Q: Allow Outlook 2007 to edit custom shared iCalendars I have been working on some custom shared Internet calendar software. I currently have a webdav server setup using apache and my software (using python) and right now it works great with Thunderbird and the Lightning plugin, I can subscribe to an icalendar and ed...
Allow Outlook 2007 to edit custom shared iCalendars
I have been working on some custom shared Internet calendar software. I currently have a webdav server setup using apache and my software (using python) and right now it works great with Thunderbird and the Lightning plugin, I can subscribe to an icalendar and edit events with no problem. However I've run into a snag w...
[ "Microsoft Outlook 2007 seems to have no ability to allow writing to an Internet Calendar. Icalendars are set to read only. You can publish a calendar to a webdav to create your own icalendar but that calendar (in your Outlook '07) would never update if someone else were to somehow edit that calendar (on the server...
[ 1 ]
[]
[]
[ "apache", "icalendar", "outlook_2007", "python", "webdav" ]
stackoverflow_0004378924_apache_icalendar_outlook_2007_python_webdav.txt
Q: Select Data from Table and Insert into a different DB I'm using python and psycopg2 to remotely query some psql databases, and I'm trying to figure out the best way to select the data I need from the remote table, and insert it into a table on a separate DB (local application server). Most of the stuff I've read ...
Select Data from Table and Insert into a different DB
I'm using python and psycopg2 to remotely query some psql databases, and I'm trying to figure out the best way to select the data I need from the remote table, and insert it into a table on a separate DB (local application server). Most of the stuff I've read has directed me to avoid executemany and look toward COPY o...
[ "\nbut I'm unsure how to implement this on a specific select statement as opposed to the entire table\n\nCOPY isn't limited to tables, you can use a query as the source as well, check out the examples in the manual, it shows how to use COPY to create a text file based on a query:\nhttp://www.postgresql.org/docs/cur...
[ 1, 0 ]
[]
[]
[ "postgresql", "psycopg2", "python", "sql" ]
stackoverflow_0004441785_postgresql_psycopg2_python_sql.txt
Q: Python: Adding Fields to Objects Dynamically I am wondering whether it is possible to add fields to objects dynamically. For example, I want to be able to add something like: user = object() user.first_name = 'John' user.last_name = 'Smith' When I execute that in Python command line interpretor I get: AttributeEr...
Python: Adding Fields to Objects Dynamically
I am wondering whether it is possible to add fields to objects dynamically. For example, I want to be able to add something like: user = object() user.first_name = 'John' user.last_name = 'Smith' When I execute that in Python command line interpretor I get: AttributeError: 'object' object has no attribute 'first_name'...
[ "Try this:\nclass Object:\n pass\n\nobj = Object()\nobj.x = 5\n\n", "You cannot assign to attributes of object instances like this. Derive from object, and use an instance of that class.\n" ]
[ 20, 7 ]
[]
[]
[ "metaprogramming", "python" ]
stackoverflow_0004443301_metaprogramming_python.txt
Q: pyLucene Installation I am on Ubuntu 10.04, Python 2.6.5 & having some trouble installing pyLucene. Here's what I have done so far, installed these packages - sudo apt-get install ant sudo apt-get install sun-java6-jdk sudo update-java-alternatives -s java-1.5.0-sun sudo apt-get install gcc sudo apt-get install g+...
pyLucene Installation
I am on Ubuntu 10.04, Python 2.6.5 & having some trouble installing pyLucene. Here's what I have done so far, installed these packages - sudo apt-get install ant sudo apt-get install sun-java6-jdk sudo update-java-alternatives -s java-1.5.0-sun sudo apt-get install gcc sudo apt-get install g++ sudo apt-get install gcj ...
[ "I think the problem may be that the patch is for setuptools 0.6-11 and you have an earlier version of setuptools (prob 0.6-10) installed from your distro's packages. \nI have had a similar problem that was resolved by removing the version of setuptools installed by the distro and installing your own downloaded fro...
[ 2, 0 ]
[]
[]
[ "lucene", "pylucene", "python" ]
stackoverflow_0004438936_lucene_pylucene_python.txt
Q: Extract integer from a list I have a list like ['-1', '1,2,3', '2'] and I want to extract all the integers in it. I don't know the number of integers in each position of the list ie the list can also be ['2,3,4','1,2,3','-1'] but it will never have an empty string. So I want that the answer should be [2,3,4,1,2,3,...
Extract integer from a list
I have a list like ['-1', '1,2,3', '2'] and I want to extract all the integers in it. I don't know the number of integers in each position of the list ie the list can also be ['2,3,4','1,2,3','-1'] but it will never have an empty string. So I want that the answer should be [2,3,4,1,2,3,-1] What is the best way to do so...
[ "map(int, ','.join(l).split(','))\n\nwhere l is your list.\n", "Here's a ist comprehension:\nnew_list = [ int(i) for i in ','.join(old_list).split(',') ]\n\n", "And another list comprehension.\n>>> l = ['-1', '1,2,3', '2']\n>>> [ int(x) for s in l for x in s.split(',')]\n[-1, 1, 2, 3, 2]\n\n", "Not the same. ...
[ 3, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004441652_python.txt
Q: Function calling in openerp reports How is this sum_taxes method getting its lot parameter set? This is a code sample from the auction addon in openerp. import pooler import time from report import report_sxw from osv import osv class seller_form_report(report_sxw.rml_parse): def __ini...
Function calling in openerp reports
How is this sum_taxes method getting its lot parameter set? This is a code sample from the auction addon in openerp. import pooler import time from report import report_sxw from osv import osv class seller_form_report(report_sxw.rml_parse): def __init__(self, cr, uid, name, context): ...
[ "check following file auction/report/buyer_form_report.sxw\n[[ repeatIn(o['lots'],'oo') ]] [[ oo.obj_num ]] Here 'oo' is defined and its called like [[ oo.obj_price + sum_taxes(oo) ]]\nand as this report is registered for the model: auction.lots it will return the BrowseRecord for the active_id when user clicks on...
[ 1, 1 ]
[]
[]
[ "openerp", "python", "report", "reportlab" ]
stackoverflow_0004438102_openerp_python_report_reportlab.txt
Q: Search many expressions in many documents using Python I often have to search many words (1000+) in many documents (million+). I need position of matched word (if matched). So slow pseudo version of code is for text in documents: for word in words: position = search(word, text) if po...
Search many expressions in many documents using Python
I often have to search many words (1000+) in many documents (million+). I need position of matched word (if matched). So slow pseudo version of code is for text in documents: for word in words: position = search(word, text) if position: print word, position Is there an...
[ "For fast exact-text, multi-keyword search, try acora - http://pypi.python.org/pypi/acora/1.4\nIf you want a few extras - result relevancy, near-matches, word-rooting etc, Whoosh might be better - http://pypi.python.org/pypi/Whoosh/1.4.1\nI don't know how well either scales to millions of docs, but it wouldn't take...
[ 4, 1, 0 ]
[]
[]
[ "nlp", "python" ]
stackoverflow_0004443481_nlp_python.txt
Q: how to represent graphs /trees in python and how to detect cycles? i want to implement kruskal's algorithm in python how can i go about representing the tree/graph and what approach should i follow to detect the cycles ? A: The simplest way of representing it (in my opinion) is by using a dict of arrays lists: g...
how to represent graphs /trees in python and how to detect cycles?
i want to implement kruskal's algorithm in python how can i go about representing the tree/graph and what approach should i follow to detect the cycles ?
[ "The simplest way of representing it (in my opinion) is by using a dict of arrays lists:\ngraph = {}\ngraph[node_id] = [other_node_id for other_node_id in neighbors(node_id)]\n\nA simple way of finding cycles is by using a BF or DF search:\ndef df(node):\n if visited(node):\n pass # found a cycle here, do...
[ 11, 4 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0004443734_algorithm_python.txt
Q: Is importing a file good in Python I have around 80 lines of a function in a file. I need the same functionality in another file so I am currently importing the other file for the function. My question is that in terms of running time on a machine which technique would be better :- importing the complete file and ...
Is importing a file good in Python
I have around 80 lines of a function in a file. I need the same functionality in another file so I am currently importing the other file for the function. My question is that in terms of running time on a machine which technique would be better :- importing the complete file and running the function or copying the func...
[ "Importing is how you're supposed to do it. That's why it's possible. Performance is a complicated question, but in general it really doesn't matter. People who really, really need performance, and can't be satisfied by just fixing the basic algorithm, are not using Python in the first place. :) (At least not for t...
[ 4, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004443509_python.txt
Q: problem in passing data to url using GET method params = urllib.urlencode(data) headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain", } conn = httplib.HTTPConnection(self.base_url) conn.request('GET', url, para...
problem in passing data to url using GET method
params = urllib.urlencode(data) headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain", } conn = httplib.HTTPConnection(self.base_url) conn.request('GET', url, params, headers) response = conn.getresponse() ...
[ "When using \"GET\" , the parameters should be really placed along with the URL - the \"body\" argument (to which ou are passing \"params\") is only used in post requests -\nIn other words, try this instead:\nconn.request('GET', url + \"?\" + params, None, headers)\n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0004443966_python.txt
Q: reducing list based on fuzzy values in python I have a list that contains groups of nearly identical numeric values. i.e. (1004.523, 1004.575, 1004.475, 791.385, 791.298, 791.301, 791.305, 791.299) What I am trying to do is read through the list and find all the 1004.5 +- values aggregate them and find the average...
reducing list based on fuzzy values in python
I have a list that contains groups of nearly identical numeric values. i.e. (1004.523, 1004.575, 1004.475, 791.385, 791.298, 791.301, 791.305, 791.299) What I am trying to do is read through the list and find all the 1004.5 +- values aggregate them and find the average value. then continue on and find all the 791.0 +- ...
[ "Perhaps you are looking for kmeans clustering. \nIn the code below, I use scipy.cluster.vq.kmeans to cluster the data into k groups.\nIf the distortion is greater than some set threshold amount, then we increase k by one, and redo the kmeans clustering. We repeat until we find groups whose total distortion is les...
[ 3, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004443349_python.txt
Q: subprocess pid different from ps output Why is it that the subprocess pid (Popen.pid) has different value from that the ps command returns? I've noticed this when ps called both from inside python (with subprocess.call()) and from another terminal. Here's a simple python file to test: #!/usr/bin/python3 ''' Test s...
subprocess pid different from ps output
Why is it that the subprocess pid (Popen.pid) has different value from that the ps command returns? I've noticed this when ps called both from inside python (with subprocess.call()) and from another terminal. Here's a simple python file to test: #!/usr/bin/python3 ''' Test subprocess termination ''' import subprocess ...
[ "Because the command is run with shell=True, the pid returned by subprocess is that of the shell process used to run the command.\n" ]
[ 5 ]
[]
[]
[ "pid", "ps", "python", "subprocess" ]
stackoverflow_0004444141_pid_ps_python_subprocess.txt
Q: How To define arguments in ironpython for the Microsoft.SqlServer.SMO.Scripter.Script Class I want to script my database objects using the ironpython code below: import sys import clr database_name = r'localhost\SQLEXPRESS' dir_assemblies = r'D:\programfiles\Microsoft SQL Server\100\SDK\Assemblies' # Import SM...
How To define arguments in ironpython for the Microsoft.SqlServer.SMO.Scripter.Script Class
I want to script my database objects using the ironpython code below: import sys import clr database_name = r'localhost\SQLEXPRESS' dir_assemblies = r'D:\programfiles\Microsoft SQL Server\100\SDK\Assemblies' # Import SMO Namespace sys.path.append(dir_assemblies) clr.AddReferenceToFile('Microsoft.SqlServer.Smo.dll')...
[ "I found the solution:\narg=System.Array[SMO.SqlSmoObject]([table])\n\nThe full script looks like:\nimport sys \nimport clr \n# import .NET Array\nimport System.Array\n\ndatabase_name = r'localhost\\SQLEXPRESS' \ndir_assemblies = r'D:\\programfiles\\Microsoft SQL Server\\100\\SDK\\Assemblies' \n\n# Impo...
[ 3, 0 ]
[]
[]
[ "ironpython", "python", "smo", "sql_server" ]
stackoverflow_0004434587_ironpython_python_smo_sql_server.txt
Q: Elegantly handle different parameter types I have a function that, in the simplest of cases, operates on an iterable of items. def foo(items): for item in items: # do stuff Sometimes, I do not want to pass it an iterable of items directly, but rather an object that provides a method to get the iterabl...
Elegantly handle different parameter types
I have a function that, in the simplest of cases, operates on an iterable of items. def foo(items): for item in items: # do stuff Sometimes, I do not want to pass it an iterable of items directly, but rather an object that provides a method to get the iterable: def foo(obj): for item in obj.iteritems()...
[ "As it stands, you should probably use at least two methods here,the third just calling the first with the itertools.chain.from_iterable result. You could also potentially have a use for *args; it depends on your precise case (providing a real example is helpful). You can also use a simple helper function to return...
[ 2, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004444179_python.txt
Q: -timestamp in Django I'm trying to learn Django. I'm completely green so far. I'm learning from not very good book - first thing we're creating is a simple blog. So, at the end of this excersie they want me to sort my blog post - so the new posts are on top. In order to achieve that im adding: class Meta: orde...
-timestamp in Django
I'm trying to learn Django. I'm completely green so far. I'm learning from not very good book - first thing we're creating is a simple blog. So, at the end of this excersie they want me to sort my blog post - so the new posts are on top. In order to achieve that im adding: class Meta: ordering = ('-timestamp',) in...
[ "You would have to present some more code, for example how you retrieve data from database. Here you have some ordering examples:\nhttp://www.djangoproject.com/documentation/models/ordering/\n", "There's a few ways to do this. By adding a Meta class, you give the object an inherent ordering. Using the manager to ...
[ 1, 1, 1, 0 ]
[]
[]
[ "django", "django_views", "python" ]
stackoverflow_0004444332_django_django_views_python.txt
Q: SWIG Python bindings for OpenCV 2.0 with MacPorts Y'all, I've been at to for 3 days trying to get OpenCV Python binds happening, and I have (the full epic struggle is documented here) but despite turning the SWIG flag on in CMake after installing swig via macports, I'm not getting any SWIG action :( My cmake comma...
SWIG Python bindings for OpenCV 2.0 with MacPorts
Y'all, I've been at to for 3 days trying to get OpenCV Python binds happening, and I have (the full epic struggle is documented here) but despite turning the SWIG flag on in CMake after installing swig via macports, I'm not getting any SWIG action :( My cmake command looks like: cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMA...
[ "Seems that the cmake flags didn't make much of a difference. I became systematic and reduced them to the minimum:\ncmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/opt/local -D BUILD_PYTHON_SUPPORT=ON -D BUILD_SWIG_PYTHON_SUPPORT=OFF -D BUILD_NEW_PYTHON_SUPPORT=ON -D PYTHON_INCLUDE_DIR=/opt/local/Library...
[ 0, 0 ]
[]
[]
[ "cmake", "macports", "opencv", "python", "swig" ]
stackoverflow_0002020228_cmake_macports_opencv_python_swig.txt
Q: How to import modules in Paver? I am using Paver for the first time and I can't import in my pavement.py a module I created in the same directory. The module was working when imported in a standalone script in the same directory. I guess paver is running from somewhere else, not the same directory. Any suggestion?...
How to import modules in Paver?
I am using Paver for the first time and I can't import in my pavement.py a module I created in the same directory. The module was working when imported in a standalone script in the same directory. I guess paver is running from somewhere else, not the same directory. Any suggestion?
[ "After a bit of investigation I found a solution...\nimport sys\nsys.path.append( os.path.abspath('.') )\nimport mymodule.myscript as myscript\n\n" ]
[ 2 ]
[]
[]
[ "paver", "python" ]
stackoverflow_0004445042_paver_python.txt
Q: In Django forms, how do I "add" an error into the queue? def clean(self): cleaned_data = self.cleaned_data current_pass = cleaned_data['current_pass'] new_pass = cleaned_data['new_pass'] new_pass2 = cleaned_data['new_pass2'] if current_pass or new_pass or new_pass2: ...
In Django forms, how do I "add" an error into the queue?
def clean(self): cleaned_data = self.cleaned_data current_pass = cleaned_data['current_pass'] new_pass = cleaned_data['new_pass'] new_pass2 = cleaned_data['new_pass2'] if current_pass or new_pass or new_pass2: if not current_pass: raise forms.Validatio...
[ "A solution could be to bind those errors to the relevant fields, as explained in the docs.\nYour code would look like this:\ndef clean(self):\n cleaned_data = self.cleaned_data\n current_pass = cleaned_data['current_pass']\n new_pass = cleaned_data['new_pass']\n new_pass2 = cleaned_data['new_pass2']\n ...
[ 3, 1, 0 ]
[]
[]
[ "django", "forms", "python", "validation" ]
stackoverflow_0004434575_django_forms_python_validation.txt
Q: Finding reachable vertices of a vertice in a graph I am having problem in my code to calculate the reachable vertices in a graph. I have the following code for the graph class Vertices(): number = 0 def __init__(self): Vertices.number += 1 self.number = Vertices.number self.Reachabl...
Finding reachable vertices of a vertice in a graph
I am having problem in my code to calculate the reachable vertices in a graph. I have the following code for the graph class Vertices(): number = 0 def __init__(self): Vertices.number += 1 self.number = Vertices.number self.Reachable= [] I create the graph in the following way a = Vert...
[ "How about using well-known solution to your problem?\nFirst, you need a data structure for a graph. You can do it as dictionary of lists where each vertex is represented as the key and reachable vertices are the list values.\ngraph = {'A': ['B', 'C'],\n 'B': ['C', 'D'],\n 'C': ['D'],\n 'D':...
[ 2, 1 ]
[ "Well first off it's Vertex, not Vertice. Secondly, you have (approximately) implemented an adjacency list as the data structure for your graph; it would be more standard to use an adjacency matrix.\nDo you know what depth-first search is? Roughly, you start at a vertex and pick a neighbour, then pick a neighbour...
[ -1 ]
[ "python" ]
stackoverflow_0004445112_python.txt
Q: how to create a '.htaccess' file using ssh i use windows xp , so i cant create a '.htaccess' file, and then update it to django hosting . so i have to create it using ssh , i use SecureCRT 6.5: i know cd , dir , mkdir , but i dont know how to create a file , and write some word in it ? thanks updated this is th...
how to create a '.htaccess' file using ssh
i use windows xp , so i cant create a '.htaccess' file, and then update it to django hosting . so i have to create it using ssh , i use SecureCRT 6.5: i know cd , dir , mkdir , but i dont know how to create a file , and write some word in it ? thanks updated this is the photo i use nano on windows xp : what should i...
[ "Use nano, vim, or emacs.\n", "Try nano, it's a basic text editor present on most *nix systems.\n", "You don't have to edit on the server (if SecureCRT provides for this, I'm not sure). Through Putty, which I do know, you can edit the file locally then upload using scp\nscp ./.htaccess username@example.com:/va...
[ 1, 1, 0 ]
[]
[]
[ "django", "python", "ssh" ]
stackoverflow_0004445346_django_python_ssh.txt
Q: assign choices to select dropdown at display time if i've got a form like this class ProductAddToCartForm(forms.Form): quantity = forms.IntegerField(widget=forms.TextInput(attrs={'size':'2', 'value':'1', 'class':'quantity', 'maxlength':'5'}), error_messages={'invalid':'Please enter a valid quantity.'}, min_val...
assign choices to select dropdown at display time
if i've got a form like this class ProductAddToCartForm(forms.Form): quantity = forms.IntegerField(widget=forms.TextInput(attrs={'size':'2', 'value':'1', 'class':'quantity', 'maxlength':'5'}), error_messages={'invalid':'Please enter a valid quantity.'}, min_value=1) size_option = forms.ChoiceField(widget=forms....
[ "Hey there, I played around in the shell / html and it looks like all this should work.\nIt looks like you can do what you posted.\nYou said you're unsure how to assign choices in the view? I tested your code, and it looks like it works? form.fields[myfield] = forms.NewField() correctly modifies the next call to fo...
[ 1, 0 ]
[]
[]
[ "django", "django_forms", "django_models", "python" ]
stackoverflow_0004421603_django_django_forms_django_models_python.txt
Q: how can I grab video from usb video capture + dvb device with gstreamer? I own a avermedia volar HX usb stick, I want to capture fromthe composite input , but I can't because I'm unable to select the input. I'm using gstreamer with + python, I think I need to use gsttuner select input but I have no experience usin...
how can I grab video from usb video capture + dvb device with gstreamer?
I own a avermedia volar HX usb stick, I want to capture fromthe composite input , but I can't because I'm unable to select the input. I'm using gstreamer with + python, I think I need to use gsttuner select input but I have no experience using gstreamer's interfaces. Could someone post a simple example? Thanks!
[ "src = gst.element_factory_make(\"v4l2src\", \"src\")\nsrc.set_state(gst.STATE_PAUSED)\ntry:\n # channel names will be different for each device\n channels = src.list_channels()\n composite = [x for x in channels if x.label == \"Composite1\"]\n if composite:\n self.src.set_channel(composite[0])\n...
[ 1, 1, 0 ]
[]
[]
[ "gstreamer", "python" ]
stackoverflow_0001284008_gstreamer_python.txt
Q: How to modify variables of another scope? Currectly, I'm trying the following: Some mutator function accepts other function's local scope using locals() def mutator(locals): locals['n'] = 10 locals['l'].append(10) def f(): n = 1 l = [1] mutator(locals()) print(n,l) # >>> 1, [1,10] f(None)...
How to modify variables of another scope?
Currectly, I'm trying the following: Some mutator function accepts other function's local scope using locals() def mutator(locals): locals['n'] = 10 locals['l'].append(10) def f(): n = 1 l = [1] mutator(locals()) print(n,l) # >>> 1, [1,10] f(None) and that works as expected: I was able to mod...
[ "class AttributeCollection(object):\n pass\nshared_settings= AttributeCollection()\n# now improvise\nshared_settings.temperature= 30\nshared_settings.samples= []\n# etc\n\nPass that shared_settings around, or make it global, and set its attributes to whatever you desire.\nYou see, the locals() of a function are ...
[ 3, 0 ]
[]
[]
[ "python", "scope" ]
stackoverflow_0004444498_python_scope.txt
Q: python alternative to the goto command? I have a python program that is essentailly made up of turtle graphics, and it is basically asking the user how many squares to draw, and then after each square, it adds 1 to a counter using: counter=1 <drawing code here> counter +=1 And then after that I wanted to do a che...
python alternative to the goto command?
I have a python program that is essentailly made up of turtle graphics, and it is basically asking the user how many squares to draw, and then after each square, it adds 1 to a counter using: counter=1 <drawing code here> counter +=1 And then after that I wanted to do a check to see if the number of squares is equal t...
[ "Does this help?\nimport turtle # don't pollute the namespace\nimport time\n\ndef getInt(msg):\n return int(raw_input(msg))\n\ndef drawBall():\n turtle.down()\n for i in range(96):\n turtle.right(105)\n turtle.forward(100)\n turtle.up()\n\ndef moveOver():\n turtle.goto(120,0)\n\ndef D...
[ 3, 2, 0, 0 ]
[]
[]
[ "batch_file", "goto", "python", "turtle_graphics" ]
stackoverflow_0004443405_batch_file_goto_python_turtle_graphics.txt
Q: django-admin: "super() argument 1 must be type, not None" when overriding save method Well, another unhelpful error has caused me to spend an hour trying to sort this problem. I have a model 'CompanyProfile' that has been working until recently, but now when i try to save the model through the admin, I get an erro...
django-admin: "super() argument 1 must be type, not None" when overriding save method
Well, another unhelpful error has caused me to spend an hour trying to sort this problem. I have a model 'CompanyProfile' that has been working until recently, but now when i try to save the model through the admin, I get an error which seems to be telling me that the Object reference is null. I have no idea how to sor...
[ "Maybe it's a cyclic import issue?\nhttp://markmail.org/message/zothlfayqkbidqfh#query:+page:1+mid:3cnpcw3e4cgo3cas+state:results\nIn the example here, he had an import statement in a signal that was the culprit.\nYou could check globals() for similar symptoms..\n", "You need to use args/kwargs when overriding mo...
[ 4, 1, 1, 0 ]
[]
[]
[ "django", "django_admin", "python", "types" ]
stackoverflow_0004411268_django_django_admin_python_types.txt
Q: Django redirect the right way? I have a similar question to this - Conditional login redirect in Django But I couldn't understand how to achieve the result from answers there. I am relatively new to django. I reused this code from somewhere, which redirects the user to login page. But after login I always get to t...
Django redirect the right way?
I have a similar question to this - Conditional login redirect in Django But I couldn't understand how to achieve the result from answers there. I am relatively new to django. I reused this code from somewhere, which redirects the user to login page. But after login I always get to the start/home page of the user. I wa...
[ "It's pretty straight forward:\nAdd a GET parameter to to your redirect line so that your login view knows where your user is coming from. It can be anything, but I'm using \"?redirect=myurl\". \nIn your login view: check for the existence of that key (redirect) in GET upon successful login. If it exists, redirect ...
[ 1, 0 ]
[]
[]
[ "django", "python", "redirect", "url_routing" ]
stackoverflow_0004392355_django_python_redirect_url_routing.txt
Q: Python, run a function based on formatting and contents of an input string I thought I'd try writing a kind of a measurements units conversion thingy just for practice. I would like it to work in a way that the user would be given a single input prompt and it would run the appropriate function based on the string....
Python, run a function based on formatting and contents of an input string
I thought I'd try writing a kind of a measurements units conversion thingy just for practice. I would like it to work in a way that the user would be given a single input prompt and it would run the appropriate function based on the string. I'm just wondering what would be the best way to tell weather the string is for...
[ "Use .split() on the string to break it into words (then you can re-interpret the first one as an int or float as appropriate). The resulting list will be in the same order as the input string, so you can look at each element in turn and check it against your reference list of units.\nMaking a separate function for...
[ 4, 3, 2, 0, 0 ]
[]
[]
[ "python", "string_comparison" ]
stackoverflow_0004445521_python_string_comparison.txt
Q: Can't change the values of fields of model objects in lists Why is it that when trying to set the value of a field of a model object contained in a list, the value doesn't get set, but when I store the object at that index into a variable, and then try to change it, I am successful? Below is an example of what I m...
Can't change the values of fields of model objects in lists
Why is it that when trying to set the value of a field of a model object contained in a list, the value doesn't get set, but when I store the object at that index into a variable, and then try to change it, I am successful? Below is an example of what I mean. In [64]: profile[0].screen_name = "clutch" In [65]: profile...
[ "My guess is that profile in your case is not a list but a QuerySet. So every time you index it, it will execute the query against your database to get the object.\nTry this before your code:\nprofile = list(profile)\n\nThat way the query executes and the results are now in a list.\n" ]
[ 1 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0004445888_django_django_models_python.txt
Q: Find deepest nested path? Is there a way to find the deepest nested path with python? Like say if you had a list of directories like /cats/xmas/1.jpg /cats/beach/2.jpg /dogs/xmas/2010/1.jpg it would print /dogs/xmas/2010/1.jpg as being the longest path A: Something like def longest_path( paths ): key = lamb...
Find deepest nested path?
Is there a way to find the deepest nested path with python? Like say if you had a list of directories like /cats/xmas/1.jpg /cats/beach/2.jpg /dogs/xmas/2010/1.jpg it would print /dogs/xmas/2010/1.jpg as being the longest path
[ "Something like\ndef longest_path( paths ):\n key = lambda path:path.count('/')\n return max(paths, key=key)\n\nYou should use os.path.normpath on the paths before counting.\nI guess on Windows this could get a bit tricky since the path separator can be either \\ or / ... the code below lets os.path.split fig...
[ 6, 1 ]
[]
[]
[ "directory", "python" ]
stackoverflow_0004445831_directory_python.txt
Q: Python: Unit testing for date changes I was doing the following for a Django form definition (embarrassing, yes): class DealAdvancedSearchForm(forms.Form): weekday_choices = [ ['monday', 'Monday'], ['tuesday', 'Tuesday'], ['wednesday', 'Wednesday'], ['thursday', 'Thursday'], ...
Python: Unit testing for date changes
I was doing the following for a Django form definition (embarrassing, yes): class DealAdvancedSearchForm(forms.Form): weekday_choices = [ ['monday', 'Monday'], ['tuesday', 'Tuesday'], ['wednesday', 'Wednesday'], ['thursday', 'Thursday'], ['friday', 'Friday'], ['saturd...
[ "Index out of bounds error:\nWatch out for [weekday_index+1] for 'sunday', \nuse [(weekday_index+1)%7] to wrap down to 0. \n\nExtract the choices into a method to make it easy to test. If the method only contains python and no django, it will be easier to test and thus easier to understand. I also agree that you ...
[ 1 ]
[]
[]
[ "django", "python", "testing", "unit_testing" ]
stackoverflow_0004445659_django_python_testing_unit_testing.txt
Q: How does argparse's add_argument take variable length arguments before keyword arguments? In python2.7, the argparse module has an add_argument method which can take a variable number of unnamed arguments before its keyword arguments as shown below: parser = argparse.ArgumentParser(description='D') parser.add_argu...
How does argparse's add_argument take variable length arguments before keyword arguments?
In python2.7, the argparse module has an add_argument method which can take a variable number of unnamed arguments before its keyword arguments as shown below: parser = argparse.ArgumentParser(description='D') parser.add_argument('-a', '-b', ... '-n', action='store', ... <other keyword args>) As far as I know, functio...
[ "Python's argument definition order is...\n\nRequired and/or default-value arguments (if any)\nvariable-length positional arguments placeholder (*<name> if desired)\nkeyword arguments placeholder (**<name> if desired)\n\nThe positional arguments placeholder gets a list, the keyword arguments placeholder gets a dict...
[ 3, 2 ]
[]
[]
[ "argparse", "python" ]
stackoverflow_0004446275_argparse_python.txt
Q: Programmatically connecting to Quickbooks Online on a Mac I'm looking to programmatically connect to QuickBooks Online using a Python script. I understand that the SDK is not available for the Mac platform. Is there a simple way for me to do http post of qbXML? Any Python libraries that make it easier? A: I alre...
Programmatically connecting to Quickbooks Online on a Mac
I'm looking to programmatically connect to QuickBooks Online using a Python script. I understand that the SDK is not available for the Mac platform. Is there a simple way for me to do http post of qbXML? Any Python libraries that make it easier?
[ "I already answered your question over here:\n\nhttps://idnforums.intuit.com/messageview.aspx?catid=7&threadid=15018&enterthread=y\n\nThere's a ton of documentation on my wiki on this:\n\nhttp://wiki.consolibyte.com/wiki/doku.php/quickbooks_online_edition\n\nFor QuickBooks Online, there's absolutely no reason you n...
[ 4 ]
[]
[]
[ "macos", "python", "quickbooks", "quickbooks_online" ]
stackoverflow_0004445039_macos_python_quickbooks_quickbooks_online.txt
Q: Following a relationship backwards, and annotating the results Say I've got a couple of models, one related to the other via foreign key like so: class Tourist(models.Model): age = models.IntegerField() class Country(models.Model): tourist = models.ForeignKey(Tourist) I know that I can work backwards fro...
Following a relationship backwards, and annotating the results
Say I've got a couple of models, one related to the other via foreign key like so: class Tourist(models.Model): age = models.IntegerField() class Country(models.Model): tourist = models.ForeignKey(Tourist) I know that I can work backwards from Tourist to find out how many countries he's been in using: t = Tou...
[ "You are pretty close already.\nfrom django.db.models import Count\n\nTourist.objects.annotate(countries_visited=Count('country'))\n\ndoes what you want, even though you are following the relationship backwards.\n" ]
[ 2 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0004446297_django_django_models_python.txt
Q: How do wave files store multiple channels? I've created two wave files using Audacity. Both have 44100hz sample rate, 32-bit float samples, were saved as WAV (Microsoft) 16-bit signed and contain 1s of silence (according to Audacity). The difference is that one file contains one channel, while the other have two (...
How do wave files store multiple channels?
I've created two wave files using Audacity. Both have 44100hz sample rate, 32-bit float samples, were saved as WAV (Microsoft) 16-bit signed and contain 1s of silence (according to Audacity). The difference is that one file contains one channel, while the other have two (stereo). When reading the one channel file I got...
[ "The data is not random\nLooking at it i seem to see 2 int values per line, each 2 bytes in little-endian:\n0x00 0x00 0x00 0x00 \n0x01 0x00 0xff 0xff \n0x00 0x00 0x00 0x00 \n0x00 0x00 0x01 0x00 \n0xff 0xff 0x01 0x00 \n0xfe 0xff 0x03 0x00 \n\nDecodes as:\n 0 0\n 1 -1\n 0 0\n 0 1\n-1 1\n-2 3\n\nSo you see ...
[ 3, 1, 1, 0, 0 ]
[]
[]
[ "audio", "python", "wave" ]
stackoverflow_0002977171_audio_python_wave.txt
Q: Any reasons to switch from SVN for a one-man linear Django project that's virtualenv isolated? I see this question but it's from 2008. Seems like many version control systems have become trendy lately. Also, the question was exactly my situation: Django based web application Using an isolated virtulaenv environme...
Any reasons to switch from SVN for a one-man linear Django project that's virtualenv isolated?
I see this question but it's from 2008. Seems like many version control systems have become trendy lately. Also, the question was exactly my situation: Django based web application Using an isolated virtulaenv environment One man developer Will not be open sourced Linear project (no branches) Perhaps will be using tag...
[ "For a one-person development effort, use whatever version control system lets you get your work down most effectively. For my own private projects, I do use Git these days, but that's only because I feel it gives me benefits vs. other choices. It is really up to personal preference.\nLately I've felt like I should...
[ 1 ]
[]
[]
[ "django", "python", "svn", "version_control", "virtualenv" ]
stackoverflow_0004446559_django_python_svn_version_control_virtualenv.txt
Q: how to prompt for user input without blocking in python3? I'm trying to type-check the commands I want to send to a server from a client. I want to use select so I don't block anything, but if I blatantly ask for input(), I block. So, it seems I should use sys.stdin.readline() instead. However, then there is a dis...
how to prompt for user input without blocking in python3?
I'm trying to type-check the commands I want to send to a server from a client. I want to use select so I don't block anything, but if I blatantly ask for input(), I block. So, it seems I should use sys.stdin.readline() instead. However, then there is a disconnect between the commands entered and the type checking I wa...
[ "I don't think it is possible to use input() in a non-blocking way without resorting to threads. \n" ]
[ 1 ]
[]
[]
[ "asynchronous", "python", "select" ]
stackoverflow_0004446544_asynchronous_python_select.txt
Q: How do you submit a form to an app engine python application without refreshing the sending page? As a newbie to app engine and python I can follow the examples given by Google and have created a python application with a template HTML page where I can enter data, submit it to the datastore and by reading back the...
How do you submit a form to an app engine python application without refreshing the sending page?
As a newbie to app engine and python I can follow the examples given by Google and have created a python application with a template HTML page where I can enter data, submit it to the datastore and by reading back the data, just sent, recreate the sending page so I can continue adding data and store again. However wha...
[ "Sounds like you want to look into AJAX. The simplest way to do this is probably to use the ajax functions in one of the popular Javascript libraries, like jQuery.\n", "AJAX. If you want a specific resource concerning AppEngine - \nhttp://code.google.com/appengine/articles/rpc.html (uses Python) is very good.\nHe...
[ 8, 1 ]
[ "Have a look at Pyjamas pyjs.org\nIt's a Python Compiler for web browsers. Write your client side in Python and Pyjamas will compile it into JavaScript.\n" ]
[ -1 ]
[ "datastore", "forms", "google_app_engine", "python", "submit" ]
stackoverflow_0004437307_datastore_forms_google_app_engine_python_submit.txt
Q: pyopengl: Could it replace c++? I'm starting a computer graphics course, and I have to choose a language. Choices are between C++ and Python. I have no problem with C++, python is a work in progress. So i was thinking to go down the python road, using pyopengl for graphics part. I have heard though, that performan...
pyopengl: Could it replace c++?
I'm starting a computer graphics course, and I have to choose a language. Choices are between C++ and Python. I have no problem with C++, python is a work in progress. So i was thinking to go down the python road, using pyopengl for graphics part. I have heard though, that performance is an issue. Is python / pyopengl ...
[ "It depends a LOT on the contents of your computer graphics course. If you are doing anything like the introductory course I've taught in the past, it's basically spinning cubes and spheres, some texture mapping and some vertex animation, and that's about it. In this case, Python would be perfectly adequate, assumi...
[ 30, 7, 7, 2, 0 ]
[]
[]
[ "3d", "c++", "opengl", "pyopengl", "python" ]
stackoverflow_0002488730_3d_c++_opengl_pyopengl_python.txt
Q: Python integrals I'm trying to solve the integral of (2**(1/2)*y**(1/2)/2)**2 from 0 to 5 (also shown here). I've been using func = lambda y: ( 2**(1/2) * y**(1/2)/2 )**2 and a == 0 and b == 5 from scipy import integrate integrate.quad(func, a b) For some reason, I keep getting the value 1.25, while wolfram sa...
Python integrals
I'm trying to solve the integral of (2**(1/2)*y**(1/2)/2)**2 from 0 to 5 (also shown here). I've been using func = lambda y: ( 2**(1/2) * y**(1/2)/2 )**2 and a == 0 and b == 5 from scipy import integrate integrate.quad(func, a b) For some reason, I keep getting the value 1.25, while wolfram says it should be 6.25? ...
[ "Well, let me write your function in normal mathematical notation (I can't think in Python). I don't like **, as it gets confusing:\n(2**(1/2)*y**(1/2)/2)**2 =>\n(2^(1/2) * (1/2) * y^(1/2))^2 =>\n2 * (1/4) * y =>\ny / 2\n\nSo to integrate, antidifferentiate (I'm just thinking aloud):\nantidiffe...
[ 3, 2, 0 ]
[]
[]
[ "integrate", "integration", "lambda", "python", "scipy" ]
stackoverflow_0004446611_integrate_integration_lambda_python_scipy.txt
Q: Twitter Python-OAuth API with Proxy Support Does anyone know of any other Python twitter module's that have OAuth and Proxy support besides Python-OAuth2? Because it's broken for me and has started giving me "incorrect signature" errors. Thanks, A: I know Twython has OAuth support, along with a lot of other feat...
Twitter Python-OAuth API with Proxy Support
Does anyone know of any other Python twitter module's that have OAuth and Proxy support besides Python-OAuth2? Because it's broken for me and has started giving me "incorrect signature" errors. Thanks,
[ "I know Twython has OAuth support, along with a lot of other features.\nI use it in one of my projects and have been very impressed with its API.\n" ]
[ 2 ]
[]
[]
[ "oauth", "proxy", "python", "signature", "twitter" ]
stackoverflow_0004442665_oauth_proxy_python_signature_twitter.txt
Q: __package__ is None when importing a Python module I want to import the modules dynamically, by the following way: I create a folder named pkg with this structure: pkg |__init__.py |foo.py In the head of __init__.py, add this code fragement: pkgpath = os.path.dirname(pkg.__file__); for module in pkgutil.ite...
__package__ is None when importing a Python module
I want to import the modules dynamically, by the following way: I create a folder named pkg with this structure: pkg |__init__.py |foo.py In the head of __init__.py, add this code fragement: pkgpath = os.path.dirname(pkg.__file__); for module in pkgutil.iter_modules([pkgpath]): __import__(module[1], locals(...
[ "The __package__ attribute, as you've noticed, isn't set consistently. (More information at the bottom.) However, you should always be able to get the package name by taking everything before the last period in a module's __name__ attribute. Eg. mymod.__name__.rpartition('.')[0]. For your purpose though, it's pr...
[ 10 ]
[]
[]
[ "dynamic", "load", "module", "python" ]
stackoverflow_0004437394_dynamic_load_module_python.txt
Q: how to send a non-english word (chinese) email using django if i use a chinese word subject : subject = u'邮件标题' it will be show error : UnicodeDecodeError at /account/login_view/ 'utf8' codec can't decode bytes in position 0-1: invalid data what can i do about it , thanks updated def register_view(request): ...
how to send a non-english word (chinese) email using django
if i use a chinese word subject : subject = u'邮件标题' it will be show error : UnicodeDecodeError at /account/login_view/ 'utf8' codec can't decode bytes in position 0-1: invalid data what can i do about it , thanks updated def register_view(request): if request.method == 'POST': form = SignupForm(reques...
[ "How are you sending the subject. You should encode it to utf-8 before sending.\nsubject.encode('utf-8')\n\nor\nimport codecs\nsubject = codecs.utf_8_encode(subject)\n\nAnd then send it to your view.\n", "it is ok now :\ni use Programmer’s Notepad 2 to Encoding the py and html file which has chinese word .\n\n" ...
[ 2, 0 ]
[]
[]
[ "django", "email", "non_english", "python" ]
stackoverflow_0004447195_django_email_non_english_python.txt
Q: Which scripting language performs better in vs perl vs python vs ruby? Until now, I've been writing programs in Perl. I decided to give python a try and noticed a few differences. While perl has ARGV, regex, etc. built in, these must be imported in python. I thought this gives python a performance advantage since...
Which scripting language performs better in vs perl vs python vs ruby?
Until now, I've been writing programs in Perl. I decided to give python a try and noticed a few differences. While perl has ARGV, regex, etc. built in, these must be imported in python. I thought this gives python a performance advantage since you're only loading what you really need. So, I wrote a demo program in eac...
[ "There are a few issues...\n\nYour test doesn't accumulate enough runtime, you are probably testing mostly the startup overhead of the interpreter, and not even measuring that very accurately.\nI don't care if Perl or Python are 10x faster than Ruby, I want to use what I consider the best language ... the one that ...
[ 6, 3, 0, 0 ]
[]
[]
[ "c", "perl", "python", "ruby" ]
stackoverflow_0004447248_c_perl_python_ruby.txt
Q: Python cookie is either not saved or somehow not accessible to CGI script I think this is going to have an obvious answer... I've been looking at a bunch of examples of cookies in Python and have gathered that the proper order to present things is: get the cookie if it exists, set cookie data, print the content ty...
Python cookie is either not saved or somehow not accessible to CGI script
I think this is going to have an obvious answer... I've been looking at a bunch of examples of cookies in Python and have gathered that the proper order to present things is: get the cookie if it exists, set cookie data, print the content type header, output the cookie, and then print everything else. I've built this u...
[ "I think you just had tired eyes. You're creating the cookie object and then you're running the \"redirect\" codepath, which doesn't set the cookie.\n" ]
[ 0 ]
[]
[]
[ "cgi", "cookies", "python" ]
stackoverflow_0004446313_cgi_cookies_python.txt
Q: How would I scale a 2-dimensional array in python? I'm not sure how to go about scaling a 2-dimensional array. Given the array below, whose dimensions are 8x10, say I needed to scale it to 5x6 -- I've looked for concrete examples on wikipedia, but without much grounding in matrix math I'm a bit lost. If someone ...
How would I scale a 2-dimensional array in python?
I'm not sure how to go about scaling a 2-dimensional array. Given the array below, whose dimensions are 8x10, say I needed to scale it to 5x6 -- I've looked for concrete examples on wikipedia, but without much grounding in matrix math I'm a bit lost. If someone could point me in the right direction I'd really appreci...
[ "Since your array looks like it is a binary image of a lower case 'a' letter, I'm guessing that you mean scaling in the image sense.\nTo do that, I would recommend using the imresize function in scipy.misc (which is taken from PIL, I believe). Here's an example:\nimport numpy as np\nfrom scipy.misc import imresize\...
[ 10, 2 ]
[]
[]
[ "matrix", "python" ]
stackoverflow_0004447352_matrix_python.txt
Q: Python (sympy) TypeError: cannot concatenate 'str' and 'Add' objects I'm trying to use an equation that I've generated using sympy.Eq(func, var) in a lambda. It seems to be returning a list of 'Add' objects, which I'm not sure how to use. I tried typecasting to astr before using eval, and i tried from sympy import...
Python (sympy) TypeError: cannot concatenate 'str' and 'Add' objects
I'm trying to use an equation that I've generated using sympy.Eq(func, var) in a lambda. It seems to be returning a list of 'Add' objects, which I'm not sure how to use. I tried typecasting to astr before using eval, and i tried from sympy import I, which i think has something to do with the problem. Here's the code, a...
[ "\"I tried typecasting to astr before using eval, and i tried from sympy import I, which i think has something to do with the problem\"\nYes, without a doubt that's exactly the problem. I'm sure Numpy has docuemntation on how to use the Add objects. Converting them to strings and then evaluating them definitely is ...
[ 1 ]
[]
[]
[ "integral", "python", "sympy" ]
stackoverflow_0004447426_integral_python_sympy.txt
Q: Django + Adsense on Google App Engine I have a problem with Django on Google App Engine. I finished to design html templet for my web application and I imported them on django using django template system. The problem is google ad-sense. I can say ad-sense banner on the html version of my pages if i try to open t...
Django + Adsense on Google App Engine
I have a problem with Django on Google App Engine. I finished to design html templet for my web application and I imported them on django using django template system. The problem is google ad-sense. I can say ad-sense banner on the html version of my pages if i try to open them in my browser. But nothing appear if I ...
[ "adsense is javascript, if your django is returning nothing check your HttpResponse and how you are generating the template. it looks like you need to specify in settings.py the location of the template file.\n\nyou may want add the following (in settings.py):\n\nimport os\nROOT_PATH = os.path.dirname(__file__)\nTE...
[ 1, 0 ]
[]
[]
[ "adsense", "django", "google_app_engine", "python", "templates" ]
stackoverflow_0004422754_adsense_django_google_app_engine_python_templates.txt
Q: Constructing micro blogging site in python? Any suggestions I want to write a micro blogging site with html frontend but xmpp backend (Instant messenger type). By this, I mean server should push all the updates to client browser and hence constant http polling is not required. I need your view and help in that. I ...
Constructing micro blogging site in python? Any suggestions
I want to write a micro blogging site with html frontend but xmpp backend (Instant messenger type). By this, I mean server should push all the updates to client browser and hence constant http polling is not required. I need your view and help in that. I found 3 xmpp libraries 1. xmppy 2. sleekxmpp 3. pyxmpp Should i ...
[ "This slideshow may help. The author uses django and some xmpp items that can tag along with django's authentication. This sounds pretty perfect for you.\nThe link is to google's cache because the original link wouldn't work for me anymore. Let me know if this is a problem.\n", "try this - https://github.com/hj91...
[ 1, 0 ]
[]
[]
[ "blogs", "python", "xmpp" ]
stackoverflow_0004380167_blogs_python_xmpp.txt
Q: How to bypass the 0-255 range limit for sys.exit() in python? In python (on a Linux system), I'm launching a command using os.system() and retrieving the return code. If that return code is different from 0, I would like to make the program exit with that same return code. So I wrote: ret = os.system(cmd) if ret !...
How to bypass the 0-255 range limit for sys.exit() in python?
In python (on a Linux system), I'm launching a command using os.system() and retrieving the return code. If that return code is different from 0, I would like to make the program exit with that same return code. So I wrote: ret = os.system(cmd) if ret != 0: print "exit with status %s" % ret sys.exit(ret) When th...
[ "Actually, the documentation indicates that \n\nexit status indication: a 16-bit number, whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the signal number is zero); the high bit of the low byte is set if a core file was produced.\n\nSo I need to process the nu...
[ 6, 3, -3 ]
[]
[]
[ "exit_code", "linux", "python" ]
stackoverflow_0004448339_exit_code_linux_python.txt
Q: Multiple conditions inside iteration, Python I am writing an add-on for some softwate, using its API. What i need to do is to extract necessary data. I use 'FOR' to go thought API classes. Each object has properties: index (from 0), type (Lin, Ptp, and some others), and value. Going through list of objects, I am i...
Multiple conditions inside iteration, Python
I am writing an add-on for some softwate, using its API. What i need to do is to extract necessary data. I use 'FOR' to go thought API classes. Each object has properties: index (from 0), type (Lin, Ptp, and some others), and value. Going through list of objects, I am interested in two types of objects - those that hav...
[ "\nAs i am a beginner in Python, my thoughs are mixed now and i cannot come up with appropriate algorithm.\n\nIf you are trying to come up with an appropriate algorithm, take a step back. Forget Python (C++, Fortran, Logo, Awk, etc...) and think about the problem you are trying to solve. Try writing some pseudocode...
[ 2, 1, 0 ]
[]
[]
[ "conditional_statements", "iteration", "python" ]
stackoverflow_0004448101_conditional_statements_iteration_python.txt
Q: Calculating the area underneath a mathematical function I have a range of data that I have approximated using a polynomial of degree 2 in Python. I want to calculate the area underneath this polynomial between 0 and 1. Is there a calculus, or similar package from numpy that I can use, or should I just make a simpl...
Calculating the area underneath a mathematical function
I have a range of data that I have approximated using a polynomial of degree 2 in Python. I want to calculate the area underneath this polynomial between 0 and 1. Is there a calculus, or similar package from numpy that I can use, or should I just make a simple function to integrate these functions? I'm a little unclear...
[ "If you're integrating only polynomials, you don't need to represent a general mathematical function, use numpy.poly1d, which has an integ method for integration.\n>>> import numpy\n>>> p = numpy.poly1d([2, 4, 6])\n>>> print p\n 2\n2 x + 4 x + 6\n>>> i = p.integ()\n>>> i\npoly1d([ 0.66666667, 2. , 6. ...
[ 9, 5, 3, 1, 1 ]
[]
[]
[ "numerical_integration", "polynomial_math", "python" ]
stackoverflow_0002352499_numerical_integration_polynomial_math_python.txt
Q: AttributeError: 'str' object has no attribute 'attack' "'Help!" I have q quick question regarding an Attribute Error regarding a basic Arena battler I am writing for my Intro to Programming Class. Here is the chunk of code that I am having trouble with upon running the program, class Enemy: def __init__(self,p...
AttributeError: 'str' object has no attribute 'attack' "'Help!"
I have q quick question regarding an Attribute Error regarding a basic Arena battler I am writing for my Intro to Programming Class. Here is the chunk of code that I am having trouble with upon running the program, class Enemy: def __init__(self,player,weapons,armor): self.name = "Bad Guy" self.he...
[ "Obviously, you are calling the constructor of this class (where you instantiate it) with player name (string) instead of a player object (with parameters 'attack','defence', etc.).\n", "How to read and understand error messages, so that you can help yourself:\nFirst, we read it:\nFile \"C:\\Users\\Caleb Walter\\...
[ 4, 2 ]
[]
[]
[ "attributeerror", "attributes", "python", "string", "typeerror" ]
stackoverflow_0004447932_attributeerror_attributes_python_string_typeerror.txt
Q: write matrix to image by PIL I have a 2D matrix that I want to write as a PBM file (it's only -1,1 values, black&white). I just discovered about PIL, but the following approach does not work: im = Image.new('L', (self.nx,self.ny)) data=[[255*(self.spins[i][j][0].m+1)/2 for j in range(0,self.ny)]for i in range(...
write matrix to image by PIL
I have a 2D matrix that I want to write as a PBM file (it's only -1,1 values, black&white). I just discovered about PIL, but the following approach does not work: im = Image.new('L', (self.nx,self.ny)) data=[[255*(self.spins[i][j][0].m+1)/2 for j in range(0,self.ny)]for i in range(0,self.nx)] im.putdata(data) ...
[ "Image.putdata takes a one-dimensional sequence, not a multi-dimensional sequence like what you've got in your code. \nI.e. instead of using something like\n[[v1, v2, v3],\n [v4, v5, v6],\n [v7, v8, v9]] \n\nto hold your pixel data that is being passed to putdata, it should be\n[v1, v2, v3, v4, v5, v6, v7, v8, v9]\...
[ 3 ]
[]
[]
[ "graphics", "python", "python_imaging_library" ]
stackoverflow_0004449016_graphics_python_python_imaging_library.txt