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: Two Python instances, same libraries I currently have both Python 2.6 and 2.7 running on my Linux machine. Now, from Python 2.7, I can't access the libraries that I installed through package manager for Python 2.6. I tried uninstalling the library and installing it back with Python 2.7 installed as my default runt...
Two Python instances, same libraries
I currently have both Python 2.6 and 2.7 running on my Linux machine. Now, from Python 2.7, I can't access the libraries that I installed through package manager for Python 2.6. I tried uninstalling the library and installing it back with Python 2.7 installed as my default runtime. No luck. How can I share libraries be...
[ "You should be able to install the files to an external location and define the environment variable PYTHONPATH to point to the directory that contains the modules.\n", "You should have now both a /usr/lib/python2.6 folder and a /usr/lib/python2.7. Try creating links inside the 2.7 folders to the required files o...
[ 4, 0 ]
[]
[]
[ "libraries", "linux", "python" ]
stackoverflow_0005981933_libraries_linux_python.txt
Q: ADF Scan Application: Which Library? I need to develop a custom scan application. Up to now I used old code: tcl/tk and a lot of subprocesses using the command line interface of the sane project. The app only runs on linux with an attached Fujitsu ADF scanner. The code needs to be replaced with a modern solution. ...
ADF Scan Application: Which Library?
I need to develop a custom scan application. Up to now I used old code: tcl/tk and a lot of subprocesses using the command line interface of the sane project. The app only runs on linux with an attached Fujitsu ADF scanner. The code needs to be replaced with a modern solution. We prefer Java or Python as language. It w...
[ "Try EZTwain Pro, http://www.eztwain.com/eztwain4.htm \nHas python support, or java, and is actively supported. I should add I do work for the company that sells it. \n" ]
[ 0 ]
[]
[]
[ "java", "python", "twain" ]
stackoverflow_0005969066_java_python_twain.txt
Q: Variables not working... or i'm missing something? I am trying to make some edits to a docx file... making a number into letter (i.e. if the variable is equal to 01 = 'one', equal to 02 = 'two', and so on, but in Spanish). The problem is that the variable f_dia_nom doesn't work ... it doesn't even print anything....
Variables not working... or i'm missing something?
I am trying to make some edits to a docx file... making a number into letter (i.e. if the variable is equal to 01 = 'one', equal to 02 = 'two', and so on, but in Spanish). The problem is that the variable f_dia_nom doesn't work ... it doesn't even print anything... am I doing something wrong?? or am I missing somethin...
[ "Look up 'global scoping' rules for python. In general, try to avoid global variables as much as possible(if only to avoid errors like these)\nin nombre_dia():\nf_dia_nom = \"Un\" \n\nor any other assignment for that matter has the python compiler create that number LOCAL to the nombre_dia function.\nmodify your f...
[ 5, 2, 0, 0 ]
[]
[]
[ "docx", "numbers", "python", "variables" ]
stackoverflow_0005982194_docx_numbers_python_variables.txt
Q: Boolean function optimizer package for Python I'd like to define a boolean function (with n inputs and m outputs) in a tabular form. I'd like to find an optimal boolean expression which implements the function. Optimal here means that, implementing it in hardware would require as few possible gates (with maybe eac...
Boolean function optimizer package for Python
I'd like to define a boolean function (with n inputs and m outputs) in a tabular form. I'd like to find an optimal boolean expression which implements the function. Optimal here means that, implementing it in hardware would require as few possible gates (with maybe each gate having different costs) I'm sure VHDL/Verilo...
[ "The algorithms to find the optimal solution have exponential complexity, so generally the available tools look for a good implementation rather than the optimal implementation. I'm not sure how stringent your requirements are, or how big your functions are.\nOne algorithm for logic optimization is Quine-McCluskey....
[ 5 ]
[]
[]
[ "boolean_logic", "hardware", "optimization", "python" ]
stackoverflow_0005922315_boolean_logic_hardware_optimization_python.txt
Q: Open Source Image Gallery app Can anyone recommend an open source Image Gallery for our website. No doubt going to be PHP/Python/Ruby based with a MySQL backend if necessary. It is for a Sailing Club so I am looking for something where certain members can create a new Folder for each day out and all other member...
Open Source Image Gallery app
Can anyone recommend an open source Image Gallery for our website. No doubt going to be PHP/Python/Ruby based with a MySQL backend if necessary. It is for a Sailing Club so I am looking for something where certain members can create a new Folder for each day out and all other members can then upload their pictures fr...
[ "I haven't used this in a long long time, but it used to be somewhat decent* back in the days:\nhttp://gallery.menalto.com/\n* That is as decent as PHP apps get. IIRC it had required some unsafe PHP settings on the webserver, but they fixed that in later versions. $SearchEngine is your friend for that.\n" ]
[ 0 ]
[]
[]
[ "html", "mysql", "php", "python", "ruby" ]
stackoverflow_0005982173_html_mysql_php_python_ruby.txt
Q: Could not find the GEOS library i am working on a simple employee listing Django application. i wanted to include filtering in my app, so tried installing django-filter module. i think django-filter is not installed properly ( i am not going to use it anyway). But after doing this, when i try to run my application...
Could not find the GEOS library
i am working on a simple employee listing Django application. i wanted to include filtering in my app, so tried installing django-filter module. i think django-filter is not installed properly ( i am not going to use it anyway). But after doing this, when i try to run my application, it gives this , "`ViewDoesNotExist ...
[ "Things to check:\n\nAre you using the GeoDjango database classes? If your database engine is set to something like django.contrib.gis.db.backends.postgis or django.contrib.gis.db.backends.mysql, those are the geo backends. What you want is something like django.db.backends.postgresql_psycopg2 or django.db.backends...
[ 2 ]
[]
[]
[ "django", "django_forms", "django_templates", "python" ]
stackoverflow_0005139845_django_django_forms_django_templates_python.txt
Q: fb ios sdk session for use with existing fb connect website How does my fb connect webserver authenticate a user that logged in via fb ios sdk? I have a website which uses facebook connect. In it, i do use the app secret to authenticate the user via a cookie created by the facebook javascript sdk via the facebook ...
fb ios sdk session for use with existing fb connect website
How does my fb connect webserver authenticate a user that logged in via fb ios sdk? I have a website which uses facebook connect. In it, i do use the app secret to authenticate the user via a cookie created by the facebook javascript sdk via the facebook python library: def get_user_from_cookie(cookies, app_id, app_sec...
[ "If you want use Facebook iOS API you need:\nAlloc and Init a Facebook object\nFacebook *facebookObject = [[Facebook alloc] init];\n\nCheck permissions\nNSArray *permissions = [NSArray arrayWithObjects:@\"publish_stream\", @\"offline_access\",nil];\n\nAuthorize facebook\n[facebookObject authorize:APP_ID permissions...
[ 0, 0 ]
[]
[]
[ "facebook", "iphone", "objective_c", "python" ]
stackoverflow_0005917087_facebook_iphone_objective_c_python.txt
Q: Parse Method Variable Names In Python? Given the python function: def MyPythonMethod(value1, value2): # defining some variables a = 4 myValue = 15.65 listValues = [4, 67, 83, -23] # doing some operation on the list listValues[0] = listValues[1] # looping through the values ...
Parse Method Variable Names In Python?
Given the python function: def MyPythonMethod(value1, value2): # defining some variables a = 4 myValue = 15.65 listValues = [4, 67, 83, -23] # doing some operation on the list listValues[0] = listValues[1] # looping through the values for i in listValues: print i How ...
[ "1 Variables don't have a type in python. Objects have a type, and variables point to objects. \n[2] you can use the inspect module to get info about the internals of your function. \n Read the docs -- they will tell you what is available for inspection. \n MyPythonMethod.func_code.co_varnames will give you the ...
[ 7, 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005982454_python.txt
Q: matplotlib basic question Please forgive my simple question. I have just started to use Matplotlib and I am having some difficulty. I can run the following with the interpretor without problems: >>> from pylab import * >>> plot([1,2,3]) >>> show() The above code generates a beautiful graph. However, if I pl...
matplotlib basic question
Please forgive my simple question. I have just started to use Matplotlib and I am having some difficulty. I can run the following with the interpretor without problems: >>> from pylab import * >>> plot([1,2,3]) >>> show() The above code generates a beautiful graph. However, if I place the following code inside a...
[ "Looks like you have a file on your Desktop that is shadowing the standard Python new module:\n>>> import new\n>>> new\n<module 'new' from '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/new.pyc'>\n\nRename or remove $HOME/Desktop/new.py and try again.\n" ]
[ 9 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0005982774_matplotlib_python.txt
Q: Match string segments in regular expressions In python, I'm trying to get a string like this: abcd[_FILE:foo.txt_]efghi[_FILE:bar.txt_]jklm[_FILE:foo2.txt_] to match: ['foo.txt', 'bar.txt', 'foo2.txt'] But I don't know how to match full string segments instead of single individual characters. Does anyone know h...
Match string segments in regular expressions
In python, I'm trying to get a string like this: abcd[_FILE:foo.txt_]efghi[_FILE:bar.txt_]jklm[_FILE:foo2.txt_] to match: ['foo.txt', 'bar.txt', 'foo2.txt'] But I don't know how to match full string segments instead of single individual characters. Does anyone know how I can write an regular expression to match '[FI...
[ "Try this pattern:\nimport re\ntext = 'abcd[_FILE:foo.txt_]efghi[_FILE:bar.txt_]jklm[_FILE:foo2.txt_]'\npattern = re.compile('FILE:([\\w\\.]+)_\\]')\npattern.findall(text)\n\nOutput:\n['foo.txt', 'bar.txt', 'foo2.txt']\n\n", "import re\nprint re.findall('FILE:(\\w+\\.txt)', mystring)\n\n", "import re\n\nregx = ...
[ 4, 2, 2, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0005983049_python_regex.txt
Q: How to send an email in GAE on behalf of a yahoo, hotmail, or .edu user? On GAE, a non-gmail user can create a Google Account using their non-gmail email and log into a google app engine application. However, sending from that email does not appear to work all the time. For example, suppose foobar@yahoo.com creat...
How to send an email in GAE on behalf of a yahoo, hotmail, or .edu user?
On GAE, a non-gmail user can create a Google Account using their non-gmail email and log into a google app engine application. However, sending from that email does not appear to work all the time. For example, suppose foobar@yahoo.com creates a google account and they log in. Then, GAE should be able to send email fr...
[ "Your application has no right to originate email from addresses you don't own.\nDoing so is called spoofing and there has been a lot of work done in the last 8 years to prevent spoofing: DKIM, SPF...\nIf you need to send email you need to have your own email address(es)/domain to send the email from for this appli...
[ 2, 2, 1 ]
[]
[]
[ "email", "gmail", "google_app_engine", "python" ]
stackoverflow_0005917547_email_gmail_google_app_engine_python.txt
Q: python multiprocessing arguments: deep copy? from multiprocessing import Process # c is a container p = Process(target = f, args = (c,)) p.start() I assume a deep copy of c is passed to function f because shallow copy would make no sense in the case of a new process (the new process doesn't have access to the dat...
python multiprocessing arguments: deep copy?
from multiprocessing import Process # c is a container p = Process(target = f, args = (c,)) p.start() I assume a deep copy of c is passed to function f because shallow copy would make no sense in the case of a new process (the new process doesn't have access to the data from the calling process). But how is this deep ...
[ "When you create a Process instance, under the hood Python issues a fork(). This creates a child process whose memory space is an exact copy of its parent -- so everything existing at the time of the fork is copied. \nOn Linux this is made efficient through \"copy-on-write\". From the fork man page:\n\nfork() creat...
[ 19 ]
[]
[]
[ "deep_copy", "multiprocessing", "python" ]
stackoverflow_0005983159_deep_copy_multiprocessing_python.txt
Q: xul menulist bug with pydom i know pydom is deprecated .but my application already used this,this is so easy my xul is like this. <menulist name="mailencode" id="mailencode"> <menupopup id="mailencodepop"> <menuitem label="UTF-8" value="UTF-8" selected="true"/> <menuitem label="ISO-8859-1" value="...
xul menulist bug with pydom
i know pydom is deprecated .but my application already used this,this is so easy my xul is like this. <menulist name="mailencode" id="mailencode"> <menupopup id="mailencodepop"> <menuitem label="UTF-8" value="UTF-8" selected="true"/> <menuitem label="ISO-8859-1" value="ISO-8859-1" /> </menupopup> ...
[ "Your first problem is that the tag name you're after is \"menulist\". I used xml.dom.minidom to parse this just as a basic example to illustrate because I have never used PyDOM:\n>>> ecd = document.getElementsByTagName('menulist')\n[<DOM Element: menulist at 0x1006e2710>]\n>>> ecd[0].tagName\nu'menulist'\n>>> ecd...
[ 0, 0 ]
[]
[]
[ "python", "xul" ]
stackoverflow_0005850598_python_xul.txt
Q: Moving files and dir, even if they already exist in dest So I want to copy some files and directories from one location to another. Easy enough with shutil.move, but I run into problems when the files or directories are already in the destination. The error I get is Destination path '...' already exists. I tried ...
Moving files and dir, even if they already exist in dest
So I want to copy some files and directories from one location to another. Easy enough with shutil.move, but I run into problems when the files or directories are already in the destination. The error I get is Destination path '...' already exists. I tried os.rename and it didn't produce the desired results either. I...
[ "How about:\ndef move_over(src_dir, dest_dir):\n fileList = os.listdir(src_dir)\n for i in fileList:\n src = os.path.join(src_dir, i)\n dest = os.path.join(dest_dir, i)\n if os.path.exists(dest):\n if os.path.isdir(dest):\n move_over(src, dest)\n c...
[ 7 ]
[]
[]
[ "move", "python", "shutil" ]
stackoverflow_0005983320_move_python_shutil.txt
Q: method __getattr__ is not inherited from parent class Trying to subclass mechanize.Browser class: from mechanize import Browser class LLManager(Browser, object): IS_AUTHORIZED = False def __init__(self, login = "", passw = "", *args, **kwargs): super(LLManager, self).__init__(*args, **kwargs) ...
method __getattr__ is not inherited from parent class
Trying to subclass mechanize.Browser class: from mechanize import Browser class LLManager(Browser, object): IS_AUTHORIZED = False def __init__(self, login = "", passw = "", *args, **kwargs): super(LLManager, self).__init__(*args, **kwargs) self.set_handle_robots(False) But when I make somethin...
[ "You need to override __setattr__ to support assignment in this fashion. __getattr__ is only for retrieval\n", "There's difference between items and attributes. Items are accessed using ob[item], while attributes are accessed using ob.item. The methods that define item assignment are __getitem__ and __setitem__,...
[ 1, 1, 1 ]
[]
[]
[ "class", "getattr", "inheritance", "methods", "python" ]
stackoverflow_0004887952_class_getattr_inheritance_methods_python.txt
Q: why am I getting a 'closed file' message when I run my python script? simple bit of code, just prints out a list of urls I put into a text file (it was printing them with the \n char at the end of each one though - how do I get rid of the \n?): import mechanize, fileinput with open('F:\Python\url_list2.txt') as u...
why am I getting a 'closed file' message when I run my python script?
simple bit of code, just prints out a list of urls I put into a text file (it was printing them with the \n char at the end of each one though - how do I get rid of the \n?): import mechanize, fileinput with open('F:\Python\url_list2.txt') as urls: content = urls.readlines() print content anyway, it worked printe...
[ "with only keeps the file open within the indentation block. Try:\nimport mechanize, fileinput\n\nwith open('F:\\Python\\url_list2.txt') as urls:\n content = urls.readlines()\n print urls # file still open.\nprint content\n\nBasically with is syntactic sugar for a common try except finally pattern:\ntry:\n ...
[ 3, 2, 2, 1, 0, 0 ]
[]
[]
[ "file", "python" ]
stackoverflow_0005983339_file_python.txt
Q: Set assignee field when creating an issue in JIRA via Python suds Using JIRA version 4.2. With Python 2.7 and suds 0.4, how can I create an issue with assignee field set? The assignee field gets ignored in the code below. new_issue = client.service.createIssue(auth, { 'project': 'NAHLP', ...
Set assignee field when creating an issue in JIRA via Python suds
Using JIRA version 4.2. With Python 2.7 and suds 0.4, how can I create an issue with assignee field set? The assignee field gets ignored in the code below. new_issue = client.service.createIssue(auth, { 'project': 'NAHLP', # issue_type = Incident Report. 'type': '11', '...
[ "Thanks to Dave for this alternative of updating the issue with an assignee. Note, this does not answer the question of how to assign a ticket when creating an issue.\nI need to be passing an array as the value of the assignee field even though it only allows one value. (The same applies to any field you want to ...
[ 4, 1, 1 ]
[]
[]
[ "jira", "python", "soap", "suds" ]
stackoverflow_0005944627_jira_python_soap_suds.txt
Q: python working with files as they are written So I'm trying to create a little script to deal with some logs. I'm just learning python, but know about loops and such in other languages. It seems that I don't understand quite how the loops work in python. I have a raw log from which I'm trying to isolate just the...
python working with files as they are written
So I'm trying to create a little script to deal with some logs. I'm just learning python, but know about loops and such in other languages. It seems that I don't understand quite how the loops work in python. I have a raw log from which I'm trying to isolate just the external IP addresses. An example line: 05/09/201...
[ "DISCLAIMER: Since you are new to python, I am going to try to show off a little, so you can lookup some interesting \"python things\".\nI'm going to print all the IPs to console:\ndef parseips():\n with open(\"126logs.txt\",'r') as f:\n for line in f:\n ip = line.split()[3]\n if ip....
[ 4, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005983496_python.txt
Q: dynamic forms in django with ajax/dajax I have this simple form with a queryset to display job objects and allow the user to select one. Now, i would like to have a group of two radio buttons that would allow the user to select a 'filtering option'. If the user selects a group filter with the radio buttons, i wo...
dynamic forms in django with ajax/dajax
I have this simple form with a queryset to display job objects and allow the user to select one. Now, i would like to have a group of two radio buttons that would allow the user to select a 'filtering option'. If the user selects a group filter with the radio buttons, i would a drop down to appear that allows them to...
[ "You need to add your dajaxice function to the select onchange to reference your function in the template.\nSomething like:\n<select name=\"combo2\" id=\"combo2\" onchange=\"Dajaxice.your_project.your_appname.updatefilter(Dajax.process,{'option':this.value}\" size=\"1\"></select>\n\n(Replace your_project with your ...
[ 1, 1 ]
[]
[]
[ "ajax", "django", "python" ]
stackoverflow_0005983603_ajax_django_python.txt
Q: Parse several XML declarations in a single file by means of lxml.etree.iterparse I need to parse a file that contains various XML files, i.e., <xml></xml> <xml></xml> .. and so forth. While using etree.iterparse, I get the following (correct) error: lxml.etree.XMLSyntaxError: XML declaration allowed only at the st...
Parse several XML declarations in a single file by means of lxml.etree.iterparse
I need to parse a file that contains various XML files, i.e., <xml></xml> <xml></xml> .. and so forth. While using etree.iterparse, I get the following (correct) error: lxml.etree.XMLSyntaxError: XML declaration allowed only at the start of the document Now, I can preprocess the input file and produce for each contain...
[ "The sample data you've provided suggests one problem, while the question and the exception you've provided suggests another. Do you have multiple XML documents concatenated together, each with its own XML declaration, or do you have an XML fragment with multiple top-level elements?\nIf it's the former, then the s...
[ 3, 0 ]
[]
[]
[ "elementtree", "lxml", "python", "xml" ]
stackoverflow_0005651219_elementtree_lxml_python_xml.txt
Q: How to get a set of unique random entries from the Datastore I used a slightly modified solution from this thread to get a set of randomly chosen items from Datastore. I use ProtoRPC, though it doesn't make much difference, just for your information. My code looks like this: @remote.method(RandomImagesRequest, Ran...
How to get a set of unique random entries from the Datastore
I used a slightly modified solution from this thread to get a set of randomly chosen items from Datastore. I use ProtoRPC, though it doesn't make much difference, just for your information. My code looks like this: @remote.method(RandomImagesRequest, RandomImagesResponse) def get_random_images(self, request): image...
[ "Instead of fetching N items separately, just do a fetch for three items where random_number >= the new random_number.\nThe downside is that you will occasionally get 0-2 items, in which case if you absolutely need 3 items you can re-fetch the rest with another random number (or switch the >= to a <)\n", "You cou...
[ 0, 0 ]
[]
[]
[ "datastore", "google_app_engine", "python" ]
stackoverflow_0005980706_datastore_google_app_engine_python.txt
Q: How can I close pygames without closing tkinter? So I am trying to use Tkinter to receive a text input, and then run pygames from that to do an animation. I get an error though when I close Pygames. A simplified version of how I plan to use Pygames: def the_program(): if spot.get().strip() == "": tkMes...
How can I close pygames without closing tkinter?
So I am trying to use Tkinter to receive a text input, and then run pygames from that to do an animation. I get an error though when I close Pygames. A simplified version of how I plan to use Pygames: def the_program(): if spot.get().strip() == "": tkMessageBox.showerror("X", "Y") else: code = s...
[ "You are trying to exit from the pygame mainloop with sys.exit(), which exits the whole running application, including the tkinter GUI you started before pygame. You should exit the pygame mainloop (the only while clause) with a conditional. e.g:\nrunning = True\nwhile running:\n for event in pygame.event.get():...
[ 0 ]
[]
[]
[ "pygame", "python", "sys", "tkinter" ]
stackoverflow_0005983869_pygame_python_sys_tkinter.txt
Q: python mechanize - can login to site but can't grab html for a list of URLs? I've written the following in python using the mechanize module in order to print out the HTML from a list URLs: import mechanize, fileinput urls = open('F:\Python\url_list.txt') content = [x.strip() for x in urls.readlines()] print cont...
python mechanize - can login to site but can't grab html for a list of URLs?
I've written the following in python using the mechanize module in order to print out the HTML from a list URLs: import mechanize, fileinput urls = open('F:\Python\url_list.txt') content = [x.strip() for x in urls.readlines()] print content browser = mechanize.Browser() browser.open("https://login.asp") browser.selec...
[ "It's mechanize.urlopen(s) \nor as you said browser.open(s).\n" ]
[ 2 ]
[]
[]
[ "html", "loops", "mechanize", "python", "url" ]
stackoverflow_0005984192_html_loops_mechanize_python_url.txt
Q: How do I make 'import x' return a subclass of types.ModuleType? Can Python's import statement return a subclass of types.ModuleType using import hooks? I would like to override __getattribute__ to display a runtime warning when code outside a certain module reference names that aren't in __all__. I know how to rep...
How do I make 'import x' return a subclass of types.ModuleType?
Can Python's import statement return a subclass of types.ModuleType using import hooks? I would like to override __getattribute__ to display a runtime warning when code outside a certain module reference names that aren't in __all__. I know how to replace sys.modules['foo'] after it's been imported. What I want is to i...
[ "Since I missed the point of your question before you edited it, I thought I'd take another whack (while leaving my original answer for posterity).\nHere's an alternative that also doesn't need the import hook. It can easily be used on a module-by-module basis: a module that includes this code will have the special...
[ 5, 3, 3 ]
[]
[]
[ "python" ]
stackoverflow_0005983237_python.txt
Q: python re.sub group: number after \number How can I replace foobar with foo123bar? This doesn't work: >>> re.sub(r'(foo)', r'\1123', 'foobar') 'J3bar' This works: >>> re.sub(r'(foo)', r'\1hi', 'foobar') 'foohibar' I think it's a common issue when having something like \number. Can anyone give me a hint on how t...
python re.sub group: number after \number
How can I replace foobar with foo123bar? This doesn't work: >>> re.sub(r'(foo)', r'\1123', 'foobar') 'J3bar' This works: >>> re.sub(r'(foo)', r'\1hi', 'foobar') 'foohibar' I think it's a common issue when having something like \number. Can anyone give me a hint on how to handle this?
[ "The answer is:\nre.sub(r'(foo)', r'\\g<1>123', 'foobar')\n\nRelevant excerpt from the docs:\n\nIn addition to character escapes and\n backreferences as described above,\n \\g will use the substring\n matched by the group named name, as\n defined by the (?P...) syntax.\n \\g uses the corresponding\n group num...
[ 446 ]
[]
[]
[ "numbers", "python", "regex", "regex_group" ]
stackoverflow_0005984633_numbers_python_regex_regex_group.txt
Q: loading tab separated text files with multipled data into arrays in python I want to load tab separated input file as an array into python and I know that genfromtxt in numpy does that but the problem is that I have multiple sets of data that i would like to be loaded. Basically my sample file could be : #FILE STA...
loading tab separated text files with multipled data into arrays in python
I want to load tab separated input file as an array into python and I know that genfromtxt in numpy does that but the problem is that I have multiple sets of data that i would like to be loaded. Basically my sample file could be : #FILE START #intensities 11 1 1 0 1 2 #indexes 1 2 3 4 5 6 7 8 9 1 1 2 #FILE END So i wo...
[ "f = open(filepath, 'r')\ntags = [\"#intensities\"]\nanswer = {}\nfor line in f:\n if line.strip() in tags: # we've encountered a new tag\n curr = line.strip()[1:]\n answer[curr] = []\n else:\n answer[curr].append(line.strip().split('\\t'))\n\nf.close()\n\nNow, answer will look like this:...
[ 2 ]
[]
[]
[ "numpy", "python", "scipy" ]
stackoverflow_0005984806_numpy_python_scipy.txt
Q: Hangman word chosen I'm trying to let the user chose the length of the word they want, but I'm having a hard time trying to figure out what is wrong. I'm a noob at Python, I have learned for 3 months and I have searched about Python. I don't know all the Python built in functions or I might know but didn't know ho...
Hangman word chosen
I'm trying to let the user chose the length of the word they want, but I'm having a hard time trying to figure out what is wrong. I'm a noob at Python, I have learned for 3 months and I have searched about Python. I don't know all the Python built in functions or I might know but didn't know how to use them. Here is my...
[ "To address the error about randint not existing, you've imported the function names in the random module.\nfrom random import *\n\nSo just call the function directly.\nwordindex = randint(0,len(wordlist)-1)\n\nSo you're not importing more than you have to, I'd suggest importing the module (so you don't need to cha...
[ 5 ]
[]
[]
[ "graphics", "python" ]
stackoverflow_0005985242_graphics_python.txt
Q: Better way to get user input to plot in iPython module? I have a module to be used in iPython. I'd like a user to enter everything needed to make a plot- x, y, label, linewidth, etc. So the user might do something like this: In[1] import this_script In[2] x=range(0,10) In[3] y=x In[4] magically_exposed_function ...
Better way to get user input to plot in iPython module?
I have a module to be used in iPython. I'd like a user to enter everything needed to make a plot- x, y, label, linewidth, etc. So the user might do something like this: In[1] import this_script In[2] x=range(0,10) In[3] y=x In[4] magically_exposed_function plot(x,y,'r+', linewidth=2) This means that my function gets...
[ "Parsing the actual string is better left to python. Maybe you want to create a wrapper:\nreal_plot = plot\ndef my_plot(*args, **kwargs):\n x, y = args[0], args[1]\n ...your extra code here...\n real_plot(*args, **kwargs)\nplot = my_plot\n\n" ]
[ 1 ]
[]
[]
[ "ipython", "matplotlib", "python" ]
stackoverflow_0005983636_ipython_matplotlib_python.txt
Q: Implementation of spreadsheet in Python? Does anyone know of any open-source implementations of spreadsheets in Python? What I am really after is providing the user with the ability to modify formulas used by my Python program using possibly complex spreadsheets. I am not looking for solutions to interact with spr...
Implementation of spreadsheet in Python?
Does anyone know of any open-source implementations of spreadsheets in Python? What I am really after is providing the user with the ability to modify formulas used by my Python program using possibly complex spreadsheets. I am not looking for solutions to interact with spreadsheet applications like Excel. EDIT: The so...
[ "How about pyspread\n" ]
[ 3 ]
[]
[]
[ "python", "spreadsheet" ]
stackoverflow_0005985496_python_spreadsheet.txt
Q: ssh client with paramiko (python) # sshpy v1 by s0urd # simple ssh client # irc.gonullyourself.org 6667 #code import paramiko import os ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) privatekey = os.path.expanduser('/home/rabia/private') mkey = paramiko.RSAKey.from_private_...
ssh client with paramiko (python)
# sshpy v1 by s0urd # simple ssh client # irc.gonullyourself.org 6667 #code import paramiko import os ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) privatekey = os.path.expanduser('/home/rabia/private') mkey = paramiko.RSAKey.from_private_key_file(privatekey) ssh.connect('78.46...
[ "Looks like it's because at the end of the while loop you do ssh.close() (thus closing the session).\n" ]
[ 5 ]
[]
[]
[ "attributeerror", "paramiko", "python", "ssh" ]
stackoverflow_0005985611_attributeerror_paramiko_python_ssh.txt
Q: Generate sequences of adjecent subsets (from a list of lists) I have an matrix (array of arrays) in the form [1, 2, 3, 4] [12, 23, 34] [123, 234] [1234] And want to produce sequences of this matrix that is following each other and is (converted to a string) in the same length as the array at index 0 (top-most). S...
Generate sequences of adjecent subsets (from a list of lists)
I have an matrix (array of arrays) in the form [1, 2, 3, 4] [12, 23, 34] [123, 234] [1234] And want to produce sequences of this matrix that is following each other and is (converted to a string) in the same length as the array at index 0 (top-most). So i.e. the result of this would be [1, 2, 3, 4] [12, 3, 4] [1, 23, ...
[ "I improved the code from my previous one.\na = [\"1\", \"2\", \"3\", \"4\"]\n\n['', '.'].repeated_permutation(a.length - 1).map{|b| a.zip(b).join.split('.')}\n\nwill give you:\n[\n [\"1234\"],\n [\"123\", \"4\"],\n [\"12\", \"34\"],\n [\"12\", \"3\", \"4\"],\n [\"1\", \"234\"],\n [\"1\", \"23\", \"4\"],\n [...
[ 4, 2, 1, 1, 0 ]
[]
[]
[ "clojure", "java", "python", "ruby", "seq" ]
stackoverflow_0005984489_clojure_java_python_ruby_seq.txt
Q: Need to remove line breaks from a text file with certain conditions I have a text file running into 20,000 lines. A block of meaningful data for me would consist of name, address, city, state,zip, phone. My file has each of these on a new line, so a file would go like: StoreName1 , Address , City ,State ,Zip , Pho...
Need to remove line breaks from a text file with certain conditions
I have a text file running into 20,000 lines. A block of meaningful data for me would consist of name, address, city, state,zip, phone. My file has each of these on a new line, so a file would go like: StoreName1 , Address , City ,State ,Zip , Phone StoreName2 , Address , City ,State ,Zip , Phone I need to create a C...
[ "s/[\\r\\n]+,/,/g\nGlobally substitute 'linebreak(s),' with ','\nEdit:\nIf you want to reduce it further with a single linebreak between records:\ns/[\\r\\n]+(,|[\\r\\n])/$1/g\nGlobally substitute 'linebreaks(s) (comma or linebreak) with capture group 1.\nEdit:\nAnd, if it really gets out of whack, this might cure ...
[ 3, 2, 1, 0 ]
[ "f = open(infilepath, 'r')\ns = ''.join([line for line in f])\ns = s.replace('\\n\\n', '\\\\n')\ns = s.replace('\\n', '')\ns = s.replace(\"\\\\n\", \"\\n\")\nf.close()\n\nf = open(infilepath, 'r')\nf.write(s)\nf.close()\n\nThat should do it. It will replace your input file with the new format\n" ]
[ -1 ]
[ "python", "regex" ]
stackoverflow_0005984839_python_regex.txt
Q: Get the name of a list item I have easy access to a list of variables as such: [a, b, c,] I was wondering, can you introspect (or something) on the variable names to get a dict that looks like this: { 'a'=a, 'b'=b, 'c'=c } A: The list doesn't “contain variables”. It refers to the objects it contains; just as th...
Get the name of a list item
I have easy access to a list of variables as such: [a, b, c,] I was wondering, can you introspect (or something) on the variable names to get a dict that looks like this: { 'a'=a, 'b'=b, 'c'=c }
[ "The list doesn't “contain variables”. It refers to the objects it contains; just as the names ‘a’, ‘b’, ‘c’ refer to those same objects.\nSo getting an item from the list gets you the object. That object may have zero, one, or many names; it doesn't know any of them.\nIf you know at the time you create the list th...
[ 1, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0005985832_dictionary_python.txt
Q: Python "how many elements have" I have some data, for example: input=[['1', '7', 'U1'], ['1.5', '8', 'U1'], ['2', '5.5', 'U1'], ['2', '9', 'U1'], ['2.5', '6.5', 'U1'], ['2.5', '8', 'U1'], ['2.5', '10', 'U2'], ['3', '4.5', 'U2'], ['3', '9', 'U2'], ['3.5', '5.5', 'U2']] How can I get numbers of how many U1 and U2 d...
Python "how many elements have"
I have some data, for example: input=[['1', '7', 'U1'], ['1.5', '8', 'U1'], ['2', '5.5', 'U1'], ['2', '9', 'U1'], ['2.5', '6.5', 'U1'], ['2.5', '8', 'U1'], ['2.5', '10', 'U2'], ['3', '4.5', 'U2'], ['3', '9', 'U2'], ['3.5', '5.5', 'U2']] How can I get numbers of how many U1 and U2 data is in all my data? This U1 and U2...
[ "I modified the index from 2 to -1 to reflect your requirement of 'last element on every row' in case each row has a different number of elements.\nfrom collections import defaultdict\nd = defaultdict(int)\nfor record in input:\n d[record[-1]] += 1\nprint d\n\n", "You can do this using a list comprehension:\nn...
[ 6, 4, 3 ]
[]
[]
[ "python" ]
stackoverflow_0005985992_python.txt
Q: python classes and variable scope class Test: def c(self, args): print args def b(self, args): args.append('d') def a(self): args = ['a', 'b', 'c'] self.b(args) self.c(args) Test().a() Why doesn't this print ['a', 'b', 'c']? A: When you pass a list to a fu...
python classes and variable scope
class Test: def c(self, args): print args def b(self, args): args.append('d') def a(self): args = ['a', 'b', 'c'] self.b(args) self.c(args) Test().a() Why doesn't this print ['a', 'b', 'c']?
[ "When you pass a list to a function, you're really passing it a pointer to the list and not a copy of the list. So b is appending a value to the original args, not its own local copy of it. \n", "The parameter you pass to methods b and c is a reference to the list args, not a copy of it. In method b, you append t...
[ 2, 1 ]
[]
[]
[ "parameters", "pass_by_reference", "python" ]
stackoverflow_0005986377_parameters_pass_by_reference_python.txt
Q: Regex for multi character strings embedded in rest of match? How can I match something like "AB|CD|EF" followed by "12|34" and get, for instance, "AB12" back? If the string was "zzAB34zz" I'd get "AB34", "zzABCD12" and get "CD12", etc? A: No need for named groups here, really: import re re.search('(AB|CD|EF)(12|...
Regex for multi character strings embedded in rest of match?
How can I match something like "AB|CD|EF" followed by "12|34" and get, for instance, "AB12" back? If the string was "zzAB34zz" I'd get "AB34", "zzABCD12" and get "CD12", etc?
[ "No need for named groups here, really:\nimport re\nre.search('(AB|CD|EF)(12|34)', 'zzAB34zz').group()\n\n", "Use parentheses to capture:\nimport re\nr = re.compile(r'(?P<stuff>(AB|CD|EF)(12|34))')\n\nr.findall('__ABCD12__EF34__')\n#[('CD12', 'CD', '12'), ('EF34', 'EF', '34')]\n\nr.search('__ABCD12__EF34__').grou...
[ 3, 0, 0 ]
[]
[]
[ "pattern_matching", "python", "regex" ]
stackoverflow_0005986460_pattern_matching_python_regex.txt
Q: Python distutils gcc path I'm trying to cross-compile the pycrypto package, and I'm getting closer and closer however, I've hit an issue I just can't figure out. I want distutils to use the cross-compile specific gcc- so I set the CC env var and it seems to respect the setting for the first invocation of the compi...
Python distutils gcc path
I'm trying to cross-compile the pycrypto package, and I'm getting closer and closer however, I've hit an issue I just can't figure out. I want distutils to use the cross-compile specific gcc- so I set the CC env var and it seems to respect the setting for the first invocation of the compiler, but thats it. export CC="/...
[ "This sounds similar to another answer I recently gave for customizing the distutils compiler. You'll also need to define LDSHARED which is the command used to produce the final shared object. See if this works:\n>>> from distutils import sysconfig\n>>> sysconfig.get_config_var('LDSHARED')\n'gcc -pthread -shared -...
[ 16 ]
[]
[]
[ "compilation", "distutils", "python" ]
stackoverflow_0005986256_compilation_distutils_python.txt
Q: Cannot Launch Interactive Program While Piping to Script in Python I have a python script that needs to call the defined $EDITOR or $VISUAL. When the Python script is called alone, I am able to launch the $EDITOR without a hitch, but the moment I pipe something to the Python script, the $EDITOR is unable to launch...
Cannot Launch Interactive Program While Piping to Script in Python
I have a python script that needs to call the defined $EDITOR or $VISUAL. When the Python script is called alone, I am able to launch the $EDITOR without a hitch, but the moment I pipe something to the Python script, the $EDITOR is unable to launch. Right now, I am using nano which shows Received SIGHUP or SIGTERM ev...
[ "When you pipe something to a process, the pipe is connected to that process's standard input. This means your terminal input won't be connected to the editor. Most editors also check whether their standard input is a terminal (isatty), which a pipe isn't; and if it isn't a terminal, they'll refuse to start. In ...
[ 4, 2 ]
[]
[]
[ "interactive", "nano", "python", "subprocess" ]
stackoverflow_0005986544_interactive_nano_python_subprocess.txt
Q: Linux user scheme for a Django production server I'm currently trying to set up nginx + uWSGI server for my Django homepage. Some tutorials advice me to create specific UNIX users for certain daemons. Like nginx user for nginx daemon and so on. As I'm new to Linux administration, I thought just to create second us...
Linux user scheme for a Django production server
I'm currently trying to set up nginx + uWSGI server for my Django homepage. Some tutorials advice me to create specific UNIX users for certain daemons. Like nginx user for nginx daemon and so on. As I'm new to Linux administration, I thought just to create second user for running all the processes (nginx, uWSGI etc.), ...
[ "I like having regular users on a system:\n\nmultiple admins show up in sudo logs -- there's nothing quite like asking a specific person why they made a specific change.\nnot all tasks require admin privileges, but admin-level mistakes can be more costly to repair\nit is easier to manage the ~/.ssh/authorized_keys ...
[ 2 ]
[]
[]
[ "django", "linux", "nginx", "python", "uwsgi" ]
stackoverflow_0005986472_django_linux_nginx_python_uwsgi.txt
Q: Parse External Methods Calls Within Python Function? Given the python code: import sys import os def MyPythonMethod(value1, value2): # defining some variables a = 4 myValue = 15.65 listValues = [4, 67, 83, -23] # check if a file exists if ( os.path.exists('/home/hello/myfile.txt') ): ...
Parse External Methods Calls Within Python Function?
Given the python code: import sys import os def MyPythonMethod(value1, value2): # defining some variables a = 4 myValue = 15.65 listValues = [4, 67, 83, -23] # check if a file exists if ( os.path.exists('/home/hello/myfile.txt') ): pass # doing some operation on the list lis...
[ "You can't ever fully know what functions (and in your case we're talking about plain functions, not methods, since methods are member functions of a class), a function will call without parsing it, because it might do so dynamically and their names may depend on what is imported into the global namespace when the ...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0005986565_python.txt
Q: Missing expected output I am trying to run this file from the ebook Learning Python The Hard Way with the "python ex18.py" command, but it is not outputting anything. What's wrong? # this one is like your scripts with argv def print_two(*args): arg1, arg2 = args print "arg1: %r, arg2: %r" % (arg1, arg2) #...
Missing expected output
I am trying to run this file from the ebook Learning Python The Hard Way with the "python ex18.py" command, but it is not outputting anything. What's wrong? # this one is like your scripts with argv def print_two(*args): arg1, arg2 = args print "arg1: %r, arg2: %r" % (arg1, arg2) # ok, that *args is actually p...
[ "Because that file doesn't actually call any functions, there's nothing to output.\nThat file just defines four functions and then does nothing with them. :)\nTry adding calls to print_none, print_one, and so forth:\nprint_none()\nprint_one(\"hello\")\nprint_two(\"hello\", \"world\")\nprint_two_again(\"hello\", \"w...
[ 8, 3, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005987143_python.txt
Q: does C has anything like python pickle for object serialisation? I'm wondering if C has anything similar to the python pickle module that can dump some structured data on disk and then load it back later. I know that I can write my structure byte by byte to a file on disk and then read it back later, but with thi...
does C has anything like python pickle for object serialisation?
I'm wondering if C has anything similar to the python pickle module that can dump some structured data on disk and then load it back later. I know that I can write my structure byte by byte to a file on disk and then read it back later, but with this approach there's still quite some work to do. For example, if I have...
[ "An emphatic NO on that one, I'm afraid. C has basic file I/O. Any structuring of data is up to you. Make up a format, dump it out, read it in.\nThere may be libraries which can do this, but by itself no C doesn't do this.\n", "The C library functions fread(3) and fwrite(3) will read and write 'elements of data',...
[ 4, 2 ]
[ "Boost has a serialization library, if by \"C\" you mean \"C or C++.\"\n" ]
[ -1 ]
[ "c", "python" ]
stackoverflow_0005987185_c_python.txt
Q: Unknown quantity of items in configuration files using ConfigParser To be honest I'm writing this question to try to clear up my mind in the process. If I can't figure it out, I'll post it (which happened). I would appreciate if someone could shed some light on how to approach this problem. I'm still noob enough t...
Unknown quantity of items in configuration files using ConfigParser
To be honest I'm writing this question to try to clear up my mind in the process. If I can't figure it out, I'll post it (which happened). I would appreciate if someone could shed some light on how to approach this problem. I'm still noob enough to get overwhelmed by this kind of problems. Let's say that in certain sec...
[ "If I understand your question correctly, it seems to me that ConfigParser.items(section) offers the functionality you need. \n\nPerhaps it would help to know that you can call dict on the resulting list of tuples? As in...\n>>> l = [('name1', 'val1'), ('name2', 'val2')]\n>>> d = dict(l)\n>>> d\n{'name2': 'val2', '...
[ 3 ]
[]
[]
[ "configparser", "configuration_files", "python" ]
stackoverflow_0005987483_configparser_configuration_files_python.txt
Q: Python Easy_Install Update Report Is there an easy way to get a report of all Python libraries installed via easy_install that have a more recent version available? I don't want to simply re-run easy_install on a list of known installed libraries, because the newer library might have a non-backwards compatible cha...
Python Easy_Install Update Report
Is there an easy way to get a report of all Python libraries installed via easy_install that have a more recent version available? I don't want to simply re-run easy_install on a list of known installed libraries, because the newer library might have a non-backwards compatible change. I'd like to get a list so I quickl...
[ "Here is a quick script to scan the easy-install.pth file and print a list of newer versions of installed packages. You could customize it to only show the newest version available (take max of parsed_version), tweak the output format, etc:\n#!/usr/bin/env python\nimport os, sys\nfrom distutils import sysconfig\nfr...
[ 5 ]
[]
[]
[ "easy_install", "python" ]
stackoverflow_0005195764_easy_install_python.txt
Q: how to get dirname of a GFile? When using GIO and GVFS, how do I best get the directory name of a GFile object? There is a get_basename() function but no get_dirname(). The function should work for remote URIs as well. Also, it should be available in Python. A: First get the GFile for the dir, then get the name ...
how to get dirname of a GFile?
When using GIO and GVFS, how do I best get the directory name of a GFile object? There is a get_basename() function but no get_dirname(). The function should work for remote URIs as well. Also, it should be available in Python.
[ "First get the GFile for the dir, then get the name of the dir:\nGFile* dir = g_file_get_parent(gfile));\nchar* dir_name = g_file_get_parse_name(dir);\n\n", "Take a look at this: http://docs.python.org/library/os.path.html. There is a dirname function which might help. Dont know if it will work for remote URIs as...
[ 2, 0 ]
[]
[]
[ "dirname", "gio", "python" ]
stackoverflow_0005056904_dirname_gio_python.txt
Q: Can python shell have some pre-input? When testing in python shell, I always have to type some import like: Python 2.5.4 (r254:67916, Jun 24 2010, 15:23:27) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>>import sys >>>import datetime Can someone help me to automa...
Can python shell have some pre-input?
When testing in python shell, I always have to type some import like: Python 2.5.4 (r254:67916, Jun 24 2010, 15:23:27) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>>import sys >>>import datetime Can someone help me to automatically finish these? It means I run some c...
[ "Try:\npython -i -c \"import sys; import datetime;\"\n\nMore info:\n-i : inspect interactively after running script; forces a prompt even\n if stdin does not appear to be a terminal; also PYTHONINSPECT=x\n\n&\n-c cmd : program passed in as string (terminates option list)\n\n", "Create a file with the ...
[ 3, 1 ]
[]
[]
[ "command_line", "linux", "python" ]
stackoverflow_0005988246_command_line_linux_python.txt
Q: How vertical bars literal determine the formal regular expression in python? According to the python doc, vertical bars literal are used as an 'or' operator. It matches A|B,where A and B can be arbitrary REs. For example, if the regular expression is as following: ABC|DEF,it matches strings like these: "ABC", "DEF...
How vertical bars literal determine the formal regular expression in python?
According to the python doc, vertical bars literal are used as an 'or' operator. It matches A|B,where A and B can be arbitrary REs. For example, if the regular expression is as following: ABC|DEF,it matches strings like these: "ABC", "DEF" But what if I want to match strings as following: "ABCF", "ADEF" Perhaps what I ...
[ "These will work:\nA(BC|DE)F\nA(?:BC|DE)F\n\nThe difference is the number of groups generated: 1 with the first, 0 with the second.\nYours will match either ABC or DEF, with 2 groups, one containing nothing and the other containing the matched fragment (BC or DE).\n", "The only difference between parentheses in P...
[ 7, 3 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0005988617_python_regex.txt
Q: Django Show user that upload is in progress I have a filemanager application that allows users to upload files to the server and ofcourse download them. Now in the state it is when an user starts uploading the browser only shows that small loading circle until upload is finished. And the usage for this server woul...
Django Show user that upload is in progress
I have a filemanager application that allows users to upload files to the server and ofcourse download them. Now in the state it is when an user starts uploading the browser only shows that small loading circle until upload is finished. And the usage for this server would be for quite big files, mostly about 100mb so i...
[ "This post: http://kuhlit.blogspot.com/2011/04/ajax-file-uploads-and-csrf-in-django-13.html discusses how to implement an upload progress bar for Django 1.3. I think a progress bar would be preferable, although if you wanted to do something simple, you could just show a dialog with javascript saying, \"HEY I'M UPLO...
[ 2 ]
[]
[]
[ "django", "django_templates", "django_views", "javascript", "python" ]
stackoverflow_0005988750_django_django_templates_django_views_javascript_python.txt
Q: Terminate process run with `exec` when program terminates I have a java program that runs another (Python) program as a process. Process p = Runtime.getRuntime().exec("program.py", envp); If the java program finish processing, the Python process is finished as well. The finish command sends a signal to the Pytho...
Terminate process run with `exec` when program terminates
I have a java program that runs another (Python) program as a process. Process p = Runtime.getRuntime().exec("program.py", envp); If the java program finish processing, the Python process is finished as well. The finish command sends a signal to the Python process to close it. In normal situation the process is clos...
[ "hey @czuk would a ShutdownHook hook be any use? This will deal with the following scenarios\nThe Java virtual machine shuts down in response to two kinds of events:\n\nThe program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System.exit) method is invoked, or\nThe virtual m...
[ 3, 2 ]
[]
[]
[ "java", "python", "runtime.exec" ]
stackoverflow_0005988622_java_python_runtime.exec.txt
Q: asynchronous file upload with ajaxupload to a tornado web server I'm using this javascript library (http://valums.com/ajax-upload/) to upload file to a tornado web server, but I don't know how to get the file content. The javascript library is uploading using XHR, so I assume I have to read the raw post data to ge...
asynchronous file upload with ajaxupload to a tornado web server
I'm using this javascript library (http://valums.com/ajax-upload/) to upload file to a tornado web server, but I don't know how to get the file content. The javascript library is uploading using XHR, so I assume I have to read the raw post data to get the file content. But I don't know how to do it with Tornado. Their ...
[ "I got the answer.\nI need to use self.request.body to get the raw post data.\nI also need to pass in the correct _xsrf token, otherwise tornado will fire a 403 exception.\nSo that's about it.\n" ]
[ 2 ]
[]
[]
[ "ajax_upload", "file_upload", "python", "tornado" ]
stackoverflow_0005983032_ajax_upload_file_upload_python_tornado.txt
Q: django forms: change attribute of formfield dynamically I have a form like the one below: class ConsentFormTpl(forms.Form): title = forms.CharField() message = forms.CharField(widget=EditorWidget,label='Description') acknowledge = forms.BooleanField(label="Require acknowledgement?") deadline = for...
django forms: change attribute of formfield dynamically
I have a form like the one below: class ConsentFormTpl(forms.Form): title = forms.CharField() message = forms.CharField(widget=EditorWidget,label='Description') acknowledge = forms.BooleanField(label="Require acknowledgement?") deadline = forms.DateField(widget=CalendarTimeWidget,label="Acknowledge By"...
[ "The fields aren't available as attributes on the form instance. They're available as dictionary elements in self.fields. So:\nself.fields['acknowledge'].required = False\n\nand so on.\n" ]
[ 19 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0005989293_django_django_forms_python.txt
Q: Why can I write some things out-of-order in python but not others? Please have a look below: a = 5 print a + b b = 4 When I try to run the code above, it gives an error: Traceback (most recent call last): File "C:/Users/user/Documents/modules/ab.py", line 2, in print a + b NameError: name 'b' is not define...
Why can I write some things out-of-order in python but not others?
Please have a look below: a = 5 print a + b b = 4 When I try to run the code above, it gives an error: Traceback (most recent call last): File "C:/Users/user/Documents/modules/ab.py", line 2, in print a + b NameError: name 'b' is not defined Ok. a + b is called before b is defined. That means Python runs the co...
[ "You're not actually \"running\" the code yet. In your example, all you have is a method declaration inside the Data class. In it, Python will not check for the existence of class fields because they may be set at another time, in some other method (Python's classes are malleable in that sense).\nIf you try to run ...
[ 5, 4, 2, 1, 1, 0 ]
[]
[]
[ "closures", "compilation", "declaration", "python", "scope" ]
stackoverflow_0005989342_closures_compilation_declaration_python_scope.txt
Q: PyExc_ValueError and Firefox extension I'm developing a firefox addon which is depended on Python (which means that the user must install PyXpcomExt on his firefox). On the other hand I used PyCrypto lib (based on python) for encryption purposes. So when firefox is loaded I have registered path to this library. Ho...
PyExc_ValueError and Firefox extension
I'm developing a firefox addon which is depended on Python (which means that the user must install PyXpcomExt on his firefox). On the other hand I used PyCrypto lib (based on python) for encryption purposes. So when firefox is loaded I have registered path to this library. However when the extension is run I get the fo...
[ "AES.so has not been linked against the Python dynamic library. It's finding other symbols it needs in the process's symbol table, but it can't find that one and doesn't know where it is.\n" ]
[ 0 ]
[]
[]
[ "firefox_addon", "pycrypto", "python", "xpcom" ]
stackoverflow_0005981117_firefox_addon_pycrypto_python_xpcom.txt
Q: How can I count the line number between two character in a file with python? Hi I'm new to python and I have a 3.2 python! I have a file which has some sort of format like this: Number of segment pairs = 108570; number of pairwise comparisons = 54234 '+' means given segment; '-' means reverse complement Overlaps ...
How can I count the line number between two character in a file with python?
Hi I'm new to python and I have a 3.2 python! I have a file which has some sort of format like this: Number of segment pairs = 108570; number of pairwise comparisons = 54234 '+' means given segment; '-' means reverse complement Overlaps Containments No. of Constraints Supporting Overlap ******************...
[ "Probably, it's best to use regular expressions here. You can try the following:\nimport re\nstr = open(file).read()\npairs = re.findall(r'\\*+ (Contig \\d+) \\*+\\n([^*]*)',str)\n\npairs is a list of tuples, where the tuples have the form ('Contig x', '...')\nThe second component of each tuple contains the text af...
[ 3, 1 ]
[]
[]
[ "count", "line", "python" ]
stackoverflow_0005989158_count_line_python.txt
Q: Python: tool to keep track of deployments I'm looking for a tool to keep track of "what's running where". We have a bunch of servers, and on each of those a bunch of projects. These projects may be running on a specific version (hg tag/commit nr) and have their requirements at specific versions as well. Fabric loo...
Python: tool to keep track of deployments
I'm looking for a tool to keep track of "what's running where". We have a bunch of servers, and on each of those a bunch of projects. These projects may be running on a specific version (hg tag/commit nr) and have their requirements at specific versions as well. Fabric looks like a great start to do the actual deployme...
[ "pip freeze gives you a listing of all installed packages. Bonus: if you redirect the output to a file, you can use it as part of your deployment process to install all those packages (pip can programmatically install all packages from the file).\nI see you're already using virtualenv. Good. You can run pip freeze ...
[ 1, 0 ]
[]
[]
[ "deployment", "python", "web_deployment" ]
stackoverflow_0005988177_deployment_python_web_deployment.txt
Q: Connecting signal with lambda does not work in some cases? i'm experimenting pygtk programms development, with python 2.7, and i have a little problem when connecting signals using a lambda function : let us say that the class which wants to connect a signal is the class A_Class, and the signal is the string "A_S...
Connecting signal with lambda does not work in some cases?
i'm experimenting pygtk programms development, with python 2.7, and i have a little problem when connecting signals using a lambda function : let us say that the class which wants to connect a signal is the class A_Class, and the signal is the string "A_Signal" we also dispose of a second class B_class defining public...
[ "Your lambda expression should call the handler function instead of returning it:\nself.connect(\"delete-event\", lambda the_widget, the_event: \\\n self.__instance_b.manage_event(the_widget, the_event))\n\nOf course, as you said, this is unneeded because it's equivalent to:\nself.connect(\"delete-event\", self....
[ 1 ]
[]
[]
[ "lambda", "pygtk", "python" ]
stackoverflow_0005989933_lambda_pygtk_python.txt
Q: Should I migrate from Django 1.2.5 to 1.3.x ? Are there any undocumented issues? Short Question Are there any compelling reasons to update Django 1.2.5 to 1.3? If the noted changes in the release notes do not impact my application directly. EDIT: To better clarify my question (thanks S.Lott!): Are there any issu...
Should I migrate from Django 1.2.5 to 1.3.x ? Are there any undocumented issues?
Short Question Are there any compelling reasons to update Django 1.2.5 to 1.3? If the noted changes in the release notes do not impact my application directly. EDIT: To better clarify my question (thanks S.Lott!): Are there any issues not mentioned in the Django 1.3's release notes that I should be aware of if upgradi...
[ "You need reasons? Just look at the release notes. They do a very good job outlining both new features and backwards incompatible changes. I have been happy to migrate all of my Django projects to 1.3, I'm particularly happier about the changes to the way static files are managed. Class-based views are quite nice, ...
[ 5, 0, 0 ]
[]
[]
[ "django", "python", "release_management" ]
stackoverflow_0005986388_django_python_release_management.txt
Q: Reading key/value pairs from text file, line by line, and passing values/dict to urlopen http function I have to fill in multiple form fields on a web page I got the http POST part completed so I can post data to the web page. I also got the part completed where I create a dictionary of key/value pairs and have th...
Reading key/value pairs from text file, line by line, and passing values/dict to urlopen http function
I have to fill in multiple form fields on a web page I got the http POST part completed so I can post data to the web page. I also got the part completed where I create a dictionary of key/value pairs and have the form fields filled on the web page. Key/value pairs: input1 = {'hostname' : 'host', 'port' : '22', 'basedn...
[ "This is because each line in your file is ONE string. You need a KEY, VALUE pair to update a dictionary. If you post a sample line from your file in your question, I can show you how split it into the required KEY and VALUE\nEDIT: How to Split Lines from the text file\nline = \"{'hostname' : 'host', 'port' : '22',...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005984253_python.txt
Q: What is an elegant way to abstract functions - not objects? I have a function that logs into a sensor via telnet/pexpect and acts as a data collector. I don't want to rewrite the part that logs in, grabs the data, and parses out relevant output from it (pexpect). However, I need to do different things with this co...
What is an elegant way to abstract functions - not objects?
I have a function that logs into a sensor via telnet/pexpect and acts as a data collector. I don't want to rewrite the part that logs in, grabs the data, and parses out relevant output from it (pexpect). However, I need to do different things with this code and the data it gathers For example, I may need to: Time unti...
[ "This is such a common situation, I'm surprised you haven't already done what everyone else does.\nRefactor your function to decompose it into smaller functions.\nFunctions are objects, and can be passed as arguments to other functions.\ndef step1(): \n whatever\n\ndef step2(): \n whatever\n\ndef step2_altern...
[ 3, 0 ]
[]
[]
[ "abstraction", "functional_programming", "pexpect", "python" ]
stackoverflow_0005986382_abstraction_functional_programming_pexpect_python.txt
Q: Opening file from python In my python file, I create an *.bmp image, which I the open to check everything went fine. It is a bit of a hassle to open this each time I run my program (I know, I'm too lazy) and using show seems counterintuitive, since it freezes the execution and I can't keep it open. Which is the c...
Opening file from python
In my python file, I create an *.bmp image, which I the open to check everything went fine. It is a bit of a hassle to open this each time I run my program (I know, I'm too lazy) and using show seems counterintuitive, since it freezes the execution and I can't keep it open. Which is the command in python to open files...
[ "Perhaps you want the subprocess module.\nimport subprocess\nproc = subprocess.Popen(['gedit', 'file.txt'])\n\nThe above code will open gedit with the single argument 'file.txt' (i.e. open the file in gedit).\nIf you add the line,\nproc.wait()\n\nthen the script will wait until you close gedit, should you ever want...
[ 9 ]
[]
[]
[ "command_line", "execute", "python" ]
stackoverflow_0005990366_command_line_execute_python.txt
Q: UnboundLocalError from imported class I have some code that is structured as follows from my.modules import MyClass Class AnotherClass(object): def __init__(a): #line 5 if a: setup_a() else: setup_b() def setup_a(): # Do some stuff to get local_x # .. self.a = MyClass(local_x...
UnboundLocalError from imported class
I have some code that is structured as follows from my.modules import MyClass Class AnotherClass(object): def __init__(a): #line 5 if a: setup_a() else: setup_b() def setup_a(): # Do some stuff to get local_x # .. self.a = MyClass(local_x) def setup_b(): # Do some stuff to ...
[ "Somewhere in the code you're not showing you're assigning to MyClass, making the compiler think that it's a local variable when it's not.\n" ]
[ 5 ]
[]
[]
[ "global", "python" ]
stackoverflow_0005990592_global_python.txt
Q: Set background image in google app engine mail API Tried to insert background image in python. But I receive mail without Images (Text only). Why ? class MainHandler(webapp.RequestHandler): def post(self): message = mail.EmailMessage(sender="#### Team<abcd@gmail>", subject="Your account h...
Set background image in google app engine mail API
Tried to insert background image in python. But I receive mail without Images (Text only). Why ? class MainHandler(webapp.RequestHandler): def post(self): message = mail.EmailMessage(sender="#### Team<abcd@gmail>", subject="Your account has been approved") message.to = "David<qerer@gmail....
[ "Email clients are VERY picky about how they display HTML emails, they will often strip out css, rework markup and sanitise forms/javascript. This is likely not at issue with AppEngine but an issue with how email clients are presenting your emails. Checkout this article\nThere are premium services (like Litmus that...
[ 2, 1 ]
[]
[]
[ "css", "google_app_engine", "html", "python" ]
stackoverflow_0005990390_css_google_app_engine_html_python.txt
Q: Installing modules for multiple python versions I have installed python 2.6.6 and python 2.5.5 on the same machines (Ubuntu 10.0.4), since 2.6 is my default version and 2.5 I need for maintaining old stuff. But I have a problem to install modules(MySQLdb and net-snmp) to non-default 2.5v. It seems that only 2.6 is...
Installing modules for multiple python versions
I have installed python 2.6.6 and python 2.5.5 on the same machines (Ubuntu 10.0.4), since 2.6 is my default version and 2.5 I need for maintaining old stuff. But I have a problem to install modules(MySQLdb and net-snmp) to non-default 2.5v. It seems that only 2.6 is updated when 'sudo apt-get install _module_name_' is...
[ "You can use easy_install. To use it for particular version, you just execute it like for example sudo python2.5 easy_install package_name.\n", "You could install Pip for both 2.5 and 2.6 then create an alias in your bashrc like I have which I can do\npip25 install _package_\n\nor\npip26 install _package_\n\nThat...
[ 3, 1 ]
[]
[]
[ "multiple_versions", "python", "python_module" ]
stackoverflow_0005991193_multiple_versions_python_python_module.txt
Q: Why ruby 1.9 is faster than python 2.7 and 3.2? I read this bunch of links : http://pack.li/L ruby 1.9 seems to be 2 times faster than 1.8... and faster than python 2.7 and 3.2 I made some tests, it is not only on recursion (I knew python was bad about that), put for more standard stuff also. So here is my questio...
Why ruby 1.9 is faster than python 2.7 and 3.2?
I read this bunch of links : http://pack.li/L ruby 1.9 seems to be 2 times faster than 1.8... and faster than python 2.7 and 3.2 I made some tests, it is not only on recursion (I knew python was bad about that), put for more standard stuff also. So here is my question : How the ruby team have done that ? 2x improvement...
[ "I am a rubyist, and I think you didn't read those (quite old) articles fully. Both admit having used ... \"sensationalist\" headlines. And that the algorithms they use aren't optimal. So they have little value in my eyes.\nThe \"best\" place I know for comparing languages is http://benchmarksgame.alioth.debian.org...
[ 28, 6, 6 ]
[]
[]
[ "performance", "python", "ruby" ]
stackoverflow_0005990823_performance_python_ruby.txt
Q: Array subtraction and/or reshaping I would like some help with a problem. In Python: a=array([2,2]) b=ones((2,10)) I would like to know if there is a function that allows me to subtract b-a to have an array of 2x10 full of -1. I can do it one with 1D arrays, I just wanted to know if it is possible to do with 2D a...
Array subtraction and/or reshaping
I would like some help with a problem. In Python: a=array([2,2]) b=ones((2,10)) I would like to know if there is a function that allows me to subtract b-a to have an array of 2x10 full of -1. I can do it one with 1D arrays, I just wanted to know if it is possible to do with 2D arrays. Thanks
[ "Add a new dimension to a:\nb - a[:,None]\n\nwhere a[:,None] becomes array([[2], [2]]), a 2x1 array which you can substract from a 2x10 array and get a 2x10 array full of -1.\n", "You want to have an array of 2x10 full of -1.\nWhy don't you just do like this:\nb = np.ones((2, 10)) * -1\n\narray([[-1., -1., -1., -...
[ 5, 0 ]
[]
[]
[ "arrays", "numpy", "operations", "python" ]
stackoverflow_0005989909_arrays_numpy_operations_python.txt
Q: which function of mechanize is equal with urllib.urlencode urllib.urlencode could encode url's params. It seems no likely function in Mechanize. So, I have to use urllib and Mechanize, because I only need urlencode. Any function could implement the same task like urllib.urlencode in Mechanize A: Why would mecha...
which function of mechanize is equal with urllib.urlencode
urllib.urlencode could encode url's params. It seems no likely function in Mechanize. So, I have to use urllib and Mechanize, because I only need urlencode. Any function could implement the same task like urllib.urlencode in Mechanize
[ "Why would mechanize have it? It's already in urllib, which comes with Python.\n", "mechanize actually uses urllib and urllib2 for most tasks that involve urls. \nSince this functionality already exists in urllib/2 (as mentioned by Ignacio Vazquez-Abrams) there's no need for it to be implemented elsewhere. When c...
[ 3, 0 ]
[]
[]
[ "mechanize", "python", "urllib" ]
stackoverflow_0005940520_mechanize_python_urllib.txt
Q: Plotting surface without axes I want to plot a surface without axes planes.. I think I'll explain better with images: I want to get whis one: Instead, I'm getting this: A: This one disables all the axes stuff: ax.grid(False) for a in (ax.w_xaxis, ax.w_yaxis, ax.w_zaxis): for t in a.get_ticklines()+a.get_ti...
Plotting surface without axes
I want to plot a surface without axes planes.. I think I'll explain better with images: I want to get whis one: Instead, I'm getting this:
[ "This one disables all the axes stuff:\nax.grid(False)\nfor a in (ax.w_xaxis, ax.w_yaxis, ax.w_zaxis):\n for t in a.get_ticklines()+a.get_ticklabels():\n t.set_visible(False)\n a.line.set_visible(False)\n a.pane.set_visible(False)\n\n", "After much beating of head against wall, I was able to come ...
[ 6, 3, 2 ]
[]
[]
[ "3d", "geometry_surface", "matplotlib", "python" ]
stackoverflow_0005135446_3d_geometry_surface_matplotlib_python.txt
Q: Is Python cStringIO thread-safe? As title say, does Python cStringIO protect their internal structures for multithreading use? Thank you. A: I assume you are talking about the CPython implementation of Python. In CPython there is a global interpreter lock which means that only a single thread of Python code can ...
Is Python cStringIO thread-safe?
As title say, does Python cStringIO protect their internal structures for multithreading use? Thank you.
[ "I assume you are talking about the CPython implementation of Python.\nIn CPython there is a global interpreter lock which means that only a single thread of Python code can execute at a time. Code written in C will therefore also be effectively single threaded unless it explicitly releases the global lock.\nWhat t...
[ 4, 4, 1, 0 ]
[]
[]
[ "python", "stringio", "thread_safety" ]
stackoverflow_0005991605_python_stringio_thread_safety.txt
Q: What is the proper way to handle site requests with cookie handlers in Python3? I'm writing a script in Python 3.1.2 that logs into a site and then begins to make requests. I can log in without any great difficulty, but after doing that the requests return an error stating I haven't logged in. My code looks like t...
What is the proper way to handle site requests with cookie handlers in Python3?
I'm writing a script in Python 3.1.2 that logs into a site and then begins to make requests. I can log in without any great difficulty, but after doing that the requests return an error stating I haven't logged in. My code looks like this: import urllib.request from http import cookiejar from urllib.parse import urlenc...
[ "I had this issue once. I can't get the cookie the cookie management working automatically. Frustrated me for days, I ended up handling the cookie manually. That is getting the content of 'Set-Cookie' from the response header, saving it somewhere safe. Subsequently, any request made to that server, I will set the '...
[ 0 ]
[]
[]
[ "httpwebrequest", "python", "python_3.x", "urllib" ]
stackoverflow_0004194245_httpwebrequest_python_python_3.x_urllib.txt
Q: web.py - How to turn result of db.query(sql) into list of dict? I'm new to both Python and web.py (which I am currently using) so please bear with me. In the official document: import web db = web.database(dbn='postgres', db='mydata', user='dbuser', pw='') results = db.query("SELECT COUNT(*) AS total_users FROM us...
web.py - How to turn result of db.query(sql) into list of dict?
I'm new to both Python and web.py (which I am currently using) so please bear with me. In the official document: import web db = web.database(dbn='postgres', db='mydata', user='dbuser', pw='') results = db.query("SELECT COUNT(*) AS total_users FROM users") print results[0].total_users # -> prints number of entries in '...
[ "It will trigger, because you are just selecting only the title attribute from news, which obvioulsy will give tuple like (a,b,c,d) as result. \nif you want a object as result,do something like this\nself.db.query(\"SELECT * FROM news\")\n\n" ]
[ 0 ]
[]
[]
[ "python", "web.py" ]
stackoverflow_0005991597_python_web.py.txt
Q: How to get generated captcha image using mechanize I'm trying to use python and mechanize to send sms from my mobile provider website. The problem is that form has a captcha image. Using mechanize I can get the link to the image, but it's different all the time I access that link. Is there any way to get exact pic...
How to get generated captcha image using mechanize
I'm trying to use python and mechanize to send sms from my mobile provider website. The problem is that form has a captcha image. Using mechanize I can get the link to the image, but it's different all the time I access that link. Is there any way to get exact picture from mechanize?
[ "This is a rough example of how to get the image, note that mechanize uses cookies so any cookies received will be sent to the server with the request for the image (this is probably what you want).\nbr = mechanize.Browser()\nresponse = br.open('http://example.com')\nsoup = BeautifulSoup(response.get_data())\nimg =...
[ 11 ]
[]
[]
[ "captcha", "mechanize", "python" ]
stackoverflow_0005627923_captcha_mechanize_python.txt
Q: Howcome a string type variable is considered as boolean in Python? In the code below: def modify_note(self): id = input("Enter a note id: ") memo = input("Enter a memo: ") tags = input("Enter tags: ") if memo: self.notebook.modify_memo(id, memo) if tags: self.notebook.modify_tags(...
Howcome a string type variable is considered as boolean in Python?
In the code below: def modify_note(self): id = input("Enter a note id: ") memo = input("Enter a memo: ") tags = input("Enter tags: ") if memo: self.notebook.modify_memo(id, memo) if tags: self.notebook.modify_tags(id, tags) memo and tags are string type variables. How can you write th...
[ "Every object in Python has a truth value. Strings are True if they are non-empty.\n", "The if memo and if tags statements are checking the truthiness of the memo and tags variables.\n\nAny object can be tested for truth\n value, for use in an if or while\n condition or as operand of the Boolean\n operations ...
[ 8, 6, 0 ]
[]
[]
[ "boolean", "conditional_statements", "python", "string" ]
stackoverflow_0005992882_boolean_conditional_statements_python_string.txt
Q: Filter a dict of dict I new in Python and I am not sure it is a good idea to use dict of dict but here is my question. I have a dict of dict and I want to filter by the key of the inside dict: a ={ 'key1' : {'id1' :[0,1,2] , 'id2' :[0,1,2], 'id3' :[4,5,6]} 'key2' : {'id3' :[0,1,2] , 'id4' :[0,1,2]} 'key3...
Filter a dict of dict
I new in Python and I am not sure it is a good idea to use dict of dict but here is my question. I have a dict of dict and I want to filter by the key of the inside dict: a ={ 'key1' : {'id1' :[0,1,2] , 'id2' :[0,1,2], 'id3' :[4,5,6]} 'key2' : {'id3' :[0,1,2] , 'id4' :[0,1,2]} 'key3' : {'id3' :[0,1,2] , 'id1'...
[ "Try this:\n>>> { k: v['id1'] for k,v in a.items() if 'id1' in v }\n{'key3': [4, 5, 6], 'key1': [0, 1, 2]}\n\nFor Python 2.x you might prefer to use iteritems() instead of items() and you'll still need a pretty recent python (2.7 I think) for a dictionary comprehension: for older pythons use:\ndict((k, v['id1']) fo...
[ 5, 2, 1, 1 ]
[]
[]
[ "dictionary", "filter", "python" ]
stackoverflow_0005992666_dictionary_filter_python.txt
Q: python recursion on list of lists without isinstance (different) I have an arbitrary list of arbitrary (but uniform) lists of numbers. (They are the boundary coordinates of bins in an n-space whose corners I want to plot, but that's not important.) I want to generate a list of all the possible combinations. So:...
python recursion on list of lists without isinstance (different)
I have an arbitrary list of arbitrary (but uniform) lists of numbers. (They are the boundary coordinates of bins in an n-space whose corners I want to plot, but that's not important.) I want to generate a list of all the possible combinations. So: [[1,2], [3,4],[5,6]] produces [[1,3,5],[1,3,6],[1,4,5],[1,4,6],[2,3,5...
[ "From your example it seems all you want is\nfrom itertools import product\na = [[1,2,3],[4,5,6],[7,8,9],[11,12,13]]\nprint list(product(*a))\n\n", "Try with the itertools.product\nimport itertools\n\na = [[1,2,3],[4,5,6],[7,8,9],[11,12,13]]\niterator = itertools.product(*a)\nresult = [item for item in iterator.n...
[ 6, 1, 0, 0 ]
[]
[]
[ "python", "recursion" ]
stackoverflow_0005992494_python_recursion.txt
Q: Unable to import FigureCanvasWxAgg from Matplotlib in Python I'm using Python x64 with everything installed, but I'm getting an unresolved import on FigureCanvasWxAgg. I can get up to matplotlib.backends.backend_wxagg but there's no FigureCanvasWxAgg to import from there. I've also tried from matplotlib.backen...
Unable to import FigureCanvasWxAgg from Matplotlib in Python
I'm using Python x64 with everything installed, but I'm getting an unresolved import on FigureCanvasWxAgg. I can get up to matplotlib.backends.backend_wxagg but there's no FigureCanvasWxAgg to import from there. I've also tried from matplotlib.backends.backend_wxagg import * but it doesn't work either. EDIT: Probl...
[ "What OS are you on, and how did you install matplotlib?\nYour solution is quite likely to break things... You need to build and install the wx backend as you normally would. I'm not sure about the wx backend, but several of the other backends are C extensions, not just a simple python file.\nThe wx backend isn't ...
[ 2 ]
[]
[]
[ "matplotlib", "pydev", "python", "wxpython" ]
stackoverflow_0005986780_matplotlib_pydev_python_wxpython.txt
Q: how to update wikipages automatically using python scripts I am using a internal wiki for my projects is there anything available so that I can update my wiki entries automatically using a python script? So that I don't need to go always to the wikipage and edit those pages manually. Thanks, Beeth A: You could u...
how to update wikipages automatically using python scripts
I am using a internal wiki for my projects is there anything available so that I can update my wiki entries automatically using a python script? So that I don't need to go always to the wikipage and edit those pages manually. Thanks, Beeth
[ "You could use Mechanize. Using this, you can essentially automate browser activity\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0005993916_python.txt
Q: Django: Constraint on multiple model fields Example: class Author(models.Model): first_name = models.CharField() last_name = models.CharField() def _get_full_name(self): return '{0} {1}'.format(self.first_name, self.last_name) full_name = property(_get_full_name) What's the recommended way...
Django: Constraint on multiple model fields
Example: class Author(models.Model): first_name = models.CharField() last_name = models.CharField() def _get_full_name(self): return '{0} {1}'.format(self.first_name, self.last_name) full_name = property(_get_full_name) What's the recommended way of putting a unique constaint on the full_name? ...
[ "Take a look at the Meta class option unique_together\nYou could do it this way:\nclass Author(models.Model):\n first_name = models.CharField()\n last_name = models.CharField()\n\n def _get_full_name(self):\n return '{0} {1}'.format(self.first_name, self.last_name)\n\n full_name = property(_get_fu...
[ 4, 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005993898_django_python.txt
Q: What's making this security descriptor go bad? I'm trying to read the access for files and directories in Windows using this code (patterned after Tim Golden's proposed patch to os.access to make it read from ACLs on Windows): from ctypes import( windll, wintypes, c_char_p, c_void_p, byref ...
What's making this security descriptor go bad?
I'm trying to read the access for files and directories in Windows using this code (patterned after Tim Golden's proposed patch to os.access to make it read from ACLs on Windows): from ctypes import( windll, wintypes, c_char_p, c_void_p, byref ) from win32api import GetCurrentThread from win32se...
[ "Apparently by \"optional\" Windows means \"required\". I fixed it by allocating a buffer and passing the size of PRIVILEGE_SET (20).\n" ]
[ 5 ]
[]
[]
[ "advapi32", "ctypes", "python", "pywin32" ]
stackoverflow_0005984483_advapi32_ctypes_python_pywin32.txt
Q: Google App Engine OAuth endpoints throwing 400 in production I implemented the experimental OAuth support for Google App Engine using Python, and have it working locally, but the endpoints are throwing a 400 when I deploy to appspot. For example, the url http(s)://my-app.appspot.com/_ah/OAuthGetRequestToken retu...
Google App Engine OAuth endpoints throwing 400 in production
I implemented the experimental OAuth support for Google App Engine using Python, and have it working locally, but the endpoints are throwing a 400 when I deploy to appspot. For example, the url http(s)://my-app.appspot.com/_ah/OAuthGetRequestToken returns a 400, but locally that url pattern behaves as expected. I h...
[ "You must register your domain in order to have OAuth working on production.\nAlthough the following docs state that Registering is Optional:\nhttp://code.google.com/apis/accounts/docs/RegistrationForWebAppsAuto.html\nIt doesn't work without the Registration since January. \nLook at the link above and Register your...
[ 4, 0, 0 ]
[]
[]
[ "google_app_engine", "oauth", "oauth_2.0", "python" ]
stackoverflow_0005938387_google_app_engine_oauth_oauth_2.0_python.txt
Q: Bitwise operations in Python I'm looking for recommendations on how to do bitwise math in python. The main problem I have is that python's bitwise operators have infinite precision, which means that -1 is really "111.......111". That's not what I want. I want to emulate real hardware which will have some fixed pr...
Bitwise operations in Python
I'm looking for recommendations on how to do bitwise math in python. The main problem I have is that python's bitwise operators have infinite precision, which means that -1 is really "111.......111". That's not what I want. I want to emulate real hardware which will have some fixed precision, say 32 bits. Here are som...
[ "You could use numpy, it has built in int32 types and much more. \n", "You could always add a & ((1<<32) - 1) mask to limit the number to 32-bits before performing any operation, e.g.\nclass Int32(int):\n def __neg__(self):\n return Int32(int.__neg__(self) & ((1 << 32) - 1))\n def __rshift__(self, ot...
[ 6, 3 ]
[]
[]
[ "bit_manipulation", "bitwise_operators", "python" ]
stackoverflow_0005994307_bit_manipulation_bitwise_operators_python.txt
Q: search/replace content of xml I've been successful using xml.etree.ElementTree to parse an xml, search for content, then write this to a different xml. However, I just worked with text, inside of a singe tag. import os, sys, glob, xml.etree.ElementTree as ET path = r"G:\\63D RRC GIS Data\\metadata\\general\\2010_...
search/replace content of xml
I've been successful using xml.etree.ElementTree to parse an xml, search for content, then write this to a different xml. However, I just worked with text, inside of a singe tag. import os, sys, glob, xml.etree.ElementTree as ET path = r"G:\\63D RRC GIS Data\\metadata\\general\\2010_contract" for fn in os.listdir(path...
[ "Here is an example of using lxml to do this. I'm not exactly sure how you want the <attr/> nodes replaced, but this example should provide a pattern you can reuse.\nUpdate - I changed it to replace each <attr> in tree2 with the corresponding node from tree1, in document order:\nimport copy\nimport lxml.etree\n\nxm...
[ 1, 0 ]
[]
[]
[ "elementtree", "python" ]
stackoverflow_0005993286_elementtree_python.txt
Q: Why cant Scipy Install on Windows 7 using easy_install and cygwin? I have tried multiple times, but never have been able to install scipy via easy_install on cygwin. I am using python 2.6.5 and Windows 7. After installing numpy successfully, I try to install scipy via the following command: easy_install -U scipy a...
Why cant Scipy Install on Windows 7 using easy_install and cygwin?
I have tried multiple times, but never have been able to install scipy via easy_install on cygwin. I am using python 2.6.5 and Windows 7. After installing numpy successfully, I try to install scipy via the following command: easy_install -U scipy and see the following errors: bnrm2,resid,info = zstopt...
[ "This is probably the dreaded \"rebase problem\".\nInstall rebase and run \"rebaseall\" per the instructions and see if that works.\nIt has to do with the way that Windows maps DLLs into memory and sometimes they collide.\n" ]
[ 2 ]
[]
[]
[ "numpy", "python", "scipy" ]
stackoverflow_0005870723_numpy_python_scipy.txt
Q: MySQLdb is extremely slow with large result sets I executed the following query both in phpMyAdmin & MySQLdb (python). SELECT *, (SELECT CONCAT(`id`, '|', `name`, '|', `image_code`) FROM `model_artist` WHERE `id` = `artist_id`) as artist_data, FIND_IN_SET("metallica", `searchable_words`) as find_0 FROM `model_son...
MySQLdb is extremely slow with large result sets
I executed the following query both in phpMyAdmin & MySQLdb (python). SELECT *, (SELECT CONCAT(`id`, '|', `name`, '|', `image_code`) FROM `model_artist` WHERE `id` = `artist_id`) as artist_data, FIND_IN_SET("metallica", `searchable_words`) as find_0 FROM `model_song` HAVING find_0 phpMyAdmin said the query took 2ms. ...
[ "If you expect an SQL query to have a large result set which you then plan to iterate over record-by-record, then you may want to consider using the MySQLdb SSCursor instead of the default cursor. The default cursor stores the result set in the client, whereas the SSCursor stores the result set in the server. Unlik...
[ 15, 5 ]
[]
[]
[ "mysql_python", "python" ]
stackoverflow_0005994363_mysql_python_python.txt
Q: Google App Engine and Google Maps Proximity Search in Python Due to the limitations of the GQL engine it has been suggested that people wanting to perform a proximity search should find someway around these limitations using the suggested geomodel. It might not be a very elegant or fast solution but is there anyth...
Google App Engine and Google Maps Proximity Search in Python
Due to the limitations of the GQL engine it has been suggested that people wanting to perform a proximity search should find someway around these limitations using the suggested geomodel. It might not be a very elegant or fast solution but is there anything to stop anyone using the algorithm from here: SELECT id, ( 395...
[ "Obviously that snippet is some flavour of SQL and not compatible with the Datastore's much simpler index based lookup. \nIf you mean you want to just fetch ALL your entities and perform the distance calculations in memory with python; then that is certainly possible, but you will be limited to doing this on a rela...
[ 2 ]
[]
[]
[ "google_app_engine", "maps", "python" ]
stackoverflow_0005981954_google_app_engine_maps_python.txt
Q: How to initiate python program with a change in the input? I have an application made in python, this application takes input from a separate text file called input.txt, i have to design the application in such a way that application runs automatically with any input to input.txt. Such that i need not go to comman...
How to initiate python program with a change in the input?
I have an application made in python, this application takes input from a separate text file called input.txt, i have to design the application in such a way that application runs automatically with any input to input.txt. Such that i need not go to command prompt and run the program, if i give the input, or change the...
[ "You can run your program once and watch the filesystem changes for new or modified file. Try using python-inotify for linux:\nhttps://github.com/seb-m/pyinotify\n" ]
[ 1 ]
[]
[]
[ "python", "user_input" ]
stackoverflow_0005994544_python_user_input.txt
Q: How to read argv value without escape the string? I'm writing a python script called flac2m4a which calls ffmpeg to convert a .flac file to .m4a file. the core program is like this: cmd = "ffmpeg -i %s -acodec alac %s.m4a" % (sys.argv[1], sys.argv[1][:-5]) os.system(cmd) I can use the program like this: ./fla...
How to read argv value without escape the string?
I'm writing a python script called flac2m4a which calls ffmpeg to convert a .flac file to .m4a file. the core program is like this: cmd = "ffmpeg -i %s -acodec alac %s.m4a" % (sys.argv[1], sys.argv[1][:-5]) os.system(cmd) I can use the program like this: ./flac2m4a path_to_the_song.flac But when I run it for so...
[ "While it is possible to quote a string for the shell, you should not use the shell to execute your command in the first place, rendering any quoting unnecessary. Use subprocess.call() instead of os.system():\nsubprocess.call([\"ffmpeg\", \"-i\", sys.argv[1], \"-acodec\", \"alac\",\n sys.argv[1][:-...
[ 6, 1, 0 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0005994827_linux_python.txt
Q: Building an MS Access database using python A primary goal of a project I plan to bid on involves creating a Microsoft Access database using python. The main DB backend will be postgres, but the plan is to export an Access image. This will be a web app that'll take input from the user and go through a black box an...
Building an MS Access database using python
A primary goal of a project I plan to bid on involves creating a Microsoft Access database using python. The main DB backend will be postgres, but the plan is to export an Access image. This will be a web app that'll take input from the user and go through a black box and output the results as an access db. The web app...
[ "Could you use an sqlite database instead?\nedit:\nIf it HAS to be on linux and it HAS to be to MS Access, then I'm pretty sure this is your only choice, but it costs $1,550.\nYou are either going to have to shell out the money, or convince the client to change one of the other two parameters. Personally, I would ...
[ 5, 2, 2, 1, 0, 0, 0, 0 ]
[]
[]
[ "linux", "ms_access", "python" ]
stackoverflow_0005891359_linux_ms_access_python.txt
Q: python mysql write error I have a script that works taking in a csv file and output to a mysql database. Everything works well, but with a new file, I'm getting an odd error that is not getting caught by a try/error sequence, which is just below - try: rtn = csr.execute (strg) db.commit() print "Successfully pro...
python mysql write error
I have a script that works taking in a csv file and output to a mysql database. Everything works well, but with a new file, I'm getting an odd error that is not getting caught by a try/error sequence, which is just below - try: rtn = csr.execute (strg) db.commit() print "Successfully processed record " + str(row_inde...
[ "This warning means that the price column is set to a data type that is not big enough for the value you are trying to hold. How is the price column declared?\n" ]
[ 2 ]
[]
[]
[ "mysql", "python", "try_catch" ]
stackoverflow_0005995113_mysql_python_try_catch.txt
Q: Problems with python asyncore working with AF_UNIX sockets I have some problems using asyncore with AF_UNIX sockets. This code import asyncore, socket, os class testselect(asyncore.dispatcher): path = '/tmp/mysocket' def __init__(self): asyncore.dispatcher.__init__(self) self.create_so...
Problems with python asyncore working with AF_UNIX sockets
I have some problems using asyncore with AF_UNIX sockets. This code import asyncore, socket, os class testselect(asyncore.dispatcher): path = '/tmp/mysocket' def __init__(self): asyncore.dispatcher.__init__(self) self.create_socket(socket.AF_UNIX, socket.SOCK_DGRAM) self.bind(self.p...
[ "Note As the other answer points out, when you send a datagram you need to specify the receiver. As it stands, your testselect class looks more like a client than a server. \nReview some of these asyncore examples to find a server pattern you can copy. The TimeChannel example is closer to what you want -- change so...
[ 5, 1 ]
[]
[]
[ "asyncore", "python", "sockets", "unix_socket" ]
stackoverflow_0005994521_asyncore_python_sockets_unix_socket.txt
Q: equivalent of `a?b:c` Possible Duplicate: Python Ternary Operator I want to print out a string in python. I don't want to do: if isfemale_bit: print 'F' else: print 'M' The best I have right now is print ['M', 'F'][int(isfemale_bit)]? Is there a better alternative? I needs my syntactic sugar!! A: In ...
equivalent of `a?b:c`
Possible Duplicate: Python Ternary Operator I want to print out a string in python. I don't want to do: if isfemale_bit: print 'F' else: print 'M' The best I have right now is print ['M', 'F'][int(isfemale_bit)]? Is there a better alternative? I needs my syntactic sugar!!
[ "In Python 2.5, you can use ternary conditionals like this:\na if b else c\n\nThere is more discussion here: Does Python have a ternary conditional operator?\n", "Ah the ternary operator:\n>>> print 'foo' if True else 'bar'\nfoo\n>>> print 'foo' if False else 'bar'\nbar\n\n", " print 'F' if isfemale_bit else 'M...
[ 58, 17, 15, 9 ]
[]
[]
[ "python" ]
stackoverflow_0005995350_python.txt
Q: disable/enable a widget using combobox? is possible to toggle between enable/disable a widget using an option in combobox (optionmenu, dropdown)?? i mean enable it if an option is choosed... with others, disabled... if yes, how?? i tryed something like this but it didn't worked... op = StringVar(root) op.set("----...
disable/enable a widget using combobox?
is possible to toggle between enable/disable a widget using an option in combobox (optionmenu, dropdown)?? i mean enable it if an option is choosed... with others, disabled... if yes, how?? i tryed something like this but it didn't worked... op = StringVar(root) op.set("------") o0 = OptionMenu(root, op, "opt1", "opt2"...
[ "Yes, it's possible. Here's an example:\nimport Tkinter as tk\n\nclass App(tk.Tk):\n def __init__(self, *args, **kwargs):\n tk.Tk.__init__(self, *args, **kwargs)\n self.op = tk.StringVar(self)\n self.op.set(\"enable\")\n self.om = tk.OptionMenu(self, self.op, \"enable\",\"disable\", c...
[ 2 ]
[]
[]
[ "combobox", "python", "tkinter" ]
stackoverflow_0005985396_combobox_python_tkinter.txt
Q: Running a python script concurrently over the network. Is this OK? We have a python script + associated modules on a network drive. We are running this script simultaneously from several computers at once. Sometimes one of them randomly fails with an error like this: Traceback (most recent call last): File "\\...
Running a python script concurrently over the network. Is this OK?
We have a python script + associated modules on a network drive. We are running this script simultaneously from several computers at once. Sometimes one of them randomly fails with an error like this: Traceback (most recent call last): File "\\chifs02.int.tt.local\group\Development\Server Products\Automation\repos\...
[ "Don't do that, where \"that\" is have multiple computers trying to use the same .pyc(s).\nThe likely reason the pyc gets modified is that you likely have slightly different versions of Python on different computers. One writes its version of the .pyc, and another comes along and sees that it's not what it expected...
[ 4, 2 ]
[]
[]
[ "networking", "python", "windows" ]
stackoverflow_0005995467_networking_python_windows.txt
Q: Python underscore variable In interactive python, there is the 'continuation variable', the underscore. >>> import netlib >>> netdev = netlib.netface('eth1') >>> if netdev.getIP(): ... print _ ... 10.80.22.100 >>> But using this in a script, it is undefined so this fails: if netdev.getIP(): SetValue('ipaddres...
Python underscore variable
In interactive python, there is the 'continuation variable', the underscore. >>> import netlib >>> netdev = netlib.netface('eth1') >>> if netdev.getIP(): ... print _ ... 10.80.22.100 >>> But using this in a script, it is undefined so this fails: if netdev.getIP(): SetValue('ipaddress', _) Is there something simil...
[ "No. It is only available within the Python REPL.\n" ]
[ 9 ]
[]
[]
[ "python", "variables" ]
stackoverflow_0005995572_python_variables.txt
Q: How to push changes through django? I've been given the keys to a website written in Python on the Django framework. I have a php background, so I'm not used to having to worry about compliation, etc. I'm just trying to change the copyright at the footer. I found the template that holds the html... it's called b...
How to push changes through django?
I've been given the keys to a website written in Python on the Django framework. I have a php background, so I'm not used to having to worry about compliation, etc. I'm just trying to change the copyright at the footer. I found the template that holds the html... it's called base.html, in the 'templates' folder. I c...
[ "there are two different things.\nif you change your python files, it is complicated. most of time, you need restart your server to see changes.\nBut I think your problem is totally different. You use django.template.loaders.cached.Loader\nyou can check it in your settings.py\nanyway if you use this template loader...
[ 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005994922_django_python.txt
Q: Constant property/column value for objects in SQLAlchemy i have a class class User: constant_value = 5 when i use "mapper" the property goes away. how do i preserve this? A: Use exclude_properties: mapper(Address, addresses_table, exclude_properties=['street', 'city', 'state', 'zip'])
Constant property/column value for objects in SQLAlchemy
i have a class class User: constant_value = 5 when i use "mapper" the property goes away. how do i preserve this?
[ "Use exclude_properties:\nmapper(Address, addresses_table,\n exclude_properties=['street', 'city', 'state', 'zip'])\n\n" ]
[ 0 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0005994442_python_sqlalchemy.txt
Q: Python error with socket. Ntohl() I'm having an issue with the socket.ntohl() function, on some hosts. It is repeatable on all similar hosts; 32bit machines with Python 2.4.2. >>> socket.ntohl(16777215) -256 However the reverse seems to work fine - >>> socket.htonl(4294967040) 16777215 Reading the docs, It does...
Python error with socket. Ntohl()
I'm having an issue with the socket.ntohl() function, on some hosts. It is repeatable on all similar hosts; 32bit machines with Python 2.4.2. >>> socket.ntohl(16777215) -256 However the reverse seems to work fine - >>> socket.htonl(4294967040) 16777215 Reading the docs, It doesn't mention any limitations or warnings...
[ "In older 32-bit Python versions, int was limited to a signed 32-bit number. 16777215 = 0x00FFFFFF and -256 in 32-bit 2s complement is 0xFFFFFF00.\nIt works correctly in Python 2.7 by upgrading the value to a long:\n>>> socket.ntohl(16777215)\n4294967040L\n>>> hex(4294967040)\n'0xffffff00L'\n\nEdit:\nPython 2.4 wa...
[ 3 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0005995971_python_sockets.txt
Q: numpy on multicore hardware What's the state of the art with regards to getting numpy to use mutliple cores (on Intel hardware) for things like inner and outer vector products, vector-matrix multiplications etc? I am happy to rebuild numpy if necessary, but at this point I am looking at ways to speed things up wit...
numpy on multicore hardware
What's the state of the art with regards to getting numpy to use mutliple cores (on Intel hardware) for things like inner and outer vector products, vector-matrix multiplications etc? I am happy to rebuild numpy if necessary, but at this point I am looking at ways to speed things up without changing my code. For refere...
[ "You should probably start by checking whether the Atlas build that numpy is using has been built with multi-threading. You can build and run this to inspect the Atlas configuration (straight from the Atlas FAQ):\nmain()\n/*\n * Compile, link and run with something like:\n * gcc -o xprint_buildinfo -L[ATLAS lib ...
[ 7 ]
[]
[]
[ "linear_algebra", "multicore", "numpy", "performance", "python" ]
stackoverflow_0005991014_linear_algebra_multicore_numpy_performance_python.txt
Q: Django: Still getting CSRF error after trying tons of fixes I am getting "CSRF token missing or incorrect". I already checked Stack Overflow for an answer and nothing worked; I double checked my sources and really don't know what I did wrong. It only works when I comment the MIDDLEWARE_CLASSES line with CsrfViewMi...
Django: Still getting CSRF error after trying tons of fixes
I am getting "CSRF token missing or incorrect". I already checked Stack Overflow for an answer and nothing worked; I double checked my sources and really don't know what I did wrong. It only works when I comment the MIDDLEWARE_CLASSES line with CsrfViewMiddleware, but I think is something that I never need to do. Here ...
[ "You need to make sure that you include the RequestContext in your response.\nreturn render_to_response('sitfin/conturi_introducere.html',{'formset':formset},\ncontext_instance=RequestContext(request))\n\n", "Also I would remove\n'django.middleware.csrf.CsrfResponseMiddleware',\n\nThis is legacy and is being depr...
[ 9, 1 ]
[]
[]
[ "csrf", "django", "python" ]
stackoverflow_0005996209_csrf_django_python.txt
Q: Does django support hashbang in its URL? Does django support urls having #! in it.Say I have ursl like http://example.com/foo/!#/bar Any regex for that? Note: http://example.com/foo/ and http://example.com/foo/#!/bar are different URLs and having different corresponding Views. url(r'^(?P<#!>.+)/bar/$', 'my_view...
Does django support hashbang in its URL?
Does django support urls having #! in it.Say I have ursl like http://example.com/foo/!#/bar Any regex for that? Note: http://example.com/foo/ and http://example.com/foo/#!/bar are different URLs and having different corresponding Views. url(r'^(?P<#!>.+)/bar/$', 'my_view', name='my-view'), throwing bad character in ...
[ "No. Anything after the # is not even sent to your webserver. If you want to make interactivity using the anchored (#) url styles, you need to go look at ajax libraries like jquery.\n", "This is the \"evil standard\" way of denoting AJAX URLs. For a better description of the topic you should referer to this docu...
[ 4, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005994921_django_python.txt
Q: query output formting in django template I am trying to output the query in below table format in template RAW.objects.filter(at_date__year='2011',at_date__month='02').values('user','attend').order_by().annotate(total=Count('attend')) output from the query [{'user': u'sushanth', 'total': 13, 'attend': u'P'}, {'u...
query output formting in django template
I am trying to output the query in below table format in template RAW.objects.filter(at_date__year='2011',at_date__month='02').values('user','attend').order_by().annotate(total=Count('attend')) output from the query [{'user': u'sushanth', 'total': 13, 'attend': u'P'}, {'user': u'sushanthreddy', 'total': 2, 'attend': ...
[ "When you use a values clause, Django will send a DISTINCT phrase in SQL based on the values you're asking for. So, you're already getting only distinct combinations of \"user\" and \"attend\".\nHow big is this output likely to be? If you're looking at just a couple hundred rows, I would suggest simply iterating ov...
[ 0 ]
[]
[]
[ "django", "django_models", "django_templates", "django_views", "python" ]
stackoverflow_0005170058_django_django_models_django_templates_django_views_python.txt